@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
package/.env.example CHANGED
@@ -6,4 +6,4 @@ CLOPEN_PORT=9141
6
6
 
7
7
  # Development ports (two ports — Vite proxies to Elysia)
8
8
  CLOPEN_PORT_FRONTEND=9151
9
- CLOPEN_PORT_BACKEND=9161
9
+ CLOPEN_PORT_BACKEND=9161
@@ -13,7 +13,7 @@ import { join } from 'path';
13
13
  import { readdir, readFile, stat, symlink, mkdir, lstat, rm } from 'node:fs/promises';
14
14
  import { debug } from '$shared/utils/logger';
15
15
  import { resolveArtifact } from './matrix';
16
- import { readManagedBlock, markersFor } from './markers';
16
+ import { readManagedBlock, markersForType } from './markers';
17
17
  import type { ArtifactContext, ArtifactType, DetectedArtifact } from './types';
18
18
 
19
19
  async function pathExists(path: string): Promise<boolean> {
@@ -75,11 +75,23 @@ export async function detectArtifacts(type: ArtifactType, ctx: ArtifactContext):
75
75
  const bySlug = new Map<string, DetectedArtifact>();
76
76
 
77
77
  if (resolution.format === 'preamble-region') {
78
+ // A managed block, not a directory of artifacts: report the block for THIS
79
+ // type. Reading a fixed marker here (it used to always read `INSTRUCTIONS`)
80
+ // made every synthetic type report a phantom "Project instructions" entry
81
+ // whenever the memory file happened to carry an instructions block.
82
+ if (type === 'mcp' || type === 'permission') return [];
78
83
  const file = resolution.locateEffective(ctx);
79
84
  if (file && (await pathExists(file))) {
80
- const block = readManagedBlock(await readFile(file, 'utf8'), markersFor('INSTRUCTIONS'));
85
+ const block = readManagedBlock(await readFile(file, 'utf8'), markersForType(type));
81
86
  if (block != null) {
82
- bySlug.set('instructions', { slug: 'instructions', name: 'Project instructions', description: '', path: file, managed: true, adoptable: false });
87
+ bySlug.set(type, {
88
+ slug: type,
89
+ name: type === 'instruction' ? 'Project instructions' : `Managed ${type} block`,
90
+ description: '',
91
+ path: file,
92
+ managed: true,
93
+ adoptable: false
94
+ });
83
95
  }
84
96
  }
85
97
  return [...bySlug.values()];
@@ -11,7 +11,7 @@
11
11
  */
12
12
 
13
13
  import { initializeEngine } from '$backend/engine';
14
- import { resolveGenerationTarget } from '$backend/engine/resolve-model';
14
+ import { resolveGenerationTarget, GENERATION_SETTINGS } from '$backend/engine/resolve-model';
15
15
  import { getClopenDir } from '$backend/utils/paths';
16
16
  import type { EngineType } from '$shared/types/unified';
17
17
  import { debug } from '$shared/utils/logger';
@@ -95,7 +95,7 @@ ${purpose.trim()}
95
95
  Always write the draft in English, regardless of the language of the purpose. Be specific and immediately usable.`;
96
96
 
97
97
  // The caller's providerSlug/account can be stale (see resolve-model.ts).
98
- const target = await resolveGenerationTarget(engine, model.modelId, model.providerSlug);
98
+ const target = await resolveGenerationTarget(engine, model.modelId, model.providerSlug, GENERATION_SETTINGS.artifact);
99
99
  const accountId = model.accountId ?? target.accountId;
100
100
 
101
101
  debug.log('artifacts', `✨ Generating ${type} draft via ${model.engine}/${target.providerSlug}/${target.modelId}`);
@@ -2,8 +2,8 @@
2
2
  * Artifact framework — public facade.
3
3
  *
4
4
  * The shared capability-matrix foundation used by every engine-artifact feature
5
- * (Skills, Commands, Subagents, Instructions). See `types.ts` for the model and
6
- * the reserved `'mcp'` slot rationale.
5
+ * (Skills, Subagents, Instructions). See `types.ts` for the model, the reserved
6
+ * `'mcp'` slot and the legacy `'command'` slot.
7
7
  */
8
8
 
9
9
  export type {
@@ -20,11 +20,19 @@ export type {
20
20
  } from './types';
21
21
  export { ARTIFACT_ENGINES } from './types';
22
22
 
23
- export { resolveArtifact, isBestEffortTarget, isPromptScopedEngine, PROMPT_SCOPED_ENGINES, memoryFileName } from './matrix';
23
+ export {
24
+ resolveArtifact,
25
+ isBestEffortTarget,
26
+ isPromptScopedEngine,
27
+ readsGlobalMemoryFile,
28
+ canDelegateSubagents,
29
+ PROMPT_SCOPED_ENGINES,
30
+ memoryFileName
31
+ } from './matrix';
24
32
  export { materializeArtifacts } from './sync';
25
33
  export type { MaterializeInput } from './sync';
26
34
  export { detectArtifacts, adoptArtifact } from './detect';
27
- export { markersFor, writeManagedBlock, readManagedBlock, stripManagedBlock } from './markers';
35
+ export { markersFor, markersForType, MARKER_ID, writeManagedBlock, readManagedBlock, stripManagedBlock } from './markers';
28
36
  export { parseDoc, serializeDoc } from './frontmatter';
29
37
  export type { ParsedDoc } from './frontmatter';
30
38
  export { slugify, uniqueSlug, isValidSlug } from './slug';
@@ -10,7 +10,30 @@
10
10
 
11
11
  import { mkdir, readFile, writeFile, stat } from 'node:fs/promises';
12
12
  import { join } from 'path';
13
- import type { ArtifactMarkers } from './types';
13
+ import type { ArtifactMarkers, ArtifactType } from './types';
14
+
15
+ /**
16
+ * Managed-block marker id per artifact type (uppercased feature name). `'mcp'`
17
+ * and `'permission'` are excluded: neither routes through the generic file
18
+ * materializer (MCP is a config-object path; permissions have their own
19
+ * runtime-hook enforcement + `backend/permissions/materialize.ts`).
20
+ *
21
+ * `'command'` is a LEGACY entry. Commands are no longer materialized per engine
22
+ * — they are `slash`-triggered Skills that Clopen expands itself (migration 079)
23
+ * — but the id is kept so the sync path can still strip `CLOPEN:COMMANDS` blocks
24
+ * left in memory files by earlier versions.
25
+ */
26
+ export const MARKER_ID: Record<Exclude<ArtifactType, 'mcp' | 'permission'>, string> = {
27
+ skill: 'SKILLS',
28
+ command: 'COMMANDS',
29
+ subagent: 'SUBAGENTS',
30
+ instruction: 'INSTRUCTIONS'
31
+ };
32
+
33
+ /** The marker pair for an artifact type's managed block. */
34
+ export function markersForType(type: Exclude<ArtifactType, 'mcp' | 'permission'>): ArtifactMarkers {
35
+ return markersFor(MARKER_ID[type]);
36
+ }
14
37
 
15
38
  /** Build a START/END marker pair for a given managed block id (e.g. `SKILLS`). */
16
39
  export function markersFor(id: string): ArtifactMarkers {
@@ -80,13 +80,17 @@ function nativeDir(type: ArtifactType, ctx: ArtifactContext): string | null {
80
80
  default: return null;
81
81
  }
82
82
  }
83
+ // LEGACY. Commands are no longer materialized per engine — a `/slash` skill is
84
+ // expanded by Clopen itself before the prompt reaches any engine (migration
85
+ // 079), which is what makes them behave identically on all eight engines
86
+ // instead of only the four with a native command directory. These paths are
87
+ // kept so `stripLegacyCommandArtifacts` can still clean out files an earlier
88
+ // version wrote here.
83
89
  if (type === 'command') {
84
90
  switch (engine) {
85
91
  case 'claude': return scope === 'global' ? join(base, 'commands') : proj ? join(proj, '.claude', 'commands') : null;
86
92
  case 'opencode': return scope === 'global' ? join(base, 'opencode', 'command') : proj ? join(proj, '.opencode', 'command') : null;
87
93
  case 'codex': return scope === 'global' ? join(base, 'prompts') : null;
88
- // Pi's file-based prompt templates live in `<agentDir>/prompts` (global)
89
- // and `.pi/prompts` (project) — https://pi.dev/docs/latest/prompt-templates.
90
94
  case 'pi': return scope === 'global' ? join(base, 'prompts') : proj ? join(proj, '.pi', 'prompts') : null;
91
95
  default: return null;
92
96
  }
@@ -236,14 +240,54 @@ function unsupported(): ArtifactResolution {
236
240
  * fresh per-query CLI over an isolated/pruned dir, so the on-disk filter alone
237
241
  * already scopes correctly.
238
242
  */
239
- export const PROMPT_SCOPED_ENGINES: readonly ArtifactEngine[] = ['opencode', 'codex', 'copilot'];
243
+ export const PROMPT_SCOPED_ENGINES: readonly ArtifactEngine[] = ['opencode', 'codex', 'copilot', 'cline', 'cursor'];
240
244
  export function isPromptScopedEngine(engine: ArtifactEngine): boolean {
241
245
  return PROMPT_SCOPED_ENGINES.includes(engine);
242
246
  }
243
247
 
248
+ /**
249
+ * Engines whose runtime actually READS the global memory file this matrix would
250
+ * write (`CLAUDE.md` / `QWEN.md` / `AGENTS.md` inside the isolated config dir).
251
+ *
252
+ * Cline and Cursor are in-process SDKs: they build their own system prompt and
253
+ * resolve ambient rules from the WORKSPACE, never from an engine config dir. A
254
+ * managed block written there is a file nobody reads — and worse, it silently
255
+ * swallowed Instructions, which had no other delivery channel for them. Both now
256
+ * take the whole artifact context through the prompt instead (see
257
+ * `buildArtifactsPromptContext`).
258
+ */
259
+ const MEMORY_FILE_ENGINES: readonly ArtifactEngine[] = ['claude', 'codex', 'copilot', 'qwen', 'opencode', 'pi'];
260
+ export function readsGlobalMemoryFile(engine: ArtifactEngine): boolean {
261
+ return MEMORY_FILE_ENGINES.includes(engine);
262
+ }
263
+
264
+ /**
265
+ * Engines that can actually DELEGATE to a Clopen-managed subagent, and so may be
266
+ * told the subagents exist:
267
+ * - `claude` — native `agents/` directory;
268
+ * - `opencode` — agents baked inline into each per-Profile server;
269
+ * - `cursor` — native `agents` config on `Agent.create`;
270
+ * - `cline` / `pi` — an in-process `Agent` dispatch tool (see each adapter's
271
+ * `agent-tool.ts`).
272
+ *
273
+ * Codex, Copilot and Qwen have no surface Clopen can register a subagent with.
274
+ * They used to receive a preamble promising "specialized agent definitions you
275
+ * can delegate matching tasks to" with no way to do it — an invitation to
276
+ * hallucinate a delegation. They are told nothing instead.
277
+ */
278
+ const SUBAGENT_CAPABLE_ENGINES: readonly ArtifactEngine[] = ['claude', 'opencode', 'cursor', 'cline', 'pi'];
279
+ export function canDelegateSubagents(engine: ArtifactEngine): boolean {
280
+ return SUBAGENT_CAPABLE_ENGINES.includes(engine);
281
+ }
282
+
244
283
  /** Whether a synthetic (non-native) target is best-effort/unverified for the UI. */
245
284
  export function isBestEffortTarget(type: ArtifactType, engine: ArtifactEngine): boolean {
246
285
  if (type === 'instruction') return engine !== 'claude';
286
+ // A `/slash` skill is expanded by Clopen before the engine sees the prompt, so
287
+ // its delivery is engine-independent and never best-effort. Subagents are
288
+ // either supported natively/by a dispatch tool, or not advertised at all.
289
+ if (type === 'command') return false;
290
+ if (type === 'subagent') return canDelegateSubagents(engine) && engine !== 'claude' && engine !== 'opencode';
247
291
  // Permissions are enforced at a runtime hook on Claude/Qwen/Copilot/OpenCode
248
292
  // (OpenCode resolves the tool via its permission event's callID). Only Codex
249
293
  // has no per-call hook, so it alone is best-effort.
@@ -20,12 +20,12 @@ import type { ArtifactContext } from './types';
20
20
  const CONTEXT: ArtifactContext = { engine: 'opencode', scope: 'global' };
21
21
  const SLUG = 'sync-idempotence-fixture';
22
22
 
23
- const targetDir = resolveArtifact('command', CONTEXT).locateEffective(CONTEXT);
23
+ const targetDir = resolveArtifact('subagent', CONTEXT).locateEffective(CONTEXT);
24
24
  const targetFile = targetDir ? join(targetDir, `${SLUG}.md`) : '';
25
25
 
26
- /** Materialize a single command whose body is `document`. */
26
+ /** Materialize a single subagent whose body is `document`. */
27
27
  async function materialize(document: string): Promise<void> {
28
- await materializeArtifacts('command', CONTEXT, {
28
+ await materializeArtifacts('subagent', CONTEXT, {
29
29
  enabled: [{ slug: SLUG, name: 'Fixture', description: 'sync test', document }],
30
30
  managedSlugs: [SLUG]
31
31
  });
@@ -12,22 +12,9 @@
12
12
  import { join } from 'path';
13
13
  import { mkdir, readdir, readFile, rm, writeFile, cp, stat } from 'node:fs/promises';
14
14
  import { resolveArtifact } from './matrix';
15
- import { markersFor, writeManagedBlock } from './markers';
15
+ import { markersForType, writeManagedBlock } from './markers';
16
16
  import type { ArtifactContext, ArtifactType, ManagedArtifact } from './types';
17
17
 
18
- /**
19
- * Managed-block marker id per artifact type (uppercased feature name). `'mcp'`
20
- * and `'permission'` are excluded: neither routes through this generic
21
- * file-materializer (MCP is a config-object path; permissions have their own
22
- * runtime-hook enforcement + `backend/permissions/materialize.ts`).
23
- */
24
- const MARKER_ID: Record<Exclude<ArtifactType, 'mcp' | 'permission'>, string> = {
25
- skill: 'SKILLS',
26
- command: 'COMMANDS',
27
- subagent: 'SUBAGENTS',
28
- instruction: 'INSTRUCTIONS'
29
- };
30
-
31
18
  async function pathExists(path: string): Promise<boolean> {
32
19
  try {
33
20
  await stat(path);
@@ -122,7 +109,10 @@ export interface MaterializeInput {
122
109
  * start: native dirs are reconciled and synthetic blocks are rewritten in place.
123
110
  */
124
111
  export async function materializeArtifacts(
125
- type: Exclude<ArtifactType, 'mcp' | 'instruction'>,
112
+ // `permission` is excluded alongside `mcp`/`instruction`: it has no managed
113
+ // block id because its enforcement is a runtime hook, and its optional on-disk
114
+ // file is written by `backend/permissions/materialize.ts`, not here.
115
+ type: Exclude<ArtifactType, 'mcp' | 'instruction' | 'permission'>,
126
116
  ctx: ArtifactContext,
127
117
  input: MaterializeInput
128
118
  ): Promise<void> {
@@ -170,14 +160,12 @@ export async function materializeArtifacts(
170
160
  // writeManagedBlock is a no-op when no such block exists.
171
161
  const staleMemoryFile = resolveArtifact('instruction', ctx).locateEffective(ctx);
172
162
  if (staleMemoryFile) {
173
- await writeManagedBlock(staleMemoryFile, '', markersFor(MARKER_ID[type as keyof typeof MARKER_ID]));
163
+ await writeManagedBlock(staleMemoryFile, '', markersForType(type));
174
164
  }
175
165
  return;
176
166
  }
177
167
 
178
- // preamble-region → managed block inside the engine memory file. `type` is
179
- // always one of the file-materialized kinds here (mcp/permission never route
180
- // through this writer), so the MARKER_ID lookup is total in practice.
168
+ // preamble-region → managed block inside the engine memory file.
181
169
  const build = input.buildPreamble ?? ((items) => defaultPreamble(type, items));
182
- await writeManagedBlock(target, build(input.enabled), markersFor(MARKER_ID[type as keyof typeof MARKER_ID]));
170
+ await writeManagedBlock(target, build(input.enabled), markersForType(type));
183
171
  }
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * Artifact framework — shared capability matrix for engine "extension" artifacts.
3
3
  *
4
- * Clopen manages several kinds of engine artifact (Agent Skills, custom slash
5
- * Commands, Subagents, project Instructions). They differ in file shape but share
6
- * one mechanic: a canonical source (DB metadata + on-disk store, or a repo file)
4
+ * Clopen manages several kinds of engine artifact (Agent Skills — which cover
5
+ * both model-invoked skills and user-invoked `/slash` prompts — Subagents, and
6
+ * project Instructions). They differ in file shape but share one mechanic: a canonical source (DB metadata + on-disk store, or a repo file)
7
7
  * is MATERIALIZED into the shape each engine consumes at stream start.
8
8
  *
9
9
  * Rather than hardcode that mechanic per feature (as the original Skills sync
@@ -43,6 +43,12 @@ export const ARTIFACT_ENGINES: ArtifactEngine[] = ['claude', 'codex', 'copilot',
43
43
  * is a runtime hook (see `backend/permissions/`), and the matrix entry only
44
44
  * describes the optional on-disk "honesty" file (Claude `settings.json`, Codex
45
45
  * `config.toml`) for engines that read one.
46
+ *
47
+ * `'command'` is LEGACY. Commands merged into Skills in migration 079: a command
48
+ * is a Skill whose `triggers` include `slash`, and Clopen expands `/<slug>` into
49
+ * the prompt itself rather than materializing a file each engine may or may not
50
+ * read. The type survives only so the sync path can clean up the directories and
51
+ * `CLOPEN:COMMANDS` blocks earlier versions wrote.
46
52
  */
47
53
  export type ArtifactType = 'skill' | 'command' | 'subagent' | 'instruction' | 'mcp' | 'permission';
48
54
 
@@ -182,6 +182,29 @@ export const ADMIN_ONLY_ROUTES = new Set([
182
182
  // anyone who can use the connection can look.
183
183
  'db-client:supabase-apply-migration',
184
184
  'db-client:supabase-write-types',
185
+ // Worktree database branching. Pointing a project at a parent database
186
+ // commits an account's quota to it, and deleting a branch destroys a real
187
+ // database — both spend a credential that belongs to the install rather than
188
+ // to the caller, the same reason `db-client:link` is gated.
189
+ //
190
+ // `worktrees:branching-state` and `worktrees:branch-rewrite-env` are
191
+ // deliberately NOT listed: a member has to be able to see whether their own
192
+ // worktree got a branch, and to retry the dotenv write when it was refused.
193
+ //
194
+ // NEITHER ARE `worktrees:branch-parents` AND `worktrees:branching-save`, and
195
+ // that is a change rather than an oversight. They used to be here because a
196
+ // binding could only point at an integration account, and committing the
197
+ // install's quota is an admin decision. A binding can now point at a DB
198
+ // Client connection instead — a database the member themselves saved — and
199
+ // refusing that would make "give this worktree its own database" an
200
+ // admin-only feature for no reason that survives being stated. The account
201
+ // half keeps the old rule: `listBranchSources` shows accounts to admins
202
+ // only, and `requireSource` refuses anything the caller cannot see.
203
+ 'worktrees:branching-clear',
204
+ 'worktrees:branch-orphans',
205
+ 'worktrees:branch-delete',
206
+ 'worktrees:branch-forget',
207
+ 'worktrees:branch-delete-remote',
185
208
  // Memory Graph — the graph is instance-global and is injected into every
186
209
  // future turn on every engine, so editing it changes what every agent is told.
187
210
  // Mutations only: the read surface (memory:graph / :node / :search / :stats /
@@ -205,7 +228,10 @@ export const ADMIN_ONLY_ROUTES = new Set([
205
228
  'memory:retry-failed',
206
229
  // Agent Skills — creating/importing/installing skills writes to the shared
207
230
  // canonical store and applies to every engine, so the whole surface is
208
- // admin-only, mirroring MCP and Stack.
231
+ // admin-only, mirroring MCP and Stack. This now covers what used to be a
232
+ // separate Commands menu: a `/slash` prompt is a skill with a slash trigger.
233
+ // `skills:available` is deliberately NOT here — every member needs it to type
234
+ // a command, and it exposes display fields only.
209
235
  'skills:list',
210
236
  'skills:get',
211
237
  'skills:create',
@@ -216,16 +242,8 @@ export const ADMIN_ONLY_ROUTES = new Set([
216
242
  'skills:delete',
217
243
  'skills:catalog',
218
244
  'skills:install',
219
- // Custom Commands — same shared-store rationale as Skills; admin-only surface.
220
- 'commands:list',
221
- 'commands:get',
222
- 'commands:create',
223
- 'commands:update',
224
- 'commands:parse-import',
225
- 'commands:import',
226
- 'commands:toggle',
227
- 'commands:delete',
228
- 'commands:detect',
245
+ 'skills:detect',
246
+ 'skills:adopt',
229
247
  // Subagents — shared canonical store applied to every engine; admin-only.
230
248
  'subagents:list',
231
249
  'subagents:get',
@@ -1,7 +1,9 @@
1
1
  /**
2
2
  * Expired Session Cleanup Scheduler
3
3
  *
4
- * Periodically removes expired auth sessions from the database.
4
+ * Periodically removes expired auth sessions from the database, along with
5
+ * the other one-time bearer credentials that age out the same way
6
+ * (device-pairing codes, file-share links).
5
7
  * Without this, the auth_sessions table grows unbounded as expired
6
8
  * sessions are never purged in long-running deployments.
7
9
  *
@@ -9,6 +11,7 @@
9
11
  */
10
12
 
11
13
  import { authQueries } from '../database/queries';
14
+ import { sweepStaleFileShares } from '../files/file-shares';
12
15
  import { debug } from '$shared/utils/logger';
13
16
 
14
17
  /** How often to sweep for expired sessions (1 hour) */
@@ -43,6 +46,12 @@ class SessionCleanupScheduler {
43
46
  if (staleCodes > 0) {
44
47
  debug.log('auth', `Session cleanup: removed ${staleCodes} stale device code(s)`);
45
48
  }
49
+ // Same shape again: one-time file-share links that can no longer
50
+ // serve bytes (expired, or drained out after their single use).
51
+ const staleShares = sweepStaleFileShares();
52
+ if (staleShares > 0) {
53
+ debug.log('auth', `Session cleanup: removed ${staleShares} stale file share(s)`);
54
+ }
46
55
  } catch (error) {
47
56
  debug.warn('auth', 'Session cleanup failed:', error);
48
57
  }
@@ -6,12 +6,14 @@
6
6
  * - clp_pat_* — Personal Access Tokens (cross-device login, permanent)
7
7
  * - clp_inv_* — Invite tokens (for inviting new users)
8
8
  * - clp_dev_* — Device-pairing codes (one-time, short TTL; Remote Access "Add a device")
9
+ * - clp_fsh_* — File-share tokens (single-file download links, finite TTL)
9
10
  */
10
11
 
11
12
  const SESSION_PREFIX = 'clp_ses_';
12
13
  const PAT_PREFIX = 'clp_pat_';
13
14
  const INVITE_PREFIX = 'clp_inv_';
14
15
  const DEVICE_PREFIX = 'clp_dev_';
16
+ const FILE_SHARE_PREFIX = 'clp_fsh_';
15
17
 
16
18
  function randomHex(bytes: number): string {
17
19
  const arr = new Uint8Array(bytes);
@@ -38,6 +40,11 @@ export function generateDeviceCode(): string {
38
40
  return DEVICE_PREFIX + randomHex(TOKEN_BYTES);
39
41
  }
40
42
 
43
+ /** Single-file share token for "Share Link…" download links. */
44
+ export function generateFileShareToken(): string {
45
+ return FILE_SHARE_PREFIX + randomHex(TOKEN_BYTES);
46
+ }
47
+
41
48
  /**
42
49
  * SHA-256 hash a token string.
43
50
  * Uses Bun native CryptoHasher for performance.
@@ -51,10 +58,11 @@ export function hashToken(token: string): string {
51
58
  /**
52
59
  * Determine token type from prefix
53
60
  */
54
- export function getTokenType(token: string): 'session' | 'pat' | 'invite' | 'device' | 'unknown' {
61
+ export function getTokenType(token: string): 'session' | 'pat' | 'invite' | 'device' | 'file-share' | 'unknown' {
55
62
  if (token.startsWith(SESSION_PREFIX)) return 'session';
56
63
  if (token.startsWith(PAT_PREFIX)) return 'pat';
57
64
  if (token.startsWith(INVITE_PREFIX)) return 'invite';
58
65
  if (token.startsWith(DEVICE_PREFIX)) return 'device';
66
+ if (token.startsWith(FILE_SHARE_PREFIX)) return 'file-share';
59
67
  return 'unknown';
60
68
  }
@@ -39,6 +39,7 @@ import { snapshotService } from '../snapshot/snapshot-service';
39
39
  import { snapshotQueries } from '../database/queries/snapshot-queries';
40
40
  import { projectContextService, refreshExpiringExternalOAuth } from '../mcp';
41
41
  import { resolveActiveProfileId } from '../profiles';
42
+ import { expandSlashInvocation } from '../skills';
42
43
  import { browserMcpControl } from '../preview';
43
44
  import { extractMessageText } from '../snapshot/helpers';
44
45
  import { deferEpisodicIngest, ingestTurn } from '../memory/extract';
@@ -59,6 +60,12 @@ export interface StreamState {
59
60
  processId: string;
60
61
  engine: EngineType;
61
62
  accountId?: number;
63
+ /**
64
+ * Server-trusted id of the requesting user (see StreamRequest). Carried
65
+ * through so terminal lifecycle events can fan out Web Push to the right
66
+ * devices without trusting any client-supplied field.
67
+ */
68
+ requestedByUserId?: string;
62
69
  /** Reasoning/thinking level token for this run (native per engine; undefined = engine default). */
63
70
  reasoningEffort?: string;
64
71
  status: 'active' | 'completed' | 'error' | 'cancelled';
@@ -350,6 +357,7 @@ class StreamManager extends EventEmitter {
350
357
  streamId: streamState.streamId,
351
358
  projectId: streamState.projectId,
352
359
  chatSessionId: streamState.chatSessionId,
360
+ requestedByUserId: streamState.requestedByUserId,
353
361
  timestamp: (streamState.completedAt || new Date()).toISOString(),
354
362
  reason
355
363
  });
@@ -396,6 +404,7 @@ class StreamManager extends EventEmitter {
396
404
  processId,
397
405
  engine: request.engine.type,
398
406
  accountId: request.engine.account?.id || undefined,
407
+ requestedByUserId: request.requestedByUserId,
399
408
  reasoningEffort: request.reasoningEffort ?? undefined,
400
409
  status: 'active',
401
410
  startedAt: new Date(),
@@ -688,6 +697,39 @@ class StreamManager extends EventEmitter {
688
697
  // is prepended to the ENGINE prompt only — `userMessage` (already saved
689
698
  // above) stays clean, so the transcript never reaches the timeline.
690
699
  let enginePrompt = userMessage;
700
+
701
+ // ── Slash skill expansion ──
702
+ // `/review-pr 123` is resolved HERE, not by the engine. Four of the eight
703
+ // engines have no native command directory at all, so the old per-engine
704
+ // materialization delivered nothing but a name to them; expanding once,
705
+ // centrally, is what makes a slash skill behave the same everywhere and
706
+ // lets `uses:` pull in several skills deterministically. The SAVED user
707
+ // message keeps the `/slug` the user typed — only the engine prompt is
708
+ // rewritten, exactly like the handoff and memory blocks below.
709
+ try {
710
+ const firstText = enginePrompt.content.find(block => block.type === 'text');
711
+ if (firstText?.type === 'text') {
712
+ const expanded = await expandSlashInvocation(firstText.text, { profileId: activeProfileId });
713
+ if (expanded) {
714
+ enginePrompt = {
715
+ ...enginePrompt,
716
+ content: enginePrompt.content.map(block =>
717
+ block === firstText ? { ...block, text: expanded.text } : block
718
+ )
719
+ };
720
+ debug.log(
721
+ 'chat',
722
+ `Expanded /${expanded.slug} into the engine prompt` +
723
+ (expanded.used.length ? ` (requires: ${expanded.used.join(', ')})` : '')
724
+ );
725
+ }
726
+ }
727
+ } catch (error) {
728
+ // A failed expansion must not block the turn — the engine simply
729
+ // receives the message exactly as the user typed it.
730
+ debug.warn('chat', 'Slash skill expansion failed, sending the message as typed:', error);
731
+ }
732
+
691
733
  if (engineSwitched && chatSessionId) {
692
734
  try {
693
735
  const handoff = buildEngineHandoff(
@@ -31,7 +31,11 @@ export const SECRET_COLUMNS: Record<string, readonly string[]> = {
31
31
  // The secret a linked remote database needs, which is NOT always the same as
32
32
  // the account's credential — a Supabase Management API token cannot read
33
33
  // back the Postgres password, so the password lives here and nowhere else.
34
- integration_db_links: ['secrets']
34
+ integration_db_links: ['secrets'],
35
+ // A worktree's branch database answers on a connection string that carries
36
+ // its own password — generated by the provider and never typed by anyone, so
37
+ // this row is the only place it exists.
38
+ worktree_branches: ['connection_json']
35
39
  } as const;
36
40
 
37
41
  /** Column names of one table, or an empty list when the table holds no secrets. */