Branchwell

OpenTalon / app · opentalon.ai / native / migrate-installed.cjs

1// One-time cutover for the original macOS installation. The old app profile is
2// archived intact and its discovery path remains usable by installed MCP clients.
3const assert = require('node:assert/strict')
4const { execFileSync } = require('node:child_process')
5const { createHash, randomUUID } = require('node:crypto')
6const fs = require('node:fs')
7const os = require('node:os')
8const path = require('node:path')
9const { DatabaseSync, backup } = require('node:sqlite')
10const { setTimeout: pause } = require('node:timers/promises')
11const { Store } = require('./runtime/store.cjs')
12
13const support = process.env.OPENTALON_CUTOVER_TEST_SUPPORT ||
14 path.join(os.homedir(), 'Library', 'Application Support')
15const legacy = path.join(support, 'OpenTalon Prototype')
16const native = path.join(support, 'OpenTalon Native')
17const source = path.join(legacy, 'opentalon.sqlite')
18const configFile = path.join(legacy, 'mcp.json')
19
20function digest(db) {
21 const result = createHash('sha256')
22 assert.deepEqual(db.prepare('PRAGMA quick_check').get().quick_check, 'ok')
23 assert.equal(db.prepare('PRAGMA foreign_key_check').all().length, 0)
24 for (const { name, sql } of db.prepare(
25 "SELECT name, sql FROM sqlite_schema WHERE type='table' ORDER BY name"
26 ).all()) {
27 assert.match(name, /^[a-z_][a-z_0-9]*$/i)
28 result.update(sql || name)
29 for (const row of db.prepare(`SELECT * FROM "${name}" ORDER BY rowid`).iterate())
30 result.update(JSON.stringify(row)).update('\n')
31 }
32 return result.digest('hex')
33}
34
35function summary(db) {
36 const count = (table, filter = '') => db.prepare(`SELECT count(*) AS n FROM ${table} ${filter}`).get().n
37 return {
38 projects: count('boards'), liveTasks: count('tasks', 'WHERE deleted_at IS NULL'),
39 trash: count('tasks', 'WHERE deleted_at IS NOT NULL'), comments: count('task_comments'),
40 screenshots: count('comment_images'), runHistory: count('agent_jobs'),
41 }
42}
43
44function assertNoAgentRuns(db) {
45 assert.equal(db.prepare(`SELECT count(*) AS n FROM agent_jobs
46 WHERE json_extract(data,'$.state') IN ('queued','starting','working','needs-input')`).get().n, 0,
47 'Stop or finish active runs before switching the workspace.')
48}
49
50async function copyWorkspace(destination, exact) {
51 const db = new DatabaseSync(source, { readOnly: true })
52 try {
53 assertNoAgentRuns(db)
54 await backup(db, destination)
55 fs.chmodSync(destination, 0o600)
56 const clone = new DatabaseSync(destination, { readOnly: true })
57 try {
58 const hash = digest(clone)
59 if (exact) assert.equal(hash, digest(db), 'Workspace changed after the copy.')
60 return { ...summary(clone), checksum: hash }
61 } finally { clone.close() }
62 } finally { db.close() }
63}
64
65function writers() {
66 try {
67 return execFileSync('/usr/sbin/lsof', ['-t', source], { encoding: 'utf8' })
68 .trim().split(/\s+/).filter(Boolean).map(Number)
69 } catch (error) {
70 if (error.status === 1) return []
71 throw error
72 }
73}
74
75function verifyWriter(pid, executable) {
76 const real = fs.realpathSync(executable)
77 assert.match(real, /\/(Electron|OpenTalon)\.app\/Contents\/MacOS\/(Electron|OpenTalon)$/)
78 const processInfo = execFileSync('/usr/sbin/lsof', ['-a', '-p', String(pid), '-d', 'txt', '-Fn'],
79 { encoding: 'utf8' }).split('\n')
80 assert.ok(processInfo.includes('n' + real), 'An unexpected process owns the Electron database.')
81}
82
83function writeJSON(file, value) {
84 const temporary = file + '.' + randomUUID()
85 fs.writeFileSync(temporary, JSON.stringify(value) + '\n', { mode: 0o600, flag: 'wx' })
86 try { fs.renameSync(temporary, file) }
87 finally { if (fs.existsSync(temporary)) fs.unlinkSync(temporary) }
88}
89
90async function prepare(recovery) {
91 fs.mkdirSync(recovery, { mode: 0o700 })
92 const stage = path.join(recovery, 'portable-stage')
93 fs.mkdirSync(stage, { mode: 0o700 })
94 const result = await copyWorkspace(path.join(stage, 'opentalon.sqlite'), false)
95 const copy = new Store(stage)
96 try { await copy.createBackup(path.join(recovery, 'OpenTalon-before-native.json'), 'json') }
97 finally { copy.close() }
98 fs.writeFileSync(path.join(recovery, 'preflight.json'), JSON.stringify(result, null, 2) + '\n', { mode: 0o600 })
99 console.log(JSON.stringify({ recovery, ...result }))
100}
101
102async function switchProfiles(recovery, app) {
103 assert.ok(fs.existsSync(path.join(recovery, 'OpenTalon-before-native.json')), 'Run prepare first.')
104 assert.ok(!fs.existsSync(native), 'A native profile already exists; it will not be replaced.')
105 const executable = path.join(app, 'Contents', 'MacOS', 'OpenTalon')
106 fs.accessSync(executable, fs.constants.X_OK)
107 const previous = JSON.parse(fs.readFileSync(configFile, 'utf8'))
108 assert.equal(previous.profile, legacy)
109 const reader = new DatabaseSync(source, { readOnly: true })
110 try { assertNoAgentRuns(reader) } finally { reader.close() }
111 for (const pid of writers()) verifyWriter(pid, previous.executable)
112
113 const target = fs.mkdtempSync(path.join(support, '.OpenTalon-Native-'))
114 const stub = fs.mkdtempSync(path.join(support, '.OpenTalon-Retired-'))
115 const archive = path.join(support, `OpenTalon Electron Archive ${new Date().toISOString().replaceAll(':', '-')}`)
116 let oldMoved = false
117 let targetMoved = false
118 let stubMoved = false
119 try {
120 // Prevent old stdio clients from restarting Electron between shutdown and cutover.
121 writeJSON(configFile, { ...previous, enabled: false, port: 0 })
122 for (const pid of writers()) {
123 verifyWriter(pid, previous.executable)
124 process.kill(pid, 'SIGTERM')
125 }
126 for (let attempt = 0; attempt < 60 && writers().length > 0; attempt++) await pause(100)
127 assert.deepEqual(writers(), [], 'Electron is still using the workspace. Quit it before retrying.')
128 writeJSON(configFile, { ...previous, enabled: false, port: 0 })
129 const result = await copyWorkspace(path.join(target, 'opentalon.sqlite'), true)
130 fs.copyFileSync(path.join(target, 'opentalon.sqlite'), path.join(recovery, 'OpenTalon-final.sqlite'),
131 fs.constants.COPYFILE_EXCL)
132 fs.chmodSync(path.join(recovery, 'OpenTalon-final.sqlite'), 0o600)
133 writeJSON(path.join(target, 'mcp.json'), {
134 enabled: previous.enabled === true, token: previous.token, port: 0,
135 executable, launchArgs: [], profile: native,
136 })
137 fs.writeFileSync(path.join(stub, 'opentalon.sqlite'),
138 'The original OpenTalon workspace has moved to the native Swift app. This is not a database.\n',
139 { mode: 0o600 })
140 fs.symlinkSync(path.join(native, 'mcp.json'), path.join(stub, 'mcp.json'))
141 fs.writeFileSync(path.join(stub, 'README.txt'),
142 `OpenTalon's single active workspace is now at:\n${native}\n\nThe archived Electron profile is at:\n${archive}\n`,
143 { mode: 0o600 })
144 assert.deepEqual(writers(), [], 'The Electron workspace reopened. Retry the cutover.')
145 assert.ok(!fs.existsSync(native), 'A native workspace opened during migration.')
146 fs.renameSync(legacy, archive)
147 oldMoved = true
148 writeJSON(path.join(archive, 'mcp.json'), { ...previous, enabled: false, port: 0 })
149 fs.renameSync(target, native)
150 targetMoved = true
151 fs.renameSync(stub, legacy)
152 stubMoved = true
153 const receipt = { ...result, archive, profile: native, legacyDiscovery: 'redirected to native' }
154 writeJSON(path.join(recovery, 'cutover.json'), receipt)
155 console.log(JSON.stringify(receipt))
156 } catch (error) {
157 if (stubMoved) fs.renameSync(legacy, stub)
158 if (targetMoved) fs.renameSync(native, target)
159 if (oldMoved) fs.renameSync(archive, legacy)
160 writeJSON(configFile, previous)
161 throw error
162 } finally {
163 // These paths are private staging directories created by this invocation.
164 fs.rmSync(target, { recursive: true, force: true })
165 fs.rmSync(stub, { recursive: true, force: true })
166 }
167}
168
169async function main() {
170 const [mode, recovery, app] = process.argv.slice(2)
171 assert.ok(recovery && path.isAbsolute(recovery), 'Supply a private recovery folder on Expand.')
172 if (mode === 'prepare') await prepare(recovery)
173 else if (mode === 'switch') {
174 assert.ok(app && path.isAbsolute(app), 'Supply the verified native app bundle.')
175 await switchProfiles(recovery, app)
176 } else throw new Error('Use prepare <recovery folder> or switch <recovery folder> <native app>.')
177}
178
179main().catch((error) => {
180 console.error(error.message)
181 process.exitCode = 1
182})