@myrialabs/clopen 0.4.8 → 0.4.10

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 (107) hide show
  1. package/README.md +10 -7
  2. package/backend/artifacts/detect.ts +129 -0
  3. package/backend/artifacts/engine-map.ts +53 -0
  4. package/backend/artifacts/frontmatter.ts +68 -0
  5. package/backend/artifacts/generate.ts +105 -0
  6. package/backend/artifacts/index.ts +34 -0
  7. package/backend/artifacts/markers.ts +76 -0
  8. package/backend/artifacts/matrix.ts +247 -0
  9. package/backend/artifacts/slug.ts +35 -0
  10. package/backend/artifacts/sync.ts +130 -0
  11. package/backend/artifacts/types.ts +152 -0
  12. package/backend/auth/permissions.ts +51 -1
  13. package/backend/chat/stream-manager.ts +14 -1
  14. package/backend/commands/detect.ts +25 -0
  15. package/backend/commands/index.ts +9 -0
  16. package/backend/commands/service.ts +178 -0
  17. package/backend/commands/store.ts +45 -0
  18. package/backend/commands/sync.ts +94 -0
  19. package/backend/database/migrations/045_create_commands_table.ts +28 -0
  20. package/backend/database/migrations/046_create_subagents_table.ts +29 -0
  21. package/backend/database/migrations/047_create_instructions_table.ts +29 -0
  22. package/backend/database/migrations/048_add_mcp_tool_overrides.ts +23 -0
  23. package/backend/database/migrations/049_create_permission_sets_table.ts +50 -0
  24. package/backend/database/migrations/050_create_profiles_tables.ts +57 -0
  25. package/backend/database/migrations/051_add_profile_to_sessions.ts +20 -0
  26. package/backend/database/migrations/052_add_default_profile_to_projects.ts +20 -0
  27. package/backend/database/migrations/053_add_profile_to_permission_sets.ts +37 -0
  28. package/backend/database/migrations/054_drop_subagent_agent_type.ts +20 -0
  29. package/backend/database/migrations/055_artifact_model_tools_per_engine.ts +43 -0
  30. package/backend/database/migrations/index.ts +77 -0
  31. package/backend/database/queries/command-queries.ts +82 -0
  32. package/backend/database/queries/index.ts +12 -2
  33. package/backend/database/queries/instruction-queries.ts +62 -0
  34. package/backend/database/queries/mcp-server-queries.ts +25 -0
  35. package/backend/database/queries/permission-set-queries.ts +155 -0
  36. package/backend/database/queries/profile-queries.ts +118 -0
  37. package/backend/database/queries/project-queries.ts +14 -0
  38. package/backend/database/queries/session-queries.ts +21 -0
  39. package/backend/database/queries/subagent-queries.ts +92 -0
  40. package/backend/engine/adapters/claude/stream.ts +27 -3
  41. package/backend/engine/adapters/codex/stream.ts +46 -14
  42. package/backend/engine/adapters/copilot/stream.ts +58 -4
  43. package/backend/engine/adapters/opencode/message-converter.ts +22 -2
  44. package/backend/engine/adapters/opencode/server.ts +166 -210
  45. package/backend/engine/adapters/opencode/stream.ts +150 -24
  46. package/backend/engine/adapters/qwen/stream.ts +23 -3
  47. package/backend/engine/artifact-sync.ts +51 -0
  48. package/backend/engine/types.ts +6 -0
  49. package/backend/instructions/index.ts +8 -0
  50. package/backend/instructions/service.ts +63 -0
  51. package/backend/instructions/sync.ts +56 -0
  52. package/backend/mcp/external/config.ts +42 -20
  53. package/backend/mcp/external/proxy.ts +89 -5
  54. package/backend/mcp/external/tools.ts +88 -0
  55. package/backend/mcp/index.ts +38 -15
  56. package/backend/mcp/internal/config.ts +48 -11
  57. package/backend/mcp/internal/remote-server.ts +9 -1
  58. package/backend/permissions/index.ts +27 -0
  59. package/backend/permissions/materialize.ts +96 -0
  60. package/backend/permissions/resolve.test.ts +162 -0
  61. package/backend/permissions/resolve.ts +106 -0
  62. package/backend/permissions/service.ts +167 -0
  63. package/backend/profiles/index.ts +10 -0
  64. package/backend/profiles/service.ts +169 -0
  65. package/backend/project/status-manager.ts +7 -25
  66. package/backend/skills/index.ts +1 -1
  67. package/backend/skills/sync.ts +88 -128
  68. package/backend/subagents/detect.ts +23 -0
  69. package/backend/subagents/index.ts +10 -0
  70. package/backend/subagents/service.ts +166 -0
  71. package/backend/subagents/store.ts +44 -0
  72. package/backend/subagents/sync.ts +144 -0
  73. package/backend/utils/static-curl.ts +12 -54
  74. package/backend/ws/artifacts/generate.ts +51 -0
  75. package/backend/ws/artifacts/index.ts +8 -0
  76. package/backend/ws/chat/stream.ts +33 -2
  77. package/backend/ws/commands/crud.ts +157 -0
  78. package/backend/ws/commands/index.ts +8 -0
  79. package/backend/ws/git/branch.ts +4 -2
  80. package/backend/ws/git/remote.ts +21 -11
  81. package/backend/ws/index.ts +17 -1
  82. package/backend/ws/instructions/crud.ts +53 -0
  83. package/backend/ws/instructions/index.ts +8 -0
  84. package/backend/ws/mcp/crud.ts +7 -1
  85. package/backend/ws/mcp/index.ts +4 -1
  86. package/backend/ws/mcp/tools.ts +112 -0
  87. package/backend/ws/permissions/crud.ts +72 -0
  88. package/backend/ws/permissions/index.ts +8 -0
  89. package/backend/ws/profiles/crud.ts +149 -0
  90. package/backend/ws/profiles/index.ts +9 -0
  91. package/backend/ws/sessions/crud.ts +12 -0
  92. package/backend/ws/subagents/crud.ts +136 -0
  93. package/backend/ws/subagents/index.ts +8 -0
  94. package/dist/assets/{index-jGo0X72U.js → index-C3kp8wpM.js} +1 -1
  95. package/dist/assets/{index-B_F_OgoC.js → index-cVUk7das.js} +1 -1
  96. package/dist/assets/main-CuCxUeqZ.js +533 -0
  97. package/dist/assets/main-D4pdkiQK.css +1 -0
  98. package/dist/index.html +2 -2
  99. package/package.json +24 -24
  100. package/shared/constants/engine-tools.ts +56 -0
  101. package/shared/types/database/schema.ts +2 -0
  102. package/shared/types/stores/settings.ts +15 -0
  103. package/shared/types/unified/stream.ts +7 -0
  104. package/shared/utils/interactive-input.ts +71 -0
  105. package/shared/utils/logger.ts +6 -0
  106. package/dist/assets/main-BkCc3WEB.js +0 -481
  107. package/dist/assets/main-CWDwET4x.css +0 -1
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Detect on-disk commands (managed effective copies + adoptable real ones) for
3
+ * the Settings UI. Global scope only for now — project scope is surfaced by the
4
+ * per-project detection path when a project is supplied.
5
+ */
6
+
7
+ import { detectArtifacts, type DetectedArtifact, type ArtifactEngine } from '$backend/artifacts';
8
+
9
+ export interface DetectedCommandGroup {
10
+ engine: ArtifactEngine;
11
+ detected: DetectedArtifact[];
12
+ }
13
+
14
+ /** Detect commands across all engines for the given scope. */
15
+ export async function detectCommands(projectPath?: string): Promise<DetectedCommandGroup[]> {
16
+ const engines: ArtifactEngine[] = ['claude', 'codex', 'copilot', 'qwen', 'opencode'];
17
+ const scope = projectPath ? 'project' : 'global';
18
+ const groups = await Promise.all(
19
+ engines.map(async engine => ({
20
+ engine,
21
+ detected: await detectArtifacts('command', { engine, scope, projectPath })
22
+ }))
23
+ );
24
+ return groups.filter(g => g.detected.length > 0);
25
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Custom Commands — public facade. Settings → Commands manages reusable slash
3
+ * command prompts, materialized into each engine at stream start.
4
+ */
5
+
6
+ export { commandService } from './service';
7
+ export type { CommandDTO, CommandInputFields } from './service';
8
+ export { syncCommands, syncCommandsAllEngines, buildCommandsPromptContext } from './sync';
9
+ export { detectCommands } from './detect';
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Command service — keeps the `commands` table and the on-disk canonical store
3
+ * (`{clopenDir}/commands/<slug>.md`) in lockstep for the Settings → Commands
4
+ * CRUD surface. Mirrors the Skills service shape, minus the marketplace.
5
+ */
6
+
7
+ import { commandQueries, type CommandRow } from '$backend/database/queries';
8
+ import { parseDoc, serializeDoc, uniqueSlug, parseEngineMap, stringifyEngineMap, type EngineMap } from '$backend/artifacts';
9
+ import { debug } from '$shared/utils/logger';
10
+ import {
11
+ writeCommandMd,
12
+ readCommandMd,
13
+ deleteCommandMd,
14
+ commandFileExists
15
+ } from './store';
16
+
17
+ export interface CommandDTO {
18
+ id: number;
19
+ slug: string;
20
+ name: string;
21
+ description: string;
22
+ argumentHint: string | null;
23
+ /** Per-engine model override (EngineType → model id; absent = inherit). */
24
+ modelByEngine: EngineMap;
25
+ source: 'custom' | 'imported';
26
+ enabled: boolean;
27
+ /** False when the DB row exists but its `.md` is missing on disk. */
28
+ present: boolean;
29
+ createdAt: string;
30
+ }
31
+
32
+ export interface CommandInputFields {
33
+ name: string;
34
+ description: string;
35
+ argumentHint?: string | null;
36
+ modelByEngine?: EngineMap;
37
+ body: string;
38
+ }
39
+
40
+ const FRONTMATTER_ORDER = ['description', 'argument-hint'];
41
+
42
+ function toDTO(row: CommandRow, present: boolean): CommandDTO {
43
+ return {
44
+ id: row.id,
45
+ slug: row.slug,
46
+ name: row.name,
47
+ description: row.description,
48
+ argumentHint: row.argument_hint,
49
+ modelByEngine: parseEngineMap(row.model_by_engine),
50
+ source: row.source,
51
+ enabled: row.is_enabled === 1,
52
+ present,
53
+ createdAt: row.created_at
54
+ };
55
+ }
56
+
57
+ /** An imported `.md` carries a single Claude-shaped model → map to the claude slot. */
58
+ function singleModelToMap(model: string | undefined): EngineMap {
59
+ return model?.trim() ? { 'claude-code': model.trim() } : {};
60
+ }
61
+
62
+ /**
63
+ * Serialize editor fields into the canonical command `.md` document. Model is
64
+ * per-engine and injected at sync time, so it is NOT written here.
65
+ */
66
+ function buildDocument(fields: CommandInputFields): string {
67
+ const frontmatter: Record<string, string> = {};
68
+ if (fields.description.trim()) frontmatter.description = fields.description.trim();
69
+ if (fields.argumentHint?.trim()) frontmatter['argument-hint'] = fields.argumentHint.trim();
70
+ return serializeDoc({ frontmatter, body: fields.body }, FRONTMATTER_ORDER);
71
+ }
72
+
73
+ export const commandService = {
74
+ async list(): Promise<CommandDTO[]> {
75
+ const rows = commandQueries.getAll();
76
+ const presence = await Promise.all(rows.map(r => commandFileExists(r.slug)));
77
+ return rows.map((row, i) => toDTO(row, presence[i]));
78
+ },
79
+
80
+ /**
81
+ * Minimal list of commands for the chat "/" picker. Non-admin surface
82
+ * (any user can invoke a command), so it exposes only display fields — no
83
+ * bodies, no source/disk metadata.
84
+ *
85
+ * `profileFilter` mirrors {@link syncCommands}'s semantics: when an active
86
+ * profile references ≥1 command, the picker shows exactly that set (even if
87
+ * a referenced command is globally disabled) instead of the enabled set.
88
+ */
89
+ available(profileFilter?: Set<string> | null): { slug: string; name: string; description: string; argumentHint: string | null }[] {
90
+ const rows = profileFilter
91
+ ? commandQueries.getAll().filter(r => profileFilter.has(r.slug))
92
+ : commandQueries.getEnabled();
93
+ return rows.map(r => ({
94
+ slug: r.slug,
95
+ name: r.name,
96
+ description: r.description,
97
+ argumentHint: r.argument_hint
98
+ }));
99
+ },
100
+
101
+ async get(id: number): Promise<{ command: CommandDTO; body: string } | null> {
102
+ const row = commandQueries.getById(id);
103
+ if (!row) return null;
104
+ const raw = await readCommandMd(row.slug);
105
+ const body = raw ? parseDoc(raw).body : '';
106
+ return { command: toDTO(row, raw !== null), body };
107
+ },
108
+
109
+ async create(input: CommandInputFields): Promise<CommandDTO> {
110
+ if (!input.name.trim()) throw new Error('A command name is required');
111
+ const slug = uniqueSlug(input.name, s => !!commandQueries.getBySlug(s));
112
+ await writeCommandMd(slug, buildDocument(input));
113
+ const row = commandQueries.insert({
114
+ slug,
115
+ name: input.name.trim(),
116
+ description: input.description.trim(),
117
+ argumentHint: input.argumentHint?.trim() || null,
118
+ modelByEngine: stringifyEngineMap(input.modelByEngine),
119
+ source: 'custom'
120
+ });
121
+ debug.log('commands', `📦 Created command: ${slug}`);
122
+ return toDTO(row, true);
123
+ },
124
+
125
+ async update(id: number, input: CommandInputFields): Promise<CommandDTO> {
126
+ const row = commandQueries.getById(id);
127
+ if (!row) throw new Error('Command not found');
128
+ await writeCommandMd(row.slug, buildDocument(input));
129
+ commandQueries.updateMeta(
130
+ id,
131
+ input.name.trim(),
132
+ input.description.trim(),
133
+ input.argumentHint?.trim() || null,
134
+ stringifyEngineMap(input.modelByEngine)
135
+ );
136
+ debug.log('commands', `🔧 Updated command: ${row.slug}`);
137
+ return toDTO(commandQueries.getById(id)!, true);
138
+ },
139
+
140
+ /** Preview a pasted command `.md` (its frontmatter + body) before importing. */
141
+ parsePreview(raw: string): { name: string; description: string; argumentHint: string | null; modelByEngine: EngineMap; body: string } {
142
+ const parsed = parseDoc(raw);
143
+ return {
144
+ name: parsed.frontmatter.name || '',
145
+ description: parsed.frontmatter.description || '',
146
+ argumentHint: parsed.frontmatter['argument-hint'] || null,
147
+ modelByEngine: singleModelToMap(parsed.frontmatter.model),
148
+ body: parsed.body
149
+ };
150
+ },
151
+
152
+ async import(raw: string, nameHint?: string): Promise<CommandDTO> {
153
+ const parsed = parseDoc(raw);
154
+ const displayName = (nameHint?.trim() || parsed.frontmatter.name || 'command').trim();
155
+ return this.create({
156
+ name: displayName,
157
+ description: parsed.frontmatter.description || '',
158
+ argumentHint: parsed.frontmatter['argument-hint'] || null,
159
+ modelByEngine: singleModelToMap(parsed.frontmatter.model),
160
+ body: parsed.body
161
+ });
162
+ },
163
+
164
+ toggle(id: number, enabled: boolean): CommandDTO {
165
+ const row = commandQueries.getById(id);
166
+ if (!row) throw new Error('Command not found');
167
+ commandQueries.setEnabled(id, enabled);
168
+ return toDTO(commandQueries.getById(id)!, true);
169
+ },
170
+
171
+ async remove(id: number): Promise<void> {
172
+ const row = commandQueries.getById(id);
173
+ if (!row) throw new Error('Command not found');
174
+ await deleteCommandMd(row.slug);
175
+ commandQueries.remove(id);
176
+ debug.log('commands', `🗑️ Deleted command: ${row.slug}`);
177
+ }
178
+ };
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Canonical command store — the single source of truth on disk. Every managed
3
+ * command is one Markdown file under `{clopenDir}/commands/<slug>.md` (a
4
+ * `single-md` artifact). The DB (`commands` table) tracks only metadata + the
5
+ * enable toggle; the sync layer mirrors enabled commands into each engine's
6
+ * commands dir (native) or a synthetic preamble.
7
+ */
8
+
9
+ import { join } from 'path';
10
+ import { mkdir, rm, stat, writeFile, readFile } from 'node:fs/promises';
11
+ import { getClopenDir } from '$backend/utils/paths';
12
+ import { debug } from '$shared/utils/logger';
13
+
14
+ export function getCommandsRootDir(): string {
15
+ return join(getClopenDir(), 'commands');
16
+ }
17
+
18
+ export function getCommandPath(slug: string): string {
19
+ return join(getCommandsRootDir(), `${slug}.md`);
20
+ }
21
+
22
+ async function pathExists(path: string): Promise<boolean> {
23
+ try { await stat(path); return true; } catch { return false; }
24
+ }
25
+
26
+ export function commandFileExists(slug: string): Promise<boolean> {
27
+ return pathExists(getCommandPath(slug));
28
+ }
29
+
30
+ export async function readCommandMd(slug: string): Promise<string | null> {
31
+ const path = getCommandPath(slug);
32
+ if (!(await pathExists(path))) return null;
33
+ return readFile(path, 'utf8');
34
+ }
35
+
36
+ export async function writeCommandMd(slug: string, content: string): Promise<void> {
37
+ await mkdir(getCommandsRootDir(), { recursive: true });
38
+ await writeFile(getCommandPath(slug), content, 'utf8');
39
+ debug.log('commands', `💾 Wrote command ${slug}.md`);
40
+ }
41
+
42
+ export async function deleteCommandMd(slug: string): Promise<void> {
43
+ await rm(getCommandPath(slug), { force: true });
44
+ debug.log('commands', `🗑️ Removed command ${slug}.md`);
45
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Engine sync for Commands — a thin adapter over the shared artifact framework.
3
+ * Enabled commands are mirrored as `<slug>.md` into each engine's native
4
+ * commands dir (Claude: `.../commands/`) or listed in a synthetic preamble for
5
+ * engines with no native command concept (best-effort/unverified).
6
+ *
7
+ * Never throws — a stream never breaks because commands couldn't sync.
8
+ */
9
+
10
+ import { commandQueries } from '$backend/database/queries';
11
+ import { debug } from '$shared/utils/logger';
12
+ import { materializeArtifacts, resolveArtifact, isPromptScopedEngine, parseDoc, serializeDoc, parseEngineMap, artifactEngineToType, type ManagedArtifact, type ArtifactEngine } from '$backend/artifacts';
13
+ import { artifactFilter } from '$backend/profiles';
14
+ import { readCommandMd } from './store';
15
+
16
+ /**
17
+ * Shape a command document for the engine's native format, injecting that
18
+ * engine's model override (per-engine; the canonical `.md` carries no model):
19
+ * - Codex custom prompts are PLAIN markdown (no frontmatter, no model) — emit the body.
20
+ * - Claude / OpenCode read frontmatter — re-serialize with the injected model.
21
+ */
22
+ function documentForEngine(engine: ArtifactEngine, raw: string, model?: string): string {
23
+ const { frontmatter, body } = parseDoc(raw);
24
+ if (engine === 'codex') return body;
25
+ const fm: Record<string, string> = {};
26
+ if (frontmatter.description) fm.description = frontmatter.description;
27
+ if (frontmatter['argument-hint']) fm['argument-hint'] = frontmatter['argument-hint'];
28
+ if (model) fm.model = model;
29
+ return serializeDoc({ frontmatter: fm, body }, ['description', 'argument-hint', 'model']);
30
+ }
31
+
32
+ function buildCommandsPreamble(items: ManagedArtifact[]): string {
33
+ if (items.length === 0) return '';
34
+ const lines = ['# Available Commands', '', 'User-defined command prompts you can follow when the user invokes one by name:', ''];
35
+ for (const c of items) lines.push(`- **/${c.slug}** — ${c.description || c.name}`);
36
+ return lines.join('\n');
37
+ }
38
+
39
+ /** The commands active for a stream, narrowed by the active Profile (metadata only). */
40
+ function resolveEnabledCommandsMeta(profileId?: number): ManagedArtifact[] {
41
+ const filter = artifactFilter(profileId, 'command');
42
+ return (filter ? commandQueries.getAll() : commandQueries.getEnabled())
43
+ .filter(r => !filter || filter.has(r.slug))
44
+ .map(r => ({ slug: r.slug, name: r.name, description: r.description }));
45
+ }
46
+
47
+ /**
48
+ * The profile-scoped commands preamble for PER-SESSION injection into a
49
+ * prompt-scoped engine's prompt (OpenCode/Codex/Copilot). Returns '' when none
50
+ * apply. Advisory: it scopes what the model surfaces/uses, on top of whatever the
51
+ * engine's own (possibly stale/shared) command registry exposes.
52
+ */
53
+ export function buildCommandsPromptContext(profileId?: number): string {
54
+ return buildCommandsPreamble(resolveEnabledCommandsMeta(profileId));
55
+ }
56
+
57
+ export async function syncCommands(engine: ArtifactEngine, profileId?: number): Promise<void> {
58
+ try {
59
+ // On a prompt-scoped engine, a SYNTHETIC command target (no native command
60
+ // dir — Copilot) is delivered per-session via prompt injection instead, so
61
+ // materialize an empty set to strip any shared global block that would leak
62
+ // across sessions. NATIVE command engines (Claude/OpenCode/Codex) keep the
63
+ // filtered files on disk; Qwen (per-query) keeps its synthetic preamble.
64
+ const synthetic = resolveArtifact('command', { engine, scope: 'global' }).format === 'preamble-region';
65
+ const viaPrompt = synthetic && isPromptScopedEngine(engine);
66
+ const filter = artifactFilter(profileId, 'command');
67
+ // A profile activates the commands it references even if globally disabled;
68
+ // with no profile filter, only the enabled set applies (unchanged).
69
+ const rows = viaPrompt ? [] : (filter ? commandQueries.getAll() : commandQueries.getEnabled())
70
+ .filter(r => !filter || filter.has(r.slug));
71
+ const engineType = artifactEngineToType(engine);
72
+ const enabled: ManagedArtifact[] = [];
73
+ for (const row of rows) {
74
+ const raw = await readCommandMd(row.slug);
75
+ if (raw == null) continue; // file missing on disk — skip silently
76
+ const model = parseEngineMap(row.model_by_engine)[engineType];
77
+ enabled.push({ slug: row.slug, name: row.name, description: row.description, document: documentForEngine(engine, raw, model) });
78
+ }
79
+ const managedSlugs = commandQueries.getAll().map(r => r.slug);
80
+ await materializeArtifacts('command', { engine, scope: 'global' }, {
81
+ enabled,
82
+ managedSlugs,
83
+ buildPreamble: buildCommandsPreamble
84
+ });
85
+ debug.log('commands', `⌨️ Synced ${enabled.length} command(s) → ${engine}`);
86
+ } catch (error) {
87
+ debug.warn('commands', `⚠️ Command sync for ${engine} failed (continuing without):`, error);
88
+ }
89
+ }
90
+
91
+ export async function syncCommandsAllEngines(): Promise<void> {
92
+ const engines: ArtifactEngine[] = ['claude', 'codex', 'copilot', 'qwen', 'opencode'];
93
+ await Promise.all(engines.map(syncCommands));
94
+ }
@@ -0,0 +1,28 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create commands table for user-managed custom slash commands';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Creating commands table...');
8
+ db.exec(`
9
+ CREATE TABLE IF NOT EXISTS commands (
10
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
11
+ slug TEXT NOT NULL UNIQUE,
12
+ name TEXT NOT NULL,
13
+ description TEXT NOT NULL DEFAULT '',
14
+ argument_hint TEXT,
15
+ model TEXT,
16
+ source TEXT NOT NULL DEFAULT 'custom',
17
+ is_enabled INTEGER NOT NULL DEFAULT 1,
18
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
19
+ )
20
+ `);
21
+ debug.log('migration', 'commands table created');
22
+ };
23
+
24
+ export const down = (db: DatabaseConnection): void => {
25
+ debug.log('migration', 'Dropping commands table...');
26
+ db.exec('DROP TABLE IF EXISTS commands');
27
+ debug.log('migration', 'commands table dropped');
28
+ };
@@ -0,0 +1,29 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create subagents table for user-managed custom subagents';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Creating subagents table...');
8
+ db.exec(`
9
+ CREATE TABLE IF NOT EXISTS subagents (
10
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
11
+ slug TEXT NOT NULL UNIQUE,
12
+ name TEXT NOT NULL,
13
+ description TEXT NOT NULL DEFAULT '',
14
+ tools TEXT,
15
+ model TEXT,
16
+ agent_type TEXT,
17
+ source TEXT NOT NULL DEFAULT 'custom',
18
+ is_enabled INTEGER NOT NULL DEFAULT 1,
19
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP
20
+ )
21
+ `);
22
+ debug.log('migration', 'subagents table created');
23
+ };
24
+
25
+ export const down = (db: DatabaseConnection): void => {
26
+ debug.log('migration', 'Dropping subagents table...');
27
+ db.exec('DROP TABLE IF EXISTS subagents');
28
+ debug.log('migration', 'subagents table dropped');
29
+ };
@@ -0,0 +1,29 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create instructions table for managed project/global instruction blocks';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Creating instructions table...');
8
+ // One row per scope target: the single global instruction (project_id NULL),
9
+ // plus one row per project. `content` is the Clopen-managed block injected as
10
+ // a marker-region into each engine's memory file (CLAUDE.md / AGENTS.md / …).
11
+ db.exec(`
12
+ CREATE TABLE IF NOT EXISTS instructions (
13
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
14
+ scope TEXT NOT NULL,
15
+ project_id TEXT,
16
+ content TEXT NOT NULL DEFAULT '',
17
+ is_enabled INTEGER NOT NULL DEFAULT 1,
18
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
19
+ UNIQUE(scope, project_id)
20
+ )
21
+ `);
22
+ debug.log('migration', 'instructions table created');
23
+ };
24
+
25
+ export const down = (db: DatabaseConnection): void => {
26
+ debug.log('migration', 'Dropping instructions table...');
27
+ db.exec('DROP TABLE IF EXISTS instructions');
28
+ debug.log('migration', 'instructions table dropped');
29
+ };
@@ -0,0 +1,23 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Add tool_overrides column to mcp_servers (per-tool + per-engine exposure control)';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Adding tool_overrides column to mcp_servers...');
8
+ // Per-tool exposure state, keyed by the upstream tool's bare name. Holds a
9
+ // JSON map `{ "<tool>": { enabled?, engines? } }`: `enabled: false` disables a
10
+ // tool on every engine, and `engines: { "<engine>": false }` hides it from one
11
+ // engine only. An absent entry (the default) means the tool is exposed
12
+ // everywhere — so an empty `{}` preserves the pre-migration "all tools on"
13
+ // behaviour. The filter is enforced in the `/mcp/ext/<slug>` proxy bridge
14
+ // (see backend/mcp/external/proxy.ts) so it applies identically to every engine.
15
+ db.exec(`ALTER TABLE mcp_servers ADD COLUMN tool_overrides TEXT NOT NULL DEFAULT '{}'`);
16
+ debug.log('migration', 'tool_overrides column added');
17
+ };
18
+
19
+ export const down = (db: DatabaseConnection): void => {
20
+ debug.log('migration', 'Dropping tool_overrides column from mcp_servers...');
21
+ db.exec('ALTER TABLE mcp_servers DROP COLUMN tool_overrides');
22
+ debug.log('migration', 'tool_overrides column dropped');
23
+ };
@@ -0,0 +1,50 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create permission_sets table for per-engine tool allow/deny rules';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Creating permission_sets table...');
8
+ // One row holds the allow + deny tool lists for a single
9
+ // `(scope, project_id, engine)` combination — the same shape decision as
10
+ // `mcp_servers.tool_overrides` (JSON lists over a relation table). Both
11
+ // `allow` and `deny` are JSON `string[]` of tool-name patterns (exact name or
12
+ // a trailing-`*` wildcard, e.g. `mcp__github__*`).
13
+ //
14
+ // Semantics resolved per engine at stream start (see backend/permissions/resolve.ts):
15
+ // - deny = global.deny ∪ project.deny (deny always adds restriction)
16
+ // - allow = project.allow if non-empty, else global.allow
17
+ // - deny wins over allow; an empty allow means "all tools except deny".
18
+ //
19
+ // Instance-global + admin-managed: NO `user_id` column (mirrors skills /
20
+ // mcp_servers / subagents). `project_id` is NULL for global-scope rows and set
21
+ // for project-scope rows. The UNIQUE index makes save an idempotent upsert.
22
+ db.exec(`
23
+ CREATE TABLE IF NOT EXISTS permission_sets (
24
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
25
+ scope TEXT NOT NULL DEFAULT 'global',
26
+ project_id TEXT,
27
+ engine TEXT NOT NULL,
28
+ allow TEXT NOT NULL DEFAULT '[]',
29
+ deny TEXT NOT NULL DEFAULT '[]',
30
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
31
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
32
+ )
33
+ `);
34
+ // SQLite treats every NULL as distinct in a UNIQUE index, so global-scope rows
35
+ // (project_id IS NULL) would not be de-duplicated by a plain UNIQUE(...). Use a
36
+ // COALESCE expression index so `(scope, '', engine)` is unique for globals while
37
+ // project rows key on their real id.
38
+ db.exec(`
39
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_permission_sets_scope
40
+ ON permission_sets (scope, COALESCE(project_id, ''), engine)
41
+ `);
42
+ debug.log('migration', 'permission_sets table created');
43
+ };
44
+
45
+ export const down = (db: DatabaseConnection): void => {
46
+ debug.log('migration', 'Dropping permission_sets table...');
47
+ db.exec('DROP INDEX IF EXISTS idx_permission_sets_scope');
48
+ db.exec('DROP TABLE IF EXISTS permission_sets');
49
+ debug.log('migration', 'permission_sets table dropped');
50
+ };
@@ -0,0 +1,57 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Create profiles + profile_items tables (reusable artifact bundles)';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Creating profiles tables...');
8
+ // A profile is a NAMED, REUSABLE bundle of references to existing artifacts
9
+ // (Skills, Commands, Subagents, MCP Connectors). It does NOT duplicate the
10
+ // artifact data — `profile_items` only points at artifacts by their stable
11
+ // slug, so editing/deleting an artifact never desyncs a profile's copy.
12
+ //
13
+ // Instance-global + admin-managed: NO `user_id` column, exactly mirroring
14
+ // `skills` / `mcp_servers` / `subagents` / `permission_sets`. A profile is
15
+ // shared across every collaborator and consistent cross-device; activation
16
+ // (which profile a session uses) is tracked separately on `chat_sessions`.
17
+ db.exec(`
18
+ CREATE TABLE IF NOT EXISTS profiles (
19
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
20
+ slug TEXT NOT NULL UNIQUE,
21
+ name TEXT NOT NULL,
22
+ description TEXT NOT NULL DEFAULT '',
23
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
24
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
25
+ )
26
+ `);
27
+
28
+ // One row per (profile, artifact_type, ref). `ref` is the artifact's slug —
29
+ // stable and human-readable, and the same key Skills/Commands/Subagents use on
30
+ // disk and MCP servers use as their bridge namespace. `ON DELETE CASCADE`
31
+ // removes a profile's items when the profile is deleted.
32
+ //
33
+ // Presence-per-type semantics (resolved in backend/profiles/service.ts): a
34
+ // profile only NARROWS the artifact types it actually references. If a profile
35
+ // lists ≥1 item of a type, that type is filtered to those refs at stream start;
36
+ // if it lists none of a type, that type is left unconstrained (all enabled).
37
+ db.exec(`
38
+ CREATE TABLE IF NOT EXISTS profile_items (
39
+ id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
40
+ profile_id INTEGER NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
41
+ artifact_type TEXT NOT NULL,
42
+ ref TEXT NOT NULL,
43
+ UNIQUE(profile_id, artifact_type, ref)
44
+ )
45
+ `);
46
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_profile_items_profile ON profile_items (profile_id)`);
47
+
48
+ debug.log('migration', 'profiles tables created');
49
+ };
50
+
51
+ export const down = (db: DatabaseConnection): void => {
52
+ debug.log('migration', 'Dropping profiles tables...');
53
+ db.exec('DROP INDEX IF EXISTS idx_profile_items_profile');
54
+ db.exec('DROP TABLE IF EXISTS profile_items');
55
+ db.exec('DROP TABLE IF EXISTS profiles');
56
+ debug.log('migration', 'profiles tables dropped');
57
+ };
@@ -0,0 +1,20 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Add profile_id column to chat_sessions (active profile per-session)';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Adding profile_id column to chat_sessions...');
8
+ // The active Profile is selected PER-SESSION, sitting alongside `engine`,
9
+ // `model_id`, and `account_id` (migrations 014/015/019) and following the same
10
+ // persist-on-stream / restore-on-continue path. Cross-device sync is automatic
11
+ // (it's just another session column) and each collaborator can run a different
12
+ // profile in their own session without collision. NULL = no explicit choice →
13
+ // the stream resolver falls back to `projects.default_profile_id`.
14
+ db.exec(`ALTER TABLE chat_sessions ADD COLUMN profile_id INTEGER DEFAULT NULL`);
15
+ debug.log('migration', 'profile_id column added to chat_sessions');
16
+ };
17
+
18
+ export const down = (): void => {
19
+ debug.log('migration', 'SQLite does not support DROP COLUMN directly, skipping...');
20
+ };
@@ -0,0 +1,20 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Add default_profile_id column to projects (shared per-project default profile)';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Adding default_profile_id column to projects...');
8
+ // The per-project DEFAULT profile lives on `projects` (NOT `user_projects`), so
9
+ // it is SHARED by every collaborator of the project — the first
10
+ // project-scoped-shared setting in the codebase (existing per-project state
11
+ // like current_session_id / files_panel_state is per-USER on user_projects).
12
+ // A new session with no explicit `chat_sessions.profile_id` inherits this
13
+ // default at stream start. NULL = no default (sessions run with no profile).
14
+ db.exec(`ALTER TABLE projects ADD COLUMN default_profile_id INTEGER DEFAULT NULL`);
15
+ debug.log('migration', 'default_profile_id column added to projects');
16
+ };
17
+
18
+ export const down = (): void => {
19
+ debug.log('migration', 'SQLite does not support DROP COLUMN directly, skipping...');
20
+ };
@@ -0,0 +1,37 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description = 'Add profile_id + profile scope to permission_sets (per-profile allow/deny overlay)';
5
+
6
+ export const up = (db: DatabaseConnection): void => {
7
+ debug.log('migration', 'Adding profile_id to permission_sets...');
8
+ // A Profile can carry its OWN per-engine allow/deny overlay ("restricted
9
+ // mode"), stored as ordinary `permission_sets` rows with `scope = 'profile'`
10
+ // and this `profile_id` set. The resolver unions them in as a third layer:
11
+ // deny = global.deny ∪ project.deny ∪ profile.deny
12
+ // so a profile can only ADD restrictions, never loosen the base policy.
13
+ db.exec(`ALTER TABLE permission_sets ADD COLUMN profile_id INTEGER DEFAULT NULL`);
14
+
15
+ // The old UNIQUE index keyed on (scope, COALESCE(project_id,''), engine) would
16
+ // collide for two different profiles (both scope='profile', project_id NULL,
17
+ // same engine). Rebuild it to include the profile dimension. Legacy rows have
18
+ // profile_id NULL → COALESCE '' → identical key as before, so global/project
19
+ // rows are unaffected and no duplicates are introduced.
20
+ db.exec(`DROP INDEX IF EXISTS idx_permission_sets_scope`);
21
+ db.exec(`
22
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_permission_sets_scope
23
+ ON permission_sets (scope, COALESCE(project_id, ''), COALESCE(profile_id, ''), engine)
24
+ `);
25
+ debug.log('migration', 'permission_sets profile_id added');
26
+ };
27
+
28
+ export const down = (db: DatabaseConnection): void => {
29
+ debug.log('migration', 'Reverting permission_sets profile scope...');
30
+ db.exec(`DELETE FROM permission_sets WHERE scope = 'profile'`);
31
+ db.exec(`DROP INDEX IF EXISTS idx_permission_sets_scope`);
32
+ db.exec(`
33
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_permission_sets_scope
34
+ ON permission_sets (scope, COALESCE(project_id, ''), engine)
35
+ `);
36
+ debug.log('migration', 'permission_sets profile scope reverted');
37
+ };