@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,163 @@
1
+ /**
2
+ * File Share Queries
3
+ *
4
+ * Storage for shareable single-file links ("Share Link…" in the File
5
+ * Explorer). Only the token's SHA-256 hash is stored; the raw token lives in
6
+ * the shared URL and is never written down.
7
+ *
8
+ * Everything a caller can act on is keyed by `id`, not by the token: the raw
9
+ * token exists once, in the browser that minted it, so a revoke keyed on the
10
+ * secret would be unreachable the moment that view closes.
11
+ *
12
+ * A NULL `expires_at` means "until revoked" — every query that filters on the
13
+ * deadline has to admit that row, which is why the condition is spelled out
14
+ * rather than left to a plain comparison (SQL comparisons against NULL are
15
+ * neither true nor false, so `expires_at > ?` alone would silently hide them).
16
+ */
17
+
18
+ import { getDatabase } from '../index';
19
+ import { nanoid } from 'nanoid';
20
+
21
+ export interface FileShareRow {
22
+ id: string;
23
+ token_hash: string;
24
+ file_path: string;
25
+ created_by: string;
26
+ /** 1 = dies on the first open, 0 = openable until it expires or is revoked. */
27
+ one_time: number;
28
+ /** ISO deadline, or null for a link that only a revoke ends. */
29
+ expires_at: string | null;
30
+ consumed_at: string | null;
31
+ consumer_hash: string | null;
32
+ open_count: number;
33
+ last_opened_at: string | null;
34
+ created_at: string;
35
+ }
36
+
37
+ /** A row joined with its creator's display name, for the management list. */
38
+ export interface FileShareListRow extends FileShareRow {
39
+ created_by_name: string | null;
40
+ }
41
+
42
+ export interface CreateFileShareParams {
43
+ tokenHash: string;
44
+ filePath: string;
45
+ createdBy: string;
46
+ oneTime: boolean;
47
+ expiresAt: string | null;
48
+ createdAt: string;
49
+ }
50
+
51
+ const LIST_SELECT = `
52
+ SELECT s.*, u.name AS created_by_name
53
+ FROM file_shares s
54
+ LEFT JOIN users u ON u.id = s.created_by
55
+ `;
56
+
57
+ /** Rows that have not passed their deadline — including the ones without one. */
58
+ const LIVE = '(s.expires_at IS NULL OR s.expires_at > ?)';
59
+
60
+ export const fileShareQueries = {
61
+ create(params: CreateFileShareParams): FileShareRow {
62
+ const db = getDatabase();
63
+ const id = nanoid();
64
+ db.prepare(`
65
+ INSERT INTO file_shares (
66
+ id, token_hash, file_path, created_by, one_time, expires_at,
67
+ consumed_at, consumer_hash, open_count, last_opened_at, created_at
68
+ )
69
+ VALUES (?, ?, ?, ?, ?, ?, NULL, NULL, 0, NULL, ?)
70
+ `).run(
71
+ id,
72
+ params.tokenHash,
73
+ params.filePath,
74
+ params.createdBy,
75
+ params.oneTime ? 1 : 0,
76
+ params.expiresAt,
77
+ params.createdAt
78
+ );
79
+ return db.prepare('SELECT * FROM file_shares WHERE id = ?').get(id) as FileShareRow;
80
+ },
81
+
82
+ getByHash(tokenHash: string): FileShareRow | null {
83
+ const db = getDatabase();
84
+ return db.prepare('SELECT * FROM file_shares WHERE token_hash = ?').get(tokenHash) as FileShareRow | null;
85
+ },
86
+
87
+ getById(id: string): FileShareRow | null {
88
+ const db = getDatabase();
89
+ return db.prepare('SELECT * FROM file_shares WHERE id = ?').get(id) as FileShareRow | null;
90
+ },
91
+
92
+ /** Every live link, newest first — the admin view of what is currently open. */
93
+ listAll(now: string): FileShareListRow[] {
94
+ const db = getDatabase();
95
+ return db.prepare(`${LIST_SELECT} WHERE ${LIVE} ORDER BY s.created_at DESC`)
96
+ .all(now) as FileShareListRow[];
97
+ },
98
+
99
+ /** One user's live links, newest first. */
100
+ listForUser(userId: string, now: string): FileShareListRow[] {
101
+ const db = getDatabase();
102
+ return db.prepare(`${LIST_SELECT} WHERE s.created_by = ? AND ${LIVE} ORDER BY s.created_at DESC`)
103
+ .all(userId, now) as FileShareListRow[];
104
+ },
105
+
106
+ /**
107
+ * Burn the single use of a one-time link. Conditional on `consumed_at IS
108
+ * NULL` and on the deadline, so exactly one of any number of concurrent
109
+ * opens gets `changes === 1` — the same single-use guarantee
110
+ * `markDeviceCodeClaimed` relies on.
111
+ */
112
+ consume(tokenHash: string, consumedAt: string, consumerHash: string): number {
113
+ const db = getDatabase();
114
+ const result = db.prepare(`
115
+ UPDATE file_shares
116
+ SET consumed_at = ?, consumer_hash = ?, open_count = open_count + 1, last_opened_at = ?
117
+ WHERE token_hash = ?
118
+ AND one_time = 1
119
+ AND consumed_at IS NULL
120
+ AND (expires_at IS NULL OR expires_at > ?)
121
+ `).run(consumedAt, consumerHash, consumedAt, tokenHash, consumedAt) as { changes: number };
122
+ return result.changes;
123
+ },
124
+
125
+ /** Record an open of a reusable link — the counter the list reports from. */
126
+ recordOpen(tokenHash: string, openedAt: string): number {
127
+ const db = getDatabase();
128
+ const result = db.prepare(`
129
+ UPDATE file_shares
130
+ SET open_count = open_count + 1, last_opened_at = ?
131
+ WHERE token_hash = ?
132
+ `).run(openedAt, tokenHash) as { changes: number };
133
+ return result.changes;
134
+ },
135
+
136
+ deleteById(id: string): number {
137
+ const db = getDatabase();
138
+ const result = db.prepare('DELETE FROM file_shares WHERE id = ?').run(id) as { changes: number };
139
+ return result.changes;
140
+ },
141
+
142
+ deleteByHash(tokenHash: string): number {
143
+ const db = getDatabase();
144
+ const result = db.prepare('DELETE FROM file_shares WHERE token_hash = ?').run(tokenHash) as { changes: number };
145
+ return result.changes;
146
+ },
147
+
148
+ /**
149
+ * Remove links that can never serve bytes again: past their deadline, or
150
+ * burned longer ago than the streaming-continuation window. A link without
151
+ * a deadline is never swept — ending it is a deliberate revoke.
152
+ */
153
+ deleteStale(drainCutoff: string): number {
154
+ const db = getDatabase();
155
+ const now = new Date().toISOString();
156
+ const result = db.prepare(`
157
+ DELETE FROM file_shares
158
+ WHERE (expires_at IS NOT NULL AND expires_at < ?)
159
+ OR (consumed_at IS NOT NULL AND consumed_at < ?)
160
+ `).run(now, drainCutoff) as { changes: number };
161
+ return result.changes;
162
+ }
163
+ };
@@ -16,12 +16,12 @@ export { sshKnownHostQueries } from './ssh-known-host-queries';
16
16
  export { sshPortForwardQueries } from './ssh-port-forward-queries';
17
17
  export { auditLogQueries } from './audit-log-queries';
18
18
  export { fileAuditLogQueries } from './file-audit-log-queries';
19
+ export { fileShareQueries } from './file-share-queries';
20
+ export type { FileShareRow, FileShareListRow } from './file-share-queries';
19
21
  export { mcpServerQueries } from './mcp-server-queries';
20
22
  export type { McpServerRow, McpServerInput, McpTransport, McpSource, McpConfigField, McpToolOverride, McpToolOverrides } from './mcp-server-queries';
21
- export { skillQueries } from './skill-queries';
22
- export type { SkillRow, SkillInput, SkillSource } from './skill-queries';
23
- export { commandQueries } from './command-queries';
24
- export type { CommandRow, CommandInput, CommandSource } from './command-queries';
23
+ export { skillQueries, parseTriggers, stringifyTriggers, parseUses, stringifyUses, SKILL_TRIGGERS } from './skill-queries';
24
+ export type { SkillRow, SkillInput, SkillSource, SkillTrigger } from './skill-queries';
25
25
  export { subagentQueries } from './subagent-queries';
26
26
  export type { SubagentRow, SubagentInput, SubagentSource } from './subagent-queries';
27
27
  export { instructionQueries } from './instruction-queries';
@@ -41,3 +41,11 @@ export { workBindingQueries, workLinkQueries, parseBindingConfig } from './work-
41
41
  export type { WorkBindingRow, WorkLinkRow } from './work-queries';
42
42
  export { deployBindingQueries, parseDeployConfig } from './deploy-queries';
43
43
  export type { DeployBindingRow } from './deploy-queries';
44
+ export {
45
+ worktreeBranchBindingQueries,
46
+ worktreeBranchQueries,
47
+ parseWorktreeBranchConfig
48
+ } from './worktree-branch-queries';
49
+ export { pushSubscriptionQueries } from './push-subscription-queries';
50
+ export type { PushSubscription, PushSubscriptionInput } from './push-subscription-queries';
51
+ export type { WorktreeBranchBindingRow, WorktreeBranchRow } from './worktree-branch-queries';
@@ -14,10 +14,12 @@
14
14
  import { getDatabase } from '../index';
15
15
 
16
16
  /** Artifact kinds a profile can bundle. Permissions are handled separately
17
- * (they are a per-engine allow/deny overlay, not a slug-referenced artifact). */
18
- export type ProfileItemType = 'skill' | 'command' | 'subagent' | 'mcp';
17
+ * (they are a per-engine allow/deny overlay, not a slug-referenced artifact).
18
+ * `'command'` is gone since migration 079 folded Commands into Skills — the
19
+ * migration re-typed existing `command` rows to `skill` under their new slug. */
20
+ export type ProfileItemType = 'skill' | 'subagent' | 'mcp';
19
21
 
20
- export const PROFILE_ITEM_TYPES: ProfileItemType[] = ['skill', 'command', 'subagent', 'mcp'];
22
+ export const PROFILE_ITEM_TYPES: ProfileItemType[] = ['skill', 'subagent', 'mcp'];
21
23
 
22
24
  export interface ProfileRow {
23
25
  id: number;
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Tests for the Web Push subscription store.
3
+ *
4
+ * Two invariants carry the feature. One row per device endpoint, so a phone
5
+ * that re-subscribes on every app open does not accumulate duplicates and
6
+ * receive N copies of every notification. And a purge that covers the whole
7
+ * user, because `pushNotifications` is a single per-user setting synced
8
+ * across devices — switching it off on a laptop has to silence the phone.
9
+ */
10
+
11
+ import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
12
+ import { randomUUID } from 'node:crypto';
13
+
14
+ import { initializeDatabase, closeDatabase } from '../index';
15
+ import { pushSubscriptionQueries } from './push-subscription-queries';
16
+
17
+ const userA = `user-a-${randomUUID()}`;
18
+ const userB = `user-b-${randomUUID()}`;
19
+
20
+ function subscribe(userId: string, suffix: string) {
21
+ return pushSubscriptionQueries.upsert({
22
+ userId,
23
+ endpoint: `https://push.example.com/${suffix}`,
24
+ p256dh: 'p256dh-'.padEnd(20, 'x'),
25
+ auth: 'auth-'.padEnd(16, 'x'),
26
+ userAgent: 'test-agent'
27
+ });
28
+ }
29
+
30
+ beforeAll(async () => {
31
+ await initializeDatabase();
32
+ });
33
+
34
+ beforeEach(() => {
35
+ pushSubscriptionQueries.deleteAllByUser(userA);
36
+ pushSubscriptionQueries.deleteAllByUser(userB);
37
+ });
38
+
39
+ afterAll(() => {
40
+ pushSubscriptionQueries.deleteAllByUser(userA);
41
+ pushSubscriptionQueries.deleteAllByUser(userB);
42
+ closeDatabase();
43
+ });
44
+
45
+ describe('pushSubscriptionQueries', () => {
46
+ it('keeps one row per endpoint when the same device re-subscribes', () => {
47
+ const first = subscribe(userA, 'device-1');
48
+ const second = pushSubscriptionQueries.upsert({
49
+ userId: userA,
50
+ endpoint: 'https://push.example.com/device-1',
51
+ p256dh: 'rotated-p256dh'.padEnd(20, 'x'),
52
+ auth: 'rotated-auth'.padEnd(16, 'x')
53
+ });
54
+
55
+ expect(second.id).toBe(first.id);
56
+ expect(second.p256dh).toBe('rotated-p256dh'.padEnd(20, 'x'));
57
+ expect(pushSubscriptionQueries.listByUser(userA)).toHaveLength(1);
58
+ });
59
+
60
+ it('deletes every device of one user and leaves other users untouched', () => {
61
+ subscribe(userA, 'phone');
62
+ subscribe(userA, 'tablet');
63
+ subscribe(userB, 'other-phone');
64
+
65
+ expect(pushSubscriptionQueries.deleteAllByUser(userA)).toBe(2);
66
+ expect(pushSubscriptionQueries.listByUser(userA)).toHaveLength(0);
67
+ expect(pushSubscriptionQueries.listByUser(userB)).toHaveLength(1);
68
+ });
69
+
70
+ it('scopes a single-endpoint delete to its owner', () => {
71
+ subscribe(userA, 'shared-looking-endpoint');
72
+
73
+ expect(
74
+ pushSubscriptionQueries.deleteByEndpoint(
75
+ userB,
76
+ 'https://push.example.com/shared-looking-endpoint'
77
+ )
78
+ ).toBe(false);
79
+ expect(pushSubscriptionQueries.listByUser(userA)).toHaveLength(1);
80
+ });
81
+
82
+ it('prunes a stale endpoint regardless of owner', () => {
83
+ subscribe(userA, 'expired');
84
+
85
+ expect(
86
+ pushSubscriptionQueries.deleteStaleByEndpoint('https://push.example.com/expired')
87
+ ).toBe(true);
88
+ expect(pushSubscriptionQueries.listByUser(userA)).toHaveLength(0);
89
+ });
90
+ });
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Web Push subscription storage.
3
+ *
4
+ * One row per (user, device endpoint). Subscribing twice from the same
5
+ * browser reuses the same endpoint, so upsert keeps exactly one row per
6
+ * device. Rows die two ways: explicit unsubscribe, or a 404/410 from the
7
+ * push service on send (see `backend/push/sender.ts`).
8
+ */
9
+
10
+ import { getDatabase } from '../index';
11
+
12
+ export interface PushSubscription {
13
+ id: number;
14
+ user_id: string;
15
+ endpoint: string;
16
+ p256dh: string;
17
+ auth: string;
18
+ user_agent: string | null;
19
+ created_at: string;
20
+ }
21
+
22
+ export interface PushSubscriptionInput {
23
+ userId: string;
24
+ endpoint: string;
25
+ p256dh: string;
26
+ auth: string;
27
+ userAgent?: string;
28
+ }
29
+
30
+ export const pushSubscriptionQueries = {
31
+ upsert(input: PushSubscriptionInput): PushSubscription {
32
+ const db = getDatabase();
33
+ const now = new Date().toISOString();
34
+ db.prepare(
35
+ `
36
+ INSERT INTO push_subscriptions (user_id, endpoint, p256dh, auth, user_agent, created_at)
37
+ VALUES (?, ?, ?, ?, ?, ?)
38
+ ON CONFLICT(endpoint) DO UPDATE SET
39
+ user_id = excluded.user_id,
40
+ p256dh = excluded.p256dh,
41
+ auth = excluded.auth,
42
+ user_agent = excluded.user_agent
43
+ `
44
+ ).run(
45
+ input.userId,
46
+ input.endpoint,
47
+ input.p256dh,
48
+ input.auth,
49
+ input.userAgent ?? null,
50
+ now
51
+ );
52
+ return db
53
+ .prepare('SELECT * FROM push_subscriptions WHERE endpoint = ?')
54
+ .get(input.endpoint) as PushSubscription;
55
+ },
56
+
57
+ listByUser(userId: string): PushSubscription[] {
58
+ const db = getDatabase();
59
+ return db
60
+ .prepare('SELECT * FROM push_subscriptions WHERE user_id = ? ORDER BY created_at')
61
+ .all(userId) as PushSubscription[];
62
+ },
63
+
64
+ deleteByEndpoint(userId: string, endpoint: string): boolean {
65
+ const db = getDatabase();
66
+ const result = db
67
+ .prepare('DELETE FROM push_subscriptions WHERE user_id = ? AND endpoint = ?')
68
+ .run(userId, endpoint) as { changes: number | bigint };
69
+ return Number(result.changes ?? 0) > 0;
70
+ },
71
+
72
+ /**
73
+ * Drop every device this user registered.
74
+ *
75
+ * `pushNotifications` is one per-user setting shared by all of their
76
+ * devices, so turning it off anywhere has to stop the pushes everywhere —
77
+ * deleting only the calling device's endpoint would leave a phone
78
+ * receiving notifications the settings screen says are off.
79
+ */
80
+ deleteAllByUser(userId: string): number {
81
+ const db = getDatabase();
82
+ const result = db
83
+ .prepare('DELETE FROM push_subscriptions WHERE user_id = ?')
84
+ .run(userId) as { changes: number | bigint };
85
+ return Number(result.changes ?? 0);
86
+ },
87
+
88
+ /**
89
+ * Delete regardless of owner. Used when a push service reports the
90
+ * endpoint expired (404/410) — the stored user may be stale too.
91
+ */
92
+ deleteStaleByEndpoint(endpoint: string): boolean {
93
+ const db = getDatabase();
94
+ const result = db
95
+ .prepare('DELETE FROM push_subscriptions WHERE endpoint = ?')
96
+ .run(endpoint) as { changes: number | bigint };
97
+ return Number(result.changes ?? 0) > 0;
98
+ }
99
+ };
@@ -1,23 +1,35 @@
1
1
  /**
2
2
  * Skill Queries
3
3
  *
4
- * CRUD for user-managed Agent Skills — the skills managed from Settings →
5
- * Skills. The `skills` table holds only METADATA + the enable/disable toggle;
6
- * the actual SKILL.md (and any bundled resources) live on disk in the canonical
7
- * store under `{clopenDir}/skills/<slug>/` (see `backend/skills/store.ts`).
4
+ * CRUD for user-managed Agent Skills — the single artifact behind both model-
5
+ * invoked skills and user-invoked `/slash` prompts (Settings → Skills). The
6
+ * `skills` table holds only METADATA + the enable toggle; the actual SKILL.md
7
+ * (and any bundled resources) live on disk in the canonical store under
8
+ * `{clopenDir}/skills/<slug>/` (see `backend/skills/store.ts`).
8
9
  *
9
10
  * Conventions:
10
- * - `slug` : unique machine id, matches the on-disk folder name and the
11
- * SKILL.md `name` frontmatter. Only `[a-z0-9-]`.
12
- * - `source` : where the skill came from — 'custom' (created in-app),
13
- * 'imported' (pasted/uploaded), or 'marketplace' (installed from
14
- * a provider).
11
+ * - `slug` : unique machine id, matches the on-disk folder name and the
12
+ * SKILL.md `name` frontmatter. Only `[a-z0-9-]`.
13
+ * - `source` : where the skill came from — 'custom' (created in-app),
14
+ * 'imported' (pasted/uploaded), or 'marketplace' (installed
15
+ * from a provider).
16
+ * - `triggers` : comma list of how the skill can be invoked — `auto` (the
17
+ * model decides, from the description) and/or `slash` (the user
18
+ * types `/<slug>`). Migration 079 folded the old `commands`
19
+ * table in as `slash`-triggered skills.
20
+ * - `uses` : JSON array of sibling slugs force-loaded whenever this skill
21
+ * runs, so one invocation can pull in several skills at once.
15
22
  */
16
23
 
17
24
  import { getDatabase } from '../index';
18
25
 
19
26
  export type SkillSource = 'custom' | 'imported' | 'marketplace';
20
27
 
28
+ /** How a skill can be invoked. */
29
+ export type SkillTrigger = 'auto' | 'slash';
30
+
31
+ export const SKILL_TRIGGERS: SkillTrigger[] = ['auto', 'slash'];
32
+
21
33
  /** Raw DB row. */
22
34
  export interface SkillRow {
23
35
  id: number;
@@ -31,6 +43,12 @@ export interface SkillRow {
31
43
  license: string | null;
32
44
  is_enabled: number;
33
45
  created_at: string;
46
+ /** Comma-separated {@link SkillTrigger} list; never empty (defaults to `auto`). */
47
+ triggers: string;
48
+ /** Argument hint shown beside `/slug` in the chat picker (slash skills). */
49
+ argument_hint: string | null;
50
+ /** JSON array of sibling slugs force-loaded with this skill. */
51
+ uses: string;
34
52
  }
35
53
 
36
54
  export interface SkillInput {
@@ -41,6 +59,46 @@ export interface SkillInput {
41
59
  marketplaceRef?: string | null;
42
60
  version?: string | null;
43
61
  license?: string | null;
62
+ /** Comma-separated trigger list; defaults to `auto`. */
63
+ triggers?: string;
64
+ argumentHint?: string | null;
65
+ /** JSON string: array of slugs. */
66
+ uses?: string;
67
+ }
68
+
69
+ /** Parse the stored comma list into triggers, tolerating blanks/unknown values. */
70
+ export function parseTriggers(raw: string | null | undefined): SkillTrigger[] {
71
+ const list = (raw ?? '')
72
+ .split(',')
73
+ .map(t => t.trim().toLowerCase())
74
+ .filter((t): t is SkillTrigger => SKILL_TRIGGERS.includes(t as SkillTrigger));
75
+ // A skill with no recognised trigger would be invocable by nobody — fall back
76
+ // to the historical default rather than silently disappearing.
77
+ return list.length > 0 ? Array.from(new Set(list)) : ['auto'];
78
+ }
79
+
80
+ /** Serialize triggers back to the stored comma list (canonical order). */
81
+ export function stringifyTriggers(triggers: SkillTrigger[] | undefined): string {
82
+ const set = new Set(triggers ?? []);
83
+ const ordered = SKILL_TRIGGERS.filter(t => set.has(t));
84
+ return (ordered.length > 0 ? ordered : ['auto']).join(',');
85
+ }
86
+
87
+ /** Parse the stored `uses` JSON array, tolerating null/blank/corrupt values. */
88
+ export function parseUses(raw: string | null | undefined): string[] {
89
+ if (!raw) return [];
90
+ try {
91
+ const parsed = JSON.parse(raw);
92
+ if (!Array.isArray(parsed)) return [];
93
+ return Array.from(new Set(parsed.filter((v): v is string => typeof v === 'string' && !!v.trim()).map(v => v.trim())));
94
+ } catch {
95
+ return [];
96
+ }
97
+ }
98
+
99
+ /** Serialize a `uses` list to its stored JSON form. */
100
+ export function stringifyUses(uses: string[] | undefined): string {
101
+ return JSON.stringify(Array.from(new Set((uses ?? []).map(u => u.trim()).filter(Boolean))));
44
102
  }
45
103
 
46
104
  export const skillQueries = {
@@ -67,8 +125,8 @@ export const skillQueries = {
67
125
  insert(input: SkillInput): SkillRow {
68
126
  const db = getDatabase();
69
127
  const result = db.prepare(
70
- `INSERT INTO skills (slug, name, description, source, marketplace_ref, version, license)
71
- VALUES (?, ?, ?, ?, ?, ?, ?)`
128
+ `INSERT INTO skills (slug, name, description, source, marketplace_ref, version, license, triggers, argument_hint, uses)
129
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
72
130
  ).run(
73
131
  input.slug,
74
132
  input.name,
@@ -76,19 +134,39 @@ export const skillQueries = {
76
134
  input.source ?? 'custom',
77
135
  input.marketplaceRef ?? null,
78
136
  input.version ?? null,
79
- input.license ?? null
137
+ input.license ?? null,
138
+ input.triggers ?? 'auto',
139
+ input.argumentHint ?? null,
140
+ input.uses ?? '[]'
80
141
  ) as { lastInsertRowid: number | bigint };
81
142
  const id = Number(result.lastInsertRowid);
82
143
  return this.getById(id)!;
83
144
  },
84
145
 
85
- /** Update the display metadata (name/description/license) of a skill. */
86
- updateMeta(id: number, name: string, description: string, license: string | null): void {
146
+ /** Update every editable field of a skill (the SKILL.md itself is rewritten by the service). */
147
+ updateMeta(
148
+ id: number,
149
+ fields: {
150
+ name: string;
151
+ description: string;
152
+ license: string | null;
153
+ triggers: string;
154
+ argumentHint: string | null;
155
+ uses: string;
156
+ }
157
+ ): void {
87
158
  const db = getDatabase();
88
- db.prepare(`UPDATE skills SET name = ?, description = ?, license = ? WHERE id = ?`).run(
89
- name,
90
- description,
91
- license,
159
+ db.prepare(
160
+ `UPDATE skills
161
+ SET name = ?, description = ?, license = ?, triggers = ?, argument_hint = ?, uses = ?
162
+ WHERE id = ?`
163
+ ).run(
164
+ fields.name,
165
+ fields.description,
166
+ fields.license,
167
+ fields.triggers,
168
+ fields.argumentHint,
169
+ fields.uses,
92
170
  id
93
171
  );
94
172
  },