@myrialabs/clopen 0.4.39 → 0.4.41

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 (173) 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 +29 -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 +42 -0
  14. package/backend/database/crypto/secret-columns.ts +5 -1
  15. package/backend/database/migrations/078_create_worktree_branch_tables.ts +158 -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/index.ts +28 -0
  20. package/backend/database/queries/file-share-queries.ts +163 -0
  21. package/backend/database/queries/index.ts +12 -4
  22. package/backend/database/queries/profile-queries.ts +5 -3
  23. package/backend/database/queries/push-subscription-queries.test.ts +90 -0
  24. package/backend/database/queries/push-subscription-queries.ts +99 -0
  25. package/backend/database/queries/skill-queries.ts +96 -18
  26. package/backend/database/queries/worktree-branch-queries.ts +331 -0
  27. package/backend/db-client/cloning.test.ts +161 -0
  28. package/backend/db-client/cloning.ts +672 -0
  29. package/backend/db-client/connection-url.test.ts +117 -0
  30. package/backend/db-client/connection-url.ts +126 -0
  31. package/backend/db-client/drivers/mongodb.ts +2 -14
  32. package/backend/db-client/drivers/mysql.ts +2 -8
  33. package/backend/db-client/drivers/postgres.ts +10 -13
  34. package/backend/db-client/drivers/redis.ts +2 -6
  35. package/backend/db-client/env/detect.ts +438 -0
  36. package/backend/db-client/env/diff.ts +94 -0
  37. package/backend/db-client/env/env.test.ts +574 -0
  38. package/backend/db-client/env/index.ts +15 -0
  39. package/backend/db-client/env/naming.ts +202 -0
  40. package/backend/db-client/env/service.ts +487 -0
  41. package/backend/db-client/integrations/index.ts +7 -0
  42. package/backend/db-client/integrations/links.ts +41 -10
  43. package/backend/db-client/providers/neon/adapter.ts +522 -0
  44. package/backend/db-client/providers/neon/api-types.ts +182 -0
  45. package/backend/db-client/providers/neon/client.ts +298 -0
  46. package/backend/db-client/providers/neon/endpoints.test.ts +201 -0
  47. package/backend/db-client/providers/neon/endpoints.ts +314 -0
  48. package/backend/db-client/providers/neon/list.test.ts +181 -0
  49. package/backend/db-client/providers/supabase/adapter.ts +25 -2
  50. package/backend/db-client/providers/types.ts +57 -0
  51. package/backend/engine/adapters/claude/stream.ts +2 -1
  52. package/backend/engine/adapters/cline/stream.ts +3 -3
  53. package/backend/engine/adapters/codex/stream.ts +3 -3
  54. package/backend/engine/adapters/copilot/stream.ts +3 -3
  55. package/backend/engine/adapters/cursor/stream.ts +25 -3
  56. package/backend/engine/adapters/opencode/stream.ts +4 -6
  57. package/backend/engine/adapters/pi/stream.ts +2 -2
  58. package/backend/engine/adapters/qwen/stream.ts +2 -2
  59. package/backend/engine/artifact-sync.ts +26 -20
  60. package/backend/engine/docs/artifacts.md +81 -22
  61. package/backend/engine/docs/quick-reference.md +2 -1
  62. package/backend/engine/resolve-model.test.ts +108 -0
  63. package/backend/engine/resolve-model.ts +53 -10
  64. package/backend/engine/structured-helpers.ts +22 -0
  65. package/backend/env-files/discovery.ts +48 -0
  66. package/backend/env-files/edit.ts +213 -0
  67. package/backend/env-files/env-files.test.ts +515 -0
  68. package/backend/env-files/git.ts +27 -0
  69. package/backend/env-files/index.ts +44 -0
  70. package/backend/env-files/keys.ts +69 -0
  71. package/backend/env-files/parse.ts +157 -0
  72. package/backend/env-files/write.ts +229 -0
  73. package/backend/files/file-shares.ts +369 -0
  74. package/backend/files/path-browsing.ts +27 -21
  75. package/backend/http/files-shared.test.ts +505 -0
  76. package/backend/http/files-shared.ts +351 -0
  77. package/backend/http/push.ts +150 -0
  78. package/backend/index.ts +8 -0
  79. package/backend/instructions/index.ts +1 -1
  80. package/backend/instructions/sync.ts +30 -6
  81. package/backend/integrations/health.ts +18 -4
  82. package/backend/integrations/projections/types.ts +9 -2
  83. package/backend/integrations/registry/index.ts +3 -0
  84. package/backend/integrations/registry/providers/context7.ts +1 -0
  85. package/backend/integrations/registry/providers/firecrawl.ts +1 -0
  86. package/backend/integrations/registry/providers/github.ts +1 -0
  87. package/backend/integrations/registry/providers/neon.ts +55 -0
  88. package/backend/integrations/registry/providers/supabase.ts +1 -0
  89. package/backend/integrations/registry/providers/vercel.ts +1 -0
  90. package/backend/integrations/registry/types.ts +2 -0
  91. package/backend/memory/compose.ts +2 -2
  92. package/backend/memory/consolidate.ts +2 -2
  93. package/backend/memory/extract/episodic.ts +2 -2
  94. package/backend/memory/judge.ts +2 -2
  95. package/backend/profiles/service.ts +7 -6
  96. package/backend/push/sender.ts +172 -0
  97. package/backend/push/tags.ts +25 -0
  98. package/backend/push/vapid-keys.ts +77 -0
  99. package/backend/push/webpush-crypto.test.ts +200 -0
  100. package/backend/push/webpush-crypto.ts +231 -0
  101. package/backend/skills/detect.ts +28 -0
  102. package/backend/skills/index.ts +22 -4
  103. package/backend/skills/invoke.test.ts +114 -0
  104. package/backend/skills/invoke.ts +222 -0
  105. package/backend/skills/service.ts +194 -44
  106. package/backend/skills/spec.ts +35 -0
  107. package/backend/skills/sync.ts +85 -55
  108. package/backend/subagents/detect.ts +2 -3
  109. package/backend/subagents/sync.ts +15 -8
  110. package/backend/work/pull-requests.ts +2 -2
  111. package/backend/work/start-work.ts +4 -0
  112. package/backend/worktrees/branching/engine.ts +557 -0
  113. package/backend/worktrees/branching/index.ts +56 -0
  114. package/backend/worktrees/branching/naming.test.ts +118 -0
  115. package/backend/worktrees/branching/naming.ts +97 -0
  116. package/backend/worktrees/branching/projector.test.ts +229 -0
  117. package/backend/worktrees/branching/projector.ts +139 -0
  118. package/backend/worktrees/branching/providers/neon.ts +220 -0
  119. package/backend/worktrees/branching/registry.ts +27 -0
  120. package/backend/worktrees/branching/service.ts +620 -0
  121. package/backend/worktrees/branching/suggest.test.ts +154 -0
  122. package/backend/worktrees/branching/suggest.ts +202 -0
  123. package/backend/worktrees/branching/types.ts +88 -0
  124. package/backend/worktrees/index.ts +7 -0
  125. package/backend/worktrees/service.ts +48 -1
  126. package/backend/ws/chat/stream.ts +100 -8
  127. package/backend/ws/db-client/env.ts +142 -0
  128. package/backend/ws/db-client/index.ts +2 -0
  129. package/backend/ws/files/index.ts +4 -0
  130. package/backend/ws/files/share.ts +95 -0
  131. package/backend/ws/git/branch-name.ts +2 -2
  132. package/backend/ws/git/commit-message.ts +2 -2
  133. package/backend/ws/index.ts +3 -4
  134. package/backend/ws/profiles/crud.ts +2 -3
  135. package/backend/ws/projects/index.ts +6 -1
  136. package/backend/ws/projects/info.ts +70 -6
  137. package/backend/ws/projects/overview.test.ts +108 -0
  138. package/backend/ws/projects/overview.ts +300 -0
  139. package/backend/ws/skills/catalog.ts +5 -1
  140. package/backend/ws/skills/crud.ts +128 -22
  141. package/backend/ws/skills/index.ts +4 -1
  142. package/backend/ws/system/device-info.ts +307 -76
  143. package/backend/ws/user/crud.ts +12 -3
  144. package/backend/ws/worktrees/branching.ts +212 -0
  145. package/backend/ws/worktrees/crud.ts +33 -7
  146. package/backend/ws/worktrees/index.ts +14 -0
  147. package/dist/assets/{index-C8Gi-b6U.js → index-CeNKKSDR.js} +1 -1
  148. package/dist/assets/{index-BrF6nqld.js → index-DW89566K.js} +1 -1
  149. package/dist/assets/main-Cy5DXWPT.js +1207 -0
  150. package/dist/assets/main-DJKj_4By.css +1 -0
  151. package/dist/index.html +7 -2
  152. package/dist/sw.js +112 -0
  153. package/package.json +1 -1
  154. package/shared/constants/engine-tools.ts +31 -6
  155. package/shared/constants/notification-messages.ts +142 -0
  156. package/shared/constants/tool-icons.ts +6 -2
  157. package/shared/types/db-client/env.ts +192 -0
  158. package/shared/types/db-client/index.ts +1 -0
  159. package/shared/types/db-client/integrations.ts +30 -0
  160. package/shared/types/integrations.ts +9 -0
  161. package/shared/types/unified/stream.ts +7 -0
  162. package/shared/types/worktree-branching.ts +315 -0
  163. package/shared/utils/logger.ts +1 -0
  164. package/backend/commands/detect.ts +0 -25
  165. package/backend/commands/index.ts +0 -9
  166. package/backend/commands/service.ts +0 -178
  167. package/backend/commands/store.ts +0 -45
  168. package/backend/commands/sync.ts +0 -94
  169. package/backend/database/queries/command-queries.ts +0 -82
  170. package/backend/ws/commands/crud.ts +0 -157
  171. package/backend/ws/commands/index.ts +0 -8
  172. package/dist/assets/main-Bd3gb79F.css +0 -1
  173. package/dist/assets/main-Bo1hD7mt.js +0 -1191
@@ -0,0 +1,158 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create worktree_branch_bindings and worktree_branches for database branching';
5
+
6
+ /**
7
+ * Worktree database branching — the binding, and the branches it produced.
8
+ *
9
+ * Two tables, for the same reason the Issues surface has two: one records the
10
+ * decision ("give this project's worktrees their own database"), the other
11
+ * records what that decision actually created and therefore what has to be
12
+ * cleaned up.
13
+ *
14
+ * A SOURCE IS NOT ALWAYS AN ACCOUNT, which is why both tables carry
15
+ * `source_kind` and two nullable parent columns instead of a single
16
+ * `account_id`. Neon cuts a branch through its API and needs an integration
17
+ * account; a Postgres running on the user's laptop needs nothing but the DB
18
+ * Client connection that already reaches it. Tying the feature to accounts made
19
+ * it a Neon feature by accident — a database with no vendor behind it had no
20
+ * way in at all.
21
+ */
22
+ export const up = (db: DatabaseConnection): void => {
23
+ debug.log('migration', 'Creating worktree_branch_bindings table...');
24
+
25
+ // ONE BINDING PER PROJECT, which is why `project_id` is the whole primary
26
+ // key rather than half of it as in `work_bindings` and `deploy_bindings`.
27
+ //
28
+ // Those two are keyed per (project, account) because a project genuinely can
29
+ // track issues in two places or deploy to two targets. This one cannot: the
30
+ // binding's entire output is a single environment variable inside a single
31
+ // worktree, and two bindings would both claim it. Making the schema hold a
32
+ // state the feature cannot express would only produce a silent last-writer.
33
+ //
34
+ // `parent_name` is cached alongside the ref for the reason `deploy_bindings`
35
+ // caches `display_name`: a Neon project id is `winter-frost-12345678` and
36
+ // answers no question anyone asked.
37
+ //
38
+ // Exactly ONE of `account_id` and `connection_id` is set, and `source_kind`
39
+ // says which. Both cascade: a disconnected account or a deleted connection
40
+ // leaves a binding that points at nothing, and a binding that points at
41
+ // nothing would fail on every worktree create with a message about a thing
42
+ // the user already removed.
43
+ db.exec(`
44
+ CREATE TABLE IF NOT EXISTS worktree_branch_bindings (
45
+ project_id TEXT PRIMARY KEY REFERENCES projects(id) ON DELETE CASCADE,
46
+ source_kind TEXT NOT NULL DEFAULT 'account',
47
+ account_id TEXT REFERENCES integration_accounts(id) ON DELETE CASCADE,
48
+ connection_id TEXT REFERENCES db_client_connections(id) ON DELETE CASCADE,
49
+ parent_ref TEXT NOT NULL,
50
+ parent_name TEXT NOT NULL,
51
+ config_json TEXT NOT NULL DEFAULT '{}',
52
+ created_at TEXT NOT NULL,
53
+ updated_at TEXT NOT NULL
54
+ )
55
+ `);
56
+
57
+ db.exec(`
58
+ CREATE INDEX IF NOT EXISTS idx_worktree_branch_bindings_account
59
+ ON worktree_branch_bindings(account_id)
60
+ `);
61
+
62
+ db.exec(`
63
+ CREATE INDEX IF NOT EXISTS idx_worktree_branch_bindings_connection
64
+ ON worktree_branch_bindings(connection_id)
65
+ `);
66
+
67
+ debug.log('migration', 'Creating worktree_branches table...');
68
+
69
+ // `worktree_id` is NULLABLE and ON DELETE SET NULL — deliberately NOT a
70
+ // cascade, and this is the load-bearing decision in the whole table.
71
+ //
72
+ // Deleting a worktree deletes its branch at the provider. When that call
73
+ // FAILS — an expired token, a provider outage, a branch the account can no
74
+ // longer reach — the remote branch is still there, costing money and holding
75
+ // data. A cascade would delete the only record of it in the same breath, so
76
+ // the leak would be both silent and unrecoverable: nothing left would know
77
+ // the branch had ever belonged to anything.
78
+ //
79
+ // So the row survives its worktree. `worktree_id IS NULL` is precisely the
80
+ // definition of an orphan, and the orphan list is built from it.
81
+ //
82
+ // `connection_json` holds the branch's own connection string INCLUDING the
83
+ // password, so it is sealed — see `SECRET_COLUMNS`. It lives here rather than
84
+ // only on the projected connection because the projection must be
85
+ // rebuildable from the row alone; a release followed by a re-project would
86
+ // otherwise lose the password and leave a connection that cannot log in.
87
+ // `source_connection_id` deliberately carries NO foreign key, unlike its
88
+ // twin on the binding. The same reasoning as `worktree_id` above: this row
89
+ // is the only record of a real database that exists right now, and deleting
90
+ // the DB Client connection it was copied from must not erase the evidence of
91
+ // the copy. The orphan list is what the user has left to clean it up with.
92
+ db.exec(`
93
+ CREATE TABLE IF NOT EXISTS worktree_branches (
94
+ id TEXT PRIMARY KEY,
95
+ worktree_id TEXT REFERENCES worktrees(id) ON DELETE SET NULL,
96
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
97
+ source_kind TEXT NOT NULL DEFAULT 'account',
98
+ account_id TEXT REFERENCES integration_accounts(id) ON DELETE CASCADE,
99
+ source_connection_id TEXT,
100
+ parent_ref TEXT NOT NULL,
101
+ branch_ref TEXT NOT NULL,
102
+ branch_name TEXT NOT NULL,
103
+ connection_json TEXT,
104
+ connection_id TEXT,
105
+ env_var TEXT NOT NULL,
106
+ env_file TEXT NOT NULL,
107
+ env_status TEXT NOT NULL DEFAULT 'failed',
108
+ env_detail TEXT,
109
+ status TEXT NOT NULL DEFAULT 'active',
110
+ error TEXT,
111
+ strategy TEXT,
112
+ notice TEXT,
113
+ created_at TEXT NOT NULL,
114
+ updated_at TEXT NOT NULL
115
+ )
116
+ `);
117
+
118
+ db.exec(`
119
+ CREATE INDEX IF NOT EXISTS idx_worktree_branches_worktree
120
+ ON worktree_branches(worktree_id)
121
+ `);
122
+
123
+ db.exec(`
124
+ CREATE INDEX IF NOT EXISTS idx_worktree_branches_account
125
+ ON worktree_branches(account_id)
126
+ `);
127
+
128
+ // Identity is (source, parent, branch), and the source is whichever of the
129
+ // two columns is set. A table constraint cannot express that — SQLite treats
130
+ // every NULL as distinct, so `UNIQUE (account_id, …)` would stop enforcing
131
+ // anything the moment the source was a connection.
132
+ db.exec(`
133
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_worktree_branches_identity
134
+ ON worktree_branches(
135
+ source_kind,
136
+ COALESCE(account_id, source_connection_id, ''),
137
+ parent_ref,
138
+ branch_ref
139
+ )
140
+ `);
141
+
142
+ debug.log('migration', 'Worktree branching tables created');
143
+ };
144
+
145
+ export const down = (db: DatabaseConnection): void => {
146
+ debug.log('migration', 'Dropping worktree branching tables...');
147
+ db.exec('DROP INDEX IF EXISTS idx_worktree_branches_identity');
148
+ db.exec('DROP INDEX IF EXISTS idx_worktree_branches_account');
149
+ db.exec('DROP INDEX IF EXISTS idx_worktree_branches_worktree');
150
+ db.exec('DROP TABLE IF EXISTS worktree_branches');
151
+ db.exec('DROP INDEX IF EXISTS idx_worktree_branch_bindings_connection');
152
+ db.exec('DROP INDEX IF EXISTS idx_worktree_branch_bindings_account');
153
+ db.exec('DROP TABLE IF EXISTS worktree_branch_bindings');
154
+ // The remote branches themselves are deliberately left alone. A rollback is
155
+ // a schema operation, and destroying someone's databases from one would be
156
+ // the single worst thing this migration could do.
157
+ debug.log('migration', 'Worktree branching tables dropped — remote branches were left untouched');
158
+ };
@@ -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
+ };
@@ -76,6 +76,10 @@ import * as migration074 from './074_create_work_tables';
76
76
  import * as migration075 from './075_create_deploy_bindings';
77
77
  import * as migration076 from './076_remove_memory_code_graph';
78
78
  import * as migration077 from './077_create_integration_db_links';
79
+ import * as migration078 from './078_create_worktree_branch_tables';
80
+ import * as migration079 from './079_merge_commands_into_skills';
81
+ import * as migration080 from './080_create_file_shares';
82
+ import * as migration081 from './081_create_push_subscriptions';
79
83
 
80
84
  // Export all migrations in order
81
85
  export const migrations = [
@@ -540,6 +544,30 @@ export const migrations = [
540
544
  description: migration077.description,
541
545
  up: migration077.up,
542
546
  down: migration077.down
547
+ },
548
+ {
549
+ id: '078',
550
+ description: migration078.description,
551
+ up: migration078.up,
552
+ down: migration078.down
553
+ },
554
+ {
555
+ id: '079',
556
+ description: migration079.description,
557
+ up: migration079.up,
558
+ down: migration079.down
559
+ },
560
+ {
561
+ id: '080',
562
+ description: migration080.description,
563
+ up: migration080.up,
564
+ down: migration080.down
565
+ },
566
+ {
567
+ id: '081',
568
+ description: migration081.description,
569
+ up: migration081.up,
570
+ down: migration081.down
543
571
  }
544
572
  ];
545
573