Branchwell

OpenTalon / app · opentalon.ai / native / runtime / store.cjs

Raw 113.9 KB on d82caf36fa99426fea138f030e7704d2b3cf17b3
1const { DatabaseSync, backup } = require('node:sqlite')
2const fs = require('node:fs')
3const path = require('node:path')
4const { randomUUID, createHash } = require('node:crypto')
5const { AppError, validateAction, boardIcons, agentModels } = require('./contracts.cjs')
6const { defaultsVersion, validateModelOverrides, mergeAgentModels, agentNames, agentIds } = require('./agent-models.cjs')
7const {
8 comments,
9 insertComment,
10 exportComments,
11 validateComments,
12 restoreComments,
13 revisionIdPattern,
14} = require('./comments.cjs')
15
16const taskHistory = require('./task-history.cjs')
17const taskActivity = require('./task-activity.cjs')
18const taskFiles = require('./task-files.cjs')
19const FORMAT = 14
20// Older connectors copied Markdown documents into notes with explicit delimiters.
21// Recover only complete blocks; never read a referenced filesystem path.
22function legacyPlan(notes) {
23 let latest = '', current = null, fence = null
24 for (const line of (notes || '').match(/[^\n]*\n|[^\n]+$/g) || []) {
25 const text = line.replace(/\r?\n$/, '')
26 if (fence) {
27 if (current) current.push(line)
28 if (new RegExp('^ {0,3}' + fence.marker + '{' + fence.length + ',}[ \\t]*$').test(text)) fence = null
29 continue
30 }
31 const opening = text.match(/^ {0,3}(`{3,}|~{3,})/)
32 if (opening) {
33 fence = { marker: opening[1][0], length: opening[1].length }
34 if (current) current.push(line)
35 } else if (/^--- Plan: [^\r\n]+\.md[^\r\n]* ---[ \t]*$/.test(text)) current = []
36 else if (/^--- End plan ---[ \t]*$/.test(text) && current) {
37 const markdown = current.join('')
38 if (markdown.trim() && markdown.length <= 100000 && markdown.isWellFormed() && !markdown.includes('\0')) latest = markdown
39 current = null
40 } else if (current) current.push(line)
41 }
42 return latest
43}
44const archiveAfterMs = 7 * 24 * 60 * 60 * 1000
45const taskKeyPattern = /^[A-Z]{3}-[0-9]{3,16}$/
46const defaultAgentSettings = { defaultAgent: 'codex', workingFolder: '' }
47const activeRunStates = ['queued', 'starting', 'working', 'needs-input']
48const recoverableRunStates = ['waiting-input', 'review', 'failed', 'interrupted']
49const withdrawalMemoryMs = 30 * 24 * 60 * 60 * 1000
50function validDueDate(value) {
51 if (value === null) return true
52 if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false
53 const date = new Date(`${value}T00:00:00Z`)
54 return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value
55}
56const priorities = ['Urgent', 'High', 'Medium', 'Low', 'None']
57const taskSelect = `SELECT tasks.*,
58 (SELECT count(*) FROM task_comments WHERE task_id=tasks.id AND json_extract(data,'$.source')='user') AS comment_count,
59 (SELECT count(*) FROM comment_images JOIN task_comments ON task_comments.id=comment_images.comment_id WHERE task_comments.task_id=tasks.id) AS image_count
60 FROM tasks`
61const APPLICATION_ID = 0x4f54414c
62const legacyStatuses = ['To do', 'In progress', 'Done']
63const statuses = ['To do', 'Sent to agent', 'In progress', 'Done']
64const themes = ['graphite', 'warm-paper', 'native-light', 'system']
65const hash = (value) => createHash('sha256').update(value).digest('hex')
66async function fileHash(file) {
67 const digest = createHash('sha256')
68 for await (const chunk of fs.createReadStream(file)) digest.update(chunk)
69 return digest.digest('hex')
70}
71function canonical(value) {
72 if (Array.isArray(value)) return value.map(canonical)
73 if (value && typeof value === 'object')
74 return Object.fromEntries(
75 Object.keys(value)
76 .sort()
77 .map((key) => [key, canonical(value[key])])
78 )
79 return value
80}
81const argumentHash = (value) => hash(JSON.stringify(canonical(value)))
82const text = (value, name) => {
83 const result = value.trim()
84 if (!result) throw new AppError('INVALID_ARGUMENT', `${name} cannot be blank.`)
85 return result
86}
87function absolute(value) {
88 if (!path.isAbsolute(value) || value.includes('\0'))
89 throw new AppError('INVALID_PATH', 'Choose an absolute backup file path.')
90 return path.normalize(value)
91}
92function taskView(row) {
93 return {
94 id: row.id,
95 taskKey: row.task_key ?? null,
96 boardId: row.board_id,
97 title: row.title,
98 notes: row.notes,
99 planMarkdown: row.plan_markdown || '',
100 issueType: row.issue_type || 'Issue',
101 status: row.status,
102 priority: row.priority || 'None',
103 definitionOfDone: row.definition_of_done || '',
104 dueDate: row.due_date || null,
105 commentCount: row.comment_count || 0,
106 imageCount: row.image_count || 0,
107 position: row.position,
108 deleted: row.deleted_at !== null,
109 deletedAt: row.deleted_at,
110 completedAt: row.completed_at ?? null,
111 archivedAt: row.archived_at ?? null,
112 createdAt: row.created_at,
113 updatedAt: row.updated_at,
114 revision: row.revision,
115 }
116}
117function boardView(row, icons = {}) {
118 return {
119 id: row.id,
120 name: row.name,
121 icon: boardIcons.includes(icons[row.id]) ? icons[row.id] : null,
122 position: row.position,
123 createdAt: row.created_at,
124 revision: row.revision,
125 }
126}
127// Obvious name matches only; anything else keeps the default icon until someone picks one.
128const iconHints = [
129 ['house', /\b(home|house|hoa|family)\b/],
130 ['briefcase', /\b(career|work|job|consulting|clients?|business)\b/],
131 ['user', /\b(personal|me|private)\b/],
132 ['wallet', /\b(finances?|money|budget|bills?|tax(es)?)\b/],
133 ['chart-line', /\b(analytics|metrics|portfolio|reports?|stats)\b/],
134 ['server', /\b(infrastructure|infra|servers?|devops|hosting|automation)\b/],
135 ['plug', /\b(mcp|integrations?|connectors?|plugins?|api)\b/],
136 ['bot', /\b(ai|agents?|bots?|llm)\b/],
137 ['megaphone', /\b(marketing|ads?|campaigns?|launch|promo)\b/],
138 ['newspaper', /\b(newsletter|news|blog|brief|press)\b/],
139 ['plane', /\b(travel|trips?|vacation|flights?)\b/],
140 ['book-open', /\b(reading|books?|study|learning|research)\b/],
141 ['notebook-pen', /\b(notes?|journal|writing|drafts?)\b/],
142 ['palette', /\b(design|art|brand|creative)\b/],
143 ['video', /\b(video|film|youtube|reel)\b/],
144 ['music', /\b(music|songs?|audio|album)\b/],
145 ['mic', /\b(podcast|interviews?)\b/],
146 ['code', /\b(code|dev|development|engineering|software)\b/],
147 ['globe', /\b(website|web|site|seo)\b/],
148 ['shopping-cart', /\b(shopping|store|shop|orders?)\b/],
149 ['leaf', /\b(garden|plants?|yard)\b/],
150 ['dumbbell', /\b(fitness|gym|health|workouts?)\b/],
151 ['utensils', /\b(recipes?|meals?|food|cooking)\b/],
152 ['graduation-cap', /\b(school|class|course|university)\b/],
153 ['lightbulb', /\b(ideas?|someday|brainstorm)\b/],
154 ['inbox', /\b(inbox|triage|backlog)\b/],
155]
156function suggestBoardIcon(name) {
157 const lower = String(name).toLowerCase()
158 return iconHints.find(([, pattern]) => pattern.test(lower))?.[0] || null
159}
160
161class Store {
162 constructor(folder, { version = '0.1.0', changed = () => {}, agentReadiness = () => {} } = {}) {
163 // The runner replaces this. Without one, an active turn is assumed to hold its requests.
164 this.agentTurn = () => 'sent'
165 this.folder = folder
166 this.file = path.join(folder, 'opentalon.sqlite')
167 this.version = version
168 this.changed = changed
169 this.agentReadiness = agentReadiness
170 this.previews = new Map()
171 this.queue = Promise.resolve()
172 fs.mkdirSync(folder, { recursive: true, mode: 0o700 })
173 fs.chmodSync(folder, 0o700)
174 const existed = fs.existsSync(this.file)
175 this.db = new DatabaseSync(this.file)
176 try {
177 this.db.exec('PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;')
178 const current = this.db.prepare('PRAGMA user_version').get().user_version
179 if (current > FORMAT)
180 throw new AppError(
181 'NEWER_DATABASE',
182 'This database needs a newer OpenTalon. Your existing data has not been replaced.'
183 )
184 if (
185 existed &&
186 (!current ||
187 this.db.prepare('PRAGMA application_id').get().application_id !== APPLICATION_ID)
188 )
189 throw new AppError(
190 'INVALID_DATABASE',
191 'The existing file is not a supported OpenTalon database. It has not been replaced.'
192 )
193 if (this.db.prepare('PRAGMA quick_check').get().quick_check !== 'ok')
194 throw new AppError(
195 'DAMAGED_DATABASE',
196 'SQLite found a problem in the existing database. It has not been replaced.'
197 )
198 if (!current) this.migrate()
199 if (current < 2) this.migrateAgents()
200 if (current < 3) this.migrateComments()
201 if (current < 4) this.migratePriorities()
202 if (current < 5) this.migrateDueDates()
203 if (current < 6) this.migrateTaskKeys()
204 if (current < 7) this.migrateArchive()
205 if (current < 8) this.migratePlans()
206 if (current < 9) this.migrateIssueTypes()
207 if (current < 10) taskHistory.migrate(this)
208 if (current < 11) taskActivity.migrate(this)
209 this.activityReady = true
210 if (current < 12) this.migrateLegacyPlans()
211 if (current < 13) {
212 this.db.exec('BEGIN IMMEDIATE')
213 try {
214 this.db.prepare('INSERT INTO schema_migrations VALUES (?,?)').run(13, new Date().toISOString())
215 this.db.exec('PRAGMA user_version=13; COMMIT;')
216 } catch (error) { this.db.exec('ROLLBACK'); throw error }
217 }
218 if (current < 14) taskFiles.migrate(this)
219 this.db.exec('PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;')
220 fs.chmodSync(this.file, 0o600)
221 } catch (error) {
222 this.db.close()
223 throw error
224 }
225 }
226 migrate() {
227 this.db.exec(`BEGIN IMMEDIATE;
228 CREATE TABLE boards (id TEXT PRIMARY KEY, name TEXT NOT NULL CHECK(length(trim(name)) BETWEEN 1 AND 100), position INTEGER NOT NULL, created_at TEXT NOT NULL, revision INTEGER NOT NULL CHECK(revision>0)) STRICT;
229 CREATE TABLE tasks (id TEXT PRIMARY KEY, board_id TEXT NOT NULL REFERENCES boards(id) ON DELETE RESTRICT, title TEXT NOT NULL CHECK(length(trim(title)) BETWEEN 1 AND 500), notes TEXT NOT NULL CHECK(length(notes)<=100000), status TEXT NOT NULL CHECK(status IN ('To do','In progress','Done')), position INTEGER NOT NULL CHECK(position>=0), created_at TEXT NOT NULL, updated_at TEXT NOT NULL, deleted_at TEXT, revision INTEGER NOT NULL CHECK(revision>0)) STRICT;
230 CREATE INDEX tasks_board_order ON tasks(board_id,deleted_at,status,position,id);
231 CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL) STRICT;
232 CREATE TABLE operation_receipts (request_key TEXT PRIMARY KEY, argument_hash TEXT NOT NULL, result TEXT NOT NULL) STRICT;
233 CREATE TABLE schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL) STRICT;
234 PRAGMA application_id=${APPLICATION_ID}; PRAGMA user_version=1;`)
235 const id = randomUUID()
236 try {
237 this.db
238 .prepare('INSERT INTO boards VALUES (?,?,?,?,?)')
239 .run(id, 'Tasks', 0, new Date().toISOString(), 1)
240 for (const [key, value] of Object.entries({
241 theme: 'system',
242 selectedBoard: id,
243 revision: 1,
244 preferencesRevision: 1,
245 prototypeImported: false,
246 }))
247 this.set(key, value)
248 this.db.prepare('INSERT INTO schema_migrations VALUES (?,?)').run(1, new Date().toISOString())
249 this.db.exec('COMMIT')
250 } catch (error) {
251 this.db.exec('ROLLBACK')
252 throw error
253 }
254 }
255 close() {
256 this.db.close()
257 }
258 migratePriorities() {
259 this.db.exec('BEGIN IMMEDIATE')
260 try {
261 this.db.exec(
262 "ALTER TABLE tasks ADD COLUMN priority TEXT NOT NULL DEFAULT 'None' CHECK(priority IN ('Urgent','High','Medium','Low','None')); ALTER TABLE tasks ADD COLUMN definition_of_done TEXT NOT NULL DEFAULT '' CHECK(length(definition_of_done)<=10000); PRAGMA user_version=4;"
263 )
264 this.db.prepare('INSERT INTO schema_migrations VALUES (?,?)').run(4, new Date().toISOString())
265 this.db.exec('COMMIT')
266 } catch (error) {
267 this.db.exec('ROLLBACK')
268 throw error
269 }
270 }
271 migrateDueDates() {
272 this.db.exec('BEGIN IMMEDIATE')
273 try {
274 this.db.exec(
275 'ALTER TABLE tasks ADD COLUMN due_date TEXT CHECK(due_date IS NULL OR length(due_date)=10); PRAGMA user_version=5;'
276 )
277 this.db.prepare('INSERT INTO schema_migrations VALUES (?,?)').run(5, new Date().toISOString())
278 this.db.exec('COMMIT')
279 } catch (error) {
280 this.db.exec('ROLLBACK')
281 throw error
282 }
283 }
284 migrateTaskKeys() {
285 this.db.exec('BEGIN IMMEDIATE')
286 try {
287 this.db.exec(`
288 ALTER TABLE boards ADD COLUMN project_key TEXT;
289 ALTER TABLE boards ADD COLUMN next_task_number INTEGER NOT NULL DEFAULT 1;
290 ALTER TABLE tasks ADD COLUMN task_key TEXT;
291 CREATE UNIQUE INDEX boards_project_key ON boards(project_key);
292 CREATE UNIQUE INDEX tasks_task_key ON tasks(task_key);
293 PRAGMA user_version=6;
294 `)
295 this.backfillTaskKeys()
296 this.db.prepare('INSERT INTO schema_migrations VALUES (?,?)').run(6, new Date().toISOString())
297 this.db.exec('COMMIT')
298 } catch (error) {
299 this.db.exec('ROLLBACK')
300 throw error
301 }
302 }
303
304 migrateArchive() {
305 this.db.exec('BEGIN IMMEDIATE')
306 try {
307 this.db.exec(`
308 ALTER TABLE tasks ADD COLUMN completed_at TEXT;
309 ALTER TABLE tasks ADD COLUMN archived_at TEXT;
310 UPDATE tasks SET completed_at=updated_at WHERE status='Done';
311 CREATE TRIGGER tasks_record_completion_on_insert AFTER INSERT ON tasks
312 WHEN NEW.status='Done' AND NEW.completed_at IS NULL
313 BEGIN
314 UPDATE tasks SET completed_at=NEW.updated_at WHERE id=NEW.id;
315 END;
316 CREATE TRIGGER tasks_record_completion_on_move AFTER UPDATE OF status ON tasks
317 WHEN OLD.status<>NEW.status
318 BEGIN
319 UPDATE tasks SET completed_at=CASE WHEN NEW.status='Done' THEN NEW.updated_at END,
320 archived_at=NULL WHERE id=NEW.id;
321 END;
322 PRAGMA user_version=7;
323 `)
324 this.db.prepare('INSERT INTO schema_migrations VALUES (?,?)').run(7, new Date().toISOString())
325 this.db.exec('COMMIT')
326 } catch (error) {
327 this.db.exec('ROLLBACK')
328 throw error
329 }
330 }
331
332 migratePlans() {
333 this.db.exec('BEGIN IMMEDIATE')
334 try {
335 this.db.exec("ALTER TABLE tasks ADD COLUMN plan_markdown TEXT NOT NULL DEFAULT '' CHECK(length(plan_markdown)<=100000); PRAGMA user_version=8;")
336 this.db.prepare('INSERT INTO schema_migrations VALUES (?,?)').run(8, new Date().toISOString())
337 this.db.exec('COMMIT')
338 } catch (error) {
339 this.db.exec('ROLLBACK')
340 throw error
341 }
342 }
343
344 migrateIssueTypes() {
345 this.db.exec('BEGIN IMMEDIATE')
346 try {
347 this.db.exec("ALTER TABLE tasks ADD COLUMN issue_type TEXT NOT NULL DEFAULT 'Issue' CHECK(issue_type IN ('Issue','Bug')); PRAGMA user_version=9;")
348 this.db.prepare('INSERT INTO schema_migrations VALUES (?,?)').run(9, new Date().toISOString())
349 this.db.exec('COMMIT')
350 } catch (error) {
351 this.db.exec('ROLLBACK')
352 throw error
353 }
354 }
355
356 migrateLegacyPlans() {
357 this.db.exec('BEGIN IMMEDIATE')
358 try {
359 const revision = this.revision() + 1
360 let recovered = 0
361 for (const row of this.db.prepare("SELECT id,notes FROM tasks WHERE plan_markdown=''").all()) {
362 const markdown = legacyPlan(row.notes)
363 if (!markdown) continue
364 this.db.prepare('UPDATE tasks SET plan_markdown=? WHERE id=?').run(markdown, row.id)
365 const task = this.saveTask(this.task(row.id), revision)
366 taskHistory.record(this, task, 'recover_task_plan', 'OpenTalon')
367 recovered++
368 }
369 if (recovered) this.set('revision', revision)
370 this.db.exec('PRAGMA user_version=12')
371 this.db.prepare('INSERT INTO schema_migrations VALUES (?,?)').run(12, new Date().toISOString())
372 this.db.exec('COMMIT')
373 } catch (error) { this.db.exec('ROLLBACK'); throw error }
374 }
375
376 archiveCompletedTasks(now = new Date()) {
377 const cutoff = new Date(now.getTime() - archiveAfterMs).toISOString()
378 this.db.exec('BEGIN IMMEDIATE')
379 const revision = this.revision() + 1
380 let count
381 try {
382 const result = this.db.prepare(`
383 UPDATE tasks SET archived_at=?,revision=?
384 WHERE status='Done' AND deleted_at IS NULL AND archived_at IS NULL
385 AND julianday(completed_at)<=julianday(?)
386 `).run(now.toISOString(), revision, cutoff)
387 count = result.changes
388 if (count) {
389 taskHistory.recordRevision(this, revision, 'automatic_archive', 'OpenTalon')
390 this.set('revision', revision)
391 }
392 this.db.exec('COMMIT')
393 } catch (error) {
394 this.db.exec('ROLLBACK')
395 throw error
396 }
397 if (count) this.changed(revision)
398 return count
399 }
400
401 scheduleAutoArchive() {
402 this.archiveCompletedTasks()
403 const timer = setInterval(() => {
404 try { this.archiveCompletedTasks() }
405 catch (error) { console.error('OpenTalon automatic archive:', error.message) }
406 }, 60_000)
407 timer.unref()
408 return timer
409 }
410
411 allocateProjectKey(id, name) {
412 const stem = name.normalize('NFKD').toUpperCase().replace(/[^A-Z]/g, '').slice(0, 3).padEnd(3, 'X')
413 const occupied = new Set(this.db.prepare(`
414 SELECT project_key AS key FROM boards WHERE project_key IS NOT NULL
415 UNION SELECT substr(task_key,1,3) FROM tasks WHERE task_key IS NOT NULL
416 `).all().map(({ key }) => key))
417 const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
418 let key = [stem, ...Array.from(letters, (letter) => stem.slice(0, 2) + letter)]
419 .find((candidate) => !occupied.has(candidate))
420 for (let index = 0; !key && index < 26 ** 3; index++) {
421 const candidate = letters[Math.floor(index / 676)] + letters[Math.floor(index / 26) % 26] + letters[index % 26]
422 if (!occupied.has(candidate)) key = candidate
423 }
424 if (!key) throw new AppError('PROJECT_KEY_LIMIT', 'No project keys are available.')
425 this.db.prepare('UPDATE boards SET project_key=? WHERE id=?').run(key, id)
426 }
427
428 assignTaskKey(id, boardId) {
429 const board = this.db.prepare('SELECT project_key,next_task_number FROM boards WHERE id=?').get(boardId)
430 const number = board.next_task_number
431 const key = board.project_key + '-' + String(number).padStart(3, '0')
432 this.db.prepare('UPDATE tasks SET task_key=? WHERE id=?').run(key, id)
433 this.db.prepare('UPDATE boards SET next_task_number=? WHERE id=?').run(number + 1, boardId)
434 }
435
436 backfillTaskKeys() {
437 for (const { id, name } of this.db.prepare('SELECT id,name FROM boards WHERE project_key IS NULL ORDER BY created_at,id').all())
438 this.allocateProjectKey(id, name)
439 for (const { id, board_id } of this.db.prepare('SELECT id,board_id FROM tasks WHERE task_key IS NULL ORDER BY created_at,rowid').all())
440 this.assignTaskKey(id, board_id)
441 }
442 migrateAgents() {
443 this.db.exec(`BEGIN IMMEDIATE;
444 ALTER TABLE tasks RENAME TO tasks_v1;
445 DROP INDEX tasks_board_order;
446 CREATE TABLE tasks (id TEXT PRIMARY KEY, board_id TEXT NOT NULL REFERENCES boards(id) ON DELETE RESTRICT, title TEXT NOT NULL CHECK(length(trim(title)) BETWEEN 1 AND 500), notes TEXT NOT NULL CHECK(length(notes)<=100000), status TEXT NOT NULL CHECK(status IN ('To do','Sent to agent','In progress','Done')), position INTEGER NOT NULL CHECK(position>=0), created_at TEXT NOT NULL, updated_at TEXT NOT NULL, deleted_at TEXT, revision INTEGER NOT NULL CHECK(revision>0)) STRICT;
447 INSERT INTO tasks SELECT * FROM tasks_v1;
448 DROP TABLE tasks_v1;
449 CREATE INDEX tasks_board_order ON tasks(board_id,deleted_at,status,position,id);
450 CREATE TABLE agent_jobs (id TEXT PRIMARY KEY, task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE, data TEXT NOT NULL) STRICT;
451 PRAGMA user_version=2;`)
452 try {
453 this.db.prepare('INSERT INTO schema_migrations VALUES (?,?)').run(2, new Date().toISOString())
454 this.db.exec('COMMIT')
455 } catch (error) {
456 this.db.exec('ROLLBACK')
457 throw error
458 }
459 }
460 agentSettings(boardId) {
461 const settings = this.get('agentSettings') || defaultAgentSettings
462 return {
463 ...settings,
464 workingFolder: (boardId && this.get('projectFolders')?.[boardId]) || settings.workingFolder,
465 permissionMode: this.get('agentPermissionMode') ?? 'auto',
466 }
467 }
468 projectFolder(id) {
469 const board = this.board(id)
470 return { boardId: id, workingFolder: this.get('projectFolders')?.[id] ?? '',
471 effectiveFolder: this.agentSettings(id).workingFolder, revision: board.revision }
472 }
473 agentModelCatalog() {
474 const overrides = validateModelOverrides(this.get('agentModelOverrides') ?? [])
475 const models = mergeAgentModels(agentModels, overrides)
476 // Google's CLI lists the entitled models in account order. Match only offered catalog entries.
477 // Explicit task choices and an owner's customized Google catalog retain their original behavior.
478 if (this.googleAccountModels?.length && !overrides.some(entry => entry.agent === 'gemini')) {
479 const first = models.findIndex(entry => entry.agent === 'gemini')
480 const entitled = this.googleAccountModels.find(id => models.some(entry => entry.agent === 'gemini' && entry.id === id))
481 const preferred = models.findIndex(entry => entry.agent === 'gemini' && entry.id === entitled)
482 if (preferred > first && first >= 0) models.splice(first, 0, models.splice(preferred, 1)[0])
483 }
484 return {
485 models, defaults: agentModels,
486 defaultsVersion, overrides, catalogRevision: this.get('agentModelCatalogRevision') ?? 1,
487 }
488 }
489 agentAssignments() {
490 return this.get('agentAssignments') || {}
491 }
492 assignedRun(taskId) {
493 return this.agentAssignments()[taskId] || null
494 }
495 assignAgent(taskId, runId) {
496 const assignments = this.agentAssignments()
497 if (runId) assignments[taskId] = runId
498 else delete assignments[taskId]
499 this.set('agentAssignments', assignments)
500 }
501 migrateComments() {
502 this.db.exec(`BEGIN IMMEDIATE;
503 CREATE TABLE task_comments (id TEXT PRIMARY KEY, task_id TEXT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE, data TEXT NOT NULL) STRICT;
504 CREATE INDEX comments_task ON task_comments(task_id);
505 CREATE TABLE comment_images (id TEXT PRIMARY KEY, comment_id TEXT NOT NULL REFERENCES task_comments(id) ON DELETE CASCADE, name TEXT NOT NULL, mime_type TEXT NOT NULL, bytes BLOB NOT NULL) STRICT;
506 PRAGMA user_version=3;`)
507 try {
508 this.db.prepare('INSERT INTO schema_migrations VALUES (?,?)').run(3, new Date().toISOString())
509 this.db.exec('COMMIT')
510 } catch (error) {
511 this.db.exec('ROLLBACK')
512 throw error
513 }
514 }
515 comments(taskId) {
516 return comments(this, taskId)
517 }
518 validateRevisionReceipts(taskId, ids) {
519 if (!ids.length) return
520 const valid = new Set(this.comments(taskId).filter((request) => request.source === 'user').map((request) => request.id))
521 const withdrawn = ids.find((id) => !valid.has(id) && this.withdrawnRevision(id)?.taskId === taskId)
522 if (withdrawn)
523 throw new AppError('WITHDRAWN', `The user withdrew revision request ${withdrawn}. Leave it out of the requests you acted on.`)
524 if (ids.some((id) => !valid.has(id)))
525 throw new AppError('NOT_FOUND', 'Choose revision requests on this task.')
526 }
527 markRevisionRequestsActedOn(ids, activityID) {
528 if (!ids.length) return
529 const update = this.db.prepare("UPDATE task_comments SET data=json_set(data,'$.actedOnActivityID',?,'$.delivery','delivered') WHERE id=?")
530 for (const id of ids) update.run(activityID, id)
531 }
532 flagUnconfirmedRevisionRequests(job) {
533 if (!job.requiresRevisionReceipts || !job.commentIds?.length) return
534 const update = this.db.prepare(`UPDATE task_comments SET data=json_set(data,'$.delivery','needs-review')
535 WHERE id=? AND json_extract(data,'$.runId')=? AND json_extract(data,'$.actedOnActivityID') IS NULL`)
536 for (const id of job.commentIds) update.run(id, job.id)
537 }
538 commentImage(id) {
539 const image = this.db.prepare('SELECT * FROM comment_images WHERE id=?').get(id) || this.db.prepare('SELECT * FROM activity_images WHERE id=?').get(id)
540 if (!image) throw new AppError('NOT_FOUND', 'This screenshot no longer exists.')
541 return {
542 id: image.id,
543 name: image.name,
544 mimeType: image.mime_type,
545 data: Buffer.from(image.bytes).toString('base64'),
546 }
547 }
548 setCommentDelivery(runId, delivery, pickedUpAt) {
549 for (const row of this.db.prepare('SELECT id,data FROM task_comments').all()) {
550 const comment = JSON.parse(row.data)
551 if (comment.runId === runId && comment.delivery === 'queued')
552 this.db
553 .prepare('UPDATE task_comments SET data=? WHERE id=?')
554 .run(JSON.stringify({ ...comment, delivery, pickedUpAt }), row.id)
555 }
556 }
557 markPendingCommentsForReview(taskId) {
558 this.db.prepare(`
559 UPDATE task_comments SET data=json_set(data, '$.delivery', 'needs-review')
560 WHERE task_id=? AND json_extract(data, '$.delivery')='pending'
561 `).run(taskId)
562 }
563 withdrawnRevision(id) {
564 return (this.get('withdrawnRevisions') || {})[id] || null
565 }
566 // Remembers a withdrawal whose revision request has not reached this Mac yet.
567 rememberWithdrawnRevision(id, taskId) {
568 const now = Date.now()
569 const kept = Object.entries(this.get('withdrawnRevisions') || {})
570 .filter(([, entry]) => now - Date.parse(entry.at) < withdrawalMemoryMs)
571 .slice(-999)
572 this.set('withdrawnRevisions', Object.fromEntries([...kept, [id, { taskId, at: new Date(now).toISOString() }]]))
573 }
574 revisionRequestRow(id) {
575 const find = this.db.prepare('SELECT * FROM task_comments WHERE id=?')
576 const row = find.get(id)
577 if (row || !revisionIdPattern.test(id.toLowerCase())) return row
578 // An earlier Mac version saved phone requests under its own ID. Its receipt still names the request.
579 const receipt = this.db.prepare('SELECT result FROM operation_receipts WHERE request_key=?')
580 .get('phone:' + id.toUpperCase())
581 const saved = receipt && JSON.parse(receipt.result).comment?.id
582 return find.get(id.toLowerCase()) || (saved ? find.get(saved) : undefined)
583 }
584 withdrawRevisionRequest(a, origin) {
585 const task = this.task(a.taskId)
586 const row = this.revisionRequestRow(a.id)
587 if (!row) {
588 const id = a.id.toLowerCase()
589 if (!revisionIdPattern.test(id))
590 throw new AppError('NOT_FOUND', 'This revision request no longer exists.')
591 const known = this.withdrawnRevision(id)
592 if (known && known.taskId !== task.id)
593 throw new AppError('NOT_FOUND', 'This revision request is not on this task.')
594 if (!known) this.rememberWithdrawnRevision(id, task.id)
595 return { withdrawn: true, id, received: false }
596 }
597 const data = JSON.parse(row.data)
598 // Only the user's own requests on the named task can be withdrawn.
599 if (row.task_id !== task.id || data.source !== 'user')
600 throw new AppError('NOT_FOUND', 'This revision request is not on this task.')
601 const requests = this.comments(task.id)
602 if (data.actedOnActivityID || requests.find((request) => request.id === row.id)?.actedOnAt)
603 throw new AppError('INVALID_STATE', 'The agent already acted on this revision request. Its work remains in Activity.')
604 const jobRow = data.runId && this.db.prepare('SELECT data FROM agent_jobs WHERE id=? AND task_id=?').get(data.runId, task.id)
605 const job = jobRow ? JSON.parse(jobRow.data) : null
606 let run
607 // A finished run needs nothing: the request was never acted on, and removing it keeps it out of later turns.
608 if (job && activeRunStates.includes(job.state)) {
609 const carried = job.commentIds || (job.dispatchCommentId ? [job.dispatchCommentId] : [])
610 const outstanding = requests.some((request) =>
611 request.id !== row.id && carried.includes(request.id) && !request.actedOnAt)
612 // A follow-up turn exists only to deliver revision requests. Other turns also carry the task itself.
613 const revisionTurn = !!job.resumeThread && !job.resumeMessage && !job.externalTurn && !job.dispatchCommentId
614 const onlyThisRequest = revisionTurn && !outstanding
615 const sent = job.state !== 'queued' && (job.externalTurn || this.agentTurn(job.id) !== 'unsent')
616 const { dispatchCommentId, ...rest } = job
617 const next = {
618 ...(dispatchCommentId === row.id ? rest : job),
619 commentIds: carried.filter((id) => id !== row.id),
620 ...(onlyThisRequest ? { withdrawal: { at: new Date().toISOString() } } : {}),
621 // The agent already holds this text alongside other work, so its run is told to skip it.
622 ...(sent && !onlyThisRequest
623 ? { withdrawnRequests: [...(job.withdrawnRequests || []), { id: row.id, text: data.text, at: new Date().toISOString() }] }
624 : {}),
625 }
626 if (onlyThisRequest && job.state === 'queued') this.endWithdrawnRun(next)
627 else {
628 this.saveAgentJob(next, { activity: false })
629 if (onlyThisRequest) run = { id: job.id, stop: true }
630 else if (sent) run = { id: job.id, notify: { id: row.id, text: data.text } }
631 }
632 }
633 this.db.prepare('DELETE FROM comment_images WHERE comment_id=?').run(row.id)
634 this.db.prepare('DELETE FROM task_comments WHERE id=?').run(row.id)
635 // The request may still be in transit under its device ID after an earlier Mac version saved it.
636 if (revisionIdPattern.test(a.id.toLowerCase())) this.rememberWithdrawnRevision(a.id.toLowerCase(), task.id)
637 if (this.activityReady)
638 taskActivity.record(this, task.id, {
639 actor: origin.startsWith('You') ? origin : 'You',
640 kind: 'comment',
641 summary: 'Withdrew a revision request',
642 detail: data.text,
643 })
644 return { withdrawn: true, id: row.id, received: true, ...(run ? { run } : {}) }
645 }
646 // What a task's own active run must hear about requests withdrawn after it received them.
647 withdrawalNotice(taskId) {
648 const runId = this.assignedRun(taskId)
649 const row = runId && this.db.prepare('SELECT data FROM agent_jobs WHERE id=? AND task_id=?').get(runId, taskId)
650 const job = row ? JSON.parse(row.data) : null
651 if (!job?.withdrawnRequests?.length || ![...activeRunStates, 'waiting-input'].includes(job.state)) return {}
652 return {
653 withdrawnRevisionRequests: job.withdrawnRequests,
654 withdrawalNotice: 'The user withdrew these revision requests after this run received them. Do not start or continue work on them, and do not list them as acted on. Keep working on everything else. If you already changed something for one, say so in your next add_task_activity update instead of undoing it.',
655 }
656 }
657 // Ends a turn that existed only for withdrawn requests, and returns the task to the run it continued.
658 endWithdrawnRun(job) {
659 const applied = this.comments(job.taskId).some((request) => job.commentIds?.includes(request.id) && request.actedOnAt)
660 const result = this.saveAgentJob({
661 ...job,
662 approval: null,
663 state: applied ? 'review' : 'canceled',
664 summary: applied
665 ? 'Stopped after the remaining revision request was withdrawn. Completed revision work is ready for review.'
666 : job.pickedUpAt
667 ? 'Stopped because the revision request was withdrawn. Review the conversation; completed actions remain.'
668 : 'Revision request withdrawn before delivery.',
669 })
670 if (!applied && this.assignedRun(job.taskId) === job.id) {
671 const earlier = this.db.prepare('SELECT data FROM agent_jobs WHERE task_id=? ORDER BY rowid DESC')
672 .all(job.taskId).map(({ data }) => JSON.parse(data))
673 .find((other) => other.id !== job.id &&
674 (job.previousRunId ? other.id === job.previousRunId : other.threadId === job.threadId))
675 this.assignAgent(job.taskId, earlier?.id || null)
676 }
677 return result
678 }
679 finishWithdrawnRun(id) {
680 const operation = this.queue.then(() => {
681 this.db.exec('BEGIN IMMEDIATE')
682 try {
683 const job = this.agentJob(id)
684 if (!job.withdrawal || !activeRunStates.includes(job.state)) {
685 this.db.exec('COMMIT')
686 return job
687 }
688 const revision = this.revision() + 1
689 const result = this.endWithdrawnRun(job)
690 taskHistory.recordRevision(this, revision, 'agent_update', 'Agent', id)
691 this.set('revision', revision)
692 this.db.exec('COMMIT')
693 this.changed(revision)
694 return result
695 } catch (error) {
696 this.db.exec('ROLLBACK')
697 throw error
698 }
699 })
700 this.queue = operation.catch(() => {})
701 return operation
702 }
703 taskAgentRun(taskId) {
704 const task = this.task(taskId)
705 const assignment = this.assignedRun(taskId) || null
706 const jobs = this.db.prepare('SELECT data FROM agent_jobs WHERE task_id=? ORDER BY rowid DESC')
707 .all(taskId).map(({ data }) => JSON.parse(data))
708 const run = (assignment ? jobs.find(({ id }) => id === assignment) : jobs[0]) || null
709 const closed = task.status === 'Done' || !!task.archivedAt
710 let blocked
711 if (task.deleted) blocked = ['IN_TRASH', 'Restore the task from Trash before assigning an agent.']
712 else if (jobs.some(({ state }) => activeRunStates.includes(state)))
713 blocked = ['AGENT_ALREADY_RUNNING', 'An agent is already assigned to work on this task.']
714 else if (!run) blocked = ['NO_RUN', 'Use Send to agent to start work on this task.']
715 else if (!closed && (task.status !== 'In progress' || assignment !== run.id))
716 blocked = ['TASK_MOVED', 'This run no longer owns the task. Ask the owner to assign it again.']
717 else if (!recoverableRunStates.includes(run.state) &&
718 !(closed && (run.state === 'done' || run.closedByOwner)))
719 blocked = ['RUN_REVOKED', 'This run ended or was stopped. Ask the owner to assign the task again.']
720 else if (!run.threadId)
721 blocked = ['NO_THREAD', 'This run never saved a conversation. Ask the owner to assign a new run.']
722 else {
723 try {
724 this.agentReadiness({ ...this.agentSettings(), defaultAgent: run.agent, workingFolder: run.workingFolder }, run.agent)
725 } catch (error) {
726 blocked = [error.code || 'AGENT_SETUP_REQUIRED', error.message]
727 }
728 }
729 return {
730 task: { id: task.id, revision: task.revision, status: task.status, archivedAt: task.archivedAt, deleted: task.deleted },
731 assignedRunId: assignment,
732 run,
733 recovery: blocked
734 ? { actions: [], reason: { code: blocked[0], message: blocked[1] } }
735 : { actions: ['attach', 'queue'], requiresReopen: closed },
736 }
737 }
738 recoverAgentRun(input, revision) {
739 const { task: current, run: previous, recovery } = this.taskAgentRun(input.taskId)
740 this.expect(current, input.expectedRevision)
741 if (previous?.id !== input.expectedRunId)
742 throw new AppError('STALE_RUN', 'The assigned run changed. Read the task’s current run before retrying.')
743 if (recovery.reason) throw new AppError(recovery.reason.code, recovery.reason.message)
744 if (recovery.requiresReopen !== (input.reopenClosed === true))
745 throw new AppError('REOPEN_REQUIRED', 'Review the current task and explicitly confirm reopening a closed or archived task.')
746 if (input.mode === 'attach' && (input.threadId !== previous.threadId || input.message !== undefined))
747 throw new AppError('THREAD_MISMATCH', 'Attach from the exact saved provider conversation. Keep the owner’s input in that conversation.')
748 if (input.mode === 'queue' && (input.threadId !== undefined || !input.message?.trim()))
749 throw new AppError('CONTINUATION_REQUIRED', 'End any open provider turn and include the owner’s continuation message.')
750
751 let task = this.task(current.id)
752 if (recovery.requiresReopen)
753 task = this.move(task, { status: 'In progress' }, revision, { agentUpdate: true })
754 const requests = this.comments(task.id).filter((request) => request.source === 'user' && !request.actedOnAt)
755 const carried = requests.filter(({ id }) => previous.commentIds?.includes(id))
756 const pending = requests.filter(({ id, delivery }) =>
757 delivery === 'pending' && !previous.commentIds?.includes(id))
758 const commentIds = [...carried, ...pending.slice(0, Math.max(0, 3 - carried.length))].map(({ id }) => id)
759 const attached = input.mode === 'attach'
760 const now = new Date().toISOString()
761 const run = this.saveAgentJob({
762 id: randomUUID(),
763 taskId: task.id,
764 agent: previous.agent,
765 ...(previous.model ? { model: previous.model } : {}),
766 workingFolder: previous.workingFolder,
767 threadId: previous.threadId,
768 previousRunId: previous.id,
769 resumeThread: true,
770 ...(attached
771 ? { externalTurn: true, pickedUpAt: now }
772 : { resumeMessage: input.message.trim() }),
773 commentIds,
774 requiresRevisionReceipts: true,
775 state: attached ? 'working' : 'queued',
776 summary: attached ? 'Resumed in the existing provider turn.' : 'Continuation queued for the existing conversation.',
777 createdAt: now,
778 })
779 const deliver = this.db.prepare(`UPDATE task_comments
780 SET data=json_set(data,'$.runId',?,'$.agent',?,'$.delivery',?,'$.pickedUpAt',?) WHERE id=?`)
781 for (const id of commentIds) deliver.run(run.id, run.agent, attached ? 'delivered' : 'queued', attached ? now : null, id)
782 this.assignAgent(task.id, run.id)
783 return { task, run }
784 }
785 queueCommentFollowups() {
786 const operation = this.queue.then(() => {
787 this.db.exec('BEGIN IMMEDIATE')
788 try {
789 let count = 0
790 const jobs = this.agentJobs()
791 for (const task of this.snapshot().tasks.filter(
792 (task) => !task.deleted && !task.archivedAt && ['In progress', 'Done'].includes(task.status)
793 )) {
794 if (
795 jobs.some(
796 (job) =>
797 job.taskId === task.id &&
798 ['queued', 'starting', 'working', 'needs-input'].includes(job.state)
799 )
800 )
801 continue
802 const previous = jobs.find((job) => job.taskId === task.id)
803 if (
804 !previous?.threadId ||
805 previous.state === 'interrupted' ||
806 this.assignedRun(task.id) !== previous.id
807 )
808 continue
809 const pending = this.comments(task.id)
810 .filter((comment) => comment.delivery === 'pending')
811 .slice(0, 3)
812 if (!pending.length) continue
813 const job = this.saveAgentJob({
814 id: randomUUID(),
815 taskId: task.id,
816 agent: previous.agent,
817 model: previous.model,
818 workingFolder: previous.workingFolder,
819 threadId: previous.threadId,
820 previousRunId: previous.id,
821 resumeThread: true,
822 commentIds: pending.map((comment) => comment.id),
823 requiresRevisionReceipts: true,
824 state: 'queued',
825 summary: 'Revision requests queued for the existing conversation.',
826 createdAt: new Date().toISOString(),
827 })
828 this.assignAgent(task.id, job.id)
829 for (const comment of pending) {
830 const { id, taskId, images, ...data } = comment
831 this.db
832 .prepare('UPDATE task_comments SET data=? WHERE id=?')
833 .run(
834 JSON.stringify({ ...data, delivery: 'queued', runId: job.id, agent: job.agent }),
835 id
836 )
837 }
838 count++
839 }
840 if (count) this.set('revision', this.revision() + 1)
841 this.db.exec('COMMIT')
842 if (count) this.changed(this.revision())
843 return { queued: count }
844 } catch (error) {
845 this.db.exec('ROLLBACK')
846 throw error
847 }
848 })
849 this.queue = operation.catch(() => {})
850 return operation
851 }
852 agentJobs() {
853 return this.db
854 .prepare('SELECT data FROM agent_jobs ORDER BY rowid DESC')
855 .all()
856 .map((row) => JSON.parse(row.data))
857 }
858 agentJob(id) {
859 const row = this.db.prepare('SELECT data FROM agent_jobs WHERE id=?').get(id)
860 if (!row) throw new AppError('NOT_FOUND', 'This agent run no longer exists.')
861 return JSON.parse(row.data)
862 }
863 saveAgentJob(job, {activity=true} = {}) {
864 const previousRow = this.db.prepare('SELECT data FROM agent_jobs WHERE id=?').get(job.id)
865 const previous = previousRow ? JSON.parse(previousRow.data) : null
866 const saved = { ...job, updatedAt: new Date().toISOString() }
867 this.db
868 .prepare(
869 'INSERT INTO agent_jobs VALUES (?,?,?) ON CONFLICT(id) DO UPDATE SET data=excluded.data'
870 )
871 .run(saved.id, saved.taskId, JSON.stringify(saved))
872 if (this.activityReady && activity && (!previous || previous.state !== saved.state || previous.summary !== saved.summary || previous.pickedUpAt !== saved.pickedUpAt || JSON.stringify(previous.approval) !== JSON.stringify(saved.approval))) {
873 const agent = agentNames[saved.agent]
874 taskActivity.record(this,saved.taskId,{actor:'OpenTalon',kind:'agent',summary: saved.pickedUpAt && !previous?.pickedUpAt ? `${agent} picked up the task` : `${agent} run: ${saved.state}`,detail:saved.summary || '',data:{agent:saved.agent,runId:saved.id}})
875 }
876 return saved
877 }
878 updateAgentJob(id, patch, { pickedUp = false, finishing = false } = {}) {
879 const operation = this.queue.then(() => {
880 this.db.exec('BEGIN IMMEDIATE')
881 try {
882 const job = this.agentJob(id)
883 if (finishing && !activeRunStates.includes(job.state)) {
884 this.db.exec('COMMIT')
885 return job
886 }
887 // A queued run can be canceled or withdrawn while the runner prepares to launch it.
888 if (patch.state === 'starting' && job.state !== 'queued') {
889 this.db.exec('COMMIT')
890 return job
891 }
892 const waitingReason = finishing && (job.waitingReason ||
893 (job.state === 'needs-input' && !job.approval ? job.summary : null))
894 if (patch.state === 'review' && waitingReason)
895 patch = { ...patch, state: 'waiting-input', summary: waitingReason, waitingReason }
896 const revision = this.revision() + 1
897 const pickedUpAt = pickedUp ? new Date().toISOString() : job.pickedUpAt
898 if (pickedUp) {
899 const task = this.task(job.taskId)
900 if (
901 !['starting', 'working'].includes(job.state) ||
902 this.assignedRun(job.taskId) !== id ||
903 task.deleted ||
904 !(['Sent to agent', 'In progress'].includes(task.status) || job.resumeThread && task.status === 'Done' && !task.archivedAt) ||
905 job.pickedUpAt
906 ) {
907 this.db.exec('COMMIT')
908 return job
909 }
910 if (task.status !== 'In progress')
911 this.move(task, { status: 'In progress' }, revision, { agentUpdate: true })
912 }
913 const result = this.saveAgentJob({ ...job, ...patch, pickedUpAt })
914 if (this.assignedRun(job.taskId) === id) {
915 if (['failed', 'canceled', 'interrupted', 'review'].includes(patch.state)) {
916 this.flagUnconfirmedRevisionRequests(result)
917 const task = this.task(job.taskId)
918 if (!task.deleted && task.status === 'Sent to agent') {
919 this.move(task, { status: 'To do' }, revision)
920 this.markPendingCommentsForReview(job.taskId)
921 }
922 }
923 if (patch.state === 'canceled') this.assignAgent(job.taskId, null)
924 }
925 if (pickedUp) this.setCommentDelivery(id, 'delivered', pickedUpAt)
926 if (['failed', 'canceled', 'interrupted'].includes(patch.state))
927 this.setCommentDelivery(id, 'needs-review')
928 if (patch.state === 'canceled')
929 this.markPendingCommentsForReview(job.taskId)
930 taskHistory.recordRevision(this, revision, 'agent_update', 'Agent', id)
931 this.set('revision', revision)
932 this.db.exec('COMMIT')
933 this.changed(revision)
934 return result
935 } catch (error) {
936 this.db.exec('ROLLBACK')
937 throw error
938 }
939 })
940 this.queue = operation.catch(() => {})
941 return operation
942 }
943 enqueueAgent(task, agent, model, dispatchComment) {
944 if (model && !this.agentModelCatalog().models.some((option) => option.agent === agent && option.id === model))
945 throw new AppError('INVALID_ARGUMENT', 'Choose a current model for the selected agent.')
946 const settings = this.agentSettings(task.boardId)
947 const resolvedAgent = this.agentReadiness({ ...settings, defaultAgent: agent || settings.defaultAgent }, agent)
948 settings.defaultAgent = resolvedAgent || agent || settings.defaultAgent
949 // Gemini never runs on the CLI's own default. Agent default names the first Gemini model in the owner's list.
950 if (settings.defaultAgent === 'gemini' && !model)
951 model = this.agentModelCatalog().models.find((option) => option.agent === 'gemini')?.id
952 if (settings.defaultAgent === 'gemini' && !model)
953 throw new AppError('INVALID_ARGUMENT', 'Add a Gemini model in Settings before sending this task.')
954 if (!settings.workingFolder)
955 throw new AppError(
956 'AGENT_SETUP_REQUIRED',
957 'Choose a default agent and working folder in Settings before sending tasks.'
958 )
959 if (
960 this.agentJobs().some(
961 (job) =>
962 job.taskId === task.id &&
963 ['queued', 'starting', 'working', 'needs-input'].includes(job.state)
964 )
965 )
966 throw new AppError(
967 'AGENT_ALREADY_RUNNING',
968 'This task already has an active agent run. Stop it before sending again.'
969 )
970 const dispatchCommentId = dispatchComment === undefined
971 ? undefined
972 : insertComment(this, task.id, dispatchComment).id
973 const waiting = this.comments(task.id).filter((request) => request.source === 'user' && !request.actedOnAt
974 && ['local', 'pending'].includes(request.delivery) && request.id !== dispatchCommentId)
975 const selected = [...(dispatchCommentId ? [dispatchCommentId] : []), ...waiting.slice(0, dispatchCommentId ? 2 : 3).map((request) => request.id)]
976 const now = new Date().toISOString()
977 const job = this.saveAgentJob({
978 id: randomUUID(),
979 taskId: task.id,
980 agent: settings.defaultAgent,
981 model,
982 dispatchCommentId,
983 commentIds: selected,
984 requiresRevisionReceipts: true,
985 workingFolder: settings.workingFolder,
986 state: 'queued',
987 threadId: null,
988 summary: 'Waiting to start',
989 createdAt: now,
990 })
991 const queue = this.db.prepare("UPDATE task_comments SET data=json_set(data, '$.delivery', 'queued', '$.runId', ?) WHERE id=?")
992 for (const id of selected) queue.run(job.id, id)
993 const pending = this.db.prepare("UPDATE task_comments SET data=json_set(data, '$.delivery', 'pending') WHERE id=?")
994 const queued = new Set(selected)
995 for (const { id } of waiting) if (!queued.has(id)) pending.run(id)
996 this.assignAgent(task.id, job.id)
997 return job
998 }
999 get(key) {
1000 const row = this.db.prepare('SELECT value FROM settings WHERE key=?').get(key)
1001 return row ? JSON.parse(row.value) : undefined
1002 }
1003
1004 recoverStalledDispatches() {
1005 this.db.exec('BEGIN IMMEDIATE')
1006 const revision = this.revision() + 1
1007 let recovered = 0
1008 try {
1009 const assignments = this.agentAssignments()
1010 const liveRuns = new Set(this.agentJobs()
1011 .filter((job) => ['queued', 'starting', 'working', 'needs-input'].includes(job.state))
1012 .map((job) => job.id))
1013 for (const task of this.snapshot().tasks) {
1014 if (!task.deleted && task.status === 'Sent to agent' && !liveRuns.has(assignments[task.id])) {
1015 this.move(task, { status: 'To do' }, revision)
1016 this.markPendingCommentsForReview(task.id)
1017 recovered++
1018 }
1019 }
1020 if (recovered) { taskHistory.recordRevision(this, revision, 'dispatch_recovered', 'OpenTalon'); this.set('revision', revision) }
1021 this.db.exec('COMMIT')
1022 } catch (error) {
1023 this.db.exec('ROLLBACK')
1024 throw error
1025 }
1026 if (recovered) this.changed(revision)
1027 }
1028 set(key, value) {
1029 this.db
1030 .prepare(
1031 'INSERT INTO settings VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value'
1032 )
1033 .run(key, JSON.stringify(value))
1034 }
1035 revision() {
1036 return this.get('revision')
1037 }
1038 preferences() {
1039 return {
1040 theme: this.get('theme'),
1041 selectedBoard: this.get('selectedBoard'),
1042 revision: this.get('preferencesRevision'),
1043 }
1044 }
1045 boardIcons() {
1046 return this.get('boardIcons') || {}
1047 }
1048 setBoardIcon(id, icon) {
1049 const icons = this.boardIcons()
1050 if (icon) icons[id] = icon
1051 else delete icons[id]
1052 this.set('boardIcons', icons)
1053 }
1054 // Interleaving of tasks across projects in the All tasks view. Order within a project stays in
1055 // task positions; ids of trashed or purged tasks are dropped on the next save.
1056 allTasksOrder() {
1057 const order = this.get('allTasksOrder')
1058 return Array.isArray(order) ? order.filter((id) => typeof id === 'string') : []
1059 }
1060 boards() {
1061 const icons = this.boardIcons()
1062 return this.db
1063 .prepare('SELECT * FROM boards ORDER BY position,id')
1064 .all()
1065 .map((row) => boardView(row, icons))
1066 }
1067 task(id) {
1068 const row = this.db.prepare(`${taskSelect} WHERE tasks.id=?`).get(id) ??
1069 this.db.prepare(`${taskSelect} WHERE task_key=?`).get(id.toUpperCase())
1070 if (!row) throw new AppError('NOT_FOUND', 'Task no longer exists.')
1071 return taskView(row)
1072 }
1073 board(id) {
1074 const row = this.db.prepare('SELECT * FROM boards WHERE id=?').get(id)
1075 if (!row) throw new AppError('NOT_FOUND', 'Board no longer exists.')
1076 return boardView(row, this.boardIcons())
1077 }
1078 createBoard(name, revision, icon = suggestBoardIcon(name)) {
1079 const id = randomUUID()
1080 this.db.prepare('INSERT INTO boards (id,name,position,created_at,revision) VALUES (?,?,?,?,?)')
1081 .run(id, text(name, 'Board name'), this.db.prepare('SELECT coalesce(max(position),-1)+1 AS position FROM boards').get().position,
1082 new Date().toISOString(), revision)
1083 this.allocateProjectKey(id, name)
1084 this.setBoardIcon(id, icon)
1085 return this.board(id)
1086 }
1087 expect(record, expected) {
1088 if (record.revision !== expected)
1089 throw new AppError(
1090 'CONFLICT',
1091 'This item changed. Review the saved version before retrying your edit.',
1092 { current: record }
1093 )
1094 }
1095 snapshot({ includeRecordedCompletions = false } = {}) {
1096 const tasks = this.db.prepare(`${taskSelect} ORDER BY position,id`).all().map(taskView)
1097 if (includeRecordedCompletions) {
1098 const completions = taskHistory.recordedCompletions(this)
1099 for (const task of tasks) task.recordedCompletionAt = completions.get(task.id) ?? null
1100 }
1101 return {
1102 version: 1,
1103 ...this.preferences(),
1104 preferencesRevision: this.get('preferencesRevision'),
1105 revision: this.revision(),
1106 boards: this.boards(),
1107 tasks,
1108 agentRuns: this.agentJobs(),
1109 agentAssignments: this.agentAssignments(),
1110 allTasksOrder: this.allTasksOrder(),
1111 }
1112 }
1113 nextPosition(boardId, status) {
1114 return this.db
1115 .prepare(
1116 'SELECT coalesce(max(position),-1)+1 AS position FROM tasks WHERE board_id=? AND status=? AND deleted_at IS NULL AND archived_at IS NULL'
1117 )
1118 .get(boardId, status).position
1119 }
1120 liveColumn(boardId, status) {
1121 return this.db.prepare(
1122 'SELECT * FROM tasks WHERE board_id=? AND status=? AND deleted_at IS NULL AND archived_at IS NULL ORDER BY position,id'
1123 ).all(boardId, status).map(taskView)
1124 }
1125 saveColumnOrder(tasks, revision) {
1126 for (const [position, task] of tasks.entries()) {
1127 if (task.position !== position) this.saveTask({ ...task, position }, revision)
1128 }
1129 }
1130 saveTask(task, revision) {
1131 this.db
1132 .prepare(
1133 'UPDATE tasks SET board_id=?,title=?,notes=?,status=?,position=?,updated_at=?,deleted_at=?,revision=?,priority=?,definition_of_done=?,due_date=?,issue_type=? WHERE id=?'
1134 )
1135 .run(
1136 task.boardId,
1137 task.title,
1138 task.notes,
1139 task.status,
1140 task.position,
1141 new Date().toISOString(),
1142 task.deletedAt,
1143 revision,
1144 task.priority,
1145 task.definitionOfDone,
1146 task.dueDate,
1147 task.issueType || 'Issue',
1148 task.id
1149 )
1150 return this.task(task.id)
1151 }
1152 move(task, a, revision, { agentUpdate = false } = {}) {
1153 if (a.beforeId && a.afterId)
1154 throw new AppError('INVALID_ARGUMENT', 'Choose beforeId or afterId, not both.')
1155 if (task.deleted) throw new AppError('IN_TRASH', 'Restore the task before moving it.')
1156 const boardId = a.boardId || task.boardId
1157 const status = a.status || task.status
1158 const sending = status === 'Sent to agent' && task.status !== status
1159 if ((a.agent || a.model || a.dispatchComment !== undefined) && !sending)
1160 throw new AppError('INVALID_ARGUMENT', 'Agent options and revision requests for dispatch require sending a task.')
1161 if (task.archivedAt && a.status !== undefined) {
1162 this.db.prepare('UPDATE tasks SET archived_at=NULL WHERE id=?').run(task.id)
1163 task = { ...task, archivedAt: null }
1164 }
1165 if (task.archivedAt && status === task.status) {
1166 if (a.beforeId || a.afterId)
1167 throw new AppError('INVALID_STATE', 'Reopen the archived task before reordering it.')
1168 this.board(boardId)
1169 if (boardId !== task.boardId) this.assignTaskKey(task.id, boardId)
1170 return this.saveTask({ ...task, boardId }, revision)
1171 }
1172 if (status === 'Done' && task.status !== 'Done' && this.assignedRun(task.id) && !agentUpdate)
1173 throw new AppError(
1174 'COMPLETION_PROOF_REQUIRED',
1175 'Agent tasks need a completion report with proof and a confirmed definition of done through report_agent_progress. Return to To do first if you want to track this task manually.'
1176 )
1177 if (sending) this.enqueueAgent(task, a.agent, a.model, a.dispatchComment)
1178 if (!agentUpdate && status !== 'Sent to agent' && status !== task.status)
1179 this.assignAgent(task.id, null)
1180 if (status !== 'Sent to agent')
1181 for (const job of this.agentJobs())
1182 if (job.taskId === task.id && job.state === 'queued')
1183 this.saveAgentJob({ ...job, state: 'canceled', summary: 'Task moved before dispatch.' })
1184 this.board(boardId)
1185 const column = this.db
1186 .prepare(
1187 'SELECT * FROM tasks WHERE board_id=? AND status=? AND deleted_at IS NULL AND archived_at IS NULL AND id<>? ORDER BY position,id'
1188 )
1189 .all(boardId, status, task.id)
1190 .map(taskView)
1191 const anchorId = a.beforeId || a.afterId
1192 if (anchorId === task.id)
1193 throw new AppError('INVALID_ARGUMENT', 'A task cannot be its own position anchor.')
1194 const anchor = anchorId ? column.findIndex((item) => item.id === anchorId) : -1
1195 if (anchorId && anchor < 0)
1196 throw new AppError(
1197 'INVALID_ARGUMENT',
1198 'The position anchor must be a live task in the destination column.'
1199 )
1200 column.splice(anchor < 0 ? column.length : anchor + (a.afterId ? 1 : 0), 0, {
1201 ...task,
1202 boardId,
1203 status,
1204 })
1205 if (status !== task.status) taskHistory.beginIfMissing(this, task)
1206 column.forEach((item, position) => {
1207 if (item.id === task.id || item.position !== position)
1208 this.saveTask({ ...item, position }, revision)
1209 })
1210 if (boardId !== task.boardId) this.assignTaskKey(task.id, boardId)
1211 return this.task(task.id)
1212 }
1213 list(a, trash = false) {
1214 if (a.boardId) this.board(a.boardId)
1215 const filter = {
1216 trash,
1217 boardId: a.boardId || null,
1218 status: a.status || null,
1219 query: (a.query || '').trim().toLowerCase(),
1220 priority: a.priority || null,
1221 issueType: a.issueType || null,
1222 sort: a.sort || 'manual',
1223 }
1224 const fingerprint = argumentHash(filter)
1225 let offset = 0
1226 if (a.cursor) {
1227 let cursor
1228 try {
1229 cursor = JSON.parse(Buffer.from(a.cursor, 'base64url').toString())
1230 } catch {
1231 throw new AppError('INVALID_CURSOR', 'Invalid continuation cursor.')
1232 }
1233 if (
1234 cursor.filter !== fingerprint ||
1235 cursor.revision !== this.revision() ||
1236 !Number.isSafeInteger(cursor.offset) ||
1237 cursor.offset < 0
1238 )
1239 throw new AppError(
1240 'STALE_CURSOR',
1241 'The results changed or filters differ. Start again without cursor.'
1242 )
1243 offset = cursor.offset
1244 }
1245 const where = ['deleted_at IS ' + (trash ? 'NOT NULL' : 'NULL')]
1246 const params = []
1247 if (filter.boardId) {
1248 where.push('board_id=?')
1249 params.push(filter.boardId)
1250 }
1251 if (filter.status) {
1252 where.push('status=?')
1253 params.push(filter.status)
1254 }
1255 if (filter.priority) {
1256 where.push('priority=?')
1257 params.push(filter.priority)
1258 }
1259 if (filter.issueType) {
1260 where.push('issue_type=?')
1261 params.push(filter.issueType)
1262 }
1263 // JS Unicode lowercasing keeps UI and MCP search identical, beyond SQLite's ASCII lower().
1264 const rows = this.db
1265 .prepare(
1266 `${taskSelect} WHERE ${where.join(' AND ')} ORDER BY board_id,CASE status WHEN 'To do' THEN 0 WHEN 'Sent to agent' THEN 1 WHEN 'In progress' THEN 2 ELSE 3 END,${filter.sort === 'manual' ? '' : `CASE priority WHEN 'Urgent' THEN ${filter.sort === 'priority-asc' ? 3 : 0} WHEN 'High' THEN ${filter.sort === 'priority-asc' ? 2 : 1} WHEN 'Medium' THEN ${filter.sort === 'priority-asc' ? 1 : 2} WHEN 'Low' THEN ${filter.sort === 'priority-asc' ? 0 : 3} ELSE 4 END,`}position,id`
1267 )
1268 .all(...params)
1269 .map(taskView)
1270 .filter(
1271 (item) =>
1272 !filter.query || `${item.taskKey ?? ''}\n${item.title}\n${item.notes}`.toLowerCase().includes(filter.query)
1273 )
1274 const limit = a.limit || 100
1275 return {
1276 tasks: rows.slice(offset, offset + limit),
1277 total: rows.length,
1278 revision: this.revision(),
1279 nextCursor:
1280 offset + limit < rows.length
1281 ? Buffer.from(
1282 JSON.stringify({
1283 filter: fingerprint,
1284 revision: this.revision(),
1285 offset: offset + limit,
1286 })
1287 ).toString('base64url')
1288 : null,
1289 }
1290 }
1291 dispatch(name, input = {}, origin = 'Connected agent') {
1292 const job = this.queue.then(() => this.execute(name, input, origin))
1293 this.queue = job.catch(() => {})
1294 return job
1295 }
1296 async execute(name, a, origin = 'Connected agent') {
1297 if (a.dispatchComment && !origin.startsWith('You')) throw new AppError('INVALID_ARGUMENT','Revision requests for dispatch are only for text entered by the user. Record agent context with add_task_activity.')
1298 const markdown = name === 'set_task_plan' ? a.markdown : a.planMarkdown
1299 if (markdown !== undefined && (typeof markdown !== 'string' || markdown.length > 100000 ||
1300 !markdown.isWellFormed() || markdown.includes('\0')))
1301 throw new AppError('INVALID_ARGUMENT', 'Use valid Markdown text with no more than 100,000 characters.')
1302 if (a.dueDate !== undefined && !validDueDate(a.dueDate))
1303 throw new AppError(
1304 'INVALID_ARGUMENT',
1305 'Choose a real due date in YYYY-MM-DD format, or null to clear it.'
1306 )
1307 const contract = validateAction(
1308 name,
1309 a,
1310 [
1311 'add_user_comment',
1312 'read_task_file',
1313 'snapshot',
1314 'capture_task',
1315 'companion_organize_task',
1316 'import_prototype',
1317 'get_agent_settings',
1318 'set_agent_settings',
1319 'retry_task_comment',
1320 'withdraw_revision_request',
1321 'reorder_tasks',
1322 'reorder_all_tasks',
1323 'companion_delete_archived_task',
1324 'companion_empty_trash',
1325 'companion_set_task_field',
1326 'companion_reorder_task',
1327 'force_complete_task',
1328 'manage_archived_tasks',
1329 ].includes(name)
1330 )
1331 if (name === 'snapshot') return this.snapshot()
1332 if (name === 'import_prototype') return this.importPrototype(a.workspace)
1333 if (name === 'get_app_status')
1334 return {
1335 available: true,
1336 version: this.version,
1337 statuses,
1338 dataLocation: this.folder,
1339 revision: this.revision(),
1340 }
1341 if (name === 'list_boards') return { boards: this.boards(), revision: this.revision() }
1342 // An agent's own tool calls are the safe points where it learns that a request was withdrawn.
1343 const noticeFor = (taskId) => (origin.startsWith('You') ? {} : this.withdrawalNotice(taskId))
1344 if (name === 'get_task') {
1345 const task = this.task(a.id)
1346 return { task, ...noticeFor(task.id) }
1347 }
1348 if (name === 'list_task_files') {
1349 const task = this.task(a.taskId)
1350 return { attachments: taskFiles.list(this, task.id), revision: this.revision() }
1351 }
1352 if (name === 'read_task_file') return taskFiles.read(this, a.taskId, a.fileId)
1353 if (name === 'get_task_agent_run') return this.taskAgentRun(a.taskId)
1354 if (name === 'list_task_activity') return taskActivity.page(this, a.taskId, a.beforeSequence, a.limit, a.commentId)
1355 if (name === 'get_task_history') return taskHistory.page(this, a.id, a.beforeVersion, a.limit)
1356 if (name === 'list_tasks' || name === 'list_trash') return this.list(a, name === 'list_trash')
1357 if (name === 'get_preferences') return this.preferences()
1358 if (name === 'list_task_comments') {
1359 this.task(a.taskId)
1360 return { comments: this.comments(a.taskId).filter(comment => comment.source === 'user'), revision: this.revision(), ...noticeFor(a.taskId) }
1361 }
1362 if (name === 'read_comment_image') return this.commentImage(a.imageId)
1363 if (name === 'get_agent_settings') return this.agentSettings()
1364 if (name === 'get_agent_models') return this.agentModelCatalog()
1365 if (name === 'get_project_folder') return this.projectFolder(a.id)
1366 if (name === 'inspect_backup') return (await this.inspect(a.path)).summary
1367 if (name === 'preview_destructive_action') return this.preview(a)
1368 if (!contract.mutates) throw new AppError('UNKNOWN_ACTION', 'Unavailable action.')
1369 const digest = argumentHash({ name, ...a })
1370 const receipt = this.db
1371 .prepare('SELECT * FROM operation_receipts WHERE request_key=?')
1372 .get(a.requestKey)
1373 if (receipt) {
1374 // An earlier Mac version applied this phone request before requests carried their own ID.
1375 const { clientId, ...earlier } = a
1376 const savedEarlier = name === 'add_user_comment' && clientId !== undefined &&
1377 receipt.argument_hash === argumentHash({ name, ...earlier })
1378 if (receipt.argument_hash !== digest && !savedEarlier)
1379 throw new AppError(
1380 'REQUEST_KEY_REUSED',
1381 'This requestKey was already used with different arguments.'
1382 )
1383 return JSON.parse(receipt.result)
1384 }
1385 if (name === 'create_backup') {
1386 const result = await this.createBackup(a.destination, a.format)
1387 this.db
1388 .prepare('INSERT INTO operation_receipts VALUES (?,?,?)')
1389 .run(a.requestKey, digest, JSON.stringify(result))
1390 return result
1391 }
1392 let restore
1393 let preview
1394 if (name === 'confirm_destructive_action') {
1395 preview = this.previews.get(a.token)
1396 if (!preview || preview.expires < Date.now() || preview.revision !== this.revision())
1397 throw new AppError(
1398 'STALE_PREVIEW',
1399 'This confirmation expired or the workspace changed. Generate a new preview.'
1400 )
1401 if (preview.action === 'restore_backup') {
1402 restore = await this.inspect(preview.path)
1403 if (restore.summary.sha256 !== preview.sha256)
1404 throw new AppError('STALE_PREVIEW', 'The backup changed. Generate a new preview.')
1405 preview.safetyBackup = (await this.createBackup()).path
1406 }
1407 }
1408 this.db.exec('BEGIN IMMEDIATE')
1409 let result
1410 try {
1411 const revision = this.revision() + 1
1412 if (name === 'restore_task_revision') result = taskHistory.restore(this, a, revision)
1413 else if (name === 'reorder_tasks') {
1414 this.expect({ revision: this.revision() }, a.expectedRevision)
1415 this.board(a.boardId)
1416 const column = this.liveColumn(a.boardId, a.status)
1417 const byId = new Map(column.map((task) => [task.id, task]))
1418 if (a.taskIds.length !== column.length || a.taskIds.some((id) => !byId.has(id)))
1419 throw new AppError(
1420 'INVALID_ARGUMENT',
1421 'The order must include every current live task in this column exactly once.'
1422 )
1423 this.saveColumnOrder(a.taskIds.map((id) => byId.get(id)), revision)
1424 result = { reordered: a.taskIds.length, revision }
1425 } else if (name === 'companion_reorder_task') {
1426 if (a.id === a.anchorId)
1427 throw new AppError('INVALID_ARGUMENT', 'A task cannot be its own position anchor.')
1428 const column = this.liveColumn(a.boardId, a.status)
1429 const index = column.findIndex((task) => task.id === a.id)
1430 if (index < 0 || !column.some((task) => task.id === a.anchorId))
1431 throw new AppError('CONFLICT', 'One of the tasks moved. Check the current project order before retrying.')
1432 const [task] = column.splice(index, 1)
1433 const anchor = column.findIndex((item) => item.id === a.anchorId)
1434 column.splice(anchor + (a.before ? 0 : 1), 0, task)
1435 this.saveColumnOrder(column, revision)
1436 result = { task: this.task(a.id) }
1437 } else if (name === 'reorder_all_tasks') {
1438 this.expect({ revision: this.revision() }, a.expectedRevision)
1439 const live = new Map(
1440 this.db
1441 .prepare(`${taskSelect} WHERE deleted_at IS NULL AND archived_at IS NULL`)
1442 .all()
1443 .map((row) => [row.id, taskView(row)])
1444 )
1445 const arriving = a.taskIds.filter((id) => live.get(id)?.status !== a.status)
1446 const column = [...live.values()].filter((task) => task.status === a.status)
1447 if (
1448 a.taskIds.some((id) => !live.has(id)) ||
1449 arriving.length > 1 ||
1450 a.taskIds.length !== column.length + arriving.length
1451 )
1452 throw new AppError(
1453 'INVALID_ARGUMENT',
1454 'The order must include every current live task in this column exactly once, plus at most one task moved in from another column.'
1455 )
1456 // A card dragged in from another column changes status exactly as move_task would.
1457 if ((a.agent || a.model) && arriving.length !== 1)
1458 throw new AppError('INVALID_ARGUMENT', 'Choose an agent or model only when sending a task.')
1459 for (const id of arriving)
1460 this.move(live.get(id), { status: a.status, agent: a.agent, model: a.model }, revision)
1461 const projects = new Map()
1462 for (const id of a.taskIds) {
1463 const boardId = live.get(id).boardId
1464 projects.set(boardId, [...(projects.get(boardId) || []), id])
1465 }
1466 for (const ids of projects.values())
1467 for (const [position, id] of ids.entries()) {
1468 const task = this.task(id)
1469 if (task.position !== position) this.saveTask({ ...task, position }, revision)
1470 }
1471 const moved = new Set(a.taskIds)
1472 this.set('allTasksOrder', [
1473 ...this.allTasksOrder().filter((id) => live.has(id) && !moved.has(id)),
1474 ...a.taskIds,
1475 ])
1476 result = { reordered: a.taskIds.length, revision }
1477 } else if (name === 'retry_task_comment') {
1478 const row = this.db.prepare('SELECT * FROM task_comments WHERE id=?').get(a.id)
1479 if (!row) throw new AppError('NOT_FOUND', 'This revision request no longer exists.')
1480 if (!this.assignedRun(row.task_id))
1481 throw new AppError(
1482 'TASK_MANUAL',
1483 'This task is manual. Move it to Sent to agent before asking an agent to continue.'
1484 )
1485 const data = JSON.parse(row.data)
1486 if (data.delivery !== 'needs-review')
1487 throw new AppError('INVALID_STATE', 'This revision request is already queued or delivered.')
1488 const previous = this.agentJobs().find((job) => job.taskId === row.task_id)
1489 if (previous?.state === 'interrupted') this.saveAgentJob({ ...previous, state: 'review' })
1490 this.db
1491 .prepare('UPDATE task_comments SET data=? WHERE id=?')
1492 .run(JSON.stringify({ ...data, delivery: 'pending', runId: null }), a.id)
1493 result = { comment: this.comments(row.task_id).find((comment) => comment.id === a.id) }
1494 } else if (name === 'withdraw_revision_request') {
1495 result = this.withdrawRevisionRequest(a, origin)
1496 } else if (name === 'add_user_comment') {
1497 result = { comment: insertComment(this, a.taskId, a.text, a.images, a.notifyAgent, {actor:origin.startsWith('You') ? origin : 'You', clientId: a.clientId}) }
1498 } else if (name === 'attach_task_file') {
1499 const attachment = taskFiles.attach(this, a)
1500 taskActivity.record(this, attachment.taskId, { actor: origin, kind: 'system', summary: 'Attached a file', detail: attachment.name })
1501 result = { attachment }
1502 } else if (name === 'add_task_comment' || name === 'add_task_activity') {
1503 const task = this.task(a.taskId)
1504 if(task.deleted) throw new AppError('IN_TRASH','Restore the task before adding activity.')
1505 if(!a.text.trim() && !a.images?.length) throw new AppError('EMPTY_COMMENT','Write an activity update or attach a screenshot.')
1506 if (a.commentId && a.commentIds) throw new AppError('INVALID_ARGUMENT', 'Use either commentId or commentIds.')
1507 const ids = a.commentIds || (a.commentId ? [a.commentId] : [])
1508 this.validateRevisionReceipts(task.id, ids)
1509 const runId = this.assignedRun(task.id)
1510 const activity = taskActivity.record(this,task.id,{actor:origin,kind:'agent',summary:ids.length?'Revision request response':'Agent update',detail:a.text,data:{...(runId?{runId}:{}),...(ids.length === 1 ? {commentID:ids[0]} : ids.length ? {commentIDs:ids} : {})}},a.images || [])
1511 this.markRevisionRequestsActedOn(ids, activity.id)
1512 result = {activity,...(name === 'add_task_comment' ? {comment:activity,redirectedToActivity:true} : {}),...noticeFor(task.id)}
1513 } else if (name === 'set_project_folder') {
1514 this.expect(this.board(a.id), a.expectedRevision)
1515 let folder = ''
1516 if (a.workingFolder) {
1517 try {
1518 if (!path.isAbsolute(a.workingFolder) || !fs.statSync(a.workingFolder).isDirectory()) throw new Error('Invalid folder')
1519 folder = fs.realpathSync(a.workingFolder)
1520 if (folder.length > 4000 || /\p{Cc}/u.test(folder)) throw new Error('Invalid folder')
1521 } catch { throw new AppError('INVALID_ARGUMENT', 'Choose an existing project folder, or use the global OpenTalon folder.') }
1522 }
1523 const folders = this.get('projectFolders') || {}
1524 if (folder) folders[a.id] = folder
1525 else delete folders[a.id]
1526 this.set('projectFolders', folders)
1527 this.db.prepare('UPDATE boards SET revision=? WHERE id=?').run(revision, a.id)
1528 result = this.projectFolder(a.id)
1529 } else if (name === 'set_agent_models') {
1530 const catalog = this.agentModelCatalog()
1531 if (a.expectedCatalogRevision !== catalog.catalogRevision)
1532 throw new AppError('CONFLICT', 'The model catalog changed. Reload it before saving.', { current: catalog })
1533 let overrides
1534 try { overrides = validateModelOverrides(a.overrides) }
1535 catch (error) { throw new AppError('INVALID_ARGUMENT', error.message) }
1536 this.set('agentModelOverrides', overrides)
1537 this.set('agentModelCatalogRevision', catalog.catalogRevision + 1)
1538 result = this.agentModelCatalog()
1539 } else if (name === 'set_agent_settings') {
1540 if (
1541 a.workingFolder &&
1542 (!path.isAbsolute(a.workingFolder) || !fs.statSync(a.workingFolder).isDirectory())
1543 )
1544 throw new AppError('INVALID_PATH', 'Choose an existing working folder.')
1545 this.set('agentSettings', { defaultAgent: a.defaultAgent, workingFolder: a.workingFolder })
1546 if (a.permissionMode !== undefined) this.set('agentPermissionMode', a.permissionMode)
1547 result = { settings: this.agentSettings() }
1548 } else if (name === 'recover_agent_run') {
1549 result = this.recoverAgentRun(a, revision)
1550 } else if (name === 'report_agent_progress') {
1551 const job = this.agentJob(a.runId)
1552 if (!['starting', 'working', 'needs-input'].includes(job.state))
1553 throw new AppError('INACTIVE_RUN', 'This agent run is no longer active.')
1554 if (this.assignedRun(job.taskId) !== job.id)
1555 throw new AppError(
1556 'TASK_MANUAL',
1557 'This task is being tracked manually. Stop agent work on it.'
1558 )
1559 if (job.withdrawal)
1560 throw new AppError('WITHDRAWN', 'The user withdrew the revision request this turn was started for. Stop this turn.')
1561 let task = this.task(job.taskId)
1562 if (task.deleted || !['Sent to agent', 'In progress'].includes(task.status))
1563 throw new AppError('TASK_MOVED', 'The task was moved or removed. Stop work on it.')
1564 let completionReport
1565 if (a.actedOnCommentIds && a.state !== 'done')
1566 throw new AppError('INVALID_ARGUMENT', 'Link acted-on revision requests to a completed report or Activity update.')
1567 if (a.state === 'done') {
1568 if (
1569 a.definitionOfDoneMet !== true ||
1570 !a.proof ||
1571 a.proof.trim().length < 20 ||
1572 !a.summary.trim()
1573 )
1574 throw new AppError(
1575 'COMPLETION_PROOF_REQUIRED',
1576 'Before Done, provide proof describing concrete checks/results or deliverables, explain how the definition of done was met, and set definitionOfDoneMet true. Otherwise report needs-input or failed.'
1577 )
1578 const report = `${agentNames[job.agent]} completion report\n\nOutcome\n${a.summary.trim()}\n\nDefinition of done: met\n${task.definitionOfDone || 'Complete the requested outcome, verify it with relevant checks, and post concrete proof on this task.'}\n\nProof and verification\n${a.proof.trim()}`
1579 if (report.length > 10000)
1580 throw new AppError(
1581 'INVALID_ARGUMENT',
1582 'Keep the completion report, proof and definition of done within 10,000 characters combined.'
1583 )
1584 const ids = a.actedOnCommentIds || []
1585 this.validateRevisionReceipts(task.id, ids)
1586 if (job.requiresRevisionReceipts && this.comments(task.id).some((request) =>
1587 job.commentIds?.includes(request.id) && !request.actedOnAt && !ids.includes(request.id)))
1588 throw new AppError('REVISION_PROOF_REQUIRED', 'Record which revision requests were acted on before completing this run. Report needs-input when a request cannot be completed.')
1589 completionReport = taskActivity.record(this, task.id, {actor:agentNames[job.agent],kind:'agent',summary:'Completion report',detail:report,data:{agent:job.agent,runId:job.id,...(ids.length ? {commentIDs:ids} : {})}})
1590 this.markRevisionRequestsActedOn(ids, completionReport.id)
1591 }
1592 if (a.state !== 'done') taskActivity.record(this, task.id, {actor:agentNames[job.agent],kind:'agent',summary:a.state === 'working' ? 'Agent progress' : a.state === 'needs-input' ? 'Agent needs your input' : 'Agent run failed',detail:a.summary,data:{agent:job.agent,runId:job.id}})
1593 if (a.state === 'failed') this.flagUnconfirmedRevisionRequests(job)
1594 const hasNewComments =
1595 a.state === 'done' &&
1596 this.comments(task.id).some((comment) => ['pending', 'queued'].includes(comment.delivery))
1597 const state = hasNewComments ? 'review' : a.state === 'needs-input' && job.externalTurn ? 'waiting-input' : a.state
1598 if (['working', 'done', 'needs-input'].includes(state))
1599 task = this.move(task, { status: state === 'done' ? 'Done' : 'In progress' }, revision, {
1600 agentUpdate: true,
1601 })
1602 result = {
1603 run: this.saveAgentJob({
1604 ...job,
1605 state,
1606 waitingReason: a.state === 'needs-input' ? a.summary : null,
1607 summary:
1608 a.summary +
1609 (hasNewComments
1610 ? '\nNew revision requests are waiting for the next check. The task remains In progress.'
1611 : ''),
1612 }, {activity:false}),
1613 task,
1614 ...(completionReport ? { completionReport } : {}),
1615 }
1616 Object.assign(result, noticeFor(task.id))
1617 } else if (name === 'create_board') {
1618 result = { board: this.createBoard(a.name, revision, a.icon) }
1619 } else if (name === 'set_board_icon') {
1620 this.expect(this.board(a.id), a.expectedRevision)
1621 this.db.prepare('UPDATE boards SET revision=? WHERE id=?').run(revision, a.id)
1622 this.setBoardIcon(a.id, a.icon)
1623 result = { board: this.board(a.id) }
1624 } else if (name === 'rename_board' || name === 'delete_board') {
1625 const board = this.board(a.id)
1626 this.expect(board, a.expectedRevision)
1627 if (name === 'rename_board') {
1628 this.db
1629 .prepare('UPDATE boards SET name=?,revision=? WHERE id=?')
1630 .run(text(a.name, 'Board name'), revision, a.id)
1631 result = { board: this.board(a.id) }
1632 for (const task of this.db.prepare('SELECT id FROM tasks WHERE board_id=?').all(a.id))
1633 taskHistory.record(this,this.task(task.id),'rename_board',origin)
1634 } else {
1635 if (this.db.prepare('SELECT 1 FROM tasks WHERE board_id=? LIMIT 1').get(a.id))
1636 throw new AppError(
1637 'BOARD_NOT_EMPTY',
1638 'Move or remove all live and trashed tasks before deleting this board.'
1639 )
1640 if (this.boards().length === 1)
1641 throw new AppError('LAST_BOARD', 'Keep at least one board.')
1642 this.db.prepare('DELETE FROM boards WHERE id=?').run(a.id)
1643 this.setBoardIcon(a.id, null)
1644 const folders = this.get('projectFolders') || {}
1645 delete folders[a.id]
1646 this.set('projectFolders', folders)
1647 if (this.get('selectedBoard') === a.id) {
1648 this.set('selectedBoard', this.boards()[0].id)
1649 this.set('preferencesRevision', revision)
1650 }
1651 result = { deletedBoardId: a.id }
1652 }
1653 } else if (name === 'set_preferences') {
1654 this.expect(this.preferences(), a.expectedRevision)
1655 if (a.theme !== undefined) this.set('theme', a.theme)
1656 if (a.selectedBoard !== undefined) {
1657 this.board(a.selectedBoard)
1658 this.set('selectedBoard', a.selectedBoard)
1659 }
1660 this.set('preferencesRevision', revision)
1661 result = { preferences: this.preferences() }
1662 } else if (name === 'create_task' || name === 'capture_task') {
1663 let boardId = a.boardId
1664 if (name === 'capture_task' && a.newProjectName) {
1665 const projectName = text(a.newProjectName, 'Project name')
1666 const existing = this.boards().find((board) => board.name.trim().toLowerCase() === projectName.toLowerCase())
1667 boardId = (existing ?? this.createBoard(projectName, revision)).id
1668 }
1669 this.board(boardId)
1670 const id = randomUUID(),
1671 now = new Date().toISOString(),
1672 status = a.status || 'To do'
1673 this.db
1674 .prepare(
1675 'INSERT INTO tasks (id,board_id,title,notes,status,position,created_at,updated_at,deleted_at,revision,priority,definition_of_done,due_date) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)'
1676 )
1677 .run(
1678 id,
1679 boardId,
1680 text(a.title, 'Title'),
1681 a.notes || '',
1682 status,
1683 this.nextPosition(boardId, status),
1684 now,
1685 now,
1686 null,
1687 revision,
1688 a.priority || 'None',
1689 a.definitionOfDone || '',
1690 a.dueDate || null
1691 )
1692 this.assignTaskKey(id, boardId)
1693 if (a.issueType !== undefined) this.db.prepare('UPDATE tasks SET issue_type=? WHERE id=?').run(a.issueType, id)
1694 this.db.prepare('UPDATE tasks SET plan_markdown=? WHERE id=?')
1695 .run(a.planMarkdown ?? legacyPlan(a.notes), id)
1696 result = { task: this.task(id) }
1697 if ((a.agent || a.model || a.dispatchComment !== undefined) && status !== 'Sent to agent')
1698 throw new AppError('INVALID_ARGUMENT', 'Agent options and revision requests for dispatch require sending a task.')
1699 if (status === 'Sent to agent') this.enqueueAgent(result.task, a.agent, a.model, a.dispatchComment)
1700 } else if (['update_task', 'move_task', 'trash_task', 'restore_task'].includes(name)) {
1701 let task = this.task(a.id)
1702 this.expect(task, a.expectedRevision)
1703 if (name === 'move_task') task = this.move(task, a, revision)
1704 else if (name === 'update_task') {
1705 if (task.deleted) throw new AppError('IN_TRASH', 'Restore the task before editing it.')
1706 if (a.title !== undefined) {
1707 text(a.title, 'Title')
1708 task.title = a.title
1709 }
1710 if (a.notes !== undefined) task.notes = a.notes
1711 if (a.planMarkdown !== undefined)
1712 this.db.prepare('UPDATE tasks SET plan_markdown=? WHERE id=?').run(a.planMarkdown, task.id)
1713 else if (a.notes !== undefined && !task.planMarkdown)
1714 this.db.prepare('UPDATE tasks SET plan_markdown=? WHERE id=?').run(legacyPlan(a.notes), task.id)
1715 if (a.issueType !== undefined) task.issueType = a.issueType
1716 if (a.priority !== undefined) task.priority = a.priority
1717 if (a.definitionOfDone !== undefined) task.definitionOfDone = a.definitionOfDone
1718 if (a.dueDate !== undefined) task.dueDate = a.dueDate
1719 if (a.status !== undefined && a.status !== task.status)
1720 task = this.move(task, { status: a.status }, revision)
1721 task = this.saveTask(task, revision)
1722 } else {
1723 const deleted = name === 'trash_task'
1724 if (deleted) this.assignAgent(task.id, null)
1725 if (task.deleted === deleted)
1726 throw new AppError(
1727 'INVALID_STATE',
1728 deleted ? 'Task is already in Trash.' : 'Task is not in Trash.'
1729 )
1730 const occupied =
1731 !deleted &&
1732 this.db
1733 .prepare(
1734 'SELECT 1 FROM tasks WHERE board_id=? AND status=? AND deleted_at IS NULL AND position=? LIMIT 1'
1735 )
1736 .get(task.boardId, task.status, task.position)
1737 task = this.saveTask(
1738 {
1739 ...task,
1740 deletedAt: deleted ? new Date().toISOString() : null,
1741 position: occupied ? this.nextPosition(task.boardId, task.status) : task.position,
1742 },
1743 revision
1744 )
1745 }
1746 result = { task }
1747 } else if (name === 'set_task_plan') {
1748 const task = this.task(a.id)
1749 if (task.deleted) throw new AppError('IN_TRASH', 'Restore the task before editing its plan.')
1750 if (task.planMarkdown !== a.expectedMarkdown)
1751 throw new AppError('CONFLICT', 'The plan changed on another device. Your draft is preserved; review both versions before saving.')
1752 this.db.prepare('UPDATE tasks SET plan_markdown=? WHERE id=?').run(a.markdown, task.id)
1753 result = { task: this.saveTask(task, revision) }
1754 } else if (name === 'companion_organize_task') {
1755 let task = this.task(a.id)
1756 if (task.deleted) throw new AppError('IN_TRASH', 'Restore the task from Trash first.')
1757 if (a.destination === 'active') {
1758 if (!task.archivedAt) throw new AppError('INVALID_STATE', 'This task is no longer in Archive.')
1759 this.db.prepare('UPDATE tasks SET archived_at=NULL WHERE id=?').run(task.id)
1760 task = this.move({ ...task, archivedAt: null }, { status: 'To do' }, revision)
1761 } else {
1762 for (const job of this.agentJobs()) {
1763 if (job.taskId !== task.id || !['queued', 'starting', 'working', 'needs-input'].includes(job.state)) continue
1764 this.saveAgentJob({ ...job, state: 'canceled', approval: null,
1765 closedByOwner: a.destination === 'archive',
1766 summary: a.destination === 'archive' ? 'Archived by the user.' : 'Moved to Trash by the user.' })
1767 this.setCommentDelivery(job.id, 'needs-review')
1768 }
1769 this.markPendingCommentsForReview(task.id)
1770 this.assignAgent(task.id, null)
1771 task = this.saveTask(task, revision)
1772 const now = new Date().toISOString()
1773 if (a.destination === 'archive')
1774 this.db.prepare('UPDATE tasks SET archived_at=? WHERE id=?').run(now, task.id)
1775 else this.db.prepare('UPDATE tasks SET deleted_at=? WHERE id=?').run(now, task.id)
1776 }
1777 result = { task: this.task(task.id) }
1778 } else if (name === 'companion_set_task_field') {
1779 const task = this.task(a.id)
1780 if (task.deleted) throw new AppError('IN_TRASH', 'Restore the task before editing it.')
1781 const currentValue = a.field === 'project' ? task.boardId : task[a.field]
1782 if (currentValue !== a.expectedValue)
1783 throw new AppError('CONFLICT', 'This field changed on another device. Check its current value before retrying.')
1784 if (a.field === 'project' || a.field === 'status') {
1785 const move = { id: task.id, expectedRevision: task.revision, requestKey: a.requestKey }
1786 if (a.field === 'project') move.boardId = a.value
1787 else Object.assign(move, { status: a.value, agent: a.agent, model: a.model, dispatchComment: a.dispatchComment })
1788 validateAction('move_task', move)
1789 result = { task: this.move(task, move, revision) }
1790 } else {
1791 validateAction('update_task', { id: task.id, expectedRevision: task.revision, requestKey: a.requestKey, [a.field]: a.value })
1792 if (a.field === 'dueDate' && !validDueDate(a.value))
1793 throw new AppError('INVALID_ARGUMENT', 'Choose a valid due date.')
1794 result = { task: this.saveTask({ ...task, [a.field]: a.value }, revision) }
1795 }
1796 } else if (name === 'force_complete_task') {
1797 const task = this.task(a.id)
1798 if (task.deleted) throw new AppError('IN_TRASH', 'Restore the task before marking it done.')
1799 for (const job of this.agentJobs()) {
1800 if (job.taskId !== task.id || !['queued', 'starting', 'working', 'needs-input'].includes(job.state)) continue
1801 this.saveAgentJob({ ...job, state: 'canceled', approval: null, closedByOwner: true, summary: 'Marked done by the user.' })
1802 this.setCommentDelivery(job.id, 'needs-review')
1803 }
1804 this.markPendingCommentsForReview(task.id)
1805 this.assignAgent(task.id, null)
1806 result = { task: task.status === 'Done' ? task : this.move(task, { status: 'Done' }, revision) }
1807 } else if (name === 'companion_delete_archived_task') {
1808 const task = this.task(a.id)
1809 this.expect(task, a.expectedRevision)
1810 if (!task.archivedAt || task.deleted)
1811 throw new AppError('INVALID_STATE', 'This task is no longer in Archive.')
1812 this.assignAgent(task.id, null)
1813 this.db.prepare('DELETE FROM tasks WHERE id=?').run(task.id)
1814 result = { permanentlyDeleted: 1 }
1815 } else if (name === 'companion_empty_trash') {
1816 this.expect({ revision: this.revision() }, a.expectedRevision)
1817 result = { permanentlyDeleted: this.db.prepare('DELETE FROM tasks WHERE deleted_at IS NOT NULL').run().changes }
1818 } else if (name === 'manage_archived_tasks') {
1819 this.expect({ revision: this.revision() }, a.expectedRevision)
1820 const tasks = a.taskIds.map((id) => this.task(id))
1821 if (tasks.some((task) => !task.archivedAt || task.deleted))
1822 throw new AppError('INVALID_STATE', 'Review the current Archive before applying this action.')
1823 const now = new Date().toISOString()
1824 const deleteTask = this.db.prepare('DELETE FROM tasks WHERE id=?')
1825 const assignments = this.agentAssignments()
1826 for (const task of tasks) {
1827 delete assignments[task.id]
1828 if (a.permanently) deleteTask.run(task.id)
1829 else this.saveTask({ ...task, deletedAt: now }, revision)
1830 }
1831 this.set('agentAssignments', assignments)
1832 result = a.permanently ? { permanentlyDeleted: tasks.length } : { trashed: tasks.length }
1833 } else if (name === 'confirm_destructive_action') {
1834 if (restore) {
1835 this.db.exec(
1836 'DELETE FROM agent_jobs; DELETE FROM tasks; DELETE FROM boards; DELETE FROM operation_receipts;'
1837 )
1838 for (const board of restore.boards)
1839 this.db
1840 .prepare('INSERT INTO boards VALUES (?,?,?,?,?,?,?)')
1841 .run(board.id, board.name, board.position, board.created_at, revision, board.project_key, board.next_task_number)
1842 for (const task of restore.tasks)
1843 this.db
1844 .prepare('INSERT INTO tasks VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)')
1845 .run(
1846 task.id,
1847 task.board_id,
1848 task.title,
1849 task.notes,
1850 task.status,
1851 task.position,
1852 task.created_at,
1853 task.updated_at,
1854 task.deleted_at,
1855 revision,
1856 task.priority,
1857 task.definition_of_done,
1858 task.due_date,
1859 task.task_key,
1860 task.completed_at,
1861 task.archived_at,
1862 task.plan_markdown || legacyPlan(task.notes),
1863 task.issue_type
1864 )
1865 this.backfillTaskKeys()
1866 for (const row of restore.taskHistory) this.db.prepare('INSERT INTO task_history VALUES (?,?,?,?,?,?,?,?)').run(row.id,row.task_id,row.version,row.saved_at,row.action,row.origin,row.changes_json,row.state_json)
1867 restoreComments(this, restore.comments, restore.commentImages)
1868 taskActivity.restoreRows(this, restore.activity, restore.activityImages)
1869 taskFiles.restoreRows(this, restore.files)
1870 this.set('theme', restore.preferences.theme)
1871 this.set('selectedBoard', restore.preferences.selectedBoard)
1872 this.set('preferencesRevision', revision)
1873 this.set('boardIcons', restore.boardIcons)
1874 this.set('allTasksOrder', restore.allTasksOrder)
1875 this.set('agentSettings', restore.agentSettings)
1876 this.set('agentPermissionMode', restore.agentSettings.permissionMode ?? 'auto')
1877 this.set('agentModelOverrides', restore.agentModelOverrides)
1878 this.set('projectFolders', restore.projectFolders)
1879 this.set('agentModelCatalogRevision', (this.get('agentModelCatalogRevision') ?? 1) + 1)
1880 this.set('agentAssignments', {})
1881 for (const job of [...restore.agentRuns].reverse()) {
1882 const historical = ['done', 'failed', 'canceled', 'review', 'waiting-input'].includes(job.state)
1883 this.saveAgentJob({
1884 ...job,
1885 state: historical ? job.state : 'interrupted',
1886 approval: null,
1887 summary: historical ? job.summary : 'Restored from backup. Review the existing thread before sending again.',
1888 }, {activity:false})
1889 }
1890 for (const task of this.snapshot().tasks)
1891 if (!task.deleted && task.status === 'Sent to agent')
1892 this.move(task, { status: 'To do' }, revision)
1893 for (const task of this.db.prepare('SELECT id FROM tasks').all()) taskActivity.record(this,task.id,{actor:origin,kind:'restore',summary:'Workspace restored from backup',detail:'Task data, revision requests, activity and revision history were restored from the reviewed backup.'})
1894 result = { restored: restore.summary, safetyBackup: preview.safetyBackup }
1895 } else {
1896 const deletion = preview.action === 'purge_archived_tasks'
1897 ? this.db.prepare('DELETE FROM tasks WHERE id=? AND archived_at IS NOT NULL AND deleted_at IS NULL')
1898 : this.db.prepare('DELETE FROM tasks WHERE id=? AND deleted_at IS NOT NULL')
1899 for (const id of preview.taskIds) {
1900 if (preview.action === 'purge_archived_tasks') this.assignAgent(id, null)
1901 deletion.run(id)
1902 }
1903 result = { permanentlyDeleted: preview.taskIds.length }
1904 }
1905 } else throw new AppError('UNKNOWN_ACTION', 'Unavailable action.')
1906 taskHistory.recordRevision(this, revision, name, origin)
1907 this.set('revision', revision)
1908 result.revision = revision
1909 this.db
1910 .prepare('INSERT INTO operation_receipts VALUES (?,?,?)')
1911 .run(a.requestKey, digest, JSON.stringify(result))
1912 this.db.exec('COMMIT')
1913 } catch (error) {
1914 if (this.db.isTransaction) this.db.exec('ROLLBACK')
1915 throw error
1916 }
1917 if (preview) this.previews.delete(a.token)
1918 this.changed(result.revision)
1919 return result
1920 }
1921 async createBackup(destination, format = 'sqlite') {
1922 const folder = path.join(this.folder, 'Backups')
1923 if (!destination) fs.mkdirSync(folder, { recursive: true, mode: 0o700 })
1924 const target = absolute(
1925 destination ||
1926 path.join(
1927 folder,
1928 `OpenTalon-${new Date().toISOString().replaceAll(':', '-')}-${randomUUID().slice(0, 8)}.${format === 'json' ? 'json' : 'opentalon'}`
1929 )
1930 )
1931 if (format === 'json') {
1932 const snapshot = this.snapshot()
1933 const payload = {
1934 format: 'opentalon-backup',
1935 formatVersion: FORMAT,
1936 appVersion: this.version,
1937 exportedAt: new Date().toISOString(),
1938 columns: statuses,
1939 preferences: { theme: snapshot.theme, selectedBoard: snapshot.selectedBoard },
1940 boardIcons: this.boardIcons(),
1941 allTasksOrder: this.allTasksOrder(),
1942 agentSettings: this.agentSettings(),
1943 agentModelOverrides: this.agentModelCatalog().overrides,
1944 projectFolders: this.get('projectFolders') || {},
1945 agentRuns: this.agentJobs().map(({ approval, ...job }) => job),
1946 agentAssignments: this.agentAssignments(),
1947 ...exportComments(this),
1948 ...taskActivity.exportRows(this),
1949 files: taskFiles.exportRows(this),
1950 boards: this.db.prepare('SELECT * FROM boards ORDER BY position,id').all(),
1951 tasks: this.db.prepare('SELECT * FROM tasks ORDER BY position,id').all(),
1952 taskHistory: this.db.prepare('SELECT * FROM task_history ORDER BY task_id,version').all(),
1953 }
1954 const stageFolder = fs.mkdtempSync(path.join(this.folder, '.backup-'))
1955 try {
1956 const stage = path.join(stageFolder, 'backup.json')
1957 fs.writeFileSync(stage, JSON.stringify(payload, null, 2) + '\n', { mode: 0o600 })
1958 fs.copyFileSync(stage, target, fs.constants.COPYFILE_EXCL)
1959 fs.chmodSync(target, 0o600)
1960 return {
1961 path: target,
1962 format: 'json',
1963 formatVersion: FORMAT,
1964 ...this.counts(),
1965 revision: this.revision(),
1966 }
1967 } catch (error) {
1968 if (error.code === 'EEXIST')
1969 throw new AppError(
1970 'FILE_EXISTS',
1971 'A file already exists at that destination. Choose another filename.'
1972 )
1973 throw error
1974 } finally {
1975 fs.rmSync(stageFolder, { recursive: true, force: true })
1976 }
1977 }
1978 const stageFolder = fs.mkdtempSync(path.join(this.folder, '.backup-'))
1979 const stage = path.join(stageFolder, 'backup.sqlite')
1980 try {
1981 await backup(this.db, stage)
1982 const copy = new DatabaseSync(stage)
1983 try {
1984 copy.exec('PRAGMA journal_mode=DELETE; DELETE FROM operation_receipts;')
1985 for (const row of copy.prepare('SELECT id,data FROM agent_jobs').all()) {
1986 const { approval, ...job } = JSON.parse(row.data)
1987 copy.prepare('UPDATE agent_jobs SET data=? WHERE id=?').run(JSON.stringify(job), row.id)
1988 }
1989 copy
1990 .prepare(
1991 "DELETE FROM settings WHERE key NOT IN ('theme','selectedBoard','revision','preferencesRevision','agentSettings','agentPermissionMode','agentModelOverrides','projectFolders','boardIcons','allTasksOrder')"
1992 )
1993 .run()
1994 copy.exec('VACUUM;')
1995 } finally {
1996 copy.close()
1997 }
1998 fs.copyFileSync(stage, target, fs.constants.COPYFILE_EXCL)
1999 fs.chmodSync(target, 0o600)
2000 return { path: target, formatVersion: FORMAT, ...this.counts(), revision: this.revision() }
2001 } catch (error) {
2002 if (error.code === 'EEXIST')
2003 throw new AppError(
2004 'FILE_EXISTS',
2005 'A file already exists at that destination. Choose another filename.'
2006 )
2007 throw error
2008 } finally {
2009 fs.rmSync(stageFolder, { recursive: true, force: true })
2010 }
2011 }
2012 counts() {
2013 return {
2014 boards: this.boards().length,
2015 tasks: this.db.prepare('SELECT count(*) AS n FROM tasks WHERE deleted_at IS NULL').get().n,
2016 trash: this.db.prepare('SELECT count(*) AS n FROM tasks WHERE deleted_at IS NOT NULL').get()
2017 .n,
2018 }
2019 }
2020 async inspect(file) {
2021 const source = absolute(file)
2022 if (source === this.file)
2023 throw new AppError(
2024 'INVALID_BACKUP',
2025 'Choose an exported backup, rather than the active workspace database.'
2026 )
2027 if (!fs.statSync(source).isFile())
2028 throw new AppError('INVALID_BACKUP', 'Choose a regular backup file.')
2029 const temp = fs.mkdtempSync(path.join(this.folder, '.inspect-'))
2030 let db
2031 try {
2032 const stage = path.join(temp, 'backup.sqlite')
2033 fs.copyFileSync(source, stage)
2034 const sha256 = await fileHash(stage)
2035 const descriptor = fs.openSync(stage, 'r')
2036 const header = Buffer.alloc(16)
2037 try {
2038 fs.readSync(descriptor, header, 0, 16, 0)
2039 } finally {
2040 fs.closeSync(descriptor)
2041 }
2042 let boards, tasks, settings, format
2043 let history = [], activity = [], activityImages = []
2044 let files = []
2045 let icons = {}
2046 let allTasksOrder = []
2047 let commentData = { comments: [], commentImages: [] }
2048 let agentSettings = defaultAgentSettings,
2049 agentRuns = []
2050 let agentModelOverrides = []
2051 let projectFolders = {}
2052 if (header.toString() !== 'SQLite format 3\0') {
2053 const payload = JSON.parse(fs.readFileSync(stage, 'utf8'))
2054 if (!payload || payload.format !== 'opentalon-backup')
2055 throw new AppError('INVALID_BACKUP', 'This is not an OpenTalon backup.')
2056 if (payload.formatVersion > FORMAT)
2057 throw new AppError(
2058 'NEWER_BACKUP',
2059 'This backup needs a newer OpenTalon. Current data is unchanged.'
2060 )
2061 if (
2062 ![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, FORMAT].includes(payload.formatVersion) ||
2063 !Array.isArray(payload.boards) ||
2064 !Array.isArray(payload.tasks) ||
2065 !payload.preferences ||
2066 JSON.stringify(payload.columns) !==
2067 JSON.stringify(payload.formatVersion === 1 ? legacyStatuses : statuses)
2068 )
2069 throw new AppError(
2070 'INVALID_BACKUP',
2071 'This backup has an unsupported format or invalid columns.'
2072 )
2073 boards = payload.boards
2074 tasks = payload.tasks
2075 history = payload.formatVersion >= 10 ? payload.taskHistory : []
2076 activity = payload.formatVersion >= 11 ? payload.activity : []
2077 activityImages = payload.formatVersion >= 11 ? payload.activityImages : []
2078 settings = payload.preferences
2079 icons = payload.boardIcons
2080 allTasksOrder = payload.allTasksOrder
2081 format = payload.formatVersion
2082 if (format >= 14) files = payload.files
2083 agentSettings = payload.agentSettings || agentSettings
2084 agentModelOverrides = validateModelOverrides(payload.agentModelOverrides ?? [])
2085 projectFolders = payload.projectFolders ?? {}
2086 agentRuns = payload.agentRuns || []
2087 if (format >= 3)
2088 commentData = { comments: payload.comments, commentImages: payload.commentImages }
2089 } else {
2090 db = new DatabaseSync(stage, { readOnly: true })
2091 format = db.prepare('PRAGMA user_version').get().user_version
2092 if (format > FORMAT)
2093 throw new AppError(
2094 'NEWER_BACKUP',
2095 'This backup needs a newer OpenTalon. Current data is unchanged.'
2096 )
2097 if (
2098 ![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, FORMAT].includes(format) ||
2099 db.prepare('PRAGMA application_id').get().application_id !== APPLICATION_ID
2100 )
2101 throw new AppError('INVALID_BACKUP', 'This is not a supported OpenTalon backup.')
2102 if (
2103 db
2104 .prepare('PRAGMA integrity_check')
2105 .all()
2106 .some((row) => row.integrity_check !== 'ok') ||
2107 db.prepare('PRAGMA foreign_key_check').all().length
2108 )
2109 throw new AppError('INVALID_BACKUP', 'This backup failed SQLite integrity validation.')
2110 boards = db.prepare('SELECT * FROM boards ORDER BY position,id').all()
2111 tasks = db.prepare('SELECT * FROM tasks ORDER BY position,id').all()
2112 history = format >= 10 ? db.prepare('SELECT * FROM task_history ORDER BY task_id,version').all() : []
2113 if(format >= 11) {
2114 activity = db.prepare('SELECT * FROM task_activity ORDER BY sequence').all()
2115 activityImages = db.prepare('SELECT * FROM activity_images ORDER BY rowid').all().map(row=>({...row,data:Buffer.from(row.bytes).toString('base64'),bytes:undefined}))
2116 }
2117 settings = Object.fromEntries(
2118 db
2119 .prepare('SELECT key,value FROM settings')
2120 .all()
2121 .map((row) => [row.key, JSON.parse(row.value)])
2122 )
2123 agentSettings = settings.agentSettings || agentSettings
2124 agentSettings = { ...agentSettings, permissionMode: settings.agentPermissionMode ?? agentSettings.permissionMode }
2125 agentModelOverrides = validateModelOverrides(settings.agentModelOverrides ?? [])
2126 projectFolders = settings.projectFolders ?? {}
2127 icons = settings.boardIcons
2128 allTasksOrder = settings.allTasksOrder
2129 if (format >= 3) commentData = exportComments({ db })
2130 if (format >= 14) files = taskFiles.exportRows({ db })
2131 if (format >= 2)
2132 agentRuns = db
2133 .prepare('SELECT data FROM agent_jobs ORDER BY rowid DESC')
2134 .all()
2135 .map((row) => JSON.parse(row.data))
2136 }
2137 if (
2138 !boards.length ||
2139 !themes.includes(settings.theme) ||
2140 !boards.some((board) => board.id === settings.selectedBoard)
2141 )
2142 throw new AppError('INVALID_BACKUP', 'This backup has invalid preferences or no boards.')
2143 const ids = new Set(boards.map((board) => board.id))
2144 if (format < 6)
2145 boards = boards.map((board) => ({ ...board, project_key: null, next_task_number: 1 }))
2146 tasks = tasks.map((task) => ({
2147 ...task,
2148 priority: format < 4 ? 'None' : task?.priority,
2149 definition_of_done: format < 4 ? '' : task?.definition_of_done,
2150 due_date: format < 5 ? null : task?.due_date,
2151 task_key: format < 6 ? null : task?.task_key,
2152 completed_at: format < 7 ? (task?.status === 'Done' ? task.updated_at : null) : task?.completed_at,
2153 archived_at: format < 7 ? null : task?.archived_at,
2154 plan_markdown: format < 8 ? '' : task?.plan_markdown,
2155 issue_type: format < 9 ? 'Issue' : task?.issue_type,
2156 }))
2157 if (ids.size !== boards.length || new Set(tasks.map((task) => task.id)).size !== tasks.length)
2158 throw new AppError('INVALID_BACKUP', 'This backup contains duplicate record IDs.')
2159 for (const board of boards)
2160 if (
2161 !board ||
2162 typeof board.id !== 'string' ||
2163 !board.id.length ||
2164 board.id.length > 150 ||
2165 typeof board.name !== 'string' ||
2166 !board.name.trim() ||
2167 (format >= 6 && (typeof board.project_key !== 'string' || !/^[A-Z]{3}$/.test(board.project_key) ||
2168 !Number.isSafeInteger(board.next_task_number) || board.next_task_number < 1)) ||
2169 board.name.length > 100 ||
2170 !Number.isSafeInteger(board.position) ||
2171 board.position < 0 ||
2172 !Number.isSafeInteger(board.revision) ||
2173 board.revision < 1 ||
2174 typeof board.created_at !== 'string' ||
2175 !Number.isFinite(Date.parse(board.created_at))
2176 )
2177 throw new AppError('INVALID_BACKUP', 'This backup contains an invalid board.')
2178 for (const task of tasks)
2179 if (
2180 !task ||
2181 typeof task.id !== 'string' ||
2182 !task.id.length ||
2183 task.id.length > 150 ||
2184 !ids.has(task.board_id) ||
2185 (format >= 6 && (typeof task.task_key !== 'string' || !taskKeyPattern.test(task.task_key))) ||
2186 typeof task.title !== 'string' ||
2187 !task.title.trim() ||
2188 task.title.length > 500 ||
2189 typeof task.notes !== 'string' ||
2190 task.notes.length > 100000 ||
2191 typeof task.plan_markdown !== 'string' || task.plan_markdown.length > 100000 ||
2192 !task.plan_markdown.isWellFormed() || task.plan_markdown.includes('\0') ||
2193 !statuses.includes(task.status) ||
2194 !['Issue', 'Bug'].includes(task.issue_type) ||
2195 !priorities.includes(task.priority) ||
2196 typeof task.definition_of_done !== 'string' ||
2197 task.definition_of_done.length > 10000 ||
2198 !validDueDate(task.due_date) ||
2199 !Number.isSafeInteger(task.position) ||
2200 task.position < 0 ||
2201 !Number.isSafeInteger(task.revision) ||
2202 task.revision < 1 ||
2203 typeof task.created_at !== 'string' ||
2204 !Number.isFinite(Date.parse(task.created_at)) ||
2205 typeof task.updated_at !== 'string' ||
2206 !Number.isFinite(Date.parse(task.updated_at)) ||
2207 (task.completed_at !== null && (task.status !== 'Done' || typeof task.completed_at !== 'string' ||
2208 !Number.isFinite(Date.parse(task.completed_at)))) ||
2209 (task.archived_at !== null && (typeof task.archived_at !== 'string' ||
2210 !Number.isFinite(Date.parse(task.archived_at)))) ||
2211 !(
2212 task.deleted_at === null ||
2213 (typeof task.deleted_at === 'string' && Number.isFinite(Date.parse(task.deleted_at)))
2214 )
2215 )
2216 throw new AppError('INVALID_BACKUP', 'This backup contains an invalid task.')
2217 if (!projectFolders || typeof projectFolders !== 'object' || Array.isArray(projectFolders) ||
2218 Object.entries(projectFolders).some(([id, folder]) => !ids.has(id) || typeof folder !== 'string' ||
2219 !folder || folder.length > 4000 || !path.isAbsolute(folder) || /\p{Cc}/u.test(folder)))
2220 throw new AppError('INVALID_BACKUP', 'This backup has invalid project folders.')
2221 if (
2222 !agentIds.includes(agentSettings.defaultAgent) ||
2223 (agentSettings.permissionMode !== undefined && !['auto', 'manual', 'full-access'].includes(agentSettings.permissionMode)) ||
2224 typeof agentSettings.workingFolder !== 'string' ||
2225 agentSettings.workingFolder.length > 4000 ||
2226 !Array.isArray(agentRuns) ||
2227 new Set(agentRuns.map((job) => job?.id)).size !== agentRuns.length
2228 )
2229 throw new AppError('INVALID_BACKUP', 'This backup has invalid agent settings or history.')
2230 for (const job of agentRuns) {
2231 if (
2232 !job ||
2233 typeof job.id !== 'string' ||
2234 !job.id.length ||
2235 job.id.length > 150 ||
2236 !tasks.some((task) => task.id === job.taskId) ||
2237 !agentIds.includes(job.agent) ||
2238 (job.model != null && (typeof job.model !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:/@+\[\]-]{0,99}$/.test(job.model))) ||
2239 ![
2240 'queued',
2241 'starting',
2242 'working',
2243 'needs-input',
2244 'waiting-input',
2245 'review',
2246 'done',
2247 'failed',
2248 'canceled',
2249 'interrupted',
2250 ].includes(job.state) ||
2251 typeof job.workingFolder !== 'string' ||
2252 job.workingFolder.length > 4000 ||
2253 typeof job.summary !== 'string' ||
2254 job.summary.length > 10000 ||
2255 !(
2256 job.threadId === null ||
2257 (typeof job.threadId === 'string' && /^[a-zA-Z0-9_-]{1,150}$/.test(job.threadId))
2258 ) ||
2259 !Number.isFinite(Date.parse(job.createdAt)) ||
2260 !Number.isFinite(Date.parse(job.updatedAt))
2261 )
2262 throw new AppError('INVALID_BACKUP', 'This backup contains invalid agent history.')
2263 }
2264 taskActivity.validateRows(activity, activityImages, tasks, commentData.comments)
2265 taskHistory.validateRows(history, tasks)
2266 validateComments(commentData.comments, commentData.commentImages, tasks)
2267 taskFiles.validateRows(files, tasks)
2268 const taskIds = new Set(tasks.map((task) => task.id))
2269 return {
2270 boards,
2271 tasks,
2272 ...commentData,
2273 files,
2274 taskHistory: history, activity, activityImages,
2275 agentSettings,
2276 agentModelOverrides,
2277 projectFolders,
2278 agentRuns: agentRuns.map(
2279 ({
2280 id,
2281 taskId,
2282 agent,
2283 model,
2284 workingFolder,
2285 state,
2286 threadId,
2287 summary,
2288 createdAt,
2289 updatedAt,
2290 }) => ({
2291 id,
2292 taskId,
2293 agent,
2294 model,
2295 workingFolder,
2296 state,
2297 threadId,
2298 summary,
2299 createdAt,
2300 updatedAt,
2301 })
2302 ),
2303 preferences: { theme: settings.theme, selectedBoard: settings.selectedBoard },
2304 // Icons are optional: older backups have none, and unknown values fall back to the default.
2305 boardIcons: Object.fromEntries(
2306 Object.entries(
2307 icons && typeof icons === 'object' && !Array.isArray(icons) ? icons : {}
2308 ).filter(([id, icon]) => ids.has(id) && boardIcons.includes(icon))
2309 ),
2310 // Optional too: keep only ids of tasks in this backup, once each.
2311 allTasksOrder: [
2312 ...new Set(
2313 (Array.isArray(allTasksOrder) ? allTasksOrder : []).filter((id) => taskIds.has(id))
2314 ),
2315 ],
2316 summary: {
2317 path: source,
2318 formatVersion: format,
2319 boards: boards.length,
2320 tasks: tasks.filter((task) => task.deleted_at === null).length,
2321 trash: tasks.filter((task) => task.deleted_at !== null).length,
2322 sha256,
2323 },
2324 }
2325 } catch (error) {
2326 if (error instanceof AppError) throw error
2327 throw new AppError(
2328 'INVALID_BACKUP',
2329 `Could not read this backup: ${error.message}. Current data is unchanged.`
2330 )
2331 } finally {
2332 db?.close()
2333 fs.rmSync(temp, { recursive: true, force: true })
2334 }
2335 }
2336 async preview(a) {
2337 if (a.action === 'restore_backup' && (!a.path || a.taskIds))
2338 throw new AppError('INVALID_ARGUMENT', 'Restore requires path and no taskIds.')
2339 if (['purge_tasks', 'purge_archived_tasks'].includes(a.action) && (!a.taskIds || a.path))
2340 throw new AppError('INVALID_ARGUMENT', 'Task removal requires taskIds and no path.')
2341 if (a.action === 'empty_trash' && (a.taskIds || a.path))
2342 throw new AppError('INVALID_ARGUMENT', 'Empty Trash takes no path or taskIds.')
2343 const token = randomUUID()
2344 const preview = {
2345 action: a.action,
2346 revision: this.revision(),
2347 expires: Date.now() + 5 * 60 * 1000,
2348 }
2349 let summary
2350 if (a.action === 'restore_backup') {
2351 summary = (await this.inspect(a.path)).summary
2352 Object.assign(preview, { path: summary.path, sha256: summary.sha256 })
2353 } else {
2354 const tasks =
2355 a.action === 'empty_trash'
2356 ? this.db.prepare('SELECT * FROM tasks WHERE deleted_at IS NOT NULL').all().map(taskView)
2357 : a.taskIds.map((id) => this.task(id))
2358 if (a.action === 'purge_archived_tasks') {
2359 if (tasks.some((task) => task.deleted || !task.archivedAt))
2360 throw new AppError('INVALID_STATE', 'Only tasks in Archive can be removed with this action.')
2361 } else if (tasks.some((task) => !task.deleted)) {
2362 throw new AppError('INVALID_STATE', 'Only tasks in Trash can be permanently removed.')
2363 }
2364 preview.taskIds = tasks.map((task) => task.id)
2365 summary = {
2366 count: tasks.length,
2367 tasks: tasks.map((task) => ({ id: task.id, title: task.title, boardId: task.boardId })),
2368 }
2369 }
2370 for (const [key, value] of this.previews)
2371 if (value.expires < Date.now()) this.previews.delete(key)
2372 if (this.previews.size > 100) this.previews.delete(this.previews.keys().next().value)
2373 this.previews.set(token, preview)
2374 return {
2375 token,
2376 action: a.action,
2377 summary,
2378 current: this.counts(),
2379 revision: preview.revision,
2380 expiresAt: new Date(preview.expires).toISOString(),
2381 requiresConfirmation: true,
2382 }
2383 }
2384 importPrototype(workspace) {
2385 if (this.get('prototypeImported')) return { imported: false }
2386 const fresh =
2387 this.revision() === 1 &&
2388 this.counts().tasks === 0 &&
2389 this.counts().trash === 0 &&
2390 this.boards().length === 1
2391 if (!fresh) return { imported: false }
2392 if (
2393 !workspace ||
2394 workspace.version !== 1 ||
2395 !Array.isArray(workspace.boards) ||
2396 !workspace.boards.length ||
2397 !Array.isArray(workspace.tasks) ||
2398 workspace.boards.length > 1000 ||
2399 workspace.tasks.length > 100000 ||
2400 !themes.includes(workspace.theme)
2401 )
2402 throw new AppError(
2403 'INVALID_PROTOTYPE',
2404 'The earlier prototype could not be imported. Its original data is preserved.'
2405 )
2406 const boards = workspace.boards.map((board, position) => ({
2407 id: board.id,
2408 name: board.name,
2409 position,
2410 created_at: new Date().toISOString(),
2411 }))
2412 const ids = new Set(boards.map((board) => board.id))
2413 if (
2414 ids.size !== boards.length ||
2415 boards.some(
2416 (board) =>
2417 typeof board.id !== 'string' ||
2418 !board.id ||
2419 board.id.length > 150 ||
2420 typeof board.name !== 'string' ||
2421 !board.name.trim() ||
2422 board.name.length > 100
2423 )
2424 )
2425 throw new AppError('INVALID_PROTOTYPE', 'Invalid prototype boards; original data preserved.')
2426 if (
2427 new Set(workspace.tasks.map((task) => task.id)).size !== workspace.tasks.length ||
2428 workspace.tasks.some(
2429 (task) =>
2430 typeof task.id !== 'string' ||
2431 !task.id ||
2432 task.id.length > 150 ||
2433 !ids.has(task.boardId) ||
2434 typeof task.title !== 'string' ||
2435 !task.title.trim() ||
2436 task.title.length > 500 ||
2437 typeof task.notes !== 'string' ||
2438 task.notes.length > 100000 ||
2439 !statuses.includes(task.status) ||
2440 !Number.isSafeInteger(task.position) ||
2441 task.position < 0 ||
2442 typeof task.deleted !== 'boolean'
2443 )
2444 )
2445 throw new AppError('INVALID_PROTOTYPE', 'Invalid prototype tasks; original data preserved.')
2446 this.db.exec('BEGIN IMMEDIATE')
2447 try {
2448 this.db.exec('DELETE FROM boards')
2449 for (const board of boards)
2450 this.db
2451 .prepare('INSERT INTO boards (id,name,position,created_at,revision) VALUES (?,?,?,?,?)')
2452 .run(board.id, board.name, board.position, board.created_at, 2)
2453 const now = new Date().toISOString()
2454 for (const task of workspace.tasks)
2455 this.db
2456 .prepare(
2457 'INSERT INTO tasks (id,board_id,title,notes,status,position,created_at,updated_at,deleted_at,revision) VALUES (?,?,?,?,?,?,?,?,?,?)'
2458 )
2459 .run(
2460 task.id,
2461 task.boardId,
2462 task.title.trim(),
2463 task.notes,
2464 task.status,
2465 task.position,
2466 now,
2467 now,
2468 task.deleted ? now : null,
2469 2
2470 )
2471 this.backfillTaskKeys()
2472 this.set('theme', workspace.theme)
2473 this.set(
2474 'selectedBoard',
2475 ids.has(workspace.selectedBoard) ? workspace.selectedBoard : boards[0].id
2476 )
2477 this.set('preferencesRevision', 2)
2478 this.set('revision', 2)
2479 taskHistory.recordRevision(this, 2, 'imported', 'OpenTalon')
2480 this.set('prototypeImported', true)
2481 this.db.exec('COMMIT')
2482 this.changed(2)
2483 return { imported: true }
2484 } catch (error) {
2485 this.db.exec('ROLLBACK')
2486 throw error
2487 }
2488 }
2489}
2490module.exports = { Store, statuses, FORMAT, APPLICATION_ID, argumentHash }