@myrialabs/clopen 0.4.40 → 0.4.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/.env.example +1 -1
  2. package/backend/artifacts/detect.ts +15 -3
  3. package/backend/artifacts/generate.ts +2 -2
  4. package/backend/artifacts/index.ts +12 -4
  5. package/backend/artifacts/markers.ts +24 -1
  6. package/backend/artifacts/matrix.ts +47 -3
  7. package/backend/artifacts/sync.test.ts +3 -3
  8. package/backend/artifacts/sync.ts +8 -20
  9. package/backend/artifacts/types.ts +9 -3
  10. package/backend/auth/permissions.ts +6 -11
  11. package/backend/auth/session-cleanup.ts +10 -1
  12. package/backend/auth/tokens.ts +9 -1
  13. package/backend/chat/stream-manager.ts +50 -0
  14. package/backend/database/crypto/secret-columns.ts +5 -1
  15. package/backend/database/index.ts +18 -0
  16. package/backend/database/migrations/079_merge_commands_into_skills.ts +222 -0
  17. package/backend/database/migrations/080_create_file_shares.ts +111 -0
  18. package/backend/database/migrations/081_create_push_subscriptions.ts +32 -0
  19. package/backend/database/migrations/082_create_git_identities.test.ts +186 -0
  20. package/backend/database/migrations/082_create_git_identities.ts +122 -0
  21. package/backend/database/migrations/index.ts +28 -0
  22. package/backend/database/queries/file-share-queries.ts +163 -0
  23. package/backend/database/queries/git-identity-queries.ts +290 -0
  24. package/backend/database/queries/index.ts +8 -4
  25. package/backend/database/queries/profile-queries.ts +5 -3
  26. package/backend/database/queries/push-subscription-queries.test.ts +90 -0
  27. package/backend/database/queries/push-subscription-queries.ts +99 -0
  28. package/backend/database/queries/skill-queries.ts +96 -18
  29. package/backend/engine/adapters/claude/environment.ts +11 -1
  30. package/backend/engine/adapters/claude/stream.ts +3 -2
  31. package/backend/engine/adapters/cline/stream.ts +3 -3
  32. package/backend/engine/adapters/codex/stream.ts +38 -6
  33. package/backend/engine/adapters/copilot/stream.ts +3 -3
  34. package/backend/engine/adapters/cursor/stream.ts +25 -3
  35. package/backend/engine/adapters/opencode/server.ts +26 -2
  36. package/backend/engine/adapters/opencode/stream.ts +8 -7
  37. package/backend/engine/adapters/pi/stream.ts +2 -2
  38. package/backend/engine/adapters/qwen/stream.ts +5 -3
  39. package/backend/engine/artifact-sync.ts +26 -20
  40. package/backend/engine/docs/artifacts.md +81 -22
  41. package/backend/engine/docs/quick-reference.md +2 -1
  42. package/backend/engine/resolve-model.test.ts +108 -0
  43. package/backend/engine/resolve-model.ts +53 -10
  44. package/backend/engine/structured-helpers.ts +22 -0
  45. package/backend/engine/types.ts +10 -0
  46. package/backend/files/file-shares.ts +369 -0
  47. package/backend/files/path-browsing.ts +27 -21
  48. package/backend/git/git-executor.ts +28 -2
  49. package/backend/git/git-service.ts +59 -40
  50. package/backend/git/identity/cli.test.ts +58 -0
  51. package/backend/git/identity/cli.ts +201 -0
  52. package/backend/git/identity/credential-helper.test.ts +242 -0
  53. package/backend/git/identity/env.test.ts +214 -0
  54. package/backend/git/identity/env.ts +193 -0
  55. package/backend/git/identity/import-local.test.ts +199 -0
  56. package/backend/git/identity/import-local.ts +141 -0
  57. package/backend/git/identity/index.ts +78 -0
  58. package/backend/git/identity/keys.ts +183 -0
  59. package/backend/git/identity/resolve.ts +140 -0
  60. package/backend/git/identity/scope-config.test.ts +145 -0
  61. package/backend/git/identity/scope-config.ts +175 -0
  62. package/backend/git/identity/service.ts +297 -0
  63. package/backend/http/files-shared.test.ts +505 -0
  64. package/backend/http/files-shared.ts +351 -0
  65. package/backend/http/push.ts +150 -0
  66. package/backend/index.ts +24 -0
  67. package/backend/instructions/index.ts +1 -1
  68. package/backend/instructions/sync.ts +30 -6
  69. package/backend/memory/compose.ts +2 -2
  70. package/backend/memory/consolidate.ts +2 -2
  71. package/backend/memory/extract/episodic.ts +2 -2
  72. package/backend/memory/judge.ts +2 -2
  73. package/backend/preview/browser/browser-console-manager.ts +214 -34
  74. package/backend/preview/browser/browser-pool.ts +526 -123
  75. package/backend/preview/browser/browser-preview-service.ts +192 -8
  76. package/backend/preview/browser/browser-tab-lifecycle.test.ts +240 -0
  77. package/backend/preview/browser/browser-tab-lifecycle.ts +495 -0
  78. package/backend/preview/browser/browser-tab-manager.ts +291 -65
  79. package/backend/preview/browser/capture-profile.ts +15 -1
  80. package/backend/preview/browser/types.ts +26 -1
  81. package/backend/profiles/service.ts +7 -6
  82. package/backend/push/sender.ts +172 -0
  83. package/backend/push/tags.ts +25 -0
  84. package/backend/push/vapid-keys.ts +77 -0
  85. package/backend/push/webpush-crypto.test.ts +200 -0
  86. package/backend/push/webpush-crypto.ts +231 -0
  87. package/backend/skills/detect.ts +28 -0
  88. package/backend/skills/index.ts +22 -4
  89. package/backend/skills/invoke.test.ts +114 -0
  90. package/backend/skills/invoke.ts +222 -0
  91. package/backend/skills/service.ts +194 -44
  92. package/backend/skills/spec.ts +35 -0
  93. package/backend/skills/sync.ts +85 -55
  94. package/backend/subagents/detect.ts +2 -3
  95. package/backend/subagents/sync.ts +15 -8
  96. package/backend/terminal/ptykit.ts +24 -0
  97. package/backend/work/pull-requests.ts +2 -2
  98. package/backend/ws/chat/stream.ts +100 -8
  99. package/backend/ws/files/index.ts +4 -0
  100. package/backend/ws/files/share.ts +95 -0
  101. package/backend/ws/git/branch-name.ts +2 -2
  102. package/backend/ws/git/branch.ts +17 -6
  103. package/backend/ws/git/commit-message.ts +2 -2
  104. package/backend/ws/git/commit.ts +6 -5
  105. package/backend/ws/git/conflict.ts +3 -2
  106. package/backend/ws/git/identity-context.ts +91 -0
  107. package/backend/ws/git/identity.ts +200 -0
  108. package/backend/ws/git/index.ts +3 -1
  109. package/backend/ws/git/remote.ts +57 -11
  110. package/backend/ws/index.ts +3 -4
  111. package/backend/ws/preview/browser/data.ts +60 -0
  112. package/backend/ws/preview/browser/interact.ts +6 -0
  113. package/backend/ws/preview/browser/tab-info.ts +9 -1
  114. package/backend/ws/preview/browser/tab.ts +64 -8
  115. package/backend/ws/preview/index.ts +21 -0
  116. package/backend/ws/profiles/crud.ts +2 -3
  117. package/backend/ws/skills/catalog.ts +5 -1
  118. package/backend/ws/skills/crud.ts +128 -22
  119. package/backend/ws/skills/index.ts +4 -1
  120. package/backend/ws/user/crud.ts +12 -3
  121. package/bin/clopen.ts +9 -0
  122. package/dist/assets/{index-D4igjF6e.js → index-BynqyvF4.js} +1 -1
  123. package/dist/assets/{index-DONNwiXm.js → index-DLoJsmNQ.js} +1 -1
  124. package/dist/assets/{main-BrfXH1bL.js → main-CUyZAmqt.js} +601 -592
  125. package/dist/assets/main-DVCW3cfr.css +1 -0
  126. package/dist/index.html +7 -2
  127. package/dist/sw.js +112 -0
  128. package/package.json +2 -2
  129. package/shared/constants/engine-tools.ts +31 -6
  130. package/shared/constants/notification-messages.ts +142 -0
  131. package/shared/types/git-identity.ts +112 -0
  132. package/shared/types/unified/stream.ts +7 -0
  133. package/backend/commands/detect.ts +0 -25
  134. package/backend/commands/index.ts +0 -9
  135. package/backend/commands/service.ts +0 -178
  136. package/backend/commands/store.ts +0 -45
  137. package/backend/commands/sync.ts +0 -94
  138. package/backend/database/queries/command-queries.ts +0 -82
  139. package/backend/ws/commands/crud.ts +0 -157
  140. package/backend/ws/commands/index.ts +0 -8
  141. package/dist/assets/main-CT1PygsW.css +0 -1
@@ -0,0 +1,222 @@
1
+ import { join } from 'path';
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import type { DatabaseConnection } from '$shared/types/database/connection';
4
+ import { getClopenDir } from '$backend/utils/paths';
5
+ import { debug } from '$shared/utils/logger';
6
+
7
+ export const description = 'Merge commands into skills: one table, one on-disk store, trigger-based invocation';
8
+
9
+ /**
10
+ * Skills and Commands were two features over one mechanic. Both stored a
11
+ * frontmatter + Markdown document, both synced through `materializeArtifacts`,
12
+ * both were profile-bundled — they differed only in WHO pulls the trigger (the
13
+ * model for a Skill, the user for a Command) and in on-disk shape (folder vs
14
+ * single file).
15
+ *
16
+ * This migration folds Commands into Skills. A skill now carries:
17
+ * - `triggers` : comma list of `auto` (model-invoked) and/or `slash`
18
+ * (user-invoked as `/<slug>`). Existing skills get
19
+ * `auto`; migrated commands get `slash`.
20
+ * - `argument_hint` : the old command hint, shown in the "/" picker.
21
+ * - `uses` : JSON array of slugs force-loaded when this skill runs.
22
+ *
23
+ * The old per-command `model_by_engine` override is NOT carried across. A skill
24
+ * runs on the session's model whichever way it is invoked; keeping a model pin
25
+ * on the `slash` half only would have made the two triggers behave differently
26
+ * for no reason a user could see.
27
+ *
28
+ * Each `{clopenDir}/commands/<slug>.md` is COPIED to
29
+ * `{clopenDir}/skills/<slug>/SKILL.md`, and `profile_items` rows of type
30
+ * `'command'` are re-typed to `'skill'` under the (possibly de-duped) slug.
31
+ *
32
+ * Copied, not moved, and an existing SKILL.md is never overwritten with an empty
33
+ * body. A command document is prose the user wrote by hand and Clopen holds the
34
+ * only copy of; a migration that deletes the source has exactly one chance to be
35
+ * right, and if it runs against a database whose files aren't beside it — a DB
36
+ * restored from elsewhere, a data dir assembled by hand — it replaces every
37
+ * prompt with nothing and there is no way back. Leaving `commands/` in place
38
+ * costs a stale folder and buys a second chance.
39
+ */
40
+
41
+ interface LegacyCommandRow {
42
+ id: number;
43
+ slug: string;
44
+ name: string;
45
+ description: string;
46
+ argument_hint: string | null;
47
+ source: string;
48
+ is_enabled: number;
49
+ created_at: string;
50
+ }
51
+
52
+ /** Quote a scalar for YAML output only when it could otherwise be misparsed. */
53
+ function quoteIfNeeded(value: string): string {
54
+ if (value === '') return '""';
55
+ if (/[:#"'\n]|^[\s]|[\s]$|^[[{>|&*!%@`]/.test(value)) {
56
+ return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
57
+ }
58
+ return value;
59
+ }
60
+
61
+ /** Split a legacy command `.md` into its frontmatter map and body. */
62
+ function parseDoc(raw: string): { frontmatter: Record<string, string>; body: string } {
63
+ const text = raw.replace(/^\uFEFF/, '');
64
+ const match = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n([\s\S]*))?$/.exec(text);
65
+ if (!match) return { frontmatter: {}, body: text.trim() };
66
+ const frontmatter: Record<string, string> = {};
67
+ for (const line of match[1].split(/\r?\n/)) {
68
+ const kv = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
69
+ if (kv) frontmatter[kv[1]] = kv[2].trim().replace(/^["']|["']$/g, '');
70
+ }
71
+ return { frontmatter, body: (match[2] ?? '').replace(/^\r?\n/, '') };
72
+ }
73
+
74
+ function columnExists(db: DatabaseConnection, table: string, column: string): boolean {
75
+ const rows = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];
76
+ return rows.some(r => r.name === column);
77
+ }
78
+
79
+ function tableExists(db: DatabaseConnection, table: string): boolean {
80
+ const row = db.prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`).get(table);
81
+ return !!row;
82
+ }
83
+
84
+ export const up = (db: DatabaseConnection): void => {
85
+ debug.log('migration', 'Merging commands into skills...');
86
+
87
+ // ── 1. Widen the skills table ──
88
+ const columns: [string, string][] = [
89
+ ['triggers', `TEXT NOT NULL DEFAULT 'auto'`],
90
+ ['argument_hint', 'TEXT'],
91
+ ['uses', `TEXT NOT NULL DEFAULT '[]'`]
92
+ ];
93
+ for (const [name, definition] of columns) {
94
+ if (!columnExists(db, 'skills', name)) {
95
+ db.exec(`ALTER TABLE skills ADD COLUMN ${name} ${definition}`);
96
+ }
97
+ }
98
+
99
+ if (!tableExists(db, 'commands')) {
100
+ debug.log('migration', 'No commands table — skills widened, nothing to fold');
101
+ return;
102
+ }
103
+
104
+ // ── 2. Fold every command row into skills ──
105
+ const commands = db.prepare(`SELECT * FROM commands ORDER BY created_at ASC`).all() as LegacyCommandRow[];
106
+ const skillsRoot = join(getClopenDir(), 'skills');
107
+ const commandsRoot = join(getClopenDir(), 'commands');
108
+
109
+ const slugTaken = (slug: string): boolean =>
110
+ !!db.prepare(`SELECT 1 FROM skills WHERE slug = ?`).get(slug);
111
+
112
+ for (const command of commands) {
113
+ // A command slug may collide with an existing skill slug — they were
114
+ // separate namespaces until now. Keep both, suffixing the newcomer.
115
+ let slug = command.slug;
116
+ if (slugTaken(slug)) {
117
+ slug = `${command.slug}-command`.slice(0, 64);
118
+ for (let i = 2; slugTaken(slug) && i < 1000; i++) {
119
+ slug = `${command.slug}-command-${i}`.slice(0, 64);
120
+ }
121
+ }
122
+
123
+ // Copy the document: `commands/<slug>.md` → `skills/<slug>/SKILL.md`.
124
+ const legacyPath = join(commandsRoot, `${command.slug}.md`);
125
+ const skillMdPath = join(skillsRoot, slug, 'SKILL.md');
126
+
127
+ const readBody = (path: string): string => {
128
+ if (!existsSync(path)) return '';
129
+ try {
130
+ return parseDoc(readFileSync(path, 'utf8')).body.trim();
131
+ } catch (error) {
132
+ debug.warn('migration', `Could not read ${path}:`, error);
133
+ return '';
134
+ }
135
+ };
136
+
137
+ // Prefer the legacy document; fall back to whatever is already at the
138
+ // destination. The fallback is what makes a second run harmless instead of
139
+ // destructive: without it, a re-run after the source is gone would write an
140
+ // empty body over the one the first run migrated correctly.
141
+ const body = readBody(legacyPath) || readBody(skillMdPath);
142
+ if (!body) {
143
+ debug.warn(
144
+ 'migration',
145
+ `Command "${command.slug}" has no body to migrate — ${legacyPath} is missing or empty. ` +
146
+ `The skill is created so it still appears in Settings → Skills, but its instructions must be re-entered.`
147
+ );
148
+ }
149
+
150
+ const description = command.description.trim() || command.name.trim() || slug;
151
+ const lines = ['---', `name: ${quoteIfNeeded(slug)}`, `description: ${quoteIfNeeded(description)}`, 'triggers: slash'];
152
+ if (command.argument_hint?.trim()) lines.push(`argument-hint: ${quoteIfNeeded(command.argument_hint.trim())}`);
153
+ lines.push('---');
154
+ const document = `${lines.join('\n')}\n\n${body}\n`;
155
+
156
+ try {
157
+ mkdirSync(join(skillsRoot, slug), { recursive: true });
158
+ writeFileSync(skillMdPath, document, 'utf8');
159
+ } catch (error) {
160
+ debug.warn('migration', `Could not write skills/${slug}/SKILL.md:`, error);
161
+ }
162
+
163
+ db.prepare(
164
+ `INSERT INTO skills (slug, name, description, source, license, is_enabled, created_at, triggers, argument_hint, uses)
165
+ VALUES (?, ?, ?, ?, NULL, ?, ?, 'slash', ?, '[]')`
166
+ ).run(
167
+ slug,
168
+ command.name,
169
+ description,
170
+ command.source === 'imported' ? 'imported' : 'custom',
171
+ command.is_enabled,
172
+ command.created_at,
173
+ command.argument_hint
174
+ );
175
+
176
+ // Re-type profile references so a profile that bundled the command keeps
177
+ // bundling it under its new identity.
178
+ db.prepare(
179
+ `UPDATE profile_items SET artifact_type = 'skill', ref = ? WHERE artifact_type = 'command' AND ref = ?`
180
+ ).run(slug, command.slug);
181
+ }
182
+
183
+ // Any profile reference to a command that no longer exists is dead weight.
184
+ db.prepare(`DELETE FROM profile_items WHERE artifact_type = 'command'`).run();
185
+
186
+ db.exec('DROP TABLE commands');
187
+
188
+ // `commandsRoot` is deliberately left on disk. Nothing reads it any more, but
189
+ // it is the user's own writing and the only copy Clopen ever had.
190
+ debug.log('migration', `Folded ${commands.length} command(s) into skills (originals kept in ${commandsRoot})`);
191
+ };
192
+
193
+ export const down = (db: DatabaseConnection): void => {
194
+ debug.log('migration', 'Splitting slash skills back into a commands table...');
195
+ db.exec(`
196
+ CREATE TABLE IF NOT EXISTS commands (
197
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
198
+ slug TEXT NOT NULL UNIQUE,
199
+ name TEXT NOT NULL,
200
+ description TEXT NOT NULL DEFAULT '',
201
+ argument_hint TEXT,
202
+ model TEXT,
203
+ model_by_engine TEXT NOT NULL DEFAULT '{}',
204
+ source TEXT NOT NULL DEFAULT 'custom',
205
+ is_enabled INTEGER NOT NULL DEFAULT 1,
206
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
207
+ )
208
+ `);
209
+ // Slash-only skills came from commands; move them back. Skills that carry both
210
+ // triggers stay put — they have no pre-merge equivalent.
211
+ db.exec(`
212
+ INSERT INTO commands (slug, name, description, argument_hint, source, is_enabled, created_at)
213
+ SELECT slug, name, description, argument_hint,
214
+ CASE WHEN source = 'imported' THEN 'imported' ELSE 'custom' END,
215
+ is_enabled, created_at
216
+ FROM skills WHERE triggers = 'slash'
217
+ `);
218
+ db.exec(`DELETE FROM skills WHERE triggers = 'slash'`);
219
+ // The widened columns are left in place: SQLite cannot drop a column without a
220
+ // table rebuild, and leaving them is harmless for the pre-merge code path.
221
+ debug.log('migration', 'commands table restored');
222
+ };
@@ -0,0 +1,111 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create file_shares table for shareable single-file links';
5
+
6
+ /**
7
+ * File shares back "Share Link…" in the File Explorer: an authenticated user
8
+ * mints a link for one file, embeds it in a link/QR, and the receiving device
9
+ * opens exactly that file without signing in.
10
+ *
11
+ * Stored in SQLite rather than process memory for the same reason
12
+ * `device_codes` is (migration 060): the token is a bearer credential, so a
13
+ * restart must not silently invalidate links a user already handed out. Only
14
+ * the SHA-256 hash is kept.
15
+ *
16
+ * Two knobs the creator chooses per link:
17
+ * - `one_time` — burn on the first open (the default), or stay openable.
18
+ * - `expires_at` — a deadline, or NULL for a link that only a revoke ends.
19
+ *
20
+ * `consumed_at` is the one-time burn, set exactly once by a conditional
21
+ * UPDATE, so concurrent opens cannot both win. `consumer_hash` binds the short
22
+ * streaming-continuation window (byte ranges from an already-open media
23
+ * player) to the client that burned the link, so a leaked URL cannot be
24
+ * range-read by anyone else afterwards. `open_count` / `last_opened_at` track
25
+ * use for both modes, which is what the management list reports.
26
+ */
27
+ export const up = (db: DatabaseConnection): void => {
28
+ debug.log('migration', 'Creating file_shares table...');
29
+
30
+ db.exec(`
31
+ CREATE TABLE IF NOT EXISTS file_shares (
32
+ id TEXT PRIMARY KEY,
33
+ token_hash TEXT NOT NULL UNIQUE,
34
+ file_path TEXT NOT NULL,
35
+ created_by TEXT NOT NULL,
36
+ one_time INTEGER NOT NULL DEFAULT 1,
37
+ expires_at TEXT,
38
+ consumed_at TEXT,
39
+ consumer_hash TEXT,
40
+ open_count INTEGER NOT NULL DEFAULT 0,
41
+ last_opened_at TEXT,
42
+ created_at TEXT NOT NULL,
43
+ FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE CASCADE
44
+ )
45
+ `);
46
+
47
+ // `CREATE TABLE IF NOT EXISTS` leaves an existing table exactly as it was.
48
+ // A database that already holds a `file_shares` from an earlier revision of
49
+ // this migration would therefore keep the older shape and fail at runtime —
50
+ // missing `one_time`, and a NOT NULL `expires_at` that rejects the
51
+ // "until revoked" links this version allows. SQLite cannot relax a column
52
+ // constraint in place, so the table is rebuilt (rows carried over, older
53
+ // rows defaulting to the strict one-time behaviour) rather than patched.
54
+ const columns = db.prepare('PRAGMA table_info(file_shares)').all() as { name: string; notnull: number }[];
55
+ const names = new Set(columns.map((c) => c.name));
56
+ const expiresAt = columns.find((c) => c.name === 'expires_at');
57
+ const needsRebuild =
58
+ !names.has('one_time') ||
59
+ !names.has('open_count') ||
60
+ !names.has('last_opened_at') ||
61
+ expiresAt?.notnull === 1;
62
+
63
+ if (needsRebuild) {
64
+ debug.log('migration', 'file_shares: rebuilding an out-of-date table shape...');
65
+ db.exec('DROP TABLE IF EXISTS file_shares_rebuilt');
66
+ db.exec(`
67
+ CREATE TABLE file_shares_rebuilt (
68
+ id TEXT PRIMARY KEY,
69
+ token_hash TEXT NOT NULL UNIQUE,
70
+ file_path TEXT NOT NULL,
71
+ created_by TEXT NOT NULL,
72
+ one_time INTEGER NOT NULL DEFAULT 1,
73
+ expires_at TEXT,
74
+ consumed_at TEXT,
75
+ consumer_hash TEXT,
76
+ open_count INTEGER NOT NULL DEFAULT 0,
77
+ last_opened_at TEXT,
78
+ created_at TEXT NOT NULL,
79
+ FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE CASCADE
80
+ )
81
+ `);
82
+ db.exec(`
83
+ INSERT INTO file_shares_rebuilt (
84
+ id, token_hash, file_path, created_by, one_time, expires_at,
85
+ consumed_at, consumer_hash, open_count, last_opened_at, created_at
86
+ )
87
+ SELECT
88
+ id, token_hash, file_path, created_by,
89
+ ${names.has('one_time') ? 'one_time' : '1'},
90
+ expires_at, consumed_at,
91
+ ${names.has('consumer_hash') ? 'consumer_hash' : 'NULL'},
92
+ ${names.has('open_count') ? 'open_count' : '0'},
93
+ ${names.has('last_opened_at') ? 'last_opened_at' : 'NULL'},
94
+ created_at
95
+ FROM file_shares
96
+ `);
97
+ db.exec('DROP TABLE file_shares');
98
+ db.exec('ALTER TABLE file_shares_rebuilt RENAME TO file_shares');
99
+ }
100
+
101
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_file_shares_user ON file_shares(created_by)`);
102
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_file_shares_expires ON file_shares(expires_at)`);
103
+
104
+ debug.log('migration', 'file_shares table ready');
105
+ };
106
+
107
+ export const down = (db: DatabaseConnection): void => {
108
+ debug.log('migration', 'Dropping file_shares table...');
109
+ db.exec('DROP TABLE IF EXISTS file_shares');
110
+ debug.log('migration', 'file_shares table dropped');
111
+ };
@@ -0,0 +1,32 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+
3
+ import { debug } from '$shared/utils/logger';
4
+ export const description = 'Create push_subscriptions table for Web Push (mobile background notifications)';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', '📋 Creating push_subscriptions table...');
8
+
9
+ db.exec(`
10
+ CREATE TABLE push_subscriptions (
11
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
12
+ user_id TEXT NOT NULL,
13
+ endpoint TEXT NOT NULL UNIQUE,
14
+ p256dh TEXT NOT NULL,
15
+ auth TEXT NOT NULL,
16
+ user_agent TEXT,
17
+ created_at TEXT NOT NULL
18
+ )
19
+ `);
20
+
21
+ db.exec(`
22
+ CREATE INDEX idx_push_subscriptions_user_id ON push_subscriptions (user_id)
23
+ `);
24
+
25
+ debug.log('migration', '✅ push_subscriptions table created');
26
+ };
27
+
28
+ export const down = (db: DatabaseConnection): void => {
29
+ debug.log('migration', '🗑️ Dropping push_subscriptions table...');
30
+ db.exec('DROP TABLE IF EXISTS push_subscriptions');
31
+ debug.log('migration', '✅ push_subscriptions table dropped');
32
+ };
@@ -0,0 +1,186 @@
1
+ /**
2
+ * The migration's guarantees are in the SQL, so this runs it against a real
3
+ * in-memory SQLite rather than asserting over a mock.
4
+ *
5
+ * Two of them are easy to write and easy to get wrong: the partial unique index
6
+ * that allows at most one default per user, and the cascades that stop a
7
+ * deleted user or project from leaving rows pointing at nothing.
8
+ */
9
+
10
+ import { describe, expect, test } from 'bun:test';
11
+ import { Database } from 'bun:sqlite';
12
+ import type { DatabaseConnection } from '$shared/types/database/connection';
13
+ import { up, down } from './082_create_git_identities';
14
+
15
+ /** Only the columns the new tables reference. */
16
+ function freshDb(): Database {
17
+ const db = new Database(':memory:');
18
+ db.exec('PRAGMA foreign_keys = ON');
19
+ db.exec(`CREATE TABLE users (id TEXT PRIMARY KEY, name TEXT NOT NULL)`);
20
+ db.exec(`CREATE TABLE projects (id TEXT PRIMARY KEY, name TEXT NOT NULL)`);
21
+ db.exec(`CREATE TABLE integration_accounts (id TEXT PRIMARY KEY, label TEXT NOT NULL)`);
22
+ db.exec(`INSERT INTO users (id, name) VALUES ('u1', 'Ada'), ('u2', 'Grace')`);
23
+ db.exec(`INSERT INTO projects (id, name) VALUES ('p1', 'Proj')`);
24
+ up(db as unknown as DatabaseConnection);
25
+ return db;
26
+ }
27
+
28
+ function insertIdentity(db: Database, id: string, userId: string, isDefault = 0): void {
29
+ db.prepare(
30
+ `INSERT INTO git_identities (id, owner_user_id, label, name, email, is_default, created_at, updated_at)
31
+ VALUES (?, ?, ?, 'Ada', 'ada@example.com', ?, '2026-01-01', '2026-01-01')`
32
+ ).run(id, userId, `label-${id}`, isDefault);
33
+ }
34
+
35
+ describe('migration 082', () => {
36
+ test('a user can hold at most one default identity', () => {
37
+ const db = freshDb();
38
+ insertIdentity(db, 'i1', 'u1', 1);
39
+ expect(() => insertIdentity(db, 'i2', 'u1', 1)).toThrow();
40
+ // Non-defaults are unconstrained — the index is partial, not global.
41
+ expect(() => insertIdentity(db, 'i3', 'u1', 0)).not.toThrow();
42
+ expect(() => insertIdentity(db, 'i4', 'u1', 0)).not.toThrow();
43
+ db.close();
44
+ });
45
+
46
+ test('the default is per user, not per install', () => {
47
+ const db = freshDb();
48
+ insertIdentity(db, 'i1', 'u1', 1);
49
+ expect(() => insertIdentity(db, 'i2', 'u2', 1)).not.toThrow();
50
+ db.close();
51
+ });
52
+
53
+ test('one user cannot reuse a label', () => {
54
+ const db = freshDb();
55
+ insertIdentity(db, 'i1', 'u1');
56
+ expect(() =>
57
+ db
58
+ .prepare(
59
+ `INSERT INTO git_identities (id, owner_user_id, label, name, email, created_at, updated_at)
60
+ VALUES ('i2', 'u1', 'label-i1', 'A', 'a@b.c', '2026-01-01', '2026-01-01')`
61
+ )
62
+ .run()
63
+ ).toThrow();
64
+ db.close();
65
+ });
66
+
67
+ test('auth_method is constrained to the methods the code handles', () => {
68
+ const db = freshDb();
69
+ expect(() =>
70
+ db
71
+ .prepare(
72
+ `INSERT INTO git_identities (id, owner_user_id, label, name, email, auth_method, created_at, updated_at)
73
+ VALUES ('i9', 'u1', 'l9', 'A', 'a@b.c', 'carrier-pigeon', '2026-01-01', '2026-01-01')`
74
+ )
75
+ .run()
76
+ ).toThrow();
77
+ db.close();
78
+ });
79
+
80
+ test('deleting a user takes their identities and bindings with them', () => {
81
+ const db = freshDb();
82
+ insertIdentity(db, 'i1', 'u1');
83
+ db.prepare(
84
+ `INSERT INTO git_identity_bindings (project_id, user_id, identity_id, created_at, updated_at)
85
+ VALUES ('p1', 'u1', 'i1', '2026-01-01', '2026-01-01')`
86
+ ).run();
87
+
88
+ db.prepare(`DELETE FROM users WHERE id = 'u1'`).run();
89
+
90
+ expect(db.prepare('SELECT COUNT(*) as c FROM git_identities').get()).toEqual({ c: 0 });
91
+ expect(db.prepare('SELECT COUNT(*) as c FROM git_identity_bindings').get()).toEqual({ c: 0 });
92
+ db.close();
93
+ });
94
+
95
+ test('deleting an identity clears the bindings that pointed at it', () => {
96
+ const db = freshDb();
97
+ insertIdentity(db, 'i1', 'u1');
98
+ db.prepare(
99
+ `INSERT INTO git_identity_bindings (project_id, user_id, identity_id, created_at, updated_at)
100
+ VALUES ('p1', 'u1', 'i1', '2026-01-01', '2026-01-01')`
101
+ ).run();
102
+
103
+ db.prepare(`DELETE FROM git_identities WHERE id = 'i1'`).run();
104
+ expect(db.prepare('SELECT COUNT(*) as c FROM git_identity_bindings').get()).toEqual({ c: 0 });
105
+ db.close();
106
+ });
107
+
108
+ test('one project holds one binding per user', () => {
109
+ const db = freshDb();
110
+ insertIdentity(db, 'i1', 'u1');
111
+ insertIdentity(db, 'i2', 'u1');
112
+ const bind = (identityId: string) =>
113
+ db
114
+ .prepare(
115
+ `INSERT INTO git_identity_bindings (project_id, user_id, identity_id, created_at, updated_at)
116
+ VALUES ('p1', 'u1', ?, '2026-01-01', '2026-01-01')
117
+ ON CONFLICT(project_id, user_id) DO UPDATE SET identity_id = excluded.identity_id`
118
+ )
119
+ .run(identityId);
120
+
121
+ bind('i1');
122
+ bind('i2');
123
+ const rows = db.prepare('SELECT identity_id FROM git_identity_bindings').all();
124
+ expect(rows).toEqual([{ identity_id: 'i2' }]);
125
+ db.close();
126
+ });
127
+
128
+ test('a disconnected integration account leaves the identity intact', () => {
129
+ // The account is where a borrowed token lives; losing it must not delete
130
+ // the identity, which still carries the user's name and email.
131
+ const db = freshDb();
132
+ db.prepare(`INSERT INTO integration_accounts (id, label) VALUES ('a1', 'GitHub')`).run();
133
+ db.prepare(
134
+ `INSERT INTO git_identities (id, owner_user_id, label, name, email, auth_method, integration_account_id, created_at, updated_at)
135
+ VALUES ('i1', 'u1', 'l1', 'Ada', 'ada@example.com', 'https-account', 'a1', '2026-01-01', '2026-01-01')`
136
+ ).run();
137
+
138
+ db.prepare(`DELETE FROM integration_accounts WHERE id = 'a1'`).run();
139
+
140
+ const row = db.prepare('SELECT integration_account_id FROM git_identities WHERE id = ?').get('i1');
141
+ expect(row).toEqual({ integration_account_id: null });
142
+ db.close();
143
+ });
144
+
145
+ test('a user holds at most one mirrored machine identity', () => {
146
+ // The import runs on every list read, so without this a machine config
147
+ // change would append a second copy instead of updating the first.
148
+ const db = freshDb();
149
+ const insertLocal = (id: string, userId: string) =>
150
+ db
151
+ .prepare(
152
+ `INSERT INTO git_identities (id, owner_user_id, label, name, email, source, created_at, updated_at)
153
+ VALUES (?, ?, ?, 'A', 'a@b.c', 'local-machine', '2026-01-01', '2026-01-01')`
154
+ )
155
+ .run(id, userId, `l-${id}`);
156
+
157
+ insertLocal('m1', 'u1');
158
+ expect(() => insertLocal('m2', 'u1')).toThrow();
159
+ // Still per user, not per install.
160
+ expect(() => insertLocal('m3', 'u2')).not.toThrow();
161
+ db.close();
162
+ });
163
+
164
+ test('source is constrained to the two the code knows', () => {
165
+ const db = freshDb();
166
+ expect(() =>
167
+ db
168
+ .prepare(
169
+ `INSERT INTO git_identities (id, owner_user_id, label, name, email, source, created_at, updated_at)
170
+ VALUES ('x', 'u1', 'lx', 'A', 'a@b.c', 'imported-from-space', '2026-01-01', '2026-01-01')`
171
+ )
172
+ .run()
173
+ ).toThrow();
174
+ db.close();
175
+ });
176
+
177
+ test('down() removes both tables', () => {
178
+ const db = freshDb();
179
+ down(db as unknown as DatabaseConnection);
180
+ const tables = db
181
+ .prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE 'git_identit%'`)
182
+ .all();
183
+ expect(tables).toEqual([]);
184
+ db.close();
185
+ });
186
+ });
@@ -0,0 +1,122 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+
3
+ import { debug } from '$shared/utils/logger';
4
+ export const description = 'Create git_identities and git_identity_bindings for per-project git accounts';
5
+
6
+ /**
7
+ * Who a commit is authored by, and which credential reaches the remote.
8
+ *
9
+ * Until now Clopen ran `git` with whatever the machine's `.git/config` or
10
+ * `~/.gitconfig` said. On a laptop that silently works; on a VPS or in Docker
11
+ * it means commits carry a fabricated identity, or fail outright, and an HTTPS
12
+ * push dies against `GIT_TERMINAL_PROMPT=0` with no way to ask for a password.
13
+ *
14
+ * ── Two tables, not one ──
15
+ * An identity is a reusable account: a name, an email, and the credential that
16
+ * proves it to a host. A binding is a per-project, per-user choice of which one
17
+ * to use. They are split for the same reason `deploy_bindings` is separate from
18
+ * `integration_accounts`: one identity normally serves many projects, and
19
+ * folding the choice into the account would make a user re-enter (and re-rotate)
20
+ * the same key for every repository.
21
+ *
22
+ * ── Why identities belong to a user ──
23
+ * Clopen is multi-user. An identity is a claim about who a person is, so it is
24
+ * owned by `users.id` and a teammate's commits can never be attributed to
25
+ * someone else. The binding is keyed `(project_id, user_id)` for the same
26
+ * reason: two people sharing a project each commit as themselves.
27
+ *
28
+ * ── `hosts` ──
29
+ * A JSON array of hostnames this identity's credential is valid for
30
+ * (`["github.com"]`). Resolution is per project first, but a repository can
31
+ * have `origin` and `upstream` on different accounts, so the credential is
32
+ * chosen by matching the remote URL's host. An empty array means "no host
33
+ * claim" — usable for attribution, never selected for credentials.
34
+ *
35
+ * ── `source` ──
36
+ * `local-machine` marks the identity mirrored from the machine's own
37
+ * `git config --global`. It exists so a fresh install already lists the account
38
+ * the user has been committing with rather than showing an empty page, and it is
39
+ * NOT deletable: the machine's config is the thing it reflects, so deleting the
40
+ * row would only make it reappear. Everything else about it is editable — a user
41
+ * who wants a different email on it is expressing a preference, not a mistake,
42
+ * and Clopen stops mirroring once they do.
43
+ *
44
+ * Secrets (`ssh_private_key`, `ssh_passphrase`, `https_token`) are stored
45
+ * through the AES-256-GCM envelope in `backend/database/crypto`, the same way
46
+ * `ssh_connections` stores its keys.
47
+ */
48
+ export const up = (db: DatabaseConnection): void => {
49
+ debug.log('migration', '📋 Creating git_identities table...');
50
+
51
+ db.exec(`
52
+ CREATE TABLE git_identities (
53
+ id TEXT PRIMARY KEY,
54
+ owner_user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
55
+ label TEXT NOT NULL,
56
+ name TEXT NOT NULL,
57
+ email TEXT NOT NULL,
58
+ auth_method TEXT NOT NULL DEFAULT 'none'
59
+ CHECK (auth_method IN ('none','ssh-key','https-token','https-account')),
60
+ ssh_private_key TEXT,
61
+ ssh_public_key TEXT,
62
+ ssh_passphrase TEXT,
63
+ https_username TEXT,
64
+ https_token TEXT,
65
+ integration_account_id TEXT REFERENCES integration_accounts(id) ON DELETE SET NULL,
66
+ hosts TEXT NOT NULL DEFAULT '[]',
67
+ is_default INTEGER NOT NULL DEFAULT 0,
68
+ source TEXT NOT NULL DEFAULT 'manual'
69
+ CHECK (source IN ('manual','local-machine')),
70
+ created_at TEXT NOT NULL,
71
+ updated_at TEXT NOT NULL,
72
+ UNIQUE (owner_user_id, label)
73
+ )
74
+ `);
75
+
76
+ db.exec(`
77
+ CREATE INDEX idx_git_identities_owner ON git_identities (owner_user_id)
78
+ `);
79
+
80
+ // At most one default per user. A partial index is the only way SQLite can
81
+ // state that rule, and stating it here means a bug in the service layer
82
+ // surfaces as a constraint error rather than as two defaults and a coin flip
83
+ // over which identity a project inherits.
84
+ db.exec(`
85
+ CREATE UNIQUE INDEX idx_git_identities_one_default
86
+ ON git_identities (owner_user_id) WHERE is_default = 1
87
+ `);
88
+
89
+ // One mirrored row per user. The import runs whenever the list is read, so
90
+ // without this a machine config change would append a second copy instead of
91
+ // updating the first.
92
+ db.exec(`
93
+ CREATE UNIQUE INDEX idx_git_identities_one_local
94
+ ON git_identities (owner_user_id) WHERE source = 'local-machine'
95
+ `);
96
+
97
+ debug.log('migration', '📋 Creating git_identity_bindings table...');
98
+
99
+ db.exec(`
100
+ CREATE TABLE git_identity_bindings (
101
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
102
+ user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
103
+ identity_id TEXT NOT NULL REFERENCES git_identities(id) ON DELETE CASCADE,
104
+ created_at TEXT NOT NULL,
105
+ updated_at TEXT NOT NULL,
106
+ PRIMARY KEY (project_id, user_id)
107
+ )
108
+ `);
109
+
110
+ db.exec(`
111
+ CREATE INDEX idx_git_identity_bindings_identity ON git_identity_bindings (identity_id)
112
+ `);
113
+
114
+ debug.log('migration', '✅ git_identities and git_identity_bindings created');
115
+ };
116
+
117
+ export const down = (db: DatabaseConnection): void => {
118
+ debug.log('migration', '🗑️ Dropping git identity tables...');
119
+ db.exec('DROP TABLE IF EXISTS git_identity_bindings');
120
+ db.exec('DROP TABLE IF EXISTS git_identities');
121
+ debug.log('migration', '✅ git identity tables dropped');
122
+ };