` | 某个会话始终同步或永不同步 |
+| `opencode-sync repair-sessions [--apply]` | OpenCode 2:把 `/session` 里看不到的会话移回所属项目(不加 `--apply` 只预览) |
| `opencode-sync overrides` | 创建或找到专属设置文件 |
| `opencode-sync config` | 打印设置 |
@@ -299,7 +396,9 @@ OpenCode 1.0–1.3.3 无法加载 3.1.0 及以后的版本,请在这些版本
| `SYNC_REMOTE_URL` | 覆盖仓库地址 |
| `NO_COLOR` | 不输出颜色 |
-### 设置文件
+---
+
+## 设置文件
`~/.config/opencode/opencode-sync.jsonc` 只留在本机,永远不会提交。菜单会帮你改,所有键都可以省略。
@@ -308,6 +407,7 @@ OpenCode 1.0–1.3.3 无法加载 3.1.0 及以后的版本,请在这些版本
"repo": { "owner": "you", "name": "my-opencode-config", "branch": "main" },
"machineAlias": "laptop",
"includeCredentials": false,
+ "openaiRefreshLease": true,
"includeSkills": true,
"includeState": true,
"extraPaths": [".config/gh/config.yml"],
@@ -323,11 +423,24 @@ OpenCode 1.0–1.3.3 无法加载 3.1.0 及以后的版本,请在这些版本
}
```
+| 键 | 含义 |
+| --- | --- |
+| `machineAlias` | 提交里这台电脑的名字;不填就用一个固定的代号 |
+| `includeCredentials` | 同步登录凭据(见[登录凭据](#登录凭据)),只限私有仓库 |
+| `openaiRefreshLease` | 开启凭据同步时,让共用的 ChatGPT 登录同一时间只由一台电脑续期 |
+| `includeSkills` / `includeState` | 同步 `~/.agents/skills` / `~/.local/state/opencode` |
+| `extraPaths` | 额外的文件或文件夹,相对于用户目录 |
+| `categories` | 配置目录里哪些部分要共享 |
+| `sessions` | [会话同步](#会话同步)的时间范围、数量和大小上限 |
+| `autosync` | [自动同步](#自动同步)的间隔、安静时长、注销后运行、每日自动更新 |
+| `guard` | [大改动保护](#安全机制)的上限 |
+| `autoPullOnStartup` / `autoPushOnIdle` | [插件](#opencode-插件)的行为 |
+
---
## 常见问题
-**我得走代理。** 给安装脚本加 `--proxy http://主机:端口`(Windows 上是 `-Proxy`)。安装时 npm 和 git 都会用它,之后同步也会继续用。随时可以在**网络代理**里改。
+**我得走代理。** 给安装脚本加 `--proxy http://主机:端口`(Windows 上是 `-Proxy`)。安装时 npm 和 git 都会用它,之后同步也会继续用,包括 ChatGPT 登录续期。随时可以在**网络代理**里改。
**`curl | sh` 怎么不问我问题?** 脚本本身是从管道传进来的,所以它改从终端读你的回答。如果根本没有终端(CI、Dockerfile),就没人可问了:加上 `--mode` 和 `--repo`;可能需要装 Node.js 或 git 的话再加 `--yes`。
@@ -337,9 +450,15 @@ OpenCode 1.0–1.3.3 无法加载 3.1.0 及以后的版本,请在这些版本
**开了自动同步却没动静。** 运行 `opencode-sync autosync status`,看看是不是被暂停了、出错后在退避,还是因为文件还在变化而在等。菜单里的**诊断**可以看定时任务有没有注册上。
+**同步过来的会话在 `/session` 里看不到(OpenCode 2)。** 在那个会话所在的文件夹里打开 OpenCode;`/session` 只列出当前文件夹所属项目的会话。如果是升级到 OpenCode 2 之前的老会话,运行 `opencode-sync repair-sessions --apply`。
+
+**会话完全没同步。** 看看 `opencode-sync status` 里会话同步是不是开着,以及 `node --version` 是不是 22.5 或更新。
+
+**登录没传到另一台电脑(OpenCode 2)。** 两台电脑都要开启凭据同步。先在登录的那台同步一次,再在另一台同步。如果同一个服务有两个账号都被标成“当前使用”,这个服务不会被改动;在 OpenCode 里切换一次账号就能理顺。
+
**拉取时和本地改动冲突了。** 你的改动保存在 git stash 里,恢复用的命令会直接打印出来。不会丢东西。
-**提示"这台电脑有 N 个提交从没推送过"。** 这时拉取会把它们丢掉,所以先停下。运行 `opencode-sync push`,或者用 `pull --force` 放弃它们。
+**提示“这台电脑有 N 个提交从没推送过”。** 这时拉取会把它们丢掉,所以先停下。运行 `opencode-sync push`,或者用 `pull --force` 放弃它们。
**认证失败。** 运行 `gh auth login -h github.com`。私有仓库需要 `repo` 权限。
@@ -353,13 +472,40 @@ opencode-sync pull --force
---
-## 从 3.1.x 升级
+## 升级
+
+### 升级到 OpenCode 2
+
+先在每台电脑上把 opencode-github-sync 升到 3.3.0 或更新。3.2.x 读不了 OpenCode 2 的会话,还会把 OpenCode 2 的 `service.json` 提交上去。
+
+1. 安装 OpenCode 2。npm 12 必须允许它的安装脚本,否则 `opencode` 命令只是个空壳:
+
+ ```bash
+ npm install -g @opencode/cli --allow-scripts=@opencode/cli
+ ```
+
+2. 可选:禁止 OpenCode 2 在后台自动更新;通过 npm 12 无人值守自更新可能把安装弄坏:
+
+ ```bash
+ opencode service set env OPENCODE_DISABLE_AUTOUPDATE 1
+ ```
+
+3. 先启动一次 OpenCode 2,让它迁移 1.x 的数据,再把 `/session` 里看不到的会话找回来:
+
+ ```bash
+ opencode-sync repair-sessions # 预览
+ opencode-sync repair-sessions --apply
+ ```
+
+**如果你在 OpenCode 2 上用 3.2.x 同步过**,仓库里可能有 `service.json` 和 `_state/service.json`。3.3.0 下次推送时会把它们删掉,但它们还留在仓库历史里。里面的密码只能打开那台电脑本地的后台服务。如果也想从历史里清掉,可以删掉仓库,再从一台电脑重新推送。
+
+### 从 3.1.x 或 3.2.x 升级
```bash
npm install -g opencode-github-sync@latest
```
-不需要别的操作:设置、专属设置和仓库都照常工作,自动同步在你打开之前一直是关的。如果你之前用自己的脚本定时同步,开启自动同步前先把它停掉,免得两边抢。如果你在插件里开了 `autoPushOnIdle`,在开启了自动同步的电脑上,由自动同步接替它。
+不需要别的操作:设置、专属设置和仓库都照常工作,自动同步在你打开之前一直是关的。如果你之前用自己的脚本定时同步,开启自动同步前先把它停掉,免得两边抢。如果你在插件里开了 `autoPushOnIdle`,在开启了自动同步的电脑上由自动同步接替它。完整改动见[更新日志](./CHANGELOG.zh-CN.md)。
---
@@ -371,17 +517,17 @@ npm run check # 代码检查、类型检查和测试
npm run build
```
-测试直接在磁盘上的真实 git 仓库里跑,并模拟多台电脑,推送、拉取、变基、自动同步调度和菜单都端到端覆盖。真正的定时任务只会在用完即弃的 CI 机器上注册。
+测试直接在磁盘上的真实 git 仓库里跑,并模拟多台电脑,推送、拉取、变基、自动同步调度和菜单都端到端覆盖。会话和凭据测试用的是真实 OpenCode 2.2.5 数据库的表结构,令牌全部是假的。真正的定时任务只会在用完即弃的 CI 机器上注册。
---
## Star 趋势
-
+
-
-
-
+
+
+
@@ -389,7 +535,7 @@ npm run build
## 许可证
-[MIT](https://github.com/doomsday616/opencode-github-sync/blob/main/LICENSE)
+[MIT](https://github.com/lazyalex616/opencode-github-sync/blob/main/LICENSE)
如果它帮你省了时间,欢迎点个 ⭐。
diff --git a/install.ps1 b/install.ps1
index c4753c5..05e3413 100644
--- a/install.ps1
+++ b/install.ps1
@@ -3,9 +3,9 @@
Install opencode-github-sync on Windows and open its menu.
.DESCRIPTION
- irm https://raw.githubusercontent.com/doomsday616/opencode-github-sync/main/install.ps1 | iex
+ irm https://raw.githubusercontent.com/lazyalex616/opencode-github-sync/main/install.ps1 | iex
- & ([scriptblock]::Create((irm https://raw.githubusercontent.com/doomsday616/opencode-github-sync/main/install.ps1))) -Mode auto -Repo owner/name
+ & ([scriptblock]::Create((irm https://raw.githubusercontent.com/lazyalex616/opencode-github-sync/main/install.ps1))) -Mode auto -Repo owner/name
What it does, and nothing else:
1. checks for Node.js 18+ and git, and offers to install a missing one with
diff --git a/install.sh b/install.sh
index 71d7c51..4a3e333 100644
--- a/install.sh
+++ b/install.sh
@@ -1,8 +1,8 @@
#!/bin/sh
# opencode-github-sync installer for macOS and Linux.
#
-# curl -fsSL https://raw.githubusercontent.com/doomsday616/opencode-github-sync/main/install.sh | sh
-# curl -fsSL https://raw.githubusercontent.com/doomsday616/opencode-github-sync/main/install.sh | sh -s -- --mode auto --repo owner/name
+# curl -fsSL https://raw.githubusercontent.com/lazyalex616/opencode-github-sync/main/install.sh | sh
+# curl -fsSL https://raw.githubusercontent.com/lazyalex616/opencode-github-sync/main/install.sh | sh -s -- --mode auto --repo owner/name
#
# What it does, and nothing else:
# 1. checks for Node.js 18+ and git, and offers to install a missing one
@@ -63,7 +63,7 @@ while [ $# -gt 0 ]; do
--yes|-y) YES=1; shift ;;
--dry-run) DRY_RUN=1; shift ;;
-h|--help)
- sed -n '2,30p' "$0" 2>/dev/null || say "See https://github.com/doomsday616/opencode-github-sync"
+ sed -n '2,30p' "$0" 2>/dev/null || say "See https://github.com/lazyalex616/opencode-github-sync"
exit 0 ;;
*) err "unknown option: $1"; exit 2 ;;
esac
diff --git a/package-lock.json b/package-lock.json
index 4f5802f..e83c6b1 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "opencode-github-sync",
- "version": "3.2.0",
+ "version": "3.3.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "opencode-github-sync",
- "version": "3.2.0",
+ "version": "3.3.0",
"license": "MIT",
"bin": {
"opencode-sync": "dist/cli/index.js"
diff --git a/package.json b/package.json
index 69937b1..3e7dbe6 100644
--- a/package.json
+++ b/package.json
@@ -1,17 +1,17 @@
{
"name": "opencode-github-sync",
- "version": "3.2.0",
+ "version": "3.3.0",
"description": "Sync your OpenCode config, skills, and selected sessions across machines via a private GitHub repo — as a plugin or a CLI.",
"type": "module",
"license": "MIT",
"author": "doomsday616",
- "homepage": "https://github.com/doomsday616/opencode-github-sync#readme",
+ "homepage": "https://github.com/lazyalex616/opencode-github-sync#readme",
"repository": {
"type": "git",
- "url": "git+https://github.com/doomsday616/opencode-github-sync.git"
+ "url": "git+https://github.com/lazyalex616/opencode-github-sync.git"
},
"bugs": {
- "url": "https://github.com/doomsday616/opencode-github-sync/issues"
+ "url": "https://github.com/lazyalex616/opencode-github-sync/issues"
},
"keywords": [
"opencode",
diff --git a/src/cli/i18n.ts b/src/cli/i18n.ts
index 4075d7e..9f745f1 100644
--- a/src/cli/i18n.ts
+++ b/src/cli/i18n.ts
@@ -92,7 +92,8 @@ const en = {
previewOutgoing: "Would push {n} change(s):",
previewIncoming: "Would receive {n} change(s):",
previewConfirm: "Go ahead?",
- restartHint: "Restart OpenCode for the new configuration to take effect.",
+ restartHint:
+ "OpenCode 2 picks up the new configuration by itself. Restart OpenCode 1, or after a plugin changed.",
largeTitle: "This push is unusually large:",
largeFiles: "{n} new files (limit {limit})",
largeBytes: "{size} in total (limit {limit})",
@@ -310,7 +311,7 @@ const en = {
initSettings: "settings {file}",
initOverrides: "overrides {file}",
initNext: "Next",
- initRestart: "Restart OpenCode",
+ initRestart: "Restart OpenCode (OpenCode 2 only needs it for plugins)",
sesTitle: "sessions",
sesNoSqlite: "No SQLite driver available. Use Node 22.5+ or run under Bun.",
@@ -326,6 +327,16 @@ const en = {
sesCap: "Per-session cap: {size}",
sesUnknown: "Unknown sessions subcommand: {sub}",
+ rpTitle: "repair sessions",
+ rpNotV2: "This database is not an OpenCode 2 database. Nothing to repair.",
+ rpSummary: "{sessions} session(s), {moves} not listed where OpenCode 2 looks for them.",
+ rpMove: "{n} session(s): {from} -> {to}",
+ rpParked: "{n} session(s) parked in the home project (their folder has no project yet)",
+ rpUnresolved: "{n} session(s) left in global: {directory}",
+ rpDryRun: "Dry run: nothing was changed. Run again with --apply to move them.",
+ rpApplied: "Moved {n} session(s). They show up in /session right away.",
+ rpNothing: "Every session is already where OpenCode 2 lists it.",
+
ovCliTitle: "per-machine overrides",
ovCreated: "Created the overrides file",
ovCliInfo: "Anything in this file stays on this machine and is re-applied after every pull.",
@@ -374,6 +385,7 @@ const en = {
helpSesToggle: "Turn selective session sync on or off",
helpSesInclude: "Always sync a session, ignoring the time window",
helpSesExclude: "Never sync a session",
+ helpRepair: "Move OpenCode 2 sessions missing from /session into their project (--apply)",
helpAsInstall: "Register or remove the scheduled job",
helpAsToggle: "Turn autosync on or off for this machine",
helpAsStatus: "Show autosync state and the last error",
@@ -482,7 +494,7 @@ const zhCN: Catalog = {
previewOutgoing: "将推送 {n} 处改动:",
previewIncoming: "将接收 {n} 处改动:",
previewConfirm: "继续吗?",
- restartHint: "重启 OpenCode 后新配置才会生效。",
+ restartHint: "OpenCode 2 会自动读取新配置。OpenCode 1 或插件有变化时需要重启 OpenCode。",
largeTitle: "这次推送的改动特别大:",
largeFiles: "新增 {n} 个文件(上限 {limit})",
largeBytes: "总共 {size}(上限 {limit})",
@@ -684,7 +696,7 @@ const zhCN: Catalog = {
initSettings: "设置文件 {file}",
initOverrides: "专属设置 {file}",
initNext: "下一步",
- initRestart: "重启 OpenCode",
+ initRestart: "重启 OpenCode(OpenCode 2 只有插件变化时才需要)",
sesTitle: "会话",
sesNoSqlite: "没有可用的 SQLite 驱动。请使用 Node 22.5+ 或 Bun。",
@@ -700,6 +712,16 @@ const zhCN: Catalog = {
sesCap: "单个会话上限:{size}",
sesUnknown: "未知的 sessions 子命令:{sub}",
+ rpTitle: "修复会话归属",
+ rpNotV2: "这不是 OpenCode 2 的数据库,不需要修复。",
+ rpSummary: "共 {sessions} 个会话,其中 {moves} 个不在 OpenCode 2 会列出的位置。",
+ rpMove: "{n} 个会话:{from} -> {to}",
+ rpParked: "{n} 个会话放进了主目录项目(它们的文件夹还没有项目)",
+ rpUnresolved: "{n} 个会话留在 global:{directory}",
+ rpDryRun: "只是预览,什么都没改。加上 --apply 再运行一次才会真正移动。",
+ rpApplied: "已移动 {n} 个会话,/session 里马上就能看到。",
+ rpNothing: "所有会话都已经在 OpenCode 2 会列出的位置。",
+
ovCliTitle: "本机专属设置",
ovCreated: "已创建专属设置文件",
ovCliInfo: "这个文件里的内容只留在本机,每次拉取后都会重新套用。",
@@ -748,6 +770,7 @@ const zhCN: Catalog = {
helpSesToggle: "开启或关闭会话同步",
helpSesInclude: "始终同步某个会话,不受时间范围限制",
helpSesExclude: "永不同步某个会话",
+ helpRepair: "把 /session 里看不到的 OpenCode 2 会话移回所属项目(加 --apply 才执行)",
helpAsInstall: "注册或删除定时任务",
helpAsToggle: "在本机开启或关闭自动同步",
helpAsStatus: "查看自动同步状态和最后的错误",
diff --git a/src/cli/index.ts b/src/cli/index.ts
index efcf7c2..3a35601 100644
--- a/src/cli/index.ts
+++ b/src/cli/index.ts
@@ -12,6 +12,7 @@ import {
import { LargeChangeError } from "../core/guard.js";
import { withSyncLock } from "../core/lock.js";
import { getDatabasePath, getRoots } from "../core/paths.js";
+import { repairSessions } from "../core/repair.js";
import { listSessions } from "../core/sessions.js";
import {
OVERRIDES_TEMPLATE,
@@ -314,6 +315,47 @@ async function runSessions(args: Args): Promise {
throw new SyncError(t("sesUnknown", { sub }));
}
+async function runRepair(args: Args): Promise {
+ banner(t("rpTitle"));
+ if (!(await sqliteAvailable())) {
+ fail(t("sesNoSqlite"));
+ write();
+ return;
+ }
+ const apply = args.flags.has("apply");
+ const result = await repairSessions(getDatabasePath(getRoots()), { apply });
+ if (!result.supported) {
+ info(t("rpNotV2"));
+ write();
+ return;
+ }
+ if (result.moves.length === 0 && result.unresolved.length === 0) {
+ ok(t("rpNothing"));
+ write();
+ return;
+ }
+ info(t("rpSummary", { sessions: result.sessions, moves: result.moves.length }));
+ const groups = new Map();
+ let parked = 0;
+ for (const move of result.moves) {
+ if (move.parked) parked++;
+ const key = `${move.from}\u0000${move.to}`;
+ groups.set(key, (groups.get(key) ?? 0) + 1);
+ }
+ for (const [key, n] of groups) {
+ const [from, to] = key.split("\u0000");
+ detail(t("rpMove", { n, from: from ?? "", to: to ?? "" }));
+ }
+ if (parked > 0) detail(t("rpParked", { n: parked }));
+ for (const u of result.unresolved) {
+ detail(t("rpUnresolved", { n: u.count, directory: u.directory }));
+ }
+ write();
+ if (apply) ok(t("rpApplied", { n: result.applied }));
+ else if (result.moves.length > 0) info(t("rpDryRun"));
+ write();
+}
+
function runOverrides(): void {
banner(t("ovCliTitle"));
const roots = getRoots();
@@ -518,6 +560,7 @@ function runHelp(): void {
command("sessions enable | disable", t("helpSesToggle"));
command("sessions include ", t("helpSesInclude"));
command("sessions exclude ", t("helpSesExclude"));
+ command("repair-sessions [--apply]", t("helpRepair"));
heading(t("helpLocal"));
command("overrides", t("helpOverrides"));
@@ -534,7 +577,7 @@ function runHelp(): void {
write();
rule();
write(
- ` ${paint("docs", style.faint)} ${paint("https://github.com/doomsday616/opencode-github-sync", style.muted)}`,
+ ` ${paint("docs", style.faint)} ${paint("https://github.com/lazyalex616/opencode-github-sync", style.muted)}`,
);
write();
}
@@ -586,6 +629,9 @@ async function main(): Promise {
case "sessions":
await runSessions(args);
return;
+ case "repair-sessions":
+ await runRepair(args);
+ return;
case "autosync":
await runAutosyncCommand(args);
return;
diff --git a/src/core/autosync.ts b/src/core/autosync.ts
index a806029..4dfd3e5 100644
--- a/src/core/autosync.ts
+++ b/src/core/autosync.ts
@@ -4,6 +4,7 @@ import path from "node:path";
import { git, parsePorcelainPaths } from "./git.js";
import { LargeChangeError } from "./guard.js";
import { hostAlias } from "./host.js";
+import { leaseEnabled, maybeRefreshOpenai } from "./lease.js";
import { acquireSyncLock, releaseSyncLock } from "./lock.js";
import { configMatchesRepo, findConfigFile } from "./overrides.js";
import type { Roots } from "./paths.js";
@@ -253,6 +254,8 @@ export interface AutosyncDeps {
log: (line: string) => void;
/** Daily self-update hook; returns a one-line summary for the log. */
selfUpdate?: () => string;
+ /** Shared-login renewal before a push; returns a one-line summary for the log. */
+ refreshLease?: (settings: Settings) => Promise;
messages: AutosyncMessages;
}
@@ -355,6 +358,13 @@ export async function runAutosync(deps: AutosyncDeps, trigger = "scheduled"): Pr
state = writeState(deps.roots, { lastAttemptAt: deps.now() });
try {
+ if (deps.refreshLease && leaseEnabled(settings)) {
+ // Before the push, so a renewed login reaches the other machines now.
+ const lease = await deps.refreshLease(settings);
+ if (lease !== "not due" && lease !== "no OpenAI login here") {
+ deps.log(`${trigger}: openai lease ${lease}`);
+ }
+ }
const result = await deps.push({
settings,
roots: deps.roots,
@@ -564,6 +574,7 @@ export function defaultDeps(
},
notify: () => false,
log: (line) => appendLog(roots, line),
+ refreshLease: (settings) => maybeRefreshOpenai({ roots, settings }),
messages: ENGLISH_MESSAGES,
...overrides,
};
diff --git a/src/core/categories.ts b/src/core/categories.ts
index bcba600..24d4d75 100644
--- a/src/core/categories.ts
+++ b/src/core/categories.ts
@@ -22,7 +22,7 @@ interface CategoryPaths {
}
export const CATEGORY_PATHS: Record = {
- config: { files: ["opencode.json", "opencode.jsonc", "tui.json", "tui.jsonc"] },
+ config: { files: ["opencode.json", "opencode.jsonc", "tui.json", "tui.jsonc", "cli.json"] },
instructions: { rootExtensions: [".md"] },
agents: { dirs: ["agent", "agents"] },
commands: { dirs: ["command", "commands"] },
diff --git a/src/core/credentials.ts b/src/core/credentials.ts
new file mode 100644
index 0000000..4c06f57
--- /dev/null
+++ b/src/core/credentials.ts
@@ -0,0 +1,401 @@
+import { createHash, randomBytes } from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+import { readRows } from "./rows.js";
+import { type SqliteDatabase, hasTable, openDatabase } from "./sqlite.js";
+
+/**
+ * Keep OpenCode 2's credential table and the synced `auth.json` in step.
+ *
+ * OpenCode 1 reads `auth.json` directly, so syncing the file was enough.
+ * OpenCode 2 keeps accounts in the `credential` table of `opencode.db` and
+ * reads `auth.json` at most once — and a database created fresh by 2.x marks
+ * that import as done without running it, so on a new machine a synced
+ * `auth.json` is never read at all. This bridge copies between the two around
+ * every sync, only when credential sync is turned on:
+ *
+ * - before a push, an account chosen or a token refreshed in OpenCode reaches
+ * `auth.json` and from there the other machines;
+ * - after a pull, what other machines published reaches the database. A
+ * running OpenCode sees the change on its next request.
+ *
+ * Which side changed is decided against a fingerprint of the last value
+ * bridged per integration, kept in a machine-local file next to the database
+ * (a hash, never the secret). When both changed, a later OAuth expiry wins;
+ * otherwise the database wins before a push and the file wins after a pull.
+ *
+ * Logging out in OpenCode removes the entry from `auth.json`, as it did with
+ * OpenCode 1. An entry missing from an incoming `auth.json` never logs this
+ * machine out. Integrations OpenCode 2 manages itself (`external`) and
+ * entries it cannot represent are left alone. Nothing here prints a secret.
+ */
+
+export const BRIDGE_STATE_FILE = "opencode-sync-credentials.json";
+
+export type BridgePreference = "database" | "file";
+
+export interface BridgeResult {
+ /** Integrations whose value was written into `auth.json`. */
+ toFile: string[];
+ /** Integrations whose value was written into the database. */
+ toDatabase: string[];
+ /** Integrations removed from `auth.json` after a logout here. */
+ removed: string[];
+}
+
+type Entry = Record;
+
+interface CredentialRow {
+ id: string;
+ value: Entry;
+ active: number | null;
+}
+
+/** The method id OpenCode 2's own importer assigns. */
+function methodFor(integration: string): string {
+ if (integration === "openai") return "chatgpt-browser";
+ if (["github-copilot", "opencode", "xai"].includes(integration)) return "device";
+ return "oauth";
+}
+
+/** A legacy `auth.json` entry this bridge can carry, or undefined. */
+function bridgeable(entry: unknown): Entry | undefined {
+ if (!entry || typeof entry !== "object") return undefined;
+ const e = entry as Entry;
+ if (e.type === "oauth" && (typeof e.access === "string" || typeof e.refresh === "string")) {
+ return e;
+ }
+ if (e.type === "api" && typeof e.key === "string") return e;
+ return undefined;
+}
+
+/** OpenCode 2 value -> legacy `auth.json` entry. */
+function toLegacy(value: Entry): Entry | undefined {
+ if (value?.type === "oauth") {
+ const out: Entry = {
+ type: "oauth",
+ refresh: value.refresh,
+ access: value.access,
+ expires: typeof value.expires === "number" ? value.expires : 0,
+ };
+ if (value.metadata?.accountID) out.accountId = value.metadata.accountID;
+ if (value.metadata?.enterpriseUrl) out.enterpriseUrl = value.metadata.enterpriseUrl;
+ return out;
+ }
+ if (value?.type === "key" && typeof value.key === "string") {
+ const out: Entry = { type: "api", key: value.key };
+ if (value.metadata && Object.keys(value.metadata).length > 0) out.metadata = value.metadata;
+ return out;
+ }
+ return undefined;
+}
+
+/** Legacy entry -> OpenCode 2 value, keeping what the existing row already knew. */
+function toV2(entry: Entry, integration: string, base?: Entry): Entry {
+ if (entry.type === "oauth") {
+ const metadata: Entry = { ...(base?.type === "oauth" ? (base.metadata ?? {}) : {}) };
+ if (entry.accountId) metadata.accountID = entry.accountId;
+ if (entry.enterpriseUrl) metadata.enterpriseUrl = entry.enterpriseUrl;
+ const out: Entry = {
+ type: "oauth",
+ methodID: base?.type === "oauth" && base.methodID ? base.methodID : methodFor(integration),
+ refresh: entry.refresh ?? entry.access,
+ access: entry.access ?? entry.refresh,
+ expires: typeof entry.expires === "number" ? entry.expires : 0,
+ };
+ if (Object.keys(metadata).length > 0) out.metadata = metadata;
+ return out;
+ }
+ const out: Entry = { type: "key", key: entry.key };
+ const metadata = entry.metadata ?? (base?.type === "key" ? base.metadata : undefined);
+ if (metadata && Object.keys(metadata).length > 0) out.metadata = metadata;
+ return out;
+}
+
+function sorted(value: unknown): unknown {
+ if (Array.isArray(value)) return value.map(sorted);
+ if (value && typeof value === "object") {
+ return Object.fromEntries(
+ Object.keys(value as Entry)
+ .sort()
+ .map((k) => [k, sorted((value as Entry)[k])]),
+ );
+ }
+ return value;
+}
+
+/** Fingerprint of the parts of an entry that matter; extra fields are ignored. */
+function fingerprint(entry: Entry | undefined): string | undefined {
+ if (!entry) return undefined;
+ const core =
+ entry.type === "oauth"
+ ? {
+ type: "oauth",
+ access: entry.access ?? null,
+ refresh: entry.refresh ?? null,
+ expires: typeof entry.expires === "number" ? entry.expires : 0,
+ accountId: entry.accountId ?? null,
+ enterpriseUrl: entry.enterpriseUrl ?? null,
+ }
+ : { type: "api", key: entry.key, metadata: entry.metadata ?? null };
+ return createHash("sha256")
+ .update(JSON.stringify(sorted(core)))
+ .digest("hex")
+ .slice(0, 32);
+}
+
+function sameSecret(value: Entry, entry: Entry): boolean {
+ if (value?.type === "oauth" && entry.type === "oauth") {
+ return (
+ (typeof entry.access === "string" && value.access === entry.access) ||
+ (typeof entry.refresh === "string" && value.refresh === entry.refresh)
+ );
+ }
+ if (value?.type === "key" && entry.type === "api") return value.key === entry.key;
+ return false;
+}
+
+/** A newer token for the same OAuth account (the refresh token rotated). */
+function isRotation(value: Entry, entry: Entry): boolean {
+ if (value?.type !== "oauth" || entry.type !== "oauth") return false;
+ if (typeof entry.expires !== "number" || typeof value.expires !== "number") return false;
+ if (entry.expires <= 0 || entry.expires <= value.expires) return false;
+ const a = value.metadata?.accountID;
+ const b = entry.accountId;
+ return !a || !b || a === b;
+}
+
+function newId(now: number): string {
+ const alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+ const random = [...randomBytes(14)].map((b) => alphabet[b % alphabet.length]).join("");
+ return `cred_${now.toString(16).padStart(12, "0")}${random}`;
+}
+
+function loadRows(db: SqliteDatabase): Map {
+ const out = new Map();
+ for (const row of readRows(
+ db,
+ "SELECT id, integration_id, value, active FROM credential ORDER BY time_updated DESC",
+ )) {
+ const integration = row.integration_id == null ? "" : String(row.integration_id);
+ if (!integration) continue;
+ let value: Entry = {};
+ try {
+ value = JSON.parse(String(row.value));
+ } catch {
+ // An unreadable row is treated as foreign and never matched.
+ }
+ const list = out.get(integration) ?? [];
+ list.push({
+ id: String(row.id),
+ value,
+ active: row.active == null ? null : Number(row.active),
+ });
+ out.set(integration, list);
+ }
+ return out;
+}
+
+type Chosen = { kind: "none" } | { kind: "ambiguous" } | { kind: "row"; row: CredentialRow };
+
+/** The account OpenCode 2 uses for an integration. */
+function chosen(rows: CredentialRow[] | undefined): Chosen {
+ if (!rows || rows.length === 0) return { kind: "none" };
+ const active = rows.filter((r) => r.active === 1);
+ if (active.length === 1) return { kind: "row", row: active[0]! };
+ if (active.length === 0 && rows.length === 1) return { kind: "row", row: rows[0]! };
+ return { kind: "ambiguous" };
+}
+
+function applyToDatabase(
+ db: SqliteDatabase,
+ integration: string,
+ entry: Entry,
+ rows: CredentialRow[],
+ now: number,
+): void {
+ const current = chosen(rows);
+ let target = rows.find((r) => sameSecret(r.value, entry));
+ if (!target && current.kind === "row" && isRotation(current.row.value, entry)) {
+ target = current.row;
+ }
+ if (target) {
+ const value = toV2(entry, integration, target.value);
+ if (JSON.stringify(sorted(value)) !== JSON.stringify(sorted(target.value))) {
+ db.prepare("UPDATE credential SET value = ?, time_updated = ? WHERE id = ?").run(
+ JSON.stringify(value),
+ now,
+ target.id,
+ );
+ }
+ } else {
+ target = { id: newId(now), value: toV2(entry, integration), active: 1 };
+ db.prepare(
+ `INSERT INTO credential (id, integration_id, label, value, active, time_created, time_updated)
+ VALUES (?, ?, ?, ?, 1, ?, ?)`,
+ ).run(
+ target.id,
+ integration,
+ entry.type === "oauth" ? "OAuth" : "API key",
+ JSON.stringify(target.value),
+ now,
+ now,
+ );
+ }
+ db.prepare(
+ `UPDATE credential
+ SET active = CASE WHEN id = ? THEN 1 ELSE 0 END,
+ time_updated = CASE WHEN id = ? AND coalesce(active, 0) <> 1 THEN ? ELSE time_updated END
+ WHERE integration_id = ?`,
+ ).run(target.id, target.id, now, integration);
+ // Copies of the same account, such as OpenCode's own first-start import
+ // next to an account added later, would show up twice in the switcher.
+ for (const other of rows) {
+ if (other.id !== target.id && sameSecret(other.value, entry)) {
+ db.prepare("DELETE FROM credential WHERE id = ?").run(other.id);
+ }
+ }
+}
+
+function readJson(file: string): { ok: boolean; value?: any } {
+ if (!fs.existsSync(file)) return { ok: true, value: undefined };
+ try {
+ return { ok: true, value: JSON.parse(fs.readFileSync(file, "utf8").replace(/^\uFEFF/, "")) };
+ } catch {
+ return { ok: false };
+ }
+}
+
+function writeJsonAtomic(file: string, value: unknown): void {
+ const temp = `${file}.bridge-${process.pid}.tmp`;
+ fs.writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
+ fs.renameSync(temp, file);
+}
+
+/** True when this database belongs to OpenCode 2 (has the credential table). */
+export async function hasCredentialTable(databaseFile: string): Promise {
+ if (!fs.existsSync(databaseFile)) return false;
+ const db = await openDatabase(databaseFile, { readOnly: true });
+ try {
+ return hasTable(db, "credential");
+ } finally {
+ db.close();
+ }
+}
+
+/** Reconcile `auth.json` and the credential table of one data directory. */
+export async function bridgeCredentials(
+ dataRoot: string,
+ prefer: BridgePreference,
+ now = Date.now(),
+): Promise {
+ const result: BridgeResult = { toFile: [], toDatabase: [], removed: [] };
+ const databaseFile = path.join(dataRoot, "opencode.db");
+ if (!(await hasCredentialTable(databaseFile))) return result;
+
+ const authFile = path.join(dataRoot, "auth.json");
+ const authRead = readJson(authFile);
+ // A half-written or hand-broken auth.json must never be overwritten.
+ if (!authRead.ok) return result;
+ const auth: Entry =
+ authRead.value && typeof authRead.value === "object" && !Array.isArray(authRead.value)
+ ? authRead.value
+ : {};
+ const stateFile = path.join(dataRoot, BRIDGE_STATE_FILE);
+ const stateRead = readJson(stateFile);
+ const last: Record = { ...(stateRead.value?.fingerprints ?? {}) };
+ const before = JSON.stringify(last);
+
+ // auth.json keys may carry a trailing slash; OpenCode 2 strips it.
+ const fileKey = new Map();
+ for (const key of Object.keys(auth)) fileKey.set(key.replace(/\/+$/, ""), key);
+
+ const db = await openDatabase(databaseFile);
+ let authChanged = false;
+ try {
+ db.exec("BEGIN IMMEDIATE");
+ try {
+ const rows = loadRows(db);
+ const integrations = new Set([...fileKey.keys(), ...rows.keys()]);
+ for (const integration of [...integrations].sort()) {
+ const key = fileKey.get(integration) ?? integration;
+ const fileEntry = bridgeable(auth[key]);
+ if (auth[key] !== undefined && !fileEntry) continue;
+ const pick = chosen(rows.get(integration));
+ if (pick.kind === "ambiguous") continue;
+ const dbEntry = pick.kind === "row" ? toLegacy(pick.row.value) : undefined;
+ if (pick.kind === "row" && !dbEntry) continue;
+
+ const fa = fingerprint(fileEntry);
+ const fd = fingerprint(dbEntry);
+ const previous = last[integration];
+ if (fa === fd) {
+ if (fa) last[integration] = fa;
+ // OpenCode 2's own import leaves `active` empty; make it explicit.
+ if (pick.kind === "row" && pick.row.active !== 1 && fileEntry) {
+ applyToDatabase(db, integration, fileEntry, rows.get(integration)!, now);
+ }
+ continue;
+ }
+
+ let winner: "file" | "database";
+ if (!fd) {
+ // A logout here is the only time the database has nothing and the
+ // file still holds exactly what was bridged last.
+ if (fa === previous && pick.kind === "none") {
+ delete auth[key];
+ delete last[integration];
+ authChanged = true;
+ result.removed.push(integration);
+ continue;
+ }
+ winner = "file";
+ } else if (!fa) {
+ // Missing from an incoming file: never log this machine out.
+ if (fd === previous) continue;
+ winner = "database";
+ } else {
+ const fileMoved = fa !== previous;
+ const dbMoved = fd !== previous;
+ if (fileMoved && !dbMoved) winner = "file";
+ else if (dbMoved && !fileMoved) winner = "database";
+ else if (
+ fileEntry!.type === "oauth" &&
+ dbEntry!.type === "oauth" &&
+ fileEntry!.expires !== dbEntry!.expires &&
+ Number(fileEntry!.expires) > 0 &&
+ Number(dbEntry!.expires) > 0
+ ) {
+ winner = Number(fileEntry!.expires) > Number(dbEntry!.expires) ? "file" : "database";
+ } else {
+ winner = prefer;
+ }
+ }
+
+ if (winner === "file") {
+ applyToDatabase(db, integration, fileEntry!, rows.get(integration) ?? [], now);
+ last[integration] = fa!;
+ result.toDatabase.push(integration);
+ } else {
+ const existing = auth[key];
+ auth[key] = existing?.type === dbEntry!.type ? { ...existing, ...dbEntry } : dbEntry;
+ last[integration] = fd!;
+ authChanged = true;
+ result.toFile.push(integration);
+ }
+ }
+ db.exec("COMMIT");
+ } catch (err) {
+ db.exec("ROLLBACK");
+ throw err;
+ }
+ } finally {
+ db.close();
+ }
+
+ if (authChanged) writeJsonAtomic(authFile, auth);
+ if (JSON.stringify(last) !== before) {
+ writeJsonAtomic(stateFile, { version: 1, fingerprints: last });
+ }
+ return result;
+}
diff --git a/src/core/fsx.ts b/src/core/fsx.ts
index ae851d7..a0e724c 100644
--- a/src/core/fsx.ts
+++ b/src/core/fsx.ts
@@ -276,6 +276,8 @@ export function replaceFileAtomically(
export interface ReplaceDirOptions extends CopyOptions {
/** Files at the destination root that survive the replacement. */
preserveRootFiles?: Iterable;
+ /** Directories at the destination root that survive the replacement. */
+ preserveRootDirs?: Iterable;
}
/** Replace a whole directory atomically. */
@@ -300,6 +302,12 @@ export function replaceDirAtomically(
for (const file of options.preserveRootFiles ?? []) {
copyFileIfExists(path.join(dst, file), path.join(temp, file));
}
+ for (const dir of options.preserveRootDirs ?? []) {
+ const kept = path.join(dst, dir);
+ if (fs.existsSync(kept) && fs.statSync(kept).isDirectory()) {
+ copyDirRecursive(kept, path.join(temp, dir));
+ }
+ }
if (fs.existsSync(dst)) fs.renameSync(dst, backup);
fs.renameSync(temp, dst);
removeRecursive(backup);
diff --git a/src/core/lease.ts b/src/core/lease.ts
new file mode 100644
index 0000000..a3a5edb
--- /dev/null
+++ b/src/core/lease.ts
@@ -0,0 +1,260 @@
+import { spawn } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { bridgeCredentials, hasCredentialTable } from "./credentials.js";
+import { childEnv } from "./env.js";
+import { git } from "./git.js";
+import { hostAlias } from "./host.js";
+import { DATA_DIR, type Roots, getDatabasePath } from "./paths.js";
+import { type Settings, repoBranch } from "./settings.js";
+import { sqliteAvailable } from "./sqlite.js";
+
+/**
+ * One machine renews the shared ChatGPT (OpenAI OAuth) login, never several.
+ *
+ * With credential sync on, every machine holds the same OpenAI login. A
+ * refresh returns a new refresh token and invalidates the old one, so when two
+ * machines refresh the same login the second one is left with a dead token —
+ * machines log each other out. This lease makes exactly one machine refresh
+ * per expiry window, three days before the token would expire; the next sync
+ * carries the new token to everyone else long before they would need it.
+ *
+ * The lease is a dedicated git ref, `refs/leases/openai`, in the sync
+ * repository. Pushing it with `--force-with-lease` is an atomic
+ * compare-and-swap on the server: of two machines claiming at the same moment,
+ * one push is rejected. The claim never touches a branch or the worktree, so
+ * it cannot conflict with an ordinary sync. A claim older than the TTL is
+ * stale (its owner crashed or lost the network) and may be taken over.
+ *
+ * Runs only from the scheduled job, and only when credential sync is on and
+ * this machine has an OpenAI login with a refresh token.
+ */
+
+export const LEASE_REF = "refs/leases/openai";
+export const MARGIN_MS = 3 * 24 * 60 * 60 * 1000;
+export const LEASE_TTL_MS = 15 * 60 * 1000;
+const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
+const DEFAULT_TOKEN_URL = "https://auth.openai.com/oauth/token";
+
+export interface TokenResponse {
+ access_token: string;
+ refresh_token?: string;
+ expires_in?: number;
+}
+
+export interface LeaseDeps {
+ roots: Roots;
+ settings: Settings;
+ now?: () => number;
+ /** Exchange a refresh token; the default runs in a child process. */
+ refresh?: (refreshToken: string) => Promise;
+}
+
+type AuthMap = Record;
+
+function authFile(roots: Roots): string {
+ return path.join(roots.data, "auth.json");
+}
+
+function readAuth(roots: Roots): AuthMap | undefined {
+ try {
+ return JSON.parse(fs.readFileSync(authFile(roots), "utf8").replace(/^\uFEFF/, ""));
+ } catch {
+ return undefined;
+ }
+}
+
+/** Expiry of the OpenAI login in a credential map, or undefined when there is none to renew. */
+export function openaiExpiry(auth: AuthMap | undefined): number | undefined {
+ const entry = auth?.openai;
+ if (!entry || entry.type !== "oauth" || typeof entry.refresh !== "string") return undefined;
+ return typeof entry.expires === "number" ? entry.expires : 0;
+}
+
+/** Due when neither this machine nor the published copy is safely in date. */
+export function isDue(
+ now: number,
+ live: number | undefined,
+ published: number | undefined,
+): boolean {
+ if (live === undefined) return false;
+ return Math.max(live, published ?? 0) - now < MARGIN_MS;
+}
+
+function publishedExpiry(root: string, branch: string): number | undefined {
+ const shown = git(["show", `origin/${branch}:${DATA_DIR}/auth.json`], { cwd: root });
+ if (!shown.ok) return undefined;
+ try {
+ return openaiExpiry(JSON.parse(shown.stdout));
+ } catch {
+ return undefined;
+ }
+}
+
+interface Lease {
+ sha: string;
+ machine?: string;
+ at: number;
+}
+
+function readLease(root: string): Lease | undefined {
+ const fetched = git(["fetch", "-q", "origin", `+${LEASE_REF}:${LEASE_REF}`], {
+ cwd: root,
+ timeoutMs: 60_000,
+ });
+ if (!fetched.ok) {
+ if (/couldn't find remote ref|no such ref|not our ref/i.test(fetched.stderr)) {
+ git(["update-ref", "-d", LEASE_REF], { cwd: root });
+ return undefined;
+ }
+ throw new Error(`lease fetch failed: ${fetched.stderr.split("\n")[0]}`);
+ }
+ const sha = git(["rev-parse", LEASE_REF], { cwd: root }).stdout;
+ let body: { machine?: string; at?: number } = {};
+ try {
+ body = JSON.parse(git(["log", "-1", "--format=%B", sha], { cwd: root }).stdout);
+ } catch {
+ // An unreadable claim counts as stale.
+ }
+ return { sha, machine: body.machine, at: Number(body.at) || 0 };
+}
+
+/** Try to take the lease. True only when this machine's push won the compare-and-swap. */
+function claim(root: string, previous: Lease | undefined, machine: string, now: number): boolean {
+ const tree = git(["mktree"], { cwd: root });
+ if (!tree.ok) return false;
+ const message = JSON.stringify({ machine, at: now });
+ const commit = git(["commit-tree", tree.stdout, "-m", message], { cwd: root });
+ if (!commit.ok) return false;
+ const expect = `--force-with-lease=${LEASE_REF}:${previous ? previous.sha : ""}`;
+ return git(["push", "-q", expect, "origin", `${commit.stdout}:${LEASE_REF}`], {
+ cwd: root,
+ timeoutMs: 60_000,
+ }).ok;
+}
+
+/**
+ * Run the token request in a child Node process. Node's built-in `fetch`
+ * ignores proxy variables unless `NODE_USE_ENV_PROXY` is set at start-up, and
+ * the configured proxy must reach this request like every git call. The
+ * refresh token travels on stdin, never on a command line.
+ */
+const CHILD_SCRIPT = `
+let input = "";
+process.stdin.on("data", (c) => (input += c));
+process.stdin.on("end", async () => {
+ const { url, body } = JSON.parse(input);
+ try {
+ const r = await fetch(url, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(30000),
+ });
+ const text = await r.text();
+ process.stdout.write(JSON.stringify({ status: r.status, text }));
+ } catch (e) {
+ process.stdout.write(JSON.stringify({ error: String(e && e.message || e) }));
+ }
+});`;
+
+export function refreshInChild(refreshToken: string): Promise {
+ const url = process.env.OPENCODE_OPENAI_TOKEN_URL || DEFAULT_TOKEN_URL;
+ return new Promise((resolve, reject) => {
+ const child = spawn(process.execPath, ["-e", CHILD_SCRIPT], {
+ env: childEnv({ NODE_USE_ENV_PROXY: "1" }),
+ stdio: ["pipe", "pipe", "ignore"],
+ windowsHide: true,
+ });
+ let out = "";
+ const timer = setTimeout(() => child.kill(), 60_000);
+ child.stdout.on("data", (chunk) => {
+ out += chunk;
+ });
+ child.on("error", (err) => {
+ clearTimeout(timer);
+ reject(err);
+ });
+ child.on("close", () => {
+ clearTimeout(timer);
+ try {
+ const result = JSON.parse(out);
+ if (result.error) return reject(new Error(result.error));
+ if (result.status < 200 || result.status >= 300) {
+ return reject(new Error(`HTTP ${result.status}`));
+ }
+ const token = JSON.parse(result.text) as TokenResponse;
+ if (!token.access_token) return reject(new Error("no access_token in response"));
+ resolve(token);
+ } catch {
+ reject(new Error("no response from the token endpoint"));
+ }
+ });
+ child.stdin.end(
+ JSON.stringify({
+ url,
+ body: { grant_type: "refresh_token", refresh_token: refreshToken, client_id: CLIENT_ID },
+ }),
+ );
+ });
+}
+
+function writeOpenai(roots: Roots, fields: Record): void {
+ // Re-read right before writing so a concurrent change to other providers is kept.
+ const current = readAuth(roots) ?? {};
+ current.openai = { ...current.openai, ...fields };
+ const file = authFile(roots);
+ const temp = `${file}.lease-${process.pid}.tmp`;
+ fs.writeFileSync(temp, `${JSON.stringify(current, null, 2)}\n`, { mode: 0o600 });
+ fs.renameSync(temp, file);
+}
+
+/** Whether the lease applies to this machine at all. */
+export function leaseEnabled(settings: Settings): boolean {
+ return settings.includeCredentials && settings.openaiRefreshLease !== false;
+}
+
+/**
+ * One check. Returns a short outcome for the autosync log; never throws and
+ * never includes a token.
+ */
+export async function maybeRefreshOpenai(deps: LeaseDeps): Promise {
+ const { roots, settings } = deps;
+ if (!leaseEnabled(settings)) return "off";
+ const now = (deps.now ?? Date.now)();
+ try {
+ const v2 = (await sqliteAvailable()) && (await hasCredentialTable(getDatabasePath(roots)));
+ // On OpenCode 2 the database is the newer truth: OpenCode may have
+ // refreshed the token by itself since the last sync.
+ if (v2) await bridgeCredentials(roots.data, "database", now);
+
+ const auth = readAuth(roots);
+ const live = openaiExpiry(auth);
+ if (live === undefined) return "no OpenAI login here";
+ if (!isDue(now, live, publishedExpiry(roots.config, repoBranch(settings)))) return "not due";
+
+ const machine = hostAlias(settings.machineAlias);
+ const lease = readLease(roots.config);
+ if (lease && lease.machine !== machine && now - lease.at < LEASE_TTL_MS) {
+ return `held by ${lease.machine ?? "another machine"}`;
+ }
+ if (!claim(roots.config, lease, machine, now)) return "lost the claim to another machine";
+
+ let token: TokenResponse;
+ try {
+ token = await (deps.refresh ?? refreshInChild)(auth!.openai.refresh);
+ } catch (error) {
+ return `claimed; refresh failed (${(error as Error).message})`;
+ }
+ const expires = now + (token.expires_in ?? 864_000) * 1000;
+ writeOpenai(roots, {
+ access: token.access_token,
+ refresh: token.refresh_token ?? auth!.openai.refresh,
+ expires,
+ });
+ if (v2) await bridgeCredentials(roots.data, "file", now);
+ return `claimed; refreshed, valid until ${new Date(expires).toISOString()}`;
+ } catch (error) {
+ return `error (${String((error as Error).message).split("\n")[0]})`;
+ }
+}
diff --git a/src/core/projects.ts b/src/core/projects.ts
new file mode 100644
index 0000000..406818b
--- /dev/null
+++ b/src/core/projects.ts
@@ -0,0 +1,232 @@
+import { createHash } from "node:crypto";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { type Row, readRows } from "./rows.js";
+import type { SqliteDatabase } from "./sqlite.js";
+
+/**
+ * Where an OpenCode 2 session belongs.
+ *
+ * OpenCode 2 lists only the sessions of the project it resolves for the
+ * current directory. A session whose `project_id` this machine would resolve
+ * differently exists in the database but never shows up in `/session`. Every
+ * imported session, and every session OpenCode itself migrated from 1.x, is
+ * therefore placed the way OpenCode 2 would place it here:
+ *
+ * - the newest project whose worktree is the session directory, or the
+ * deepest git worktree that contains it;
+ * - otherwise a project created with the id OpenCode 2 derives itself
+ * (`sha1("directory:" + path)` for a plain directory);
+ * - otherwise, for a directory this machine does not have, the home
+ * directory's project, which is where `/session` is normally opened.
+ *
+ * Project ids are deterministic in OpenCode 2 (git remote, root commit or
+ * directory path), so a project row from another machine is reused as is when
+ * its worktree also exists here.
+ */
+
+export const GLOBAL_PROJECT_ID = "global";
+
+export interface Placement {
+ projectId: string;
+ directory: string;
+ path: string | null;
+ /** Parked in the home project because no project matches the directory. */
+ parked: boolean;
+}
+
+export interface PlacementInput {
+ directory: string;
+ projectId: string;
+ path: string | null;
+ /** The exporting machine's home directory, to map paths under it. */
+ originHome?: string;
+}
+
+export interface PlacementOptions {
+ /** This machine's home directory. */
+ home: string;
+ /** Create project rows OpenCode 2 would create itself. */
+ createProjects: boolean;
+ now: number;
+ /** Test seam: whether a directory exists on this machine. */
+ exists?: (dir: string) => boolean;
+}
+
+interface ProjectRow {
+ id: string;
+ worktree: string;
+ vcs: string | null;
+ time_created: number;
+}
+
+const caseInsensitive = process.platform !== "linux";
+
+/** OpenCode 2 stores Windows paths with forward slashes. */
+export function storedPath(p: string): string {
+ let out = process.platform === "win32" ? p.replace(/\\/g, "/") : p;
+ while (out.length > 1 && out.endsWith("/") && !/^[A-Za-z]:\/$/.test(out)) out = out.slice(0, -1);
+ return out;
+}
+
+function key(p: string): string {
+ const s = String(p ?? "")
+ .replace(/\\/g, "/")
+ .replace(/\/+$/, "");
+ return caseInsensitive ? s.toLowerCase() : s;
+}
+
+/** The project id OpenCode 2 gives a directory outside any repository. */
+export function directoryProjectId(directory: string): string {
+ return createHash("sha1")
+ .update(`directory:${path.resolve(directory)}`)
+ .digest("hex");
+}
+
+export function homeDir(): string {
+ return process.env.SYNC_HOME || os.homedir();
+}
+
+/** Relative path from a worktree to a directory, the way OpenCode 2 writes it. */
+export function relativePath(
+ directory: string,
+ worktree: string,
+ fallback: string | null,
+): string | null {
+ const d = key(directory);
+ const w = key(worktree);
+ if (d === w) return "";
+ if (d.startsWith(`${w}/`)) return storedPath(directory).slice(storedPath(worktree).length + 1);
+ const rel = path.relative(path.resolve(worktree), path.resolve(directory));
+ if (!rel || path.isAbsolute(rel)) return fallback;
+ return rel.replace(/\\/g, "/");
+}
+
+function insideRepository(directory: string, exists: (dir: string) => boolean): boolean {
+ let current = path.resolve(directory);
+ for (;;) {
+ if (exists(path.join(current, ".git")) || exists(path.join(current, ".hg"))) return true;
+ const parent = path.dirname(current);
+ if (parent === current) return false;
+ current = parent;
+ }
+}
+
+export class ProjectResolver {
+ private projects: ProjectRow[];
+ private readonly exists: (dir: string) => boolean;
+
+ constructor(
+ private readonly db: SqliteDatabase,
+ private readonly options: PlacementOptions,
+ ) {
+ this.exists = options.exists ?? ((dir) => fs.existsSync(dir));
+ this.projects = this.load();
+ }
+
+ private load(): ProjectRow[] {
+ return readRows(this.db, "SELECT id, worktree, vcs, time_created FROM project WHERE id <> ?", [
+ GLOBAL_PROJECT_ID,
+ ]).map((row) => ({
+ id: String(row.id),
+ worktree: String(row.worktree ?? ""),
+ vcs: row.vcs == null ? null : String(row.vcs),
+ time_created: Number(row.time_created ?? 0),
+ }));
+ }
+
+ /** The project OpenCode 2 resolves today for a directory, if it has one. */
+ resolve(directory: string): ProjectRow | undefined {
+ const d = key(directory);
+ const newest = new Map();
+ for (const p of this.projects) {
+ const k = key(p.worktree);
+ if (!k || k === "/") continue;
+ const prev = newest.get(k);
+ if (!prev || p.time_created > prev.time_created) newest.set(k, p);
+ }
+ let best: ProjectRow | undefined;
+ for (const [k, p] of newest) {
+ const match = d === k || (p.vcs && d.startsWith(`${k}/`));
+ if (match && (!best || k.length > key(best.worktree).length)) best = p;
+ }
+ return best;
+ }
+
+ /** Insert another machine's project row when its worktree exists here too. */
+ adopt(project: Row | undefined, insert: (row: Row) => void): void {
+ if (!project || String(project.id) === GLOBAL_PROJECT_ID) return;
+ const worktree = String(project.worktree ?? "");
+ if (!worktree || !this.exists(worktree)) return;
+ if (this.projects.some((p) => p.id === String(project.id))) return;
+ insert(project);
+ this.projects = this.load();
+ }
+
+ private createDirectoryProject(directory: string): ProjectRow | undefined {
+ if (!this.options.createProjects) return undefined;
+ if (!this.exists(directory) || insideRepository(directory, this.exists)) return undefined;
+ const id = directoryProjectId(directory);
+ const now = this.options.now;
+ this.db
+ .prepare(
+ `INSERT INTO project (id, worktree, vcs, sandboxes, time_created, time_updated, time_active)
+ VALUES (?, ?, NULL, '[]', ?, ?, ?) ON CONFLICT DO NOTHING`,
+ )
+ .run(id, storedPath(path.resolve(directory)), now, now, now);
+ this.projects = this.load();
+ return this.projects.find((p) => p.id === id);
+ }
+
+ private home(): ProjectRow | undefined {
+ const home = this.options.home;
+ return this.resolve(storedPath(path.resolve(home))) ?? this.createDirectoryProject(home);
+ }
+
+ /** Map a directory under the exporting machine's home onto this machine's home. */
+ private translate(directory: string, originHome: string | undefined): string {
+ if (this.exists(directory) || !originHome) return directory;
+ const from = key(originHome);
+ const d = key(directory);
+ if (!d.startsWith(`${from}/`)) return directory;
+ const rest = storedPath(directory).slice(storedPath(originHome).length + 1);
+ const candidate = path.join(this.options.home, ...rest.split("/"));
+ return this.exists(candidate) ? storedPath(candidate) : directory;
+ }
+
+ /** Where a session belongs on this machine. */
+ place(session: PlacementInput): Placement {
+ const directory = this.translate(session.directory, session.originHome);
+ const target = this.resolve(directory) ?? this.createDirectoryProject(directory);
+ if (target) {
+ const exact = key(directory) === key(target.worktree);
+ return {
+ projectId: target.id,
+ directory: exact ? target.worktree : storedPath(directory),
+ path: relativePath(directory, target.worktree, session.path),
+ parked: false,
+ };
+ }
+ const home = this.home();
+ if (!home) {
+ return {
+ projectId: session.projectId,
+ directory: session.directory,
+ path: session.path,
+ parked: false,
+ };
+ }
+ // A directory this machine does not have would reopen in a missing
+ // folder, so the session moves to the home worktree itself.
+ if (!this.exists(directory)) {
+ return { projectId: home.id, directory: home.worktree, path: "", parked: true };
+ }
+ return {
+ projectId: home.id,
+ directory: storedPath(directory),
+ path: relativePath(directory, home.worktree, session.path),
+ parked: true,
+ };
+ }
+}
diff --git a/src/core/repair.ts b/src/core/repair.ts
new file mode 100644
index 0000000..ba27152
--- /dev/null
+++ b/src/core/repair.ts
@@ -0,0 +1,127 @@
+import fs from "node:fs";
+import { GLOBAL_PROJECT_ID, ProjectResolver, homeDir } from "./projects.js";
+import { readRows } from "./rows.js";
+import { hasTable, openDatabase } from "./sqlite.js";
+
+/**
+ * Move OpenCode 2 sessions into the project OpenCode 2 resolves for them.
+ *
+ * OpenCode 2 lists only the current project's sessions. Two kinds of session
+ * end up listed nowhere after an upgrade from 1.x, although their content is
+ * intact:
+ *
+ * - OpenCode 1 put every session outside a repository in the synthetic
+ * `global` project. OpenCode 2 gives such a directory its own project, so
+ * migrated `global` sessions are invisible.
+ * - A repository can have several project rows for one worktree (a new id
+ * after its history changed). OpenCode 2 uses the newest; sessions under
+ * the older rows are invisible.
+ *
+ * Only the project, directory spelling and relative path of a session change.
+ * Sessions already in the right project are not touched. A `global` session
+ * whose directory has no project yet is parked in the home project; any other
+ * unresolved session is left alone and reported. No project rows are created:
+ * OpenCode creates them itself the first time it opens a directory.
+ */
+
+export interface RepairMove {
+ id: string;
+ from: string;
+ to: string;
+ parked: boolean;
+}
+
+export interface RepairResult {
+ /** False when the database is not an OpenCode 2 database. */
+ supported: boolean;
+ sessions: number;
+ moves: RepairMove[];
+ /** `global` sessions with no project to move to, by directory. */
+ unresolved: { directory: string; count: number }[];
+ applied: number;
+}
+
+export interface RepairOptions {
+ apply: boolean;
+ home?: string;
+}
+
+export async function repairSessions(
+ databaseFile: string,
+ options: RepairOptions,
+): Promise {
+ const result: RepairResult = {
+ supported: false,
+ sessions: 0,
+ moves: [],
+ unresolved: [],
+ applied: 0,
+ };
+ if (!fs.existsSync(databaseFile)) return result;
+
+ const db = await openDatabase(databaseFile, { readOnly: !options.apply });
+ try {
+ if (!hasTable(db, "session_v2")) return result;
+ result.supported = true;
+
+ const resolver = new ProjectResolver(db, {
+ home: options.home ?? homeDir(),
+ createProjects: false,
+ now: Date.now(),
+ });
+ const sessions = readRows(db, "SELECT id, project_id, directory, path FROM session_v2");
+ result.sessions = sessions.length;
+
+ const updates: { id: string; project: string; directory: string; path: string | null }[] = [];
+ const unresolved = new Map();
+ for (const row of sessions) {
+ const current = String(row.project_id ?? "");
+ const directory = String(row.directory ?? "");
+ const resolved = resolver.resolve(directory);
+ // Neither placed by a project here nor invisible: leave it as it is.
+ if (!resolved && current !== GLOBAL_PROJECT_ID) continue;
+ if (resolved && resolved.id === current) continue;
+
+ const placement = resolver.place({
+ directory,
+ projectId: current,
+ path: row.path == null ? null : String(row.path),
+ });
+ if (placement.projectId === current) {
+ unresolved.set(directory, (unresolved.get(directory) ?? 0) + 1);
+ continue;
+ }
+ result.moves.push({
+ id: String(row.id),
+ from: current,
+ to: placement.projectId,
+ parked: placement.parked,
+ });
+ updates.push({
+ id: String(row.id),
+ project: placement.projectId,
+ directory: placement.directory,
+ path: placement.path,
+ });
+ }
+ result.unresolved = [...unresolved].map(([directory, count]) => ({ directory, count }));
+
+ if (options.apply && updates.length > 0) {
+ const statement = db.prepare(
+ "UPDATE session_v2 SET project_id = ?, directory = ?, path = ? WHERE id = ?",
+ );
+ db.exec("BEGIN IMMEDIATE");
+ try {
+ for (const u of updates) statement.run(u.project, u.directory, u.path, u.id);
+ db.exec("COMMIT");
+ } catch (err) {
+ db.exec("ROLLBACK");
+ throw err;
+ }
+ result.applied = updates.length;
+ }
+ } finally {
+ db.close();
+ }
+ return result;
+}
diff --git a/src/core/repo.ts b/src/core/repo.ts
index 56b5005..4ffa041 100644
--- a/src/core/repo.ts
+++ b/src/core/repo.ts
@@ -43,6 +43,15 @@ ${STATE_DIR}/session.json
${STATE_DIR}/opencode-sync-autosync.json
${STATE_DIR}/opencode-sync-autosync.json.tmp
+# OpenCode 2 machine files: the background-service record (URL, pid and a
+# plaintext password, in both the config and the state directory), lock files
+# and per-machine histories
+/service.json
+${STATE_DIR}/service.json
+${STATE_DIR}/locks/
+${STATE_DIR}/prompt-history.jsonl
+${STATE_DIR}/frecency.jsonl
+
# Empty directories recreated by OpenCode at runtime
plugin/
@@ -58,13 +67,69 @@ export const DEFAULT_GITATTRIBUTES = `# Store and check out everything with LF.
# pull look like a whole-file change.
* text=auto eol=lf
-# Append-only history files merge cleanly by taking both sides
-${STATE_DIR}/prompt-history.jsonl text eol=lf merge=union
-
# Session shards are gzipped JSON — binary, and never line-merged
${SESSIONS_DIR}/*.json.gz binary
`;
+/**
+ * Files an older version could have committed that must never be tracked:
+ * machine secrets and per-machine histories. They are dropped from the index
+ * (never from disk) on every push, so upgrading cleans existing repositories.
+ */
+export const UNTRACKED_MACHINE_FILES = [
+ "service.json",
+ `${STATE_DIR}/service.json`,
+ `${STATE_DIR}/locks`,
+ `${STATE_DIR}/prompt-history.jsonl`,
+ `${STATE_DIR}/frecency.jsonl`,
+];
+
+/** Remove machine files from the index if a previous version committed them. */
+export function untrackMachineFiles(root: string): void {
+ git(
+ [
+ "rm",
+ "-r",
+ "-q",
+ "--cached",
+ "--ignore-unmatch",
+ "--",
+ ...UNTRACKED_MACHINE_FILES.map((p) => `:(top,literal)${p}`),
+ ],
+ { cwd: root },
+ );
+}
+
+/**
+ * Keep this machine's config-dir `service.json` exactly as it is across a sync.
+ *
+ * Git treats ignored files as expendable: a reset, fast-forward or rebase onto
+ * a commit that still tracks `service.json` (pushed by an older version)
+ * overwrites the local file, and replaying the commit that untracks it then
+ * deletes it. Returns the function that puts the original back, or removes
+ * another machine's copy when this machine had none.
+ */
+export function holdMachineFiles(root: string): () => void {
+ const file = path.join(root, "service.json");
+ let original: Buffer | undefined;
+ try {
+ original = fs.readFileSync(file);
+ } catch {
+ original = undefined;
+ }
+ return () => {
+ try {
+ if (original === undefined) {
+ fs.rmSync(file, { force: true });
+ } else if (!fs.existsSync(file) || !fs.readFileSync(file).equals(original)) {
+ fs.writeFileSync(file, original, { mode: 0o600 });
+ }
+ } catch {
+ // Best effort: OpenCode recreates its service record on start.
+ }
+ };
+}
+
/**
* Paths that exist inside the worktree but must stay out of every commit.
*
diff --git a/src/core/rows.ts b/src/core/rows.ts
new file mode 100644
index 0000000..3724c4b
--- /dev/null
+++ b/src/core/rows.ts
@@ -0,0 +1,102 @@
+import type { SqliteDatabase } from "./sqlite.js";
+import { tableColumns, tablePrimaryKey } from "./sqlite.js";
+
+/**
+ * Row-level helpers shared by the session exporters and importers.
+ *
+ * Shards are JSON, so binary columns (OpenCode 2 stores attachments in
+ * `blob.data`) are written as `{ "$base64": "..." }` and turned back into
+ * bytes on import.
+ */
+
+export type Row = Record;
+
+export interface TableInfo {
+ columns: Set;
+ primaryKey: string[];
+}
+
+export function readRows(db: SqliteDatabase, sql: string, params: unknown[] = []): Row[] {
+ return db.prepare(sql).all(...params) as Row[];
+}
+
+/** Cached column and key information per table for one connection. */
+export function tableInfoCache(db: SqliteDatabase): (table: string) => TableInfo {
+ const cache = new Map();
+ return (table) => {
+ let info = cache.get(table);
+ if (!info) {
+ info = { columns: new Set(tableColumns(db, table)), primaryKey: tablePrimaryKey(db, table) };
+ cache.set(table, info);
+ }
+ return info;
+ };
+}
+
+/** Make a row JSON-safe: binary values become `{ $base64 }`. */
+export function encodeRow(row: Row): Row {
+ const out: Row = {};
+ for (const [key, value] of Object.entries(row)) {
+ out[key] =
+ value instanceof Uint8Array ? { $base64: Buffer.from(value).toString("base64") } : value;
+ }
+ return out;
+}
+
+/** SQLite drivers accept null/number/string/bigint/Buffer only. */
+export function normalize(value: unknown): unknown {
+ if (value === undefined) return null;
+ if (typeof value === "boolean") return value ? 1 : 0;
+ if (value !== null && typeof value === "object" && !Buffer.isBuffer(value)) {
+ const encoded = (value as { $base64?: unknown }).$base64;
+ if (typeof encoded === "string" && Object.keys(value).length === 1) {
+ return Buffer.from(encoded, "base64");
+ }
+ return JSON.stringify(value);
+ }
+ return value;
+}
+
+/**
+ * Insert a row, or update the existing one in place.
+ *
+ * This must be a true UPSERT, never `INSERT OR REPLACE`: REPLACE deletes the
+ * conflicting row before inserting, and with foreign keys enforced (node:sqlite
+ * enables them) deleting the shared `project` row cascades through
+ * `session.project_id ON DELETE CASCADE` and silently removes every session
+ * imported before it (#2).
+ *
+ * Primary-key columns are never rewritten, so composite keys such as
+ * `todo (session_id, position)` stay intact. A row that is newer locally, by
+ * `time_updated`, is left alone. `keepExisting` turns the update into a no-op
+ * for rows that must stay machine-local once they exist.
+ */
+export function upsert(
+ db: SqliteDatabase,
+ table: string,
+ row: Row,
+ info: TableInfo,
+ keepExisting = false,
+): void {
+ const columns = Object.keys(row).filter((column) => info.columns.has(column));
+ if (columns.length === 0) return;
+ const placeholders = columns.map(() => "?").join(", ");
+ const quoted = columns.map((column) => `"${column}"`).join(", ");
+ // No conflict target: the update applies to whichever uniqueness constraint
+ // fired (primary key, composite key or a secondary UNIQUE index), matching
+ // what REPLACE used to cover. Needs SQLite 3.35+, which both drivers bundle.
+ const updates = columns.filter((column) => !info.primaryKey.includes(column));
+
+ let action = "DO NOTHING";
+ if (!keepExisting && updates.length > 0) {
+ const assignments = updates.map((column) => `"${column}" = excluded."${column}"`).join(", ");
+ const newerWins = columns.includes("time_updated")
+ ? ` WHERE "${table}"."time_updated" IS NULL OR excluded."time_updated" >= "${table}"."time_updated"`
+ : "";
+ action = `DO UPDATE SET ${assignments}${newerWins}`;
+ }
+
+ db.prepare(
+ `INSERT INTO "${table}" (${quoted}) VALUES (${placeholders}) ON CONFLICT ${action}`,
+ ).run(...columns.map((column) => normalize(row[column])));
+}
diff --git a/src/core/sessions.ts b/src/core/sessions.ts
index 7703791..d650af9 100644
--- a/src/core/sessions.ts
+++ b/src/core/sessions.ts
@@ -3,14 +3,22 @@ import path from "node:path";
import { gunzipSync, gzipSync } from "node:zlib";
import { ensureDir } from "./fsx.js";
import { SESSIONS_DIR } from "./paths.js";
+import {
+ GLOBAL_PROJECT_ID,
+ type Placement,
+ ProjectResolver,
+ homeDir,
+ storedPath,
+} from "./projects.js";
import type { Reporter } from "./reporter.js";
+import { type Row, type TableInfo, encodeRow, readRows, tableInfoCache, upsert } from "./rows.js";
import type { SessionSettings } from "./settings.js";
import {
type SqliteDatabase,
existingTables,
+ hasTable,
openDatabase,
tableColumns,
- tablePrimaryKey,
} from "./sqlite.js";
/**
@@ -37,9 +45,17 @@ import {
*
* Import is an upsert inside a transaction, so a failure leaves the local
* database exactly as it was.
+ *
+ * Two database layouts exist. OpenCode 1 keeps sessions in `session` with
+ * `message`/`part`; OpenCode 2 keeps them in `session_v2` with
+ * `session_message`/`session_part` and never writes the old tables again (a
+ * fresh OpenCode 2 database does not even have them). The layout is detected
+ * per database: `session_v2` present means OpenCode 2. Each layout has its own
+ * shard format; a machine skips shards of the other one and never deletes them
+ * while they are inside the time window, so a mixed fleet keeps working.
*/
-/** Tables whose rows belong to exactly one session. */
+/** OpenCode 1: tables whose rows belong to exactly one session. */
const SESSION_TABLES = [
"session_message",
"message",
@@ -50,15 +66,45 @@ const SESSION_TABLES = [
"session_input",
] as const;
-/** OpenCode's synthetic project for sessions outside any repository. */
-const GLOBAL_PROJECT_ID = "global";
+/**
+ * OpenCode 2: tables whose rows belong to exactly one session, in insert
+ * order. `event_sequence` (keyed by `aggregate_id`) carries the session's
+ * message counter; without it a continued conversation restarts numbering and
+ * collides with its own history.
+ *
+ * Never exported: `session_inbox` (queued input would be delivered on the
+ * receiving machine), `job` and `schedule` (they would run there), `event`
+ * and `permission`.
+ */
+const V2_TABLES = [
+ "session_message",
+ "session_part",
+ "instruction_state",
+ "instruction_entry",
+ "blob_ref",
+] as const;
+
+/**
+ * Columns describing what the session is doing right now on the machine that
+ * exported it. Copied as they are, they would make the receiving machine
+ * resume the conversation — and call a model — on its own.
+ */
+const V2_RUNTIME_COLUMNS: Record = {
+ time_busy: null,
+ time_compacting: null,
+ time_suspended: null,
+ resume_attempts: 0,
+};
/**
- * `event` and `event_sequence` are deliberately excluded. They are an internal
- * append-only runtime log, they dwarf everything else in row count, and nothing
- * about resuming a conversation on another machine depends on them.
+ * `event` and `event_sequence` are deliberately excluded from OpenCode 1
+ * shards. They are an internal append-only runtime log, they dwarf everything
+ * else in row count, and nothing about resuming a conversation on another
+ * machine depends on them.
*/
+export type SessionSchema = "v1" | "v2";
+
export interface SessionRecord {
id: string;
title: string;
@@ -77,6 +123,21 @@ export interface SessionShard {
exportedAt: number;
}
+export interface SessionShardV2 {
+ formatVersion: 2;
+ schema: "v2";
+ /** The exporting machine's home, to map paths under it onto this machine. */
+ origin: { home: string };
+ session: Row;
+ project?: Row;
+ tables: Record;
+ /** Content-addressed rows the session references. */
+ blobs: Record;
+ exportedAt: number;
+}
+
+type AnyShard = SessionShard | SessionShardV2;
+
export interface SelectOptions extends SessionSettings {
now?: number;
}
@@ -90,9 +151,19 @@ export interface ExportResult {
export interface ImportResult {
imported: number;
skippedOlder: number;
+ /** Shards written by a machine on the other OpenCode major version. */
+ skippedOtherSchema: number;
failed: { file: string; reason: string }[];
}
+export interface ImportOptions {
+ /** Where a local version replaced by an incoming one is saved. */
+ recoveryRoot?: string;
+ /** This machine's home directory. */
+ home?: string;
+ now?: number;
+}
+
function shardPath(repoRoot: string, sessionId: string): string {
return path.join(repoRoot, SESSIONS_DIR, `${sanitizeId(sessionId)}.json.gz`);
}
@@ -102,8 +173,13 @@ export function sanitizeId(id: string): string {
return id.replace(/[^A-Za-z0-9._-]/g, "_");
}
-function readRows(db: SqliteDatabase, sql: string, params: unknown[]): Record[] {
- return db.prepare(sql).all(...params) as Record[];
+/** Which layout a database uses. */
+export function sessionSchema(db: SqliteDatabase): SessionSchema {
+ return hasTable(db, "session_v2") ? "v2" : "v1";
+}
+
+function sessionTable(schema: SessionSchema): string {
+ return schema === "v2" ? "session_v2" : "session";
}
/**
@@ -120,9 +196,8 @@ export function selectSessions(db: SqliteDatabase, options: SelectOptions): Sess
const rows = readRows(
db,
`SELECT id, title, directory, time_updated, time_created, project_id
- FROM session
+ FROM ${sessionTable(sessionSchema(db))}
ORDER BY time_updated DESC`,
- [],
) as any[];
const exclude = new Set(options.exclude);
@@ -201,6 +276,90 @@ function buildShard(db: SqliteDatabase, sessionId: string, tables: string[]): Se
return shard;
}
+const HASH = /^[0-9a-f]{64}$/;
+
+/** Every instruction-blob hash a session's instruction rows refer to. */
+function instructionHashes(rows: Row[]): string[] {
+ const found = new Set();
+ const visit = (value: unknown): void => {
+ if (typeof value === "string") {
+ if (HASH.test(value)) found.add(value);
+ else if (value.startsWith("{") || value.startsWith("[")) {
+ try {
+ visit(JSON.parse(value));
+ } catch {
+ // Not JSON — nothing to follow.
+ }
+ }
+ } else if (Array.isArray(value)) {
+ for (const item of value) visit(item);
+ } else if (value && typeof value === "object") {
+ for (const item of Object.values(value)) visit(item);
+ }
+ };
+ for (const row of rows) for (const value of Object.values(row)) visit(value);
+ return [...found].sort();
+}
+
+function buildShardV2(db: SqliteDatabase, sessionId: string, tables: string[]): SessionShardV2 {
+ const raw = readRows(db, "SELECT * FROM session_v2 WHERE id = ?", [sessionId])[0];
+ if (!raw) throw new Error(`Session ${sessionId} disappeared while exporting`);
+ const session: Row = { ...raw };
+ for (const [column, value] of Object.entries(V2_RUNTIME_COLUMNS)) {
+ if (column in session) session[column] = value;
+ }
+
+ const shard: SessionShardV2 = {
+ formatVersion: 2,
+ schema: "v2",
+ origin: { home: storedPath(homeDir()) },
+ session,
+ tables: {},
+ blobs: {},
+ exportedAt: Number(raw.time_updated ?? 0),
+ };
+
+ const projectId = raw.project_id;
+ if (projectId && projectId !== GLOBAL_PROJECT_ID) {
+ const project = readRows(db, "SELECT * FROM project WHERE id = ?", [projectId])[0];
+ if (project) shard.project = project;
+ }
+
+ for (const table of tables) {
+ shard.tables[table] = readRows(
+ db,
+ `SELECT * FROM "${table}" WHERE session_id = ? ORDER BY rowid`,
+ [sessionId],
+ ).map(encodeRow);
+ }
+ if (hasTable(db, "event_sequence")) {
+ shard.tables.event_sequence = readRows(
+ db,
+ "SELECT * FROM event_sequence WHERE aggregate_id = ?",
+ [sessionId],
+ ).map((row) => ({ ...row, owner_id: null }));
+ }
+
+ const instructionRows = [
+ ...(shard.tables.instruction_state ?? []),
+ ...(shard.tables.instruction_entry ?? []),
+ ];
+ const hashes = instructionHashes(instructionRows);
+ if (hashes.length > 0 && hasTable(db, "instruction_blob")) {
+ shard.blobs.instruction_blob = hashes.flatMap((hash) =>
+ readRows(db, "SELECT * FROM instruction_blob WHERE hash = ?", [hash]),
+ );
+ }
+ const blobHashes = [...new Set((shard.tables.blob_ref ?? []).map((r) => String(r.hash)))].sort();
+ if (blobHashes.length > 0 && hasTable(db, "blob")) {
+ shard.blobs.blob = blobHashes.flatMap((hash) =>
+ readRows(db, "SELECT * FROM blob WHERE hash = ?", [hash]).map(encodeRow),
+ );
+ }
+
+ return shard;
+}
+
/** Export the selected sessions into `/_sessions`. */
export async function exportSessions(
databaseFile: string,
@@ -213,9 +372,13 @@ export async function exportSessions(
const db = await openDatabase(databaseFile, { readOnly: true });
try {
- const tables = existingTables(db, [...SESSION_TABLES]).filter((table) =>
- tableColumns(db, table).includes("session_id"),
- );
+ const schema = sessionSchema(db);
+ const tables =
+ schema === "v2"
+ ? existingTables(db, [...V2_TABLES])
+ : existingTables(db, [...SESSION_TABLES]).filter((table) =>
+ tableColumns(db, table).includes("session_id"),
+ );
const sessions = selectSessions(db, options);
result.considered = sessions.length;
@@ -225,7 +388,20 @@ export async function exportSessions(
const keep = new Set();
for (const session of sessions) {
- const shard = buildShard(db, session.id, tables);
+ const file = shardPath(repoRoot, session.id);
+ // A shard that is already at least as new as this machine's copy stays
+ // as it is. It may differ in bytes only because another machine wrote it
+ // (its home, its placement); rewriting it would make every machine
+ // re-export every session it received, and could replace a newer copy
+ // this machine skipped on import with an older one.
+ if (existingShardTime(file) >= session.timeUpdated) {
+ keep.add(path.basename(file));
+ result.written.push(session.id);
+ continue;
+ }
+
+ const shard =
+ schema === "v2" ? buildShardV2(db, session.id, tables) : buildShard(db, session.id, tables);
const payload = gzipSync(Buffer.from(JSON.stringify(shard)), { level: 9 });
if (payload.byteLength > options.maxSessionBytes) {
@@ -237,7 +413,6 @@ export async function exportSessions(
continue;
}
- const file = shardPath(repoRoot, session.id);
keep.add(path.basename(file));
// Only rewrite when the payload actually changed, otherwise every push
// would produce a diff for every session purely from the gzip timestamp.
@@ -247,7 +422,7 @@ export async function exportSessions(
result.written.push(session.id);
}
- pruneShards(outDir, keep, options, reporter);
+ pruneShards(outDir, keep, schema, options, reporter);
} finally {
db.close();
}
@@ -260,92 +435,69 @@ export async function exportSessions(
*
* A shard is removed when it is outside the retention window, so the repository
* does not accumulate every session ever synced. Shards for explicitly included
- * sessions are always kept.
+ * sessions are always kept, and so are recent shards of the other OpenCode
+ * major version: this machine cannot judge them, a machine still on that
+ * version exported them on purpose.
*/
function pruneShards(
outDir: string,
keep: Set,
+ schema: SessionSchema,
options: SelectOptions,
reporter: Reporter,
): void {
+ const cutoff = (options.now ?? Date.now()) - options.days * 24 * 60 * 60 * 1000;
let removed = 0;
const includeFiles = new Set(options.include.map((id) => `${sanitizeId(id)}.json.gz`));
for (const entry of fs.readdirSync(outDir)) {
if (!entry.endsWith(".json.gz")) continue;
if (keep.has(entry) || includeFiles.has(entry)) continue;
- fs.rmSync(path.join(outDir, entry), { force: true });
+ const full = path.join(outDir, entry);
+ const other = otherSchemaShard(full, schema);
+ if (other && Number(other.session.time_updated ?? 0) >= cutoff) continue;
+ fs.rmSync(full, { force: true });
removed++;
}
if (removed > 0)
reporter.detail(`Removed ${removed} session shard(s) outside the retention window`);
}
-function readShard(file: string): SessionShard {
- const raw = gunzipSync(fs.readFileSync(file));
- const shard = JSON.parse(raw.toString("utf8")) as SessionShard;
- if (shard.formatVersion !== 1) {
- throw new Error(`Unsupported shard format v${shard.formatVersion}`);
+/** `time_updated` of the session in an existing shard file, or -1 when there is none. */
+function existingShardTime(file: string): number {
+ if (!fs.existsSync(file)) return -1;
+ try {
+ return Number(parseShard(file).session.time_updated ?? -1);
+ } catch {
+ return -1;
}
- return shard;
}
-interface TableInfo {
- columns: Set;
- primaryKey: string[];
+function otherSchemaShard(file: string, schema: SessionSchema): AnyShard | undefined {
+ try {
+ const shard = parseShard(file);
+ return shardSchema(shard) === schema ? undefined : shard;
+ } catch {
+ return undefined;
+ }
}
-/**
- * Insert a row, or update the existing one in place.
- *
- * This must be a true UPSERT, never `INSERT OR REPLACE`: REPLACE deletes the
- * conflicting row before inserting, and with foreign keys enforced (node:sqlite
- * enables them) deleting the shared `project` row cascades through
- * `session.project_id ON DELETE CASCADE` and silently removes every session
- * imported before it (#2).
- *
- * Primary-key columns are never rewritten, so composite keys such as
- * `todo (session_id, position)` stay intact. A row that is newer locally, by
- * `time_updated`, is left alone. `keepExisting` turns the update into a no-op
- * for rows that must stay machine-local once they exist.
- */
-function upsert(
- db: SqliteDatabase,
- table: string,
- row: Record,
- info: TableInfo,
- keepExisting = false,
-): void {
- const columns = Object.keys(row).filter((column) => info.columns.has(column));
- if (columns.length === 0) return;
- const placeholders = columns.map(() => "?").join(", ");
- const quoted = columns.map((column) => `"${column}"`).join(", ");
- // No conflict target: the update applies to whichever uniqueness constraint
- // fired (primary key, composite key or a secondary UNIQUE index), matching
- // what REPLACE used to cover. Needs SQLite 3.35+, which both drivers bundle.
- const updates = columns.filter((column) => !info.primaryKey.includes(column));
-
- let action = "DO NOTHING";
- if (!keepExisting && updates.length > 0) {
- const assignments = updates.map((column) => `"${column}" = excluded."${column}"`).join(", ");
- const newerWins = columns.includes("time_updated")
- ? ` WHERE "${table}"."time_updated" IS NULL OR excluded."time_updated" >= "${table}"."time_updated"`
- : "";
- action = `DO UPDATE SET ${assignments}${newerWins}`;
- }
+function parseShard(file: string): AnyShard {
+ const raw = gunzipSync(fs.readFileSync(file));
+ return JSON.parse(raw.toString("utf8")) as AnyShard;
+}
- db.prepare(
- `INSERT INTO "${table}" (${quoted}) VALUES (${placeholders}) ON CONFLICT ${action}`,
- ).run(...columns.map((column) => normalize(row[column])));
+function shardSchema(shard: AnyShard): SessionSchema | undefined {
+ if (shard.formatVersion === 1) return "v1";
+ if (shard.formatVersion === 2 && (shard as SessionShardV2).schema === "v2") return "v2";
+ return undefined;
}
-/** SQLite drivers accept null/number/string/bigint/Buffer only. */
-function normalize(value: unknown): unknown {
- if (value === undefined) return null;
- if (typeof value === "boolean") return value ? 1 : 0;
- if (value !== null && typeof value === "object" && !Buffer.isBuffer(value)) {
- return JSON.stringify(value);
+function readShard(file: string): AnyShard {
+ const shard = parseShard(file);
+ if (!shardSchema(shard)) {
+ throw new Error(`Unsupported shard format v${(shard as any).formatVersion}`);
}
- return value;
+ return shard;
}
/** Import every shard from `/_sessions` into the local database. */
@@ -353,8 +505,9 @@ export async function importSessions(
databaseFile: string,
repoRoot: string,
reporter: Reporter,
+ options: ImportOptions = {},
): Promise {
- const result: ImportResult = { imported: 0, skippedOlder: 0, failed: [] };
+ const result: ImportResult = { imported: 0, skippedOlder: 0, skippedOtherSchema: 0, failed: [] };
const shardDir = path.join(repoRoot, SESSIONS_DIR);
if (!fs.existsSync(shardDir)) return result;
@@ -367,62 +520,59 @@ export async function importSessions(
const db = await openDatabase(databaseFile);
try {
- const infoFor = new Map();
- const columns = (table: string): TableInfo => {
- let info = infoFor.get(table);
- if (!info) {
- info = {
- columns: new Set(tableColumns(db, table)),
- primaryKey: tablePrimaryKey(db, table),
- };
- infoFor.set(table, info);
- }
- return info;
- };
+ const schema = sessionSchema(db);
+ const columns = tableInfoCache(db);
+ const table = sessionTable(schema);
const localTimes = new Map();
- for (const row of readRows(db, "SELECT id, time_updated FROM session", []) as any[]) {
+ const localBusy = new Set();
+ const busyColumn = schema === "v2" && columns(table).columns.has("time_busy");
+ for (const row of readRows(
+ db,
+ `SELECT id, time_updated${busyColumn ? ", time_busy" : ""} FROM ${table}`,
+ ) as any[]) {
localTimes.set(String(row.id), Number(row.time_updated ?? 0));
+ if (row.time_busy != null) localBusy.add(String(row.id));
}
+ const resolver =
+ schema === "v2"
+ ? new ProjectResolver(db, {
+ home: options.home ?? homeDir(),
+ createProjects: true,
+ now: options.now ?? Date.now(),
+ })
+ : undefined;
+
for (const file of files) {
const full = path.join(shardDir, file);
try {
const shard = readShard(full);
+ if (shardSchema(shard) !== schema) {
+ result.skippedOtherSchema++;
+ continue;
+ }
const sessionId = String(shard.session.id);
const incoming = Number(shard.session.time_updated ?? 0);
const local = localTimes.get(sessionId);
// Last-writer-wins at session granularity. A session that is newer
- // locally is left completely alone, so an in-progress conversation is
- // never clobbered by a stale copy from another machine.
- if (local !== undefined && local >= incoming) {
+ // locally — or running right now — is left completely alone, so an
+ // in-progress conversation is never clobbered by a stale copy.
+ if ((local !== undefined && local >= incoming) || localBusy.has(sessionId)) {
result.skippedOlder++;
continue;
}
db.exec("BEGIN IMMEDIATE");
try {
- if (shard.project) {
- // Shards written before #4 still carry the synthetic global
- // project. Create it if missing, but never overwrite this
- // machine's own row.
- const local = String(shard.project.id) === GLOBAL_PROJECT_ID;
- upsert(db, "project", shard.project, columns("project"), local);
- }
- if (shard.workspace) upsert(db, "workspace", shard.workspace, columns("workspace"));
- upsert(db, "session", shard.session, columns("session"));
-
- for (const [table, rows] of Object.entries(shard.tables)) {
- if (rows.length === 0) continue;
- let allowed: TableInfo;
- try {
- allowed = columns(table);
- } catch {
- continue; // Table does not exist in this OpenCode version.
- }
- if (allowed.columns.size === 0) continue;
- for (const row of rows) upsert(db, table, row, allowed);
+ if (schema === "v2") {
+ importShardV2(db, shard as SessionShardV2, columns, resolver!, local !== undefined, {
+ recoveryRoot: options.recoveryRoot,
+ file,
+ });
+ } else {
+ importShardV1(db, shard as SessionShard, columns);
}
db.exec("COMMIT");
result.imported++;
@@ -441,6 +591,126 @@ export async function importSessions(
return result;
}
+function importShardV1(
+ db: SqliteDatabase,
+ shard: SessionShard,
+ columns: (table: string) => TableInfo,
+): void {
+ if (shard.project) {
+ // Shards written before #4 still carry the synthetic global project.
+ // Create it if missing, but never overwrite this machine's own row.
+ const local = String(shard.project.id) === GLOBAL_PROJECT_ID;
+ upsert(db, "project", shard.project, columns("project"), local);
+ }
+ if (shard.workspace) upsert(db, "workspace", shard.workspace, columns("workspace"));
+ upsert(db, "session", shard.session, columns("session"));
+
+ for (const [table, rows] of Object.entries(shard.tables)) {
+ if (rows.length === 0) continue;
+ if (!hasTable(db, table)) continue; // Table does not exist in this OpenCode version.
+ const allowed = columns(table);
+ if (allowed.columns.size === 0) continue;
+ for (const row of rows) upsert(db, table, row, allowed);
+ }
+}
+
+/** Child rows of one session, in an order that satisfies the foreign keys. */
+function v2ChildTables(db: SqliteDatabase): string[] {
+ return existingTables(db, [...V2_TABLES]);
+}
+
+function deleteV2Children(db: SqliteDatabase, sessionId: string): void {
+ // session_part cascades from session_message; the rest are deleted directly.
+ for (const table of [...v2ChildTables(db)].reverse()) {
+ db.prepare(`DELETE FROM "${table}" WHERE session_id = ?`).run(sessionId);
+ }
+ if (hasTable(db, "event_sequence")) {
+ db.prepare("DELETE FROM event_sequence WHERE aggregate_id = ?").run(sessionId);
+ }
+}
+
+/**
+ * Save the local copy of a session that an incoming one is about to replace,
+ * when the local copy has messages the incoming one lacks — the conversation
+ * was continued on both machines. Nothing is lost, the newer copy still wins.
+ */
+function saveDivergedLocal(
+ db: SqliteDatabase,
+ shard: SessionShardV2,
+ recoveryRoot: string | undefined,
+ file: string,
+): void {
+ if (!recoveryRoot) return;
+ const sessionId = String(shard.session.id);
+ const incoming = new Set((shard.tables.session_message ?? []).map((r) => String(r.id)));
+ const localIds = readRows(db, "SELECT id FROM session_message WHERE session_id = ?", [
+ sessionId,
+ ]).map((r) => String(r.id));
+ if (localIds.every((id) => incoming.has(id))) return;
+ const local = buildShardV2(db, sessionId, v2ChildTables(db));
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-").replace("Z", "");
+ const dir = path.join(recoveryRoot, `${stamp}-session-conflict`);
+ ensureDir(dir);
+ fs.writeFileSync(path.join(dir, file), gzipSync(Buffer.from(JSON.stringify(local))));
+}
+
+function importShardV2(
+ db: SqliteDatabase,
+ shard: SessionShardV2,
+ columns: (table: string) => TableInfo,
+ resolver: ProjectResolver,
+ existsLocally: boolean,
+ context: { recoveryRoot?: string; file: string },
+): void {
+ const sessionId = String(shard.session.id);
+
+ resolver.adopt(shard.project, (row) =>
+ upsert(db, "project", { ...row, time_archived: null }, columns("project"), true),
+ );
+ const placement: Placement = resolver.place({
+ directory: String(shard.session.directory ?? ""),
+ projectId: String(shard.session.project_id ?? ""),
+ path: shard.session.path == null ? null : String(shard.session.path),
+ originHome: shard.origin?.home,
+ });
+ // `place` may have created a project row.
+ if (!hasRow(db, "project", placement.projectId)) {
+ throw new Error(`no project for ${String(shard.session.directory)} on this machine`);
+ }
+
+ if (existsLocally) {
+ saveDivergedLocal(db, shard, context.recoveryRoot, context.file);
+ deleteV2Children(db, sessionId);
+ }
+
+ const session: Row = {
+ ...shard.session,
+ project_id: placement.projectId,
+ directory: placement.directory,
+ path: placement.path,
+ // Workspaces describe this machine's remote environments; a foreign id
+ // would point at nothing here.
+ workspace_id: null,
+ };
+ upsert(db, "session_v2", session, columns("session_v2"));
+
+ for (const [table, rows] of Object.entries(shard.blobs ?? {})) {
+ if (rows.length === 0 || !hasTable(db, table)) continue;
+ // Content-addressed: an existing row with the same hash is identical.
+ for (const row of rows) upsert(db, table, row, columns(table), true);
+ }
+ for (const table of [...v2ChildTables(db), "event_sequence"]) {
+ const rows = shard.tables[table] ?? [];
+ if (rows.length === 0 || !hasTable(db, table)) continue;
+ const info = columns(table);
+ for (const row of rows) upsert(db, table, row, info);
+ }
+}
+
+function hasRow(db: SqliteDatabase, table: string, id: string): boolean {
+ return readRows(db, `SELECT 1 AS x FROM "${table}" WHERE id = ?`, [id]).length > 0;
+}
+
/** List sessions available locally, newest first — powers `sessions list`. */
export async function listSessions(databaseFile: string, limit: number): Promise {
if (!fs.existsSync(databaseFile)) return [];
@@ -449,7 +719,7 @@ export async function listSessions(databaseFile: string, limit: number): Promise
const rows = readRows(
db,
`SELECT id, title, directory, time_updated, time_created, project_id
- FROM session ORDER BY time_updated DESC LIMIT ?`,
+ FROM ${sessionTable(sessionSchema(db))} ORDER BY time_updated DESC LIMIT ?`,
[limit],
) as any[];
return rows.map((row) => ({
diff --git a/src/core/settings.ts b/src/core/settings.ts
index c41869c..426f5a7 100644
--- a/src/core/settings.ts
+++ b/src/core/settings.ts
@@ -85,6 +85,12 @@ export interface Settings {
machineAlias?: string;
/** Sync `auth.json` / `account.json`. Requires a private repository. */
includeCredentials: boolean;
+ /**
+ * With credential sync on, let only one machine at a time renew the shared
+ * ChatGPT (OpenAI OAuth) login, from the scheduled job. Without it machines
+ * that refresh the same login log each other out.
+ */
+ openaiRefreshLease: boolean;
/** Sync `~/.agents/skills`. */
includeSkills: boolean;
/** Sync `~/.local/state/opencode`. */
@@ -113,6 +119,7 @@ export const DEFAULT_SKIP_DIRS = ["node_modules", ".venv", "venv", "__pycache__"
export const DEFAULT_SETTINGS: Settings = {
repo: { branch: "main" },
includeCredentials: false,
+ openaiRefreshLease: true,
includeSkills: true,
includeState: true,
extraPaths: [],
diff --git a/src/core/sqlite.ts b/src/core/sqlite.ts
index 948df31..c9fb853 100644
--- a/src/core/sqlite.ts
+++ b/src/core/sqlite.ts
@@ -98,10 +98,22 @@ export async function sqliteAvailable(): Promise {
return (await detectDriver()) !== "none";
}
+/**
+ * OpenCode 2 keeps a background service attached to the database, so a write
+ * can briefly find it locked. Waiting is always better than failing a sync.
+ */
+const BUSY_TIMEOUT_MS = 10_000;
+
export async function openDatabase(
file: string,
options: OpenOptions = {},
): Promise {
+ const db = await openRaw(file, options);
+ db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
+ return db;
+}
+
+async function openRaw(file: string, options: OpenOptions): Promise {
const driver = await detectDriver();
if (driver === "bun") {
@@ -139,6 +151,11 @@ export async function openDatabase(
throw new SqliteUnavailableError();
}
+/** True when the database has the given table. */
+export function hasTable(db: SqliteDatabase, name: string): boolean {
+ return existingTables(db, [name]).length > 0;
+}
+
/** Which of the given tables actually exist in this database. */
export function existingTables(db: SqliteDatabase, candidates: string[]): string[] {
const rows = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all() as {
diff --git a/src/core/stage.ts b/src/core/stage.ts
index 4beff05..4c25f15 100644
--- a/src/core/stage.ts
+++ b/src/core/stage.ts
@@ -49,13 +49,20 @@ const DATA_FILES = ["sync-state.json"];
const DATA_PATHS = ["storage/project", "storage/migration"];
/**
* State files that describe this machine, not its configuration: the current
- * UI session and the autosync scheduler's own bookkeeping.
+ * UI session, the autosync scheduler's own bookkeeping, and OpenCode 2's
+ * background-service record (`service.json` holds its URL, pid and a
+ * plaintext password) plus its per-machine prompt and file histories.
*/
export const MACHINE_STATE_FILES = new Set([
"session.json",
"opencode-sync-autosync.json",
"opencode-sync-autosync.json.tmp",
+ "service.json",
+ "prompt-history.jsonl",
+ "frecency.jsonl",
]);
+/** State directories that only hold this machine's lock files. */
+export const MACHINE_STATE_DIRS = new Set(["locks"]);
const SKILL_LOCK = ".skill-lock.json";
@@ -105,7 +112,10 @@ export function stageIn(ctx: StageContext): void {
if (settings.includeState) {
if (fs.existsSync(roots.state)) {
removeRecursive(repoState);
- copyDirRecursive(roots.state, repoState, { excludeFiles: MACHINE_STATE_FILES });
+ copyDirRecursive(roots.state, repoState, {
+ excludeFiles: MACHINE_STATE_FILES,
+ excludeDirs: MACHINE_STATE_DIRS,
+ });
} else {
removeRecursive(repoState);
}
@@ -194,6 +204,43 @@ function stageConfigIn(ctx: StageContext): void {
if (normalizeConfigForRepo(ctx)) {
ctx.reporter.detail("Removed per-machine overrides from the committed config");
}
+ if (normalizeCliJson(ctx.roots.config)) {
+ ctx.reporter.detail("Removed this machine's plugin paths from cli.json");
+ }
+}
+
+/**
+ * OpenCode 2 keeps its interface preferences in `cli.json`. Upgrading from
+ * 1.x writes `plugins: ["file:////.config/opencode/plugins/..."]` into
+ * it: absolute paths into this machine's profile that point nowhere on
+ * another one. Plugins in that global folder are discovered without the
+ * entry, so those entries are dropped; everything else is shared as is.
+ * Returns true when the file was changed.
+ */
+export function normalizeCliJson(configRoot: string): boolean {
+ const file = path.join(configRoot, "cli.json");
+ let config: any;
+ try {
+ config = parseJsonc(fs.readFileSync(file, "utf8"));
+ } catch {
+ return false;
+ }
+ if (!config || !Array.isArray(config.plugins)) return false;
+ const local = (spec: unknown): boolean => {
+ if (typeof spec !== "string" || !/^file:\/\//i.test(spec)) return false;
+ let decoded = spec;
+ try {
+ decoded = decodeURIComponent(spec);
+ } catch {
+ // Keep the raw text.
+ }
+ return /\/\.config\/opencode\/plugins?\//i.test(decoded.replace(/\\/g, "/"));
+ };
+ const kept = config.plugins.filter((spec: unknown) => !local(spec));
+ if (kept.length === config.plugins.length) return false;
+ if (kept.length > 0) config.plugins = kept;
+ else delete config.plugins;
+ return writeIfDiffers(file, `${JSON.stringify(config, null, 2)}\n`);
}
function extraPathEntries(ctx: StageContext): { entry: string; source: string; repo: string }[] {
@@ -256,7 +303,14 @@ export function stageOut(ctx: StageContext): void {
}
if (settings.includeState && fs.existsSync(repoState)) {
- replaceDirAtomically(repoState, roots.state, { preserveRootFiles: MACHINE_STATE_FILES });
+ // A repository written by an older version may still carry these files.
+ // They are never copied in; this machine's own copies survive.
+ replaceDirAtomically(repoState, roots.state, {
+ excludeFiles: MACHINE_STATE_FILES,
+ excludeDirs: MACHINE_STATE_DIRS,
+ preserveRootFiles: MACHINE_STATE_FILES,
+ preserveRootDirs: MACHINE_STATE_DIRS,
+ });
}
if (settings.includeSkills && fs.existsSync(repoAgents)) {
diff --git a/src/core/sync.ts b/src/core/sync.ts
index 5fdf986..a9b4e51 100644
--- a/src/core/sync.ts
+++ b/src/core/sync.ts
@@ -9,6 +9,7 @@ import {
restoreDisabled,
snapshotDisabled,
} from "./categories.js";
+import { type BridgePreference, bridgeCredentials } from "./credentials.js";
import {
type GitResult,
git,
@@ -22,7 +23,7 @@ import { type GuardReport, LargeChangeError, evaluateGuard, writeLocalExcludes }
import { commitMessage, hostAlias } from "./host.js";
import { applyOverrides, configMatchesRepo, findConfigFile } from "./overrides.js";
import { type Roots, getDatabasePath, getRoots } from "./paths.js";
-import { saveToRecovery } from "./recovery.js";
+import { recoveryRoot, saveToRecovery } from "./recovery.js";
import {
LOCAL_RUNTIME_PATHS,
type RepoState,
@@ -31,9 +32,11 @@ import {
ensureRepo,
excludePathspecs,
headCommit,
+ holdMachineFiles,
isLocalRuntimePath,
readStageOutMark,
unstageLocalRuntimePaths,
+ untrackMachineFiles,
writeRepoMetadata,
writeStageOutMark,
} from "./repo.js";
@@ -168,26 +171,28 @@ export async function push(options: SyncOptions = {}): Promise {
if (!fs.existsSync(root)) throw new SyncError(`Config directory not found: ${root}`);
- const state = adoptRepo(ctx, options.adopt ?? "remote", "first-push");
- if (state === "adopted" && (options.adopt ?? "remote") === "remote" && !ctx.dryRun) {
- // The remote's files are now in the worktree, but the untracked trees
- // (skills, state, extra paths) still hold this machine's old contents.
- // Write the remote's versions out first; staging the stale trees in would
- // otherwise publish every skill this machine lacks as a deletion.
- stageOut(createStageContext(root, ctx.settings, reporter, false, ctx.roots));
- writeStageOutMark(root);
- }
- assertRemoteReachable(root, branch, "Push", true);
- writeRepoMetadata(root);
- writeLocalExcludes(root, ctx.settings.guard?.skipDirs ?? []);
-
+ const restoreMachineFiles = holdMachineFiles(root);
try {
+ const state = adoptRepo(ctx, options.adopt ?? "remote", "first-push");
+ if (state === "adopted" && (options.adopt ?? "remote") === "remote" && !ctx.dryRun) {
+ // The remote's files are now in the worktree, but the untracked trees
+ // (skills, state, extra paths) still hold this machine's old contents.
+ // Write the remote's versions out first; staging the stale trees in would
+ // otherwise publish every skill this machine lacks as a deletion.
+ stageOut(createStageContext(root, ctx.settings, reporter, false, ctx.roots));
+ writeStageOutMark(root);
+ }
+ assertRemoteReachable(root, branch, "Push", true);
+ writeRepoMetadata(root);
+ writeLocalExcludes(root, ctx.settings.guard?.skipDirs ?? []);
+
return await runPush(ctx);
} finally {
// Staging rewrites the on-disk config into its shareable form. Whatever
// happens next — success, conflict, network failure — this machine must be
// left with its own effective configuration, not the stripped one.
applyOverrides(ctx.roots.config);
+ restoreMachineFiles();
}
}
@@ -207,12 +212,14 @@ async function runPush(ctx: Context): Promise {
}
reporter.step("Staging local files");
+ await bridge(ctx, "database");
stageIn(createStageContext(root, ctx.settings, reporter, ctx.force, ctx.roots));
const sessions = await maybeExportSessions(ctx);
git(["add", "-A"], { cwd: root });
unstageLocalRuntimePaths(root);
+ untrackMachineFiles(root);
unstageDisabled(ctx);
const staged = git(["diff", "--cached", "--name-status"], { cwd: root });
@@ -343,6 +350,7 @@ async function finishPush(ctx: Context, integrated: boolean): Promise {
if (integrated) {
ctx.reporter.step("Writing out changes from other machines");
stageOut(createStageContext(ctx.root, ctx.settings, ctx.reporter, false, ctx.roots));
+ await bridge(ctx, "file");
await maybeImportSessions(ctx);
}
writeStageOutMark(ctx.root);
@@ -472,9 +480,17 @@ function setAsideDisabled(ctx: Context): CategorySnapshot | null {
export async function pull(options: SyncOptions = {}): Promise {
const ctx = prepare(options);
- const { root, branch, reporter, force } = ctx;
+ fs.mkdirSync(ctx.root, { recursive: true });
+ const restoreMachineFiles = holdMachineFiles(ctx.root);
+ try {
+ return await runPull(ctx);
+ } finally {
+ restoreMachineFiles();
+ }
+}
- fs.mkdirSync(root, { recursive: true });
+async function runPull(ctx: Context): Promise {
+ const { root, branch, reporter, force } = ctx;
if (!isGitRepo(root)) {
const state = adoptRepo(ctx, "remote", "first-pull");
@@ -488,6 +504,7 @@ export async function pull(options: SyncOptions = {}): Promise {
);
}
stageOut(createStageContext(root, ctx.settings, reporter, force, ctx.roots));
+ await bridge(ctx, "file");
const sessions = await maybeImportSessions(ctx);
const count = git(["ls-files"], { cwd: root }).stdout.split("\n").filter(Boolean).length;
finishPull(ctx);
@@ -529,6 +546,7 @@ export async function pull(options: SyncOptions = {}): Promise {
if (!ctx.dryRun && mark && head && mark !== head) {
reporter.step("Writing out changes from an earlier sync");
stageOut(createStageContext(root, ctx.settings, reporter, false, ctx.roots));
+ await bridge(ctx, "file");
const sessions = await maybeImportSessions(ctx);
finishPull(ctx);
return done(
@@ -584,6 +602,7 @@ export async function pull(options: SyncOptions = {}): Promise {
}
stageOut(createStageContext(root, ctx.settings, reporter, force, ctx.roots));
+ await bridge(ctx, "file");
const sessions = await maybeImportSessions(ctx);
finishPull(ctx);
@@ -681,6 +700,32 @@ function restoreStash(ctx: Context): void {
);
}
+// ── Credentials ─────────────────────────────────────────────────────────────
+
+/**
+ * Reconcile `auth.json` with OpenCode 2's credential table (no-op on
+ * OpenCode 1 and when credential sync is off). A failure is reported and the
+ * sync carries on: the file sync itself must never depend on it.
+ */
+async function bridge(ctx: Context, prefer: BridgePreference): Promise {
+ if (!ctx.settings.includeCredentials || ctx.dryRun) return;
+ if (!(await sqliteAvailable())) return;
+ try {
+ const result = await bridgeCredentials(ctx.roots.data, prefer);
+ if (result.toFile.length > 0) {
+ ctx.reporter.detail(`Accounts from OpenCode recorded: ${result.toFile.join(", ")}`);
+ }
+ if (result.toDatabase.length > 0) {
+ ctx.reporter.detail(`Accounts applied to OpenCode: ${result.toDatabase.join(", ")}`);
+ }
+ if (result.removed.length > 0) {
+ ctx.reporter.detail(`Logged-out accounts removed: ${result.removed.join(", ")}`);
+ }
+ } catch (error) {
+ ctx.reporter.warn(`Could not bridge credentials: ${(error as Error).message}`);
+ }
+}
+
// ── Sessions ────────────────────────────────────────────────────────────────
async function maybeExportSessions(ctx: Context): Promise {
@@ -716,10 +761,17 @@ async function maybeImportSessions(ctx: Context): Promise 0) {
+ ctx.reporter.detail(
+ `Left ${result.skippedOtherSchema} session(s) from machines on another OpenCode major version`,
+ );
+ }
if (result.imported > 0) ctx.reporter.detail(`Imported ${result.imported} session(s)`);
return { imported: result.imported, skipped: result.skippedOlder };
}
diff --git a/src/plugin/index.ts b/src/plugin/index.ts
index c0cce3b..a88116a 100644
--- a/src/plugin/index.ts
+++ b/src/plugin/index.ts
@@ -130,7 +130,7 @@ async function runPullV2(announce: boolean): Promise {
if (result.changed) {
notice(
"info",
- `Config updated from GitHub (${result.files.length} file(s)). Restart OpenCode to apply.`,
+ `Config updated from GitHub (${result.files.length} file(s)). OpenCode reloads it by itself; restart only if a plugin changed.`,
);
} else if (announce) {
notice("info", "Config already up to date.");
@@ -217,7 +217,9 @@ async function executeSyncAction(args: { action?: string }): Promise {
);
}
if (result.restartRequired && result.changed) {
- lines.push("Restart OpenCode for the new configuration to take effect.");
+ lines.push(
+ "OpenCode 2 picks up the new configuration by itself. Restart OpenCode 1, or after a plugin changed.",
+ );
}
if (reporter.lines.length > 0) {
lines.push(...reporter.lines.filter((l) => l.level === "warn").map((l) => `! ${l.message}`));
diff --git a/tests/autosync.test.ts b/tests/autosync.test.ts
index 2034e79..1b99dd7 100644
--- a/tests/autosync.test.ts
+++ b/tests/autosync.test.ts
@@ -128,6 +128,26 @@ describe("autosync gate", () => {
expect(readState(roots).lastSuccessAt).toBe(T0);
});
+ it("renews the shared OpenAI login before the push, only with credential sync on", async () => {
+ const h = harness({
+ refreshLease: async () => {
+ h.calls.push("lease");
+ return "claimed; refreshed, valid until 2033-01-01T00:00:00.000Z";
+ },
+ });
+ await runAutosync(h.deps);
+ expect(h.calls).not.toContain("lease");
+
+ h.settings.includeCredentials = true;
+ h.clock.now += 10 * MIN;
+ await runAutosync(h.deps);
+ expect(h.calls.filter((c) => c === "lease" || c === "push").slice(-2)).toEqual([
+ "lease",
+ "push",
+ ]);
+ expect(h.logs.some((l) => l.includes("openai lease claimed"))).toBe(true);
+ });
+
it("respects the interval since the last attempt", async () => {
const h = harness();
writeState(roots, { lastAttemptAt: T0 - 2 * MIN });
diff --git a/tests/credentials.test.ts b/tests/credentials.test.ts
new file mode 100644
index 0000000..787290b
--- /dev/null
+++ b/tests/credentials.test.ts
@@ -0,0 +1,289 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { BRIDGE_STATE_FILE, bridgeCredentials } from "../src/core/credentials.js";
+import { type SqliteDatabase, openDatabase, sqliteAvailable } from "../src/core/sqlite.js";
+
+/**
+ * auth.json <-> OpenCode 2 credential table. Every token here is fake.
+ */
+
+const SCHEMA = fs.readFileSync(path.join(__dirname, "fixtures", "opencode-2.2.5.sql"), "utf8");
+
+let data: string;
+let available = false;
+
+beforeEach(async () => {
+ data = fs.mkdtempSync(path.join(os.tmpdir(), "ogs-cred-"));
+ available = await sqliteAvailable();
+ if (!available) return;
+ const db = await openDatabase(path.join(data, "opencode.db"));
+ db.exec(SCHEMA);
+ db.close();
+});
+
+afterEach(() => {
+ fs.rmSync(data, { recursive: true, force: true });
+});
+
+const authFile = (): string => path.join(data, "auth.json");
+const writeAuth = (value: unknown): void =>
+ fs.writeFileSync(authFile(), `${JSON.stringify(value, null, 2)}\n`);
+const readAuth = (): any => JSON.parse(fs.readFileSync(authFile(), "utf8"));
+
+async function withDb(fn: (db: SqliteDatabase) => T): Promise {
+ const db = await openDatabase(path.join(data, "opencode.db"));
+ try {
+ return fn(db);
+ } finally {
+ db.close();
+ }
+}
+
+async function rows(integration: string): Promise {
+ return withDb((db) =>
+ (
+ db
+ .prepare(
+ "SELECT id, label, value, active FROM credential WHERE integration_id = ? ORDER BY id",
+ )
+ .all(integration) as any[]
+ ).map((r) => ({ ...r, value: JSON.parse(r.value) })),
+ );
+}
+
+async function insert(id: string, integration: string, value: unknown, active: number | null) {
+ await withDb((db) =>
+ db
+ .prepare(
+ `INSERT INTO credential (id, integration_id, label, value, active, time_created, time_updated)
+ VALUES (?, ?, ?, ?, ?, 1, 1)`,
+ )
+ .run(id, integration, id, JSON.stringify(value), active),
+ );
+}
+
+const copilot = (token: string) => ({
+ type: "oauth",
+ access: token,
+ refresh: token,
+ expires: 0,
+});
+const openai = (n: number, expires: number) => ({
+ type: "oauth",
+ access: `FAKE_ACCESS_${n}`,
+ refresh: `FAKE_REFRESH_${n}`,
+ expires,
+ accountId: "acct_fake",
+});
+
+describe("credential bridge", () => {
+ it("brings a synced auth.json into a fresh OpenCode 2 database", async () => {
+ if (!available) return;
+ writeAuth({
+ "github-copilot": copilot("gho_FAKE_ONE"),
+ openai: openai(1, 2_000_000_000_000),
+ openlux: { type: "api", key: "sk-FAKE" },
+ });
+
+ const result = await bridgeCredentials(data, "file");
+ expect(result.toDatabase.sort()).toEqual(["github-copilot", "openai", "openlux"]);
+
+ const [cp] = await rows("github-copilot");
+ expect(cp.active).toBe(1);
+ expect(cp.value).toMatchObject({ type: "oauth", methodID: "device", access: "gho_FAKE_ONE" });
+ const [oa] = await rows("openai");
+ expect(oa.value).toMatchObject({
+ methodID: "chatgpt-browser",
+ refresh: "FAKE_REFRESH_1",
+ metadata: { accountID: "acct_fake" },
+ });
+ const [key] = await rows("openlux");
+ expect(key.value).toEqual({ type: "key", key: "sk-FAKE" });
+
+ const state = fs.readFileSync(path.join(data, BRIDGE_STATE_FILE), "utf8");
+ expect(state).not.toMatch(/FAKE/);
+
+ // Nothing changed since: a second run is a no-op on both sides.
+ const again = await bridgeCredentials(data, "file");
+ expect(again).toEqual({ toFile: [], toDatabase: [], removed: [] });
+ });
+
+ it("records an account switched in OpenCode before a push", async () => {
+ if (!available) return;
+ writeAuth({ "github-copilot": copilot("gho_FAKE_ONE") });
+ await bridgeCredentials(data, "file");
+ await insert(
+ "cred_two",
+ "github-copilot",
+ { ...copilot("gho_FAKE_TWO"), methodID: "device" },
+ 0,
+ );
+ await withDb((db) =>
+ db
+ .prepare(
+ "UPDATE credential SET active = CASE WHEN id = 'cred_two' THEN 1 ELSE 0 END WHERE integration_id = 'github-copilot'",
+ )
+ .run(),
+ );
+
+ const result = await bridgeCredentials(data, "database");
+ expect(result.toFile).toEqual(["github-copilot"]);
+ expect(readAuth()["github-copilot"].access).toBe("gho_FAKE_TWO");
+ });
+
+ it("switches to the account another machine chose, without duplicating it", async () => {
+ if (!available) return;
+ await insert(
+ "cred_one",
+ "github-copilot",
+ { ...copilot("gho_FAKE_ONE"), methodID: "device" },
+ 1,
+ );
+ await insert(
+ "cred_two",
+ "github-copilot",
+ { ...copilot("gho_FAKE_TWO"), methodID: "device" },
+ 0,
+ );
+ writeAuth({ "github-copilot": copilot("gho_FAKE_ONE") });
+ await bridgeCredentials(data, "file");
+
+ writeAuth({ "github-copilot": copilot("gho_FAKE_TWO") });
+ const result = await bridgeCredentials(data, "file");
+ expect(result.toDatabase).toEqual(["github-copilot"]);
+
+ const list = await rows("github-copilot");
+ expect(list).toHaveLength(2);
+ expect(list.find((r) => r.id === "cred_two").active).toBe(1);
+ expect(list.find((r) => r.id === "cred_one").active).toBe(0);
+ });
+
+ it("updates a rotated OpenAI token in place and keeps the newer expiry on conflict", async () => {
+ if (!available) return;
+ writeAuth({ openai: openai(1, 1_000) });
+ await bridgeCredentials(data, "file");
+
+ // Another machine refreshed: new tokens, later expiry.
+ writeAuth({ openai: openai(2, 5_000) });
+ await bridgeCredentials(data, "file");
+ let list = await rows("openai");
+ expect(list).toHaveLength(1);
+ expect(list[0].value.refresh).toBe("FAKE_REFRESH_2");
+
+ // Both sides moved; the database holds the later expiry and must win
+ // even though this is a pull.
+ await withDb((db) =>
+ db.prepare("UPDATE credential SET value = ? WHERE integration_id = 'openai'").run(
+ JSON.stringify({
+ type: "oauth",
+ methodID: "chatgpt-browser",
+ access: "FAKE_ACCESS_3",
+ refresh: "FAKE_REFRESH_3",
+ expires: 9_000,
+ metadata: { accountID: "acct_fake" },
+ }),
+ ),
+ );
+ writeAuth({ openai: openai(4, 7_000) });
+ const result = await bridgeCredentials(data, "file");
+ expect(result.toFile).toEqual(["openai"]);
+ expect(readAuth().openai.refresh).toBe("FAKE_REFRESH_3");
+ list = await rows("openai");
+ expect(list).toHaveLength(1);
+ });
+
+ it("never logs this machine out when an entry is missing from an incoming file", async () => {
+ if (!available) return;
+ writeAuth({ openlux: { type: "api", key: "sk-FAKE" } });
+ await bridgeCredentials(data, "file");
+
+ writeAuth({});
+ await bridgeCredentials(data, "file");
+ expect(await rows("openlux")).toHaveLength(1);
+ });
+
+ it("removes an account from auth.json after a logout in OpenCode", async () => {
+ if (!available) return;
+ writeAuth({ openlux: { type: "api", key: "sk-FAKE" }, other: { type: "api", key: "sk-KEEP" } });
+ await bridgeCredentials(data, "file");
+ await withDb((db) =>
+ db.prepare("DELETE FROM credential WHERE integration_id = 'openlux'").run(),
+ );
+
+ const result = await bridgeCredentials(data, "database");
+ expect(result.removed).toEqual(["openlux"]);
+ expect(readAuth()).toEqual({ other: { type: "api", key: "sk-KEEP" } });
+ });
+
+ it("activates OpenCode's own first-start import and leaves an ambiguous pair alone", async () => {
+ if (!available) return;
+ await insert(
+ "cred_a",
+ "openai",
+ {
+ type: "oauth",
+ methodID: "chatgpt-browser",
+ access: "FAKE_ACCESS_1",
+ refresh: "FAKE_REFRESH_1",
+ expires: 1_000,
+ },
+ null,
+ );
+ await insert(
+ "cred_b",
+ "openai",
+ {
+ type: "oauth",
+ methodID: "chatgpt-browser",
+ access: "FAKE_ACCESS_1",
+ refresh: "FAKE_REFRESH_1",
+ expires: 1_000,
+ },
+ null,
+ );
+ writeAuth({
+ openai: { type: "oauth", access: "FAKE_ACCESS_1", refresh: "FAKE_REFRESH_1", expires: 1_000 },
+ });
+
+ await bridgeCredentials(data, "file");
+ // Two rows and no active one: OpenCode would not know which to use.
+ // The bridge leaves that case alone rather than guess.
+ expect(await rows("openai")).toHaveLength(2);
+
+ await withDb((db) => db.prepare("DELETE FROM credential WHERE id = 'cred_b'").run());
+ await bridgeCredentials(data, "file");
+ const list = await rows("openai");
+ expect(list).toHaveLength(1);
+ expect(list[0].active).toBe(1);
+ });
+
+ it("leaves a broken auth.json untouched", async () => {
+ if (!available) return;
+ fs.writeFileSync(authFile(), "{ not json");
+ await insert("cred_one", "openlux", { type: "key", key: "sk-FAKE" }, 1);
+ const result = await bridgeCredentials(data, "database");
+ expect(result).toEqual({ toFile: [], toDatabase: [], removed: [] });
+ expect(fs.readFileSync(authFile(), "utf8")).toBe("{ not json");
+ });
+
+ it("does nothing on an OpenCode 1 data directory", async () => {
+ if (!available) return;
+ const v1 = fs.mkdtempSync(path.join(os.tmpdir(), "ogs-cred-v1-"));
+ try {
+ fs.writeFileSync(path.join(v1, "auth.json"), "{}");
+ const db = await openDatabase(path.join(v1, "opencode.db"));
+ db.exec("CREATE TABLE session (id TEXT PRIMARY KEY)");
+ db.close();
+ expect(await bridgeCredentials(v1, "file")).toEqual({
+ toFile: [],
+ toDatabase: [],
+ removed: [],
+ });
+ expect(fs.existsSync(path.join(v1, BRIDGE_STATE_FILE))).toBe(false);
+ } finally {
+ fs.rmSync(v1, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/tests/fixtures/opencode-2.2.5.sql b/tests/fixtures/opencode-2.2.5.sql
new file mode 100644
index 0000000..f68b956
--- /dev/null
+++ b/tests/fixtures/opencode-2.2.5.sql
@@ -0,0 +1,327 @@
+-- Schema of a fresh OpenCode 2.2.5 database (sqlite_master dump, 2026-11-05).
+-- Used by the session and credential tests so constraints match the real thing.
+
+CREATE TABLE `account` (
+ `id` text PRIMARY KEY,
+ `email` text NOT NULL,
+ `url` text NOT NULL,
+ `access_token` text NOT NULL,
+ `refresh_token` text NOT NULL,
+ `token_expiry` integer,
+ `time_created` integer NOT NULL,
+ `time_updated` integer NOT NULL
+ );
+
+CREATE TABLE `account_state` (
+ `id` integer PRIMARY KEY,
+ `active_account_id` text,
+ `active_org_id` text,
+ CONSTRAINT `fk_account_state_active_account_id_account_id_fk` FOREIGN KEY (`active_account_id`) REFERENCES `account`(`id`) ON DELETE SET NULL
+ );
+
+CREATE TABLE `blob` (
+ `hash` text PRIMARY KEY,
+ `mime` text NOT NULL,
+ `bytes` integer NOT NULL,
+ `width` integer,
+ `height` integer,
+ `data` blob NOT NULL,
+ `time_created` integer NOT NULL
+ );
+
+CREATE TABLE `blob_ref` (
+ `session_id` text NOT NULL,
+ `message_id` text NOT NULL,
+ `hash` text NOT NULL,
+ `seq` integer NOT NULL,
+ CONSTRAINT `blob_ref_pk` PRIMARY KEY(`session_id`, `message_id`, `hash`),
+ CONSTRAINT `fk_blob_ref_session_id_session_v2_id_fk` FOREIGN KEY (`session_id`) REFERENCES `session_v2`(`id`) ON DELETE CASCADE,
+ CONSTRAINT `fk_blob_ref_hash_blob_hash_fk` FOREIGN KEY (`hash`) REFERENCES `blob`(`hash`) ON DELETE CASCADE
+ );
+
+CREATE TABLE `control_account` (
+ `email` text NOT NULL,
+ `url` text NOT NULL,
+ `access_token` text NOT NULL,
+ `refresh_token` text NOT NULL,
+ `token_expiry` integer,
+ `active` integer NOT NULL,
+ `time_created` integer NOT NULL,
+ `time_updated` integer NOT NULL,
+ CONSTRAINT `control_account_pk` PRIMARY KEY(`email`, `url`)
+ );
+
+CREATE TABLE `credential` (
+ `id` text PRIMARY KEY,
+ `integration_id` text,
+ `label` text NOT NULL,
+ `value` text NOT NULL,
+ `connector_id` text,
+ `method_id` text,
+ `active` integer,
+ `time_created` integer NOT NULL,
+ `time_updated` integer NOT NULL
+ );
+
+CREATE TABLE `event` (
+ `id` text PRIMARY KEY,
+ `aggregate_id` text NOT NULL,
+ `seq` integer NOT NULL,
+ `created` integer DEFAULT 0 NOT NULL,
+ `type` text NOT NULL,
+ `data` text NOT NULL,
+ CONSTRAINT `fk_event_aggregate_id_event_sequence_aggregate_id_fk` FOREIGN KEY (`aggregate_id`) REFERENCES `event_sequence`(`aggregate_id`) ON DELETE CASCADE
+ );
+
+CREATE TABLE `event_sequence` (
+ `aggregate_id` text PRIMARY KEY,
+ `seq` integer NOT NULL,
+ `owner_id` text
+ );
+
+CREATE TABLE `instruction_blob` (
+ `hash` text PRIMARY KEY,
+ `value` text
+ );
+
+CREATE TABLE `instruction_entry` (
+ `session_id` text NOT NULL,
+ `key` text NOT NULL,
+ `value` text,
+ `removed` integer DEFAULT false NOT NULL,
+ `time_created` integer NOT NULL,
+ `time_updated` integer NOT NULL,
+ CONSTRAINT `instruction_entry_pk` PRIMARY KEY(`session_id`, `key`),
+ CONSTRAINT `fk_instruction_entry_session_id_session_v2_id_fk` FOREIGN KEY (`session_id`) REFERENCES `session_v2`(`id`) ON DELETE CASCADE
+ );
+
+CREATE TABLE `instruction_state` (
+ `session_id` text PRIMARY KEY,
+ `epoch_start` integer NOT NULL,
+ `through_seq` integer NOT NULL,
+ `initial_values` text NOT NULL,
+ `current_values` text NOT NULL,
+ CONSTRAINT `fk_instruction_state_session_id_session_v2_id_fk` FOREIGN KEY (`session_id`) REFERENCES `session_v2`(`id`) ON DELETE CASCADE
+ );
+
+CREATE TABLE `job` (
+ `notification_id` text PRIMARY KEY,
+ `id` text NOT NULL,
+ `session_id` text NOT NULL,
+ `child_session_id` text,
+ `kind` text NOT NULL,
+ `title` text,
+ `status` text NOT NULL,
+ `output` text,
+ `error` text,
+ `recovery` text NOT NULL,
+ `time_created` integer NOT NULL,
+ `time_updated` integer NOT NULL
+ );
+
+CREATE TABLE `kv` (
+ `key` text PRIMARY KEY,
+ `value` text NOT NULL,
+ `time_created` integer NOT NULL,
+ `time_updated` integer NOT NULL
+ );
+
+CREATE TABLE "migration" (id TEXT PRIMARY KEY, time_completed INTEGER NOT NULL);
+
+CREATE TABLE `permission` (
+ `id` text PRIMARY KEY,
+ `project_id` text NOT NULL,
+ `action` text NOT NULL,
+ `resource` text NOT NULL,
+ `time_created` integer NOT NULL,
+ `time_updated` integer NOT NULL,
+ CONSTRAINT `fk_permission_project_id_project_id_fk` FOREIGN KEY (`project_id`) REFERENCES `project`(`id`) ON DELETE CASCADE
+ );
+
+CREATE TABLE `project` (
+ `id` text PRIMARY KEY,
+ `worktree` text NOT NULL,
+ `vcs` text,
+ `name` text,
+ `icon_url` text,
+ `icon_url_override` text,
+ `icon_color` text,
+ `time_created` integer NOT NULL,
+ `time_updated` integer NOT NULL,
+ `time_initialized` integer,
+ `time_active` integer DEFAULT 0 NOT NULL,
+ `time_archived` integer,
+ `sandboxes` text NOT NULL,
+ `commands` text
+ );
+
+CREATE TABLE `project_directory` (
+ `project_id` text NOT NULL,
+ `directory` text NOT NULL,
+ `type` text,
+ `strategy` text,
+ `time_created` integer NOT NULL,
+ CONSTRAINT `project_directory_pk` PRIMARY KEY(`project_id`, `directory`),
+ CONSTRAINT `fk_project_directory_project_id_project_id_fk` FOREIGN KEY (`project_id`) REFERENCES `project`(`id`) ON DELETE CASCADE
+ );
+
+CREATE TABLE `schedule` (
+ `id` text PRIMARY KEY,
+ `session_id` text,
+ `name` text,
+ `action` text NOT NULL,
+ `check` text,
+ `when` text NOT NULL,
+ `tz` text NOT NULL,
+ `status` text DEFAULT 'active' NOT NULL,
+ `next_due_at` integer,
+ `ends_at` integer,
+ `remaining_runs` integer,
+ `run_count` integer DEFAULT 0 NOT NULL,
+ `checks` integer DEFAULT 0 NOT NULL,
+ `failures` integer DEFAULT 0 NOT NULL,
+ `last_fired_at` integer,
+ `last_message_id` text,
+ `last_outcome` text,
+ `retry_at` integer,
+ `state` text,
+ `time_created` integer NOT NULL,
+ `time_updated` integer NOT NULL,
+ CONSTRAINT `fk_schedule_session_id_session_v2_id_fk` FOREIGN KEY (`session_id`) REFERENCES `session_v2`(`id`) ON DELETE CASCADE
+ );
+
+CREATE TABLE `session_inbox` (
+ `id` text PRIMARY KEY,
+ `session_id` text NOT NULL,
+ `type` text NOT NULL,
+ `payload` text NOT NULL,
+ `delivery` text NOT NULL,
+ `enqueued_seq` integer NOT NULL,
+ `time_created` integer NOT NULL,
+ CONSTRAINT `fk_session_inbox_session_id_session_v2_id_fk` FOREIGN KEY (`session_id`) REFERENCES `session_v2`(`id`) ON DELETE CASCADE
+ );
+
+CREATE TABLE `session_message` (
+ `id` text PRIMARY KEY,
+ `session_id` text NOT NULL,
+ `type` text NOT NULL,
+ `seq` integer NOT NULL,
+ `time_created` integer NOT NULL,
+ `time_updated` integer NOT NULL,
+ `data` text NOT NULL,
+ CONSTRAINT `fk_session_message_session_id_session_v2_id_fk` FOREIGN KEY (`session_id`) REFERENCES `session_v2`(`id`) ON DELETE CASCADE
+ );
+
+CREATE TABLE `session_part` (
+ `message_id` text NOT NULL,
+ `session_id` text NOT NULL,
+ `ordinal` integer NOT NULL,
+ `type` text NOT NULL,
+ `call_id` text,
+ `time_created` integer NOT NULL,
+ `time_updated` integer NOT NULL,
+ `data` text NOT NULL,
+ CONSTRAINT `session_part_pk` PRIMARY KEY(`message_id`, `ordinal`),
+ CONSTRAINT `fk_session_part_message_id_session_message_id_fk` FOREIGN KEY (`message_id`) REFERENCES `session_message`(`id`) ON DELETE CASCADE,
+ CONSTRAINT `fk_session_part_session_id_session_v2_id_fk` FOREIGN KEY (`session_id`) REFERENCES `session_v2`(`id`) ON DELETE CASCADE
+ );
+
+CREATE TABLE `session_v2` (
+ `id` text PRIMARY KEY,
+ `project_id` text NOT NULL,
+ `workspace_id` text,
+ `parent_id` text,
+ `fork_session_id` text,
+ `fork_boundary` text,
+ `slug` text NOT NULL,
+ `directory` text NOT NULL,
+ `path` text,
+ `title` text,
+ `version` text NOT NULL,
+ `share_url` text,
+ `summary_additions` integer,
+ `summary_deletions` integer,
+ `summary_files` integer,
+ `summary_diffs` text,
+ `metadata` text,
+ `cost` real DEFAULT 0 NOT NULL,
+ `tokens_input` integer DEFAULT 0 NOT NULL,
+ `tokens_output` integer DEFAULT 0 NOT NULL,
+ `tokens_reasoning` integer DEFAULT 0 NOT NULL,
+ `tokens_cache_read` integer DEFAULT 0 NOT NULL,
+ `tokens_cache_write` integer DEFAULT 0 NOT NULL,
+ `revert` text,
+ `permission` text,
+ `agent` text,
+ `model` text,
+ `time_created` integer NOT NULL,
+ `time_updated` integer NOT NULL,
+ `time_busy` integer,
+ `time_idle` integer,
+ `time_viewed` integer,
+ `idle_outcome` text,
+ `time_compacting` integer,
+ `time_archived` integer,
+ `time_suspended` integer,
+ `resume_attempts` integer DEFAULT 0 NOT NULL,
+ CONSTRAINT `fk_session_v2_project_id_project_id_fk` FOREIGN KEY (`project_id`) REFERENCES `project`(`id`) ON DELETE CASCADE
+ );
+
+CREATE TABLE `workspace` (
+ `id` text PRIMARY KEY,
+ `provider` text NOT NULL,
+ `binding` text,
+ `created_at` integer NOT NULL,
+ `last_used_at` integer NOT NULL
+ );
+
+CREATE TABLE `worktree` (
+ `project_id` text NOT NULL,
+ `directory` text NOT NULL,
+ `strategy` text,
+ `time_created` integer NOT NULL,
+ CONSTRAINT `worktree_pk` PRIMARY KEY(`project_id`, `directory`),
+ CONSTRAINT `fk_worktree_project_id_project_id_fk` FOREIGN KEY (`project_id`) REFERENCES `project`(`id`) ON DELETE CASCADE
+ );
+
+CREATE INDEX `blob_ref_hash_idx` ON `blob_ref` (`hash`);
+
+CREATE INDEX `blob_ref_session_seq_idx` ON `blob_ref` (`session_id`,`seq`);
+
+CREATE UNIQUE INDEX `event_aggregate_seq_idx` ON `event` (`aggregate_id`,`seq`);
+
+CREATE INDEX `event_aggregate_type_seq_idx` ON `event` (`aggregate_id`,`type`,`seq`);
+
+CREATE INDEX `job_child_session_idx` ON `job` (`child_session_id`);
+
+CREATE INDEX `job_id_idx` ON `job` (`id`);
+
+CREATE INDEX `job_session_idx` ON `job` (`session_id`);
+
+CREATE UNIQUE INDEX `permission_project_action_resource_idx` ON `permission` (`project_id`,`action`,`resource`);
+
+CREATE INDEX `schedule_due_idx` ON `schedule` (`next_due_at`) WHERE "schedule"."status" = 'active' and "schedule"."next_due_at" is not null;
+
+CREATE INDEX `schedule_session_idx` ON `schedule` (`session_id`);
+
+CREATE INDEX `session_inbox_session_delivery_seq_idx` ON `session_inbox` (`session_id`,`delivery`,`enqueued_seq`);
+
+CREATE UNIQUE INDEX `session_inbox_session_enqueued_seq_idx` ON `session_inbox` (`session_id`,`enqueued_seq`);
+
+CREATE UNIQUE INDEX `session_message_session_seq_idx` ON `session_message` (`session_id`,`seq`);
+
+CREATE INDEX `session_message_session_time_created_id_idx` ON `session_message` (`session_id`,`time_created`,`id`);
+
+CREATE INDEX `session_message_session_type_seq_idx` ON `session_message` (`session_id`,`type`,`seq`);
+
+CREATE INDEX `session_message_time_created_idx` ON `session_message` (`time_created`);
+
+CREATE INDEX `session_part_session_message_idx` ON `session_part` (`session_id`,`message_id`,`ordinal`);
+
+CREATE INDEX `session_v2_parent_idx` ON `session_v2` (`parent_id`);
+
+CREATE INDEX `session_v2_project_idx` ON `session_v2` (`project_id`);
+
+CREATE INDEX `session_v2_time_suspended_idx` ON `session_v2` (`time_suspended`) WHERE "session_v2"."time_suspended" is not null;
+
+CREATE INDEX `session_v2_workspace_idx` ON `session_v2` (`workspace_id`);
diff --git a/tests/lease.test.ts b/tests/lease.test.ts
new file mode 100644
index 0000000..22cee1c
--- /dev/null
+++ b/tests/lease.test.ts
@@ -0,0 +1,218 @@
+import { execFileSync } from "node:child_process";
+import fs from "node:fs";
+import http from "node:http";
+import type { AddressInfo } from "node:net";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import {
+ LEASE_REF,
+ LEASE_TTL_MS,
+ MARGIN_MS,
+ isDue,
+ maybeRefreshOpenai,
+ refreshInChild,
+} from "../src/core/lease.js";
+import type { Roots } from "../src/core/paths.js";
+import { DEFAULT_SETTINGS, type Settings } from "../src/core/settings.js";
+
+/**
+ * The OpenAI refresh lease against a real bare repository. Tokens are fake and
+ * the token endpoint is either a stub function or a local HTTP server.
+ */
+
+let sandbox: string;
+let remote: string;
+const NOW = 2_000_000_000_000;
+
+beforeEach(() => {
+ sandbox = fs.mkdtempSync(path.join(os.tmpdir(), "ogs-lease-"));
+ remote = path.join(sandbox, "remote.git");
+ run(sandbox, "init", "-q", "--bare", "-b", "main", remote);
+ // Seed the branch so `origin/main` exists for the published-expiry check.
+ const seed = path.join(sandbox, "seed");
+ run(sandbox, "clone", "-q", remote, seed);
+ fs.writeFileSync(path.join(seed, "README"), "x\n");
+ run(seed, "add", "-A");
+ run(seed, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "seed");
+ run(seed, "push", "-q", "origin", "main");
+});
+
+afterEach(() => {
+ fs.rmSync(sandbox, { recursive: true, force: true });
+});
+
+function run(cwd: string, ...args: string[]): string {
+ return execFileSync("git", args, { cwd, encoding: "utf8", stdio: "pipe" }).trim();
+}
+
+function machine(name: string, expires: number): Roots {
+ const base = path.join(sandbox, name);
+ const roots: Roots = {
+ config: path.join(base, "config"),
+ data: path.join(base, "data"),
+ state: path.join(base, "state"),
+ agents: path.join(base, "agents"),
+ cache: path.join(base, "cache"),
+ };
+ run(sandbox, "clone", "-q", remote, roots.config);
+ run(roots.config, "config", "user.name", name);
+ run(roots.config, "config", "user.email", `${name}@test`);
+ fs.mkdirSync(roots.data, { recursive: true });
+ fs.writeFileSync(
+ path.join(roots.data, "auth.json"),
+ JSON.stringify({
+ openai: { type: "oauth", access: "FAKE_A0", refresh: "FAKE_R0", expires },
+ other: { type: "api", key: "sk-FAKE-KEEP" },
+ }),
+ );
+ return roots;
+}
+
+const settings = (alias: string, patch: Partial = {}): Settings => ({
+ ...DEFAULT_SETTINGS,
+ includeCredentials: true,
+ machineAlias: alias,
+ ...patch,
+});
+
+const readAuth = (roots: Roots): any =>
+ JSON.parse(fs.readFileSync(path.join(roots.data, "auth.json"), "utf8"));
+
+describe("isDue", () => {
+ it("is due only inside the margin, using the newest known expiry", () => {
+ expect(isDue(NOW, NOW + MARGIN_MS + 1, undefined)).toBe(false);
+ expect(isDue(NOW, NOW + MARGIN_MS - 1, undefined)).toBe(true);
+ // Someone already published a renewed login: not due here.
+ expect(isDue(NOW, NOW + 1, NOW + MARGIN_MS * 2)).toBe(false);
+ expect(isDue(NOW, undefined, undefined)).toBe(false);
+ });
+});
+
+describe("OpenAI refresh lease", () => {
+ it("lets exactly one machine refresh, and the other waits", async () => {
+ const a = machine("a", NOW + 1000);
+ const b = machine("b", NOW + 1000);
+ const calls: string[] = [];
+ const refresh = (who: string) => async (token: string) => {
+ calls.push(`${who}:${token}`);
+ return { access_token: "FAKE_A1", refresh_token: "FAKE_R1", expires_in: 864_000 };
+ };
+
+ const first = await maybeRefreshOpenai({
+ roots: a,
+ settings: settings("a"),
+ now: () => NOW,
+ refresh: refresh("a"),
+ });
+ const second = await maybeRefreshOpenai({
+ roots: b,
+ settings: settings("b"),
+ now: () => NOW + 1000,
+ refresh: refresh("b"),
+ });
+
+ expect(first).toMatch(/^claimed; refreshed/);
+ expect(second).toBe("held by a");
+ expect(calls).toEqual(["a:FAKE_R0"]);
+ expect(readAuth(a).openai).toMatchObject({ access: "FAKE_A1", refresh: "FAKE_R1" });
+ expect(readAuth(a).other.key).toBe("sk-FAKE-KEEP");
+ expect(readAuth(b).openai.refresh).toBe("FAKE_R0");
+ expect(run(remote, "rev-parse", "--verify", LEASE_REF)).toMatch(/^[0-9a-f]{40}$/);
+ });
+
+ it("takes over a stale claim", async () => {
+ const a = machine("a", NOW + 1000);
+ const b = machine("b", NOW + 1000);
+ const ok = async () => ({ access_token: "FAKE_A1", refresh_token: "FAKE_R1" });
+ await maybeRefreshOpenai({ roots: a, settings: settings("a"), now: () => NOW, refresh: ok });
+
+ const later = await maybeRefreshOpenai({
+ roots: b,
+ settings: settings("b"),
+ now: () => NOW + LEASE_TTL_MS + 1,
+ refresh: ok,
+ });
+ expect(later).toMatch(/^claimed; refreshed/);
+ });
+
+ it("does nothing when not due, when off, or without credential sync", async () => {
+ const a = machine("a", NOW + MARGIN_MS * 2);
+ const never = async () => {
+ throw new Error("must not be called");
+ };
+ expect(
+ await maybeRefreshOpenai({
+ roots: a,
+ settings: settings("a"),
+ now: () => NOW,
+ refresh: never,
+ }),
+ ).toBe("not due");
+ expect(
+ await maybeRefreshOpenai({
+ roots: a,
+ settings: settings("a", { openaiRefreshLease: false }),
+ refresh: never,
+ }),
+ ).toBe("off");
+ expect(
+ await maybeRefreshOpenai({
+ roots: a,
+ settings: settings("a", { includeCredentials: false }),
+ refresh: never,
+ }),
+ ).toBe("off");
+ });
+
+ it("keeps the old token when the refresh fails, and never prints a token", async () => {
+ const a = machine("a", NOW + 1000);
+ const outcome = await maybeRefreshOpenai({
+ roots: a,
+ settings: settings("a"),
+ now: () => NOW,
+ refresh: async () => {
+ throw new Error("HTTP 401");
+ },
+ });
+ expect(outcome).toBe("claimed; refresh failed (HTTP 401)");
+ expect(outcome).not.toMatch(/FAKE/);
+ expect(readAuth(a).openai.refresh).toBe("FAKE_R0");
+ });
+});
+
+describe("refreshInChild", () => {
+ it("posts the refresh token from a child process and returns the response", async () => {
+ let received: any;
+ const server = http.createServer((req, res) => {
+ let body = "";
+ req.on("data", (c) => {
+ body += c;
+ });
+ req.on("end", () => {
+ received = JSON.parse(body);
+ res.setHeader("content-type", "application/json");
+ res.end(JSON.stringify({ access_token: "FAKE_NEW", expires_in: 10 }));
+ });
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const { port } = server.address() as AddressInfo;
+ const saved = { url: process.env.OPENCODE_OPENAI_TOKEN_URL, noProxy: process.env.NO_PROXY };
+ process.env.OPENCODE_OPENAI_TOKEN_URL = `http://127.0.0.1:${port}/token`;
+ process.env.NO_PROXY = "127.0.0.1,localhost";
+ try {
+ const token = await refreshInChild("FAKE_REFRESH");
+ expect(token.access_token).toBe("FAKE_NEW");
+ expect(received).toMatchObject({
+ grant_type: "refresh_token",
+ refresh_token: "FAKE_REFRESH",
+ });
+ } finally {
+ if (saved.url === undefined) delete process.env.OPENCODE_OPENAI_TOKEN_URL;
+ else process.env.OPENCODE_OPENAI_TOKEN_URL = saved.url;
+ if (saved.noProxy === undefined) delete process.env.NO_PROXY;
+ else process.env.NO_PROXY = saved.noProxy;
+ server.close();
+ }
+ });
+});
diff --git a/tests/repair.test.ts b/tests/repair.test.ts
new file mode 100644
index 0000000..2f551b5
--- /dev/null
+++ b/tests/repair.test.ts
@@ -0,0 +1,122 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { directoryProjectId, storedPath } from "../src/core/projects.js";
+import { repairSessions } from "../src/core/repair.js";
+import { type SqliteDatabase, openDatabase, sqliteAvailable } from "../src/core/sqlite.js";
+
+const SCHEMA = fs.readFileSync(path.join(__dirname, "fixtures", "opencode-2.2.5.sql"), "utf8");
+
+let root: string;
+let available = false;
+
+beforeEach(async () => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), "ogs-repair-"));
+ available = await sqliteAvailable();
+});
+
+afterEach(() => {
+ fs.rmSync(root, { recursive: true, force: true });
+});
+
+function project(db: SqliteDatabase, id: string, worktree: string, created: number, vcs?: string) {
+ db.prepare(
+ `INSERT INTO project (id, worktree, vcs, sandboxes, time_created, time_updated)
+ VALUES (?, ?, ?, '[]', ?, ?)`,
+ ).run(id, storedPath(worktree), vcs ?? null, created, created);
+}
+
+function session(db: SqliteDatabase, id: string, projectId: string, directory: string) {
+ db.prepare(
+ `INSERT INTO session_v2 (id, project_id, slug, directory, path, version, time_created, time_updated)
+ VALUES (?, ?, ?, ?, NULL, '1.18.0', 1, 1)`,
+ ).run(id, projectId, id, storedPath(directory));
+}
+
+function placement(db: SqliteDatabase, id: string): any {
+ return db.prepare("SELECT project_id, directory, path FROM session_v2 WHERE id = ?").all(id)[0];
+}
+
+async function fixture() {
+ const home = path.join(root, "home");
+ const plain = path.join(home, "notes");
+ const repo = path.join(root, "repo");
+ for (const d of [plain, path.join(repo, "src")]) fs.mkdirSync(d, { recursive: true });
+ const file = path.join(root, "opencode.db");
+ const db = await openDatabase(file);
+ db.exec(SCHEMA);
+ project(db, "global", "/", 1);
+ project(db, directoryProjectId(home), home, 5);
+ project(db, directoryProjectId(plain), plain, 5);
+ project(db, "old-root", repo, 2, "git");
+ project(db, "new-root", repo, 9, "git");
+ // Migrated from OpenCode 1: a plain directory under `global`.
+ session(db, "ses_global", "global", plain);
+ // A repository whose project id changed: still on the old row.
+ session(db, "ses_stale", "old-root", path.join(repo, "src"));
+ // Already right.
+ session(db, "ses_ok", "new-root", repo);
+ // Another machine's path: no project here, parked in home.
+ session(db, "ses_foreign", "global", "/Users/someone/elsewhere");
+ db.close();
+ return { file, home, plain, repo };
+}
+
+describe("repair-sessions", () => {
+ it("reports without changing anything by default", async () => {
+ if (!available) return;
+ const { file, home } = await fixture();
+ const result = await repairSessions(file, { apply: false, home });
+ expect(result.supported).toBe(true);
+ expect(result.moves.map((m) => m.id).sort()).toEqual([
+ "ses_foreign",
+ "ses_global",
+ "ses_stale",
+ ]);
+ expect(result.applied).toBe(0);
+
+ const db = await openDatabase(file, { readOnly: true });
+ expect(placement(db, "ses_global").project_id).toBe("global");
+ db.close();
+ });
+
+ it("moves each session into the project OpenCode 2 resolves for it", async () => {
+ if (!available) return;
+ const { file, home, plain, repo } = await fixture();
+ const result = await repairSessions(file, { apply: true, home });
+ expect(result.applied).toBe(3);
+
+ const db = await openDatabase(file, { readOnly: true });
+ expect(placement(db, "ses_global")).toEqual({
+ project_id: directoryProjectId(plain),
+ directory: storedPath(plain),
+ path: "",
+ });
+ expect(placement(db, "ses_stale")).toEqual({
+ project_id: "new-root",
+ directory: storedPath(path.join(repo, "src")),
+ path: "src",
+ });
+ expect(placement(db, "ses_ok").project_id).toBe("new-root");
+ expect(placement(db, "ses_foreign")).toEqual({
+ project_id: directoryProjectId(home),
+ directory: storedPath(home),
+ path: "",
+ });
+ db.close();
+
+ const again = await repairSessions(file, { apply: true, home });
+ expect(again.moves).toEqual([]);
+ });
+
+ it("does nothing on an OpenCode 1 database", async () => {
+ if (!available) return;
+ const file = path.join(root, "v1.db");
+ const db = await openDatabase(file);
+ db.exec("CREATE TABLE session (id TEXT PRIMARY KEY)");
+ db.close();
+ const result = await repairSessions(file, { apply: true, home: root });
+ expect(result.supported).toBe(false);
+ });
+});
diff --git a/tests/sessions-v2.test.ts b/tests/sessions-v2.test.ts
new file mode 100644
index 0000000..ffbe401
--- /dev/null
+++ b/tests/sessions-v2.test.ts
@@ -0,0 +1,435 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { gunzipSync } from "node:zlib";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { directoryProjectId, storedPath } from "../src/core/projects.js";
+import { silentReporter } from "../src/core/reporter.js";
+import { exportSessions, importSessions, listSessions } from "../src/core/sessions.js";
+import type { SessionSettings } from "../src/core/settings.js";
+import { type SqliteDatabase, openDatabase, sqliteAvailable } from "../src/core/sqlite.js";
+
+/**
+ * OpenCode 2 session sync, against the schema of a real 2.2.5 database
+ * (`fixtures/opencode-2.2.5.sql`), so NOT NULL columns and foreign keys behave
+ * exactly as they do on a user's machine. All values are fake.
+ */
+
+const SCHEMA = fs.readFileSync(path.join(__dirname, "fixtures", "opencode-2.2.5.sql"), "utf8");
+const DAY = 24 * 60 * 60 * 1000;
+
+const settings = (patch: Partial = {}): SessionSettings & { now?: number } => ({
+ enabled: true,
+ days: 7,
+ maxSessions: 50,
+ maxSessionBytes: 5 * 1024 * 1024,
+ include: [],
+ exclude: [],
+ directories: [],
+ ...patch,
+});
+
+let root: string;
+let available = false;
+
+beforeEach(async () => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), "ogs-v2-"));
+ available = await sqliteAvailable();
+});
+
+afterEach(() => {
+ delete process.env.SYNC_HOME;
+ fs.rmSync(root, { recursive: true, force: true });
+});
+
+async function createDb(file: string): Promise {
+ const db = await openDatabase(file);
+ db.exec(SCHEMA);
+ return db;
+}
+
+function addProject(db: SqliteDatabase, id: string, worktree: string, created = 1): void {
+ db.prepare(
+ `INSERT INTO project (id, worktree, vcs, sandboxes, time_created, time_updated)
+ VALUES (?, ?, NULL, '[]', ?, ?)`,
+ ).run(id, storedPath(worktree), created, created);
+}
+
+interface SessionSpec {
+ id: string;
+ project: string;
+ directory: string;
+ updated: number;
+ messages?: number;
+ busy?: boolean;
+}
+
+function addSession(db: SqliteDatabase, spec: SessionSpec): void {
+ db.prepare(
+ `INSERT INTO session_v2 (id, project_id, slug, directory, path, title, version,
+ time_created, time_updated, time_busy, resume_attempts)
+ VALUES (?, ?, ?, ?, '', ?, '2.2.5', ?, ?, ?, ?)`,
+ ).run(
+ spec.id,
+ spec.project,
+ spec.id,
+ storedPath(spec.directory),
+ `title ${spec.id}`,
+ spec.updated - 1000,
+ spec.updated,
+ spec.busy ? spec.updated : null,
+ spec.busy ? 2 : 0,
+ );
+ const count = spec.messages ?? 2;
+ for (let seq = 1; seq <= count; seq++) {
+ db.prepare(
+ `INSERT INTO session_message (id, session_id, type, seq, time_created, time_updated, data)
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
+ ).run(
+ `msg_${spec.id}_${seq}`,
+ spec.id,
+ seq % 2 ? "user" : "assistant",
+ seq,
+ seq,
+ seq,
+ JSON.stringify({ text: `message ${seq} of ${spec.id}` }),
+ );
+ }
+ db.prepare(
+ `INSERT INTO session_part (message_id, session_id, ordinal, type, time_created, time_updated, data)
+ VALUES (?, ?, 0, 'text', 1, 1, '{}')`,
+ ).run(`msg_${spec.id}_1`, spec.id);
+ db.prepare("INSERT INTO event_sequence (aggregate_id, seq, owner_id) VALUES (?, ?, ?)").run(
+ spec.id,
+ count,
+ "owner-on-this-machine",
+ );
+ const hash = "a".repeat(64);
+ db.prepare("INSERT INTO instruction_blob (hash, value) VALUES (?, ?) ON CONFLICT DO NOTHING").run(
+ hash,
+ "system prompt text",
+ );
+ db.prepare(
+ `INSERT INTO instruction_state (session_id, epoch_start, through_seq, initial_values, current_values)
+ VALUES (?, 1, 1, ?, ?)`,
+ ).run(spec.id, JSON.stringify({ "core/date": hash }), JSON.stringify({ "core/date": hash }));
+}
+
+function readShard(repo: string, id: string): any {
+ return JSON.parse(
+ gunzipSync(fs.readFileSync(path.join(repo, "_sessions", `${id}.json.gz`))).toString(),
+ );
+}
+
+function rows(db: SqliteDatabase, sql: string, ...params: unknown[]): any[] {
+ return db.prepare(sql).all(...params) as any[];
+}
+
+/** Machine A with one recent session in a project directory that exists on both machines. */
+async function machineA(now: number, work: string, extra?: (db: SqliteDatabase) => void) {
+ const source = path.join(root, "a.db");
+ const db = await createDb(source);
+ addProject(db, directoryProjectId(work), work);
+ addSession(db, {
+ id: "ses_one",
+ project: directoryProjectId(work),
+ directory: work,
+ updated: now - DAY,
+ });
+ extra?.(db);
+ db.close();
+ return source;
+}
+
+describe("OpenCode 2 sessions", () => {
+ it("exports from session_v2 and round-trips into a fresh OpenCode 2 database", async () => {
+ if (!available) return;
+ const now = Date.now();
+ const work = path.join(root, "work");
+ fs.mkdirSync(work);
+ const source = await machineA(now, work);
+ const repo = path.join(root, "repo");
+
+ const exported = await exportSessions(source, repo, { ...settings(), now }, silentReporter);
+ expect(exported.written).toEqual(["ses_one"]);
+ const shard = readShard(repo, "ses_one");
+ expect(shard.formatVersion).toBe(2);
+ expect(shard.schema).toBe("v2");
+ expect(shard.tables.session_message).toHaveLength(2);
+ expect(shard.tables.event_sequence[0].owner_id).toBeNull();
+ expect(shard.blobs.instruction_blob).toHaveLength(1);
+
+ const target = path.join(root, "b.db");
+ (await createDb(target)).close();
+ const result = await importSessions(target, repo, silentReporter, { home: root, now });
+ expect(result.failed).toEqual([]);
+ expect(result.imported).toBe(1);
+
+ const db = await openDatabase(target, { readOnly: true });
+ const session = rows(db, "SELECT * FROM session_v2 WHERE id = 'ses_one'")[0];
+ expect(session.project_id).toBe(directoryProjectId(work));
+ expect(session.directory).toBe(storedPath(work));
+ expect(session.path).toBe("");
+ expect(rows(db, "SELECT seq FROM session_message ORDER BY seq").map((r) => r.seq)).toEqual([
+ 1, 2,
+ ]);
+ expect(rows(db, "SELECT count(*) AS n FROM session_part")[0].n).toBe(1);
+ expect(rows(db, "SELECT seq FROM event_sequence")[0].seq).toBe(2);
+ expect(rows(db, "SELECT value FROM instruction_blob")[0].value).toBe("system prompt text");
+ db.close();
+
+ expect((await listSessions(target, 10)).map((s) => s.id)).toEqual(["ses_one"]);
+ });
+
+ it("never carries a running conversation's runtime state to another machine", async () => {
+ if (!available) return;
+ const now = Date.now();
+ const work = path.join(root, "work");
+ fs.mkdirSync(work);
+ const source = await machineA(now, work, (db) => {
+ addSession(db, {
+ id: "ses_busy",
+ project: directoryProjectId(work),
+ directory: work,
+ updated: now,
+ busy: true,
+ });
+ });
+ const repo = path.join(root, "repo");
+ await exportSessions(source, repo, { ...settings(), now }, silentReporter);
+
+ const shard = readShard(repo, "ses_busy");
+ expect(shard.session.time_busy).toBeNull();
+ expect(shard.session.resume_attempts).toBe(0);
+ });
+
+ it("creates the project OpenCode 2 would create for a directory it has not opened yet", async () => {
+ if (!available) return;
+ const now = Date.now();
+ const work = path.join(root, "work");
+ fs.mkdirSync(work);
+ const source = await machineA(now, work);
+ const repo = path.join(root, "repo");
+ await exportSessions(source, repo, { ...settings(), now }, silentReporter);
+
+ const target = path.join(root, "b.db");
+ (await createDb(target)).close();
+ await importSessions(target, repo, silentReporter, { home: root, now });
+
+ const db = await openDatabase(target, { readOnly: true });
+ const project = rows(db, "SELECT * FROM project")[0];
+ db.close();
+ expect(project.id).toBe(directoryProjectId(work));
+ expect(project.worktree).toBe(storedPath(path.resolve(work)));
+ });
+
+ it("parks a session whose directory this machine does not have in the home project", async () => {
+ if (!available) return;
+ const now = Date.now();
+ const elsewhere = path.join(root, "only-on-a");
+ fs.mkdirSync(elsewhere);
+ const source = await machineA(now, elsewhere);
+ const repo = path.join(root, "repo");
+ await exportSessions(source, repo, { ...settings(), now }, silentReporter);
+ fs.rmSync(elsewhere, { recursive: true });
+
+ const home = path.join(root, "home-b");
+ fs.mkdirSync(home);
+ const target = path.join(root, "b.db");
+ (await createDb(target)).close();
+ const result = await importSessions(target, repo, silentReporter, { home, now });
+ expect(result.failed).toEqual([]);
+
+ const db = await openDatabase(target, { readOnly: true });
+ const session = rows(db, "SELECT project_id, directory, path FROM session_v2")[0];
+ db.close();
+ expect(session.project_id).toBe(directoryProjectId(home));
+ expect(session.directory).toBe(storedPath(path.resolve(home)));
+ expect(session.path).toBe("");
+ });
+
+ it("maps a directory under the exporting machine's home onto this machine's home", async () => {
+ if (!available) return;
+ const now = Date.now();
+ const homeA = path.join(root, "home-a");
+ const homeB = path.join(root, "home-b");
+ fs.mkdirSync(path.join(homeA, "proj"), { recursive: true });
+ fs.mkdirSync(path.join(homeB, "proj"), { recursive: true });
+ process.env.SYNC_HOME = homeA;
+ const source = await machineA(now, path.join(homeA, "proj"));
+ const repo = path.join(root, "repo");
+ await exportSessions(source, repo, { ...settings(), now }, silentReporter);
+ fs.rmSync(homeA, { recursive: true });
+
+ const target = path.join(root, "b.db");
+ (await createDb(target)).close();
+ await importSessions(target, repo, silentReporter, { home: homeB, now });
+
+ const db = await openDatabase(target, { readOnly: true });
+ const session = rows(db, "SELECT project_id, directory FROM session_v2")[0];
+ db.close();
+ expect(session.directory).toBe(storedPath(path.join(homeB, "proj")));
+ expect(session.project_id).toBe(directoryProjectId(path.join(homeB, "proj")));
+ });
+
+ it("replaces an older local copy and keeps a diverged one in recovery", async () => {
+ if (!available) return;
+ const now = Date.now();
+ const work = path.join(root, "work");
+ fs.mkdirSync(work);
+ const source = await machineA(now, work);
+ const repo = path.join(root, "repo");
+ await exportSessions(source, repo, { ...settings(), now }, silentReporter);
+
+ // B continued the same conversation earlier, with a message A never saw.
+ const target = path.join(root, "b.db");
+ const b = await createDb(target);
+ addProject(b, directoryProjectId(work), work);
+ addSession(b, {
+ id: "ses_one",
+ project: directoryProjectId(work),
+ directory: work,
+ updated: now - 2 * DAY,
+ messages: 3,
+ });
+ b.prepare("UPDATE session_message SET id = 'msg_only_on_b' WHERE seq = 3").run();
+ b.close();
+
+ const recovery = path.join(root, "recovery");
+ const result = await importSessions(target, repo, silentReporter, {
+ home: root,
+ now,
+ recoveryRoot: recovery,
+ });
+ expect(result.failed).toEqual([]);
+ expect(result.imported).toBe(1);
+
+ const db = await openDatabase(target, { readOnly: true });
+ expect(rows(db, "SELECT count(*) AS n FROM session_message")[0].n).toBe(2);
+ expect(rows(db, "SELECT seq FROM event_sequence")[0].seq).toBe(2);
+ db.close();
+ const saved = fs.readdirSync(recovery);
+ expect(saved).toHaveLength(1);
+ expect(fs.readdirSync(path.join(recovery, saved[0]!))).toEqual(["ses_one.json.gz"]);
+ });
+
+ it("leaves a session that is running on this machine alone", async () => {
+ if (!available) return;
+ const now = Date.now();
+ const work = path.join(root, "work");
+ fs.mkdirSync(work);
+ const source = await machineA(now, work);
+ const repo = path.join(root, "repo");
+ await exportSessions(source, repo, { ...settings(), now }, silentReporter);
+
+ const target = path.join(root, "b.db");
+ const b = await createDb(target);
+ addProject(b, directoryProjectId(work), work);
+ addSession(b, {
+ id: "ses_one",
+ project: directoryProjectId(work),
+ directory: work,
+ updated: now - 3 * DAY,
+ busy: true,
+ });
+ b.close();
+
+ const result = await importSessions(target, repo, silentReporter, { home: root, now });
+ expect(result.imported).toBe(0);
+ expect(result.skippedOlder).toBe(1);
+ });
+
+ it("skips shards of the other OpenCode major version and keeps them in the repository", async () => {
+ if (!available) return;
+ const now = Date.now();
+ const work = path.join(root, "work");
+ fs.mkdirSync(work);
+ const repo = path.join(root, "repo");
+ const dir = path.join(repo, "_sessions");
+ fs.mkdirSync(dir, { recursive: true });
+ const { gzipSync } = await import("node:zlib");
+ const v1 = {
+ formatVersion: 1,
+ session: { id: "ses_v1", time_updated: now - DAY, directory: "/x" },
+ tables: {},
+ exportedAt: now - DAY,
+ };
+ fs.writeFileSync(path.join(dir, "ses_v1.json.gz"), gzipSync(Buffer.from(JSON.stringify(v1))));
+
+ const source = await machineA(now, work);
+ await exportSessions(source, repo, { ...settings(), now }, silentReporter);
+ expect(fs.existsSync(path.join(dir, "ses_v1.json.gz"))).toBe(true);
+
+ const target = path.join(root, "b.db");
+ (await createDb(target)).close();
+ const result = await importSessions(target, repo, silentReporter, { home: root, now });
+ expect(result.skippedOtherSchema).toBe(1);
+ expect(result.imported).toBe(1);
+ expect(result.failed).toEqual([]);
+ });
+
+ it("writes byte-identical v2 shards on a repeat export", async () => {
+ if (!available) return;
+ const now = Date.now();
+ const work = path.join(root, "work");
+ fs.mkdirSync(work);
+ const source = await machineA(now, work);
+ const repo = path.join(root, "repo");
+ await exportSessions(source, repo, { ...settings(), now }, silentReporter);
+ const file = path.join(repo, "_sessions", "ses_one.json.gz");
+ const before = fs.readFileSync(file);
+ await exportSessions(source, repo, { ...settings(), now }, silentReporter);
+ expect(fs.readFileSync(file).equals(before)).toBe(true);
+ });
+
+ it("leaves a shard alone that is already as new as this machine's copy", async () => {
+ if (!available) return;
+ const now = Date.now();
+ const work = path.join(root, "work");
+ fs.mkdirSync(work);
+ const source = await machineA(now, work);
+ const repo = path.join(root, "repo");
+ await exportSessions(source, repo, { ...settings(), now }, silentReporter);
+ const file = path.join(repo, "_sessions", "ses_one.json.gz");
+
+ // Another machine wrote the same session: same time, different bytes.
+ const { gzipSync } = await import("node:zlib");
+ const theirs = readShard(repo, "ses_one");
+ theirs.origin.home = "/home/someone-else";
+ const bytes = gzipSync(Buffer.from(JSON.stringify(theirs)));
+ fs.writeFileSync(file, bytes);
+
+ const result = await exportSessions(source, repo, { ...settings(), now }, silentReporter);
+ expect(result.written).toEqual(["ses_one"]);
+ expect(fs.readFileSync(file).equals(bytes)).toBe(true);
+ });
+
+ it("round-trips binary attachments", async () => {
+ if (!available) return;
+ const now = Date.now();
+ const work = path.join(root, "work");
+ fs.mkdirSync(work);
+ const hash = "b".repeat(64);
+ const bytes = Buffer.from([0, 1, 2, 250, 255]);
+ const source = await machineA(now, work, (db) => {
+ db.prepare(
+ "INSERT INTO blob (hash, mime, bytes, data, time_created) VALUES (?, 'image/png', 5, ?, 1)",
+ ).run(hash, bytes);
+ db.prepare(
+ "INSERT INTO blob_ref (session_id, message_id, hash, seq) VALUES ('ses_one', 'msg_ses_one_1', ?, 1)",
+ ).run(hash);
+ });
+ const repo = path.join(root, "repo");
+ await exportSessions(source, repo, { ...settings(), now }, silentReporter);
+
+ const target = path.join(root, "b.db");
+ (await createDb(target)).close();
+ const result = await importSessions(target, repo, silentReporter, { home: root, now });
+ expect(result.failed).toEqual([]);
+
+ const db = await openDatabase(target, { readOnly: true });
+ const blob = rows(db, "SELECT data FROM blob WHERE hash = ?", hash)[0];
+ db.close();
+ expect(Buffer.from(blob.data).equals(bytes)).toBe(true);
+ });
+});
diff --git a/tests/sync.test.ts b/tests/sync.test.ts
index 8aef19c..30c7fc5 100644
--- a/tests/sync.test.ts
+++ b/tests/sync.test.ts
@@ -571,3 +571,119 @@ describe("status", () => {
expect(result.ahead).toBe(0);
});
});
+
+describe("OpenCode 2 machine files", () => {
+ const tracked = (root: string): string =>
+ execFileSync("git", ["ls-files"], { cwd: root, encoding: "utf8" });
+
+ it("never commits the service record, locks or per-machine histories", async () => {
+ const a = makeMachine("a");
+ useMachine(a);
+ write(path.join(a.config, "opencode.jsonc"), "{}\n");
+ write(path.join(a.config, "service.json"), '{ "password": "FAKE" }\n');
+ write(path.join(a.state, "service.json"), '{ "password": "FAKE" }\n');
+ write(path.join(a.state, "prompt-history.jsonl"), "{}\n");
+ write(path.join(a.state, "frecency.jsonl"), "{}\n");
+ write(path.join(a.state, "locks", "x.lock"), "1\n");
+ write(path.join(a.state, "model.json"), "{}\n");
+
+ await push({ settings: settings(), roots: getRoots() });
+
+ const files = tracked(a.config);
+ expect(files).not.toMatch(/service\.json/);
+ expect(files).not.toMatch(/prompt-history|frecency|locks/);
+ expect(files).toMatch(/_state\/model\.json/);
+ expect(read(path.join(a.config, "service.json"))).toContain("FAKE");
+ });
+
+ it("untracks machine files an older version committed, keeping the local copies", async () => {
+ const a = makeMachine("a");
+ useMachine(a);
+ write(path.join(a.config, "opencode.jsonc"), "{}\n");
+ await push({ settings: settings(), roots: getRoots() });
+ // What 3.2.0 did: the files went in with everything else.
+ write(path.join(a.config, "service.json"), '{ "password": "A" }\n');
+ write(path.join(a.config, "_state", "service.json"), '{ "password": "A" }\n');
+ execFileSync("git", ["add", "-f", "service.json", "_state/service.json"], { cwd: a.config });
+ execFileSync("git", ["commit", "-qm", "old version"], { cwd: a.config });
+ execFileSync("git", ["push", "-q", "origin", "main"], { cwd: a.config });
+
+ write(path.join(a.config, "command", "x.md"), "x\n");
+ await push({ settings: settings(), roots: getRoots() });
+
+ expect(tracked(a.config)).not.toMatch(/service\.json/);
+ expect(read(path.join(a.config, "service.json"))).toContain('"A"');
+ });
+
+ it("keeps this machine's service record when pulling a commit that still has another's", async () => {
+ const a = makeMachine("a");
+ useMachine(a);
+ write(path.join(a.config, "opencode.jsonc"), "{}\n");
+ await push({ settings: settings(), roots: getRoots() });
+
+ const b = makeMachine("b");
+ useMachine(b);
+ await pull({ settings: settings(), roots: getRoots() });
+ write(path.join(b.config, "service.json"), '{ "password": "B" }\n');
+
+ useMachine(a);
+ write(path.join(a.config, "service.json"), '{ "password": "A" }\n');
+ execFileSync("git", ["add", "-f", "service.json"], { cwd: a.config });
+ execFileSync("git", ["commit", "-qm", "old version"], { cwd: a.config });
+ execFileSync("git", ["push", "-q", "origin", "main"], { cwd: a.config });
+
+ useMachine(b);
+ await pull({ settings: settings(), roots: getRoots() });
+ expect(read(path.join(b.config, "service.json"))).toContain('"B"');
+
+ const c = makeMachine("c");
+ useMachine(c);
+ await pull({ settings: settings(), roots: getRoots() });
+ expect(fs.existsSync(path.join(c.config, "service.json"))).toBe(false);
+ });
+
+ it("never writes another machine's state service record or locks", async () => {
+ const a = makeMachine("a");
+ useMachine(a);
+ write(path.join(a.config, "opencode.jsonc"), "{}\n");
+ write(path.join(a.state, "model.json"), '{ "m": 1 }\n');
+ await push({ settings: settings(), roots: getRoots() });
+ write(path.join(a.config, "_state", "service.json"), '{ "password": "A" }\n');
+ execFileSync("git", ["add", "-f", "_state/service.json"], { cwd: a.config });
+ execFileSync("git", ["commit", "-qm", "old version"], { cwd: a.config });
+ execFileSync("git", ["push", "-q", "origin", "main"], { cwd: a.config });
+
+ const b = makeMachine("b");
+ useMachine(b);
+ write(path.join(b.state, "service.json"), '{ "password": "B" }\n');
+ write(path.join(b.state, "locks", "held.lock"), "1\n");
+ await pull({ settings: settings(), roots: getRoots() });
+
+ expect(read(path.join(b.state, "model.json"))).toContain('"m": 1');
+ expect(read(path.join(b.state, "service.json"))).toContain('"B"');
+ expect(fs.existsSync(path.join(b.state, "locks", "held.lock"))).toBe(true);
+ });
+
+ it("shares cli.json without this machine's plugin paths", async () => {
+ const a = makeMachine("a");
+ useMachine(a);
+ write(path.join(a.config, "opencode.jsonc"), "{}\n");
+ write(
+ path.join(a.config, "cli.json"),
+ JSON.stringify({
+ theme: "tokyonight",
+ plugins: [
+ "file:///C:/Users/fake/.config/opencode/plugins/x-tui/tui.js",
+ "some-npm-tui-plugin",
+ ],
+ }),
+ );
+ await push({ settings: settings(), roots: getRoots() });
+
+ const b = makeMachine("b");
+ useMachine(b);
+ await pull({ settings: settings(), roots: getRoots() });
+ const cli = JSON.parse(read(path.join(b.config, "cli.json")));
+ expect(cli).toEqual({ theme: "tokyonight", plugins: ["some-npm-tui-plugin"] });
+ });
+});