@notis_ai/cli 0.2.0-beta.16.1 → 0.2.0-beta.161.1

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 (161) hide show
  1. package/README.md +435 -133
  2. package/bin/check-runtime.js +15 -0
  3. package/bin/notis.js +2 -0
  4. package/config/notis_app_boundary_rules.json +50 -0
  5. package/config/notis_app_design_rules.json +135 -0
  6. package/dist/agent-hooks/notis-agent-hook.mjs +19008 -0
  7. package/dist/base-skills/notis-apps/SKILL.md +70 -0
  8. package/dist/base-skills/notis-apps/references/architecture.md +164 -0
  9. package/dist/base-skills/notis-apps/references/context.md +81 -0
  10. package/dist/base-skills/notis-apps/references/design.md +165 -0
  11. package/dist/base-skills/notis-apps/references/reading.md +89 -0
  12. package/dist/base-skills/notis-apps/references/release.md +99 -0
  13. package/dist/base-skills/notis-apps/references/sdk.md +62 -0
  14. package/dist/base-skills/notis-apps/references/troubleshooting.md +23 -0
  15. package/dist/base-skills/notis-cli/SKILL.md +140 -0
  16. package/dist/base-skills/notis-cli/references/app-delivery.md +18 -0
  17. package/dist/base-skills/notis-cli/references/native-databases.md +20 -0
  18. package/dist/base-skills/notis-cli/references/tool-examples.md +56 -0
  19. package/dist/base-skills/notis-cli/references/troubleshooting.md +39 -0
  20. package/dist/base-skills/notis-query/SKILL.md +67 -0
  21. package/dist/base-skills/notis-query/references/database-discovery.md +59 -0
  22. package/dist/base-skills/notis-query/references/documents.md +50 -0
  23. package/dist/base-skills/notis-query/references/query.md +543 -0
  24. package/dist/skill-sync/index.js +1626 -0
  25. package/dist/skill-sync/index.js.map +7 -0
  26. package/dist/skill-sync-worker.mjs +2990 -0
  27. package/package.json +18 -7
  28. package/skills/notis-apps/cli.md +313 -0
  29. package/skills/notis-cli/AGENT_INSTRUCTIONS.md +39 -0
  30. package/skills/notis-onboarding/BRIEF.md +129 -0
  31. package/skills/notis-query/cli.md +39 -0
  32. package/src/agent-hook-entry.js +5 -0
  33. package/src/cli.js +294 -25
  34. package/src/command-specs/agents.js +392 -0
  35. package/src/command-specs/apps.js +1470 -202
  36. package/src/command-specs/auth.js +114 -137
  37. package/src/command-specs/diagnostics.js +729 -0
  38. package/src/command-specs/handover.js +374 -0
  39. package/src/command-specs/helpers.js +84 -82
  40. package/src/command-specs/index.js +25 -6
  41. package/src/command-specs/meta.js +150 -18
  42. package/src/command-specs/onboarding.js +290 -0
  43. package/src/command-specs/profile.js +358 -0
  44. package/src/command-specs/reports.js +86 -0
  45. package/src/command-specs/skills.js +75 -0
  46. package/src/command-specs/smoke.js +386 -0
  47. package/src/command-specs/tools.js +455 -139
  48. package/src/runtime/agent-browser.js +632 -0
  49. package/src/runtime/agent-memory-state.js +126 -0
  50. package/src/runtime/agent-setup.js +383 -0
  51. package/src/runtime/app-boundary-validator.js +404 -0
  52. package/src/runtime/app-changelog.js +79 -0
  53. package/src/runtime/app-platform.js +2633 -210
  54. package/src/runtime/app-registry-scaffolds.js +367 -0
  55. package/src/runtime/app-test-server.js +292 -0
  56. package/src/runtime/assets/store-screenshot-dark.png +0 -0
  57. package/src/runtime/auth-recovery.js +110 -0
  58. package/src/runtime/base-skills.d.ts +20 -0
  59. package/src/runtime/base-skills.js +167 -0
  60. package/src/runtime/channel.js +133 -0
  61. package/src/runtime/delegated-context.js +68 -0
  62. package/src/runtime/errors.js +1 -0
  63. package/src/runtime/git.js +233 -0
  64. package/src/runtime/login-listener.js +15 -0
  65. package/src/runtime/oauth.js +2622 -0
  66. package/src/runtime/output.js +37 -5
  67. package/src/runtime/ports.js +31 -0
  68. package/src/runtime/profiles.js +906 -55
  69. package/src/runtime/skill-sync/cloud-client.ts +99 -0
  70. package/src/runtime/skill-sync/index.ts +697 -0
  71. package/src/runtime/skill-sync/local-scanner.ts +1046 -0
  72. package/src/runtime/skill-sync/symlink-manager.ts +433 -0
  73. package/src/runtime/skill-sync/sync-plan.ts +22 -0
  74. package/src/runtime/skill-sync/types.ts +110 -0
  75. package/src/runtime/skill-sync/write-cloud-skill.ts +50 -0
  76. package/src/runtime/skill-sync-service.js +109 -0
  77. package/src/runtime/store-screenshot.js +143 -0
  78. package/src/runtime/sync-skills.d.ts +37 -0
  79. package/src/runtime/sync-skills.js +231 -0
  80. package/src/runtime/telemetry.js +92 -0
  81. package/src/runtime/transport.js +324 -45
  82. package/src/skill-sync-worker-entry.js +2 -0
  83. package/src/skill-sync-worker.js +50 -0
  84. package/template/.harness/index.html.tmpl +430 -0
  85. package/template/CHANGELOG.md +5 -0
  86. package/template/app/globals.css +28 -3
  87. package/template/app/layout.tsx +6 -3
  88. package/template/app/page.tsx +49 -42
  89. package/template/components/page-heading.tsx +23 -0
  90. package/template/components/ui/badge.tsx +7 -4
  91. package/template/components/ui/button.tsx +1 -1
  92. package/template/components/ui/card.tsx +24 -11
  93. package/template/components/ui/native-select.tsx +24 -0
  94. package/template/notis.config.ts +24 -6
  95. package/template/package-lock.json +3642 -0
  96. package/template/package.json +19 -16
  97. package/template/packages/{notis-sdk → sdk}/package.json +14 -4
  98. package/template/packages/sdk/src/agentContext.ts +36 -0
  99. package/template/packages/sdk/src/components/DocumentEditor.tsx +103 -0
  100. package/template/packages/sdk/src/components/Markdown.tsx +60 -0
  101. package/template/packages/sdk/src/components/MarkdownEditor.tsx +121 -0
  102. package/template/packages/sdk/src/components/MultiSelectActionBar.tsx +285 -0
  103. package/template/packages/sdk/src/components/MultiSelectCheckbox.tsx +97 -0
  104. package/template/packages/sdk/src/components/MultiSelectDragOverlay.tsx +39 -0
  105. package/template/packages/sdk/src/components/NotisCommentBoundary.tsx +172 -0
  106. package/template/packages/sdk/src/components/NotisSelectionBoundary.tsx +59 -0
  107. package/template/packages/sdk/src/components/ShortcutHints.tsx +56 -0
  108. package/template/packages/sdk/src/components/Skeleton.tsx +24 -0
  109. package/template/packages/sdk/src/config.ts +257 -0
  110. package/template/packages/sdk/src/documents.ts +256 -0
  111. package/template/packages/sdk/src/hooks/useActiveResource.ts +19 -0
  112. package/template/packages/sdk/src/hooks/useAgentContext.ts +23 -0
  113. package/template/packages/sdk/src/hooks/useCloudComputer.ts +64 -0
  114. package/template/packages/sdk/src/hooks/useCollectionInteractions.ts +836 -0
  115. package/template/packages/sdk/src/hooks/useDatabaseSchema.ts +49 -0
  116. package/template/packages/sdk/src/hooks/useDatabaseSubscription.ts +76 -0
  117. package/template/packages/sdk/src/hooks/useDocument.ts +43 -0
  118. package/template/packages/sdk/src/hooks/useDocuments.ts +84 -0
  119. package/template/packages/sdk/src/hooks/useHandover.ts +78 -0
  120. package/template/packages/sdk/src/hooks/useLongPressSelection.ts +79 -0
  121. package/template/packages/sdk/src/hooks/useMultiSelect.ts +95 -0
  122. package/template/packages/{notis-sdk → sdk}/src/hooks/useNotis.ts +10 -4
  123. package/template/packages/{notis-sdk → sdk}/src/hooks/useNotisNavigation.ts +11 -8
  124. package/template/packages/sdk/src/hooks/useQuery.ts +71 -0
  125. package/template/packages/sdk/src/hooks/useTool.ts +65 -0
  126. package/template/packages/sdk/src/hooks/useToolQuery.ts +12 -0
  127. package/template/packages/sdk/src/hooks/useTopBarSearch.ts +81 -0
  128. package/template/packages/sdk/src/hooks/useUpsertDocument.ts +95 -0
  129. package/template/packages/sdk/src/index.ts +161 -0
  130. package/template/packages/sdk/src/interactions/actions.ts +59 -0
  131. package/template/packages/sdk/src/interactions/shortcuts.tsx +694 -0
  132. package/template/packages/sdk/src/interactions/visibility.ts +13 -0
  133. package/template/packages/sdk/src/interactions.ts +45 -0
  134. package/template/packages/sdk/src/provider.tsx +44 -0
  135. package/template/packages/sdk/src/queryCache.ts +170 -0
  136. package/template/packages/sdk/src/runtime.ts +451 -0
  137. package/template/packages/sdk/src/styles.css +247 -0
  138. package/template/packages/sdk/src/tailwind.ts +66 -0
  139. package/template/packages/sdk/src/vite.ts +73 -0
  140. package/template/packages/{notis-sdk → sdk}/tsconfig.json +1 -0
  141. package/template/postcss.config.mjs +1 -1
  142. package/template/tailwind.config.ts +1 -6
  143. package/template/tsconfig.json +1 -0
  144. package/src/command-specs/db.js +0 -163
  145. package/src/runtime/app-preview-server.js +0 -312
  146. package/template/packages/notis-sdk/src/config.ts +0 -48
  147. package/template/packages/notis-sdk/src/helpers.ts +0 -131
  148. package/template/packages/notis-sdk/src/hooks/useAppState.ts +0 -50
  149. package/template/packages/notis-sdk/src/hooks/useCollectionItem.ts +0 -58
  150. package/template/packages/notis-sdk/src/hooks/useDatabase.ts +0 -87
  151. package/template/packages/notis-sdk/src/hooks/useDocument.ts +0 -61
  152. package/template/packages/notis-sdk/src/hooks/useTool.ts +0 -49
  153. package/template/packages/notis-sdk/src/hooks/useUpsertDocument.ts +0 -57
  154. package/template/packages/notis-sdk/src/index.ts +0 -47
  155. package/template/packages/notis-sdk/src/provider.tsx +0 -44
  156. package/template/packages/notis-sdk/src/runtime.ts +0 -159
  157. package/template/packages/notis-sdk/src/styles.css +0 -123
  158. package/template/packages/notis-sdk/src/vite.ts +0 -54
  159. /package/template/packages/{notis-sdk → sdk}/src/hooks/useBackend.ts +0 -0
  160. /package/template/packages/{notis-sdk → sdk}/src/hooks/useTools.ts +0 -0
  161. /package/template/packages/{notis-sdk → sdk}/src/ui.ts +0 -0
@@ -0,0 +1,697 @@
1
+ import { createHash } from 'node:crypto';
2
+ import type {
3
+ AgentTargets,
4
+ LocalSkill,
5
+ NotisSyncState,
6
+ SkillSyncFailure,
7
+ SyncPullResponse,
8
+ SyncSettings,
9
+ } from "./types";
10
+ import { normalizeAgentTargets } from "./types";
11
+ import {
12
+ downloadSkillBundle,
13
+ fetchSyncSettings,
14
+ pullSkills,
15
+ pushChangedSkills,
16
+ updateAgentTargets,
17
+ } from "./cloud-client";
18
+ import {
19
+ deleteLocalSkill,
20
+ gatherTopLevelLocalSkills,
21
+ getSkillSyncPathsForUser,
22
+ readLegacySyncState,
23
+ readSyncState,
24
+ scanLocalSkills,
25
+ writeCloudSkillToDisk,
26
+ writeSyncState,
27
+ } from "./local-scanner";
28
+ import {
29
+ detectDeletedAgentSymlinks,
30
+ removeForeignAccountSymlinks,
31
+ removeAllSymlinksForSkill,
32
+ syncSymlinks,
33
+ type DeletedAgentSymlink,
34
+ } from "./symlink-manager";
35
+ import { getPushCandidates } from "./sync-plan";
36
+ import { writeCloudSkillWithBundleFallback } from "./write-cloud-skill";
37
+ export { fetchSyncSettings } from './cloud-client';
38
+
39
+ export interface RunSkillSyncResult {
40
+ syncEnabled: boolean;
41
+ pushed: number;
42
+ pulled: number;
43
+ downloaded: number;
44
+ deleted: number;
45
+ /** Skills deactivated for a specific agent because the user deleted that agent's local
46
+ * symlink (e.g. `rm ~/.claude/skills/<skill>`); the deletion is honored instead of recreated. */
47
+ deactivated: number;
48
+ linked: number;
49
+ removed: number;
50
+ skipped: number;
51
+ lastSyncedAt: string | null;
52
+ /** Skills the server rejected (e.g. an invalid SKILL.md description). The rest of
53
+ * the batch still syncs; these are surfaced so the user knows what to fix. */
54
+ failedPushes: SkillSyncFailure[];
55
+ failedLinks?: SkillSyncFailure[];
56
+ }
57
+
58
+ export interface RunSkillSyncOptions {
59
+ /** Electron's scheduled invocation honors the account preference. A manual
60
+ * CLI sync always runs, even when automatic Desktop refresh is disabled. */
61
+ honorSyncEnabled?: boolean;
62
+ }
63
+
64
+ const BASE_SKILL_NAMES = new Set(['notis-apps', 'notis-query', 'notis-cli']);
65
+
66
+ function withoutBaseSkills(pullResponse: SyncPullResponse): SyncPullResponse {
67
+ return {
68
+ ...pullResponse,
69
+ skills: pullResponse.skills.filter((skill) => !BASE_SKILL_NAMES.has(skill.name)),
70
+ };
71
+ }
72
+
73
+ function withoutBaseSkillState(state: NotisSyncState): NotisSyncState {
74
+ return {
75
+ ...state,
76
+ skills: Object.fromEntries(
77
+ Object.entries(state.skills).filter(([name]) => !BASE_SKILL_NAMES.has(name)),
78
+ ),
79
+ };
80
+ }
81
+
82
+ export interface MaterializeCloudSkillsResult {
83
+ /** Cloud skills verified present in the final scoped disk scan. */
84
+ materializedSkillNames: string[];
85
+ pulled: number;
86
+ downloaded: number;
87
+ deleted: number;
88
+ removed: number;
89
+ lastSyncedAt: string | null;
90
+ failedLinks?: SkillSyncFailure[];
91
+ }
92
+
93
+ export interface MaterializeCloudSkillsOptions {
94
+ /** Server-verified Notis identity, when Desktop's auth subject differs. */
95
+ canonicalUserId?: string;
96
+ /** Re-link only these cloud skills without removing or adopting other links. */
97
+ relinkSkillNames?: readonly string[];
98
+ }
99
+
100
+ interface RunSkillSyncDependencies {
101
+ fetchSyncSettings: typeof fetchSyncSettings;
102
+ pullSkills: typeof pullSkills;
103
+ pushChangedSkills: typeof pushChangedSkills;
104
+ downloadSkillBundle: typeof downloadSkillBundle;
105
+ gatherTopLevelLocalSkills: typeof gatherTopLevelLocalSkills;
106
+ readLegacySyncState: typeof readLegacySyncState;
107
+ readSyncState: typeof readSyncState;
108
+ scanLocalSkills: typeof scanLocalSkills;
109
+ deleteLocalSkill: typeof deleteLocalSkill;
110
+ writeCloudSkillToDisk: typeof writeCloudSkillToDisk;
111
+ writeSyncState: typeof writeSyncState;
112
+ removeAllSymlinksForSkill: typeof removeAllSymlinksForSkill;
113
+ syncSymlinks: typeof syncSymlinks;
114
+ detectDeletedAgentSymlinks: typeof detectDeletedAgentSymlinks;
115
+ removeForeignAccountSymlinks: typeof removeForeignAccountSymlinks;
116
+ updateAgentTargets: typeof updateAgentTargets;
117
+ }
118
+
119
+ const DEFAULT_RUN_SKILL_SYNC_DEPS: RunSkillSyncDependencies = {
120
+ fetchSyncSettings,
121
+ pullSkills,
122
+ pushChangedSkills,
123
+ downloadSkillBundle,
124
+ gatherTopLevelLocalSkills,
125
+ readLegacySyncState,
126
+ readSyncState,
127
+ scanLocalSkills,
128
+ deleteLocalSkill,
129
+ writeCloudSkillToDisk,
130
+ writeSyncState,
131
+ removeAllSymlinksForSkill,
132
+ syncSymlinks,
133
+ detectDeletedAgentSymlinks,
134
+ removeForeignAccountSymlinks,
135
+ updateAgentTargets,
136
+ };
137
+ function toSkillMap(skills: LocalSkill[]): Map<string, LocalSkill> {
138
+ return new Map(skills.map((skill) => [skill.name, skill]));
139
+ }
140
+
141
+ function decodeJwtSubject(jwt: string): string | null {
142
+ try {
143
+ const parts = jwt.split(".");
144
+ if (parts.length !== 3) return null;
145
+ const decoded = JSON.parse(
146
+ Buffer.from(parts[1], "base64url").toString(),
147
+ ) as { sub?: unknown };
148
+ return typeof decoded.sub === "string" && decoded.sub.trim()
149
+ ? decoded.sub.trim()
150
+ : null;
151
+ } catch {
152
+ return null;
153
+ }
154
+ }
155
+
156
+ function cloudContentHash(skill: SyncPullResponse['skills'][number]): string {
157
+ return createHash('sha256').update(JSON.stringify({
158
+ md: skill.skill_md,
159
+ hash: skill.skill_folder_hash,
160
+ source: skill.skill_source_url,
161
+ files: skill.bundle_files?.slice().sort((a, b) => a.path.localeCompare(b.path)),
162
+ hydrationFailed: skill.bundle_hydration_failed === true,
163
+ })).digest('hex');
164
+ }
165
+
166
+ export function shouldWriteCloudSkill(
167
+ cloudSkill: SyncPullResponse["skills"][number],
168
+ localSkills: Map<string, LocalSkill>,
169
+ previousState: NotisSyncState,
170
+ ): boolean {
171
+ const skillName = cloudSkill.name;
172
+ const cloudHash = cloudSkill.skill_folder_hash || "";
173
+ const localSkill = localSkills.get(skillName);
174
+ if (!localSkill) {
175
+ return true;
176
+ }
177
+
178
+ const previous = previousState.skills[skillName];
179
+ if (previous?.folderHash === localSkill.folderHash
180
+ && previous.cloudContentHash === cloudContentHash(cloudSkill)) return false;
181
+
182
+ if (cloudSkill.source === "curated") {
183
+ return cloudHash ? cloudHash !== localSkill.folderHash : true;
184
+ }
185
+
186
+ const localChangedSinceLastSync =
187
+ !previous || previous.folderHash !== localSkill.folderHash;
188
+ return (
189
+ !localChangedSinceLastSync &&
190
+ ((Boolean(cloudHash) && cloudHash !== localSkill.folderHash)
191
+ || Boolean(previous?.cloudContentHash && previous.cloudContentHash !== cloudContentHash(cloudSkill)))
192
+ );
193
+ }
194
+
195
+ function buildSyncState(
196
+ pullResponse: SyncPullResponse,
197
+ localSkills: LocalSkill[],
198
+ lastSyncedAt: string | null,
199
+ verifiedAgentLinks: Record<string, Partial<AgentTargets>> = {},
200
+ failedContentNames: ReadonlySet<string> = new Set(),
201
+ ): NotisSyncState {
202
+ const localSkillMap = toSkillMap(localSkills);
203
+ const skills = Object.fromEntries(
204
+ pullResponse.skills.map((skill) => {
205
+ const localSkill = localSkillMap.get(skill.name);
206
+ return [
207
+ skill.name,
208
+ {
209
+ cloudId: skill.id,
210
+ folderHash: localSkill?.folderHash || skill.skill_folder_hash || "",
211
+ agentTargets: normalizeAgentTargets(skill.agent_targets),
212
+ verifiedAgentLinks: skill.status === "active" ? verifiedAgentLinks[skill.name] ?? {} : {},
213
+ cloudUpdatedAt: skill.updated_at,
214
+ ...(!failedContentNames.has(skill.name) && !skill.skill_source_url
215
+ ? { cloudContentHash: cloudContentHash(skill) } : {}),
216
+ syncedAt: lastSyncedAt || new Date().toISOString(),
217
+ },
218
+ ];
219
+ }),
220
+ );
221
+
222
+ return {
223
+ version: 1,
224
+ lastSyncedAt,
225
+ skills,
226
+ };
227
+ }
228
+
229
+ function buildLocalSymlinkCandidates(
230
+ pullResponse: SyncPullResponse,
231
+ localSkills: LocalSkill[],
232
+ previousState: NotisSyncState,
233
+ ): SyncPullResponse["skills"] {
234
+ const cloudSkillNames = new Set(
235
+ pullResponse.skills.map((skill) => skill.name),
236
+ );
237
+ const localOnlySkills = localSkills
238
+ .filter((skill) => !cloudSkillNames.has(skill.name))
239
+ .map((skill) => {
240
+ const previous = previousState.skills[skill.name];
241
+ return {
242
+ id: previous?.cloudId || `local-${skill.name}`,
243
+ name: skill.name,
244
+ description: skill.description || null,
245
+ skill_md: skill.skillMd,
246
+ agent_targets: previous?.agentTargets,
247
+ skill_folder_hash: skill.folderHash,
248
+ source: "local",
249
+ status: "active",
250
+ };
251
+ });
252
+
253
+ return [...pullResponse.skills, ...localOnlySkills];
254
+ }
255
+
256
+ function isEmptySyncState(state: NotisSyncState): boolean {
257
+ return state.lastSyncedAt === null && Object.keys(state.skills).length === 0;
258
+ }
259
+
260
+ function applyLegacyFirstRunState(
261
+ localSkills: LocalSkill[],
262
+ scopedState: NotisSyncState,
263
+ legacyState: NotisSyncState | null,
264
+ ): NotisSyncState {
265
+ if (!isEmptySyncState(scopedState) || !legacyState) {
266
+ return scopedState;
267
+ }
268
+
269
+ const migratedSkills = Object.fromEntries(
270
+ localSkills.flatMap((skill) => {
271
+ const previous = legacyState.skills[skill.name];
272
+ if (!previous || previous.folderHash !== skill.folderHash) {
273
+ return [];
274
+ }
275
+ return [[skill.name, previous]];
276
+ }),
277
+ );
278
+
279
+ if (Object.keys(migratedSkills).length === 0) {
280
+ return scopedState;
281
+ }
282
+
283
+ return {
284
+ version: 1,
285
+ lastSyncedAt: legacyState.lastSyncedAt,
286
+ skills: migratedSkills,
287
+ };
288
+ }
289
+
290
+ async function writePulledSkillsToScopedMirror(
291
+ pullResponse: SyncPullResponse,
292
+ localSkills: LocalSkill[],
293
+ previousState: NotisSyncState,
294
+ syncPaths: ReturnType<typeof getSkillSyncPathsForUser>,
295
+ deps: Pick<
296
+ RunSkillSyncDependencies,
297
+ "downloadSkillBundle" | "writeCloudSkillToDisk"
298
+ >,
299
+ failures: SkillSyncFailure[] = [],
300
+ writtenSkillNames: Set<string> = new Set(),
301
+ ): Promise<number> {
302
+ const localSkillMap = toSkillMap(localSkills);
303
+ const warnSkillSync = (message: string, error: unknown): void => {
304
+ console.warn(`[Notis] ${message}`, error);
305
+ };
306
+
307
+ let downloaded = 0;
308
+ for (const cloudSkill of pullResponse.skills) {
309
+ if (!shouldWriteCloudSkill(cloudSkill, localSkillMap, previousState)) {
310
+ continue;
311
+ }
312
+
313
+ if (
314
+ await writeCloudSkillWithBundleFallback(cloudSkill, {
315
+ downloadSkillBundle: deps.downloadSkillBundle,
316
+ writeCloudSkillToDisk: (skill, bundleBytes) =>
317
+ deps.writeCloudSkillToDisk(skill, bundleBytes, syncPaths),
318
+ onWarning: warnSkillSync,
319
+ })
320
+ ) {
321
+ downloaded += 1;
322
+ writtenSkillNames.add(cloudSkill.name);
323
+ } else {
324
+ failures.push({ name: cloudSkill.name, error: "Skill content could not be downloaded or written; sync will retry" });
325
+ }
326
+ }
327
+
328
+ return downloaded;
329
+ }
330
+
331
+ function assertSkillsPullAuthorized(
332
+ pullResponse: SyncPullResponse,
333
+ ): void {
334
+ if (
335
+ pullResponse.entitlement_access?.code === "entitlement_upgrade_required"
336
+ && pullResponse.entitlement_access.entitlement === "skills"
337
+ ) {
338
+ // Current servers return HTTP 403, so cloud-client rejects before producing
339
+ // a SyncPullResponse. Keep this guard for an older server's successful
340
+ // empty-denial envelope, but fail closed: it is never authorization to
341
+ // delete a user's managed local mirror.
342
+ throw new Error(
343
+ "Skill sync access was denied; preserving existing local skills.",
344
+ );
345
+ }
346
+ }
347
+
348
+ export async function materializeCloudSkillsForLocalShell(
349
+ serverUrl: string,
350
+ jwt: string,
351
+ dependencies: Partial<Pick<
352
+ RunSkillSyncDependencies,
353
+ | "downloadSkillBundle"
354
+ | "deleteLocalSkill"
355
+ | "pullSkills"
356
+ | "readSyncState"
357
+ | "removeAllSymlinksForSkill"
358
+ | "scanLocalSkills"
359
+ | "syncSymlinks"
360
+ | "writeCloudSkillToDisk"
361
+ | "writeSyncState"
362
+ >> = {},
363
+ options: MaterializeCloudSkillsOptions = {},
364
+ ): Promise<MaterializeCloudSkillsResult> {
365
+ const deps = {
366
+ ...DEFAULT_RUN_SKILL_SYNC_DEPS,
367
+ ...dependencies,
368
+ };
369
+ const authUserId = decodeJwtSubject(jwt);
370
+ if (!authUserId) {
371
+ throw new Error(
372
+ "Cannot materialize skills without a valid authenticated desktop session.",
373
+ );
374
+ }
375
+
376
+ const syncPaths = getSkillSyncPathsForUser(options.canonicalUserId?.trim() || authUserId);
377
+ const pullResponse = await deps.pullSkills(serverUrl, jwt);
378
+ assertSkillsPullAuthorized(pullResponse);
379
+ const previousState = await deps.readSyncState(syncPaths);
380
+
381
+ const localSkills = await deps.scanLocalSkills(syncPaths);
382
+ const failedDownloads: SkillSyncFailure[] = [];
383
+ const writtenSkillNames = new Set<string>();
384
+ const downloaded = await writePulledSkillsToScopedMirror(
385
+ pullResponse,
386
+ localSkills,
387
+ previousState,
388
+ syncPaths,
389
+ deps,
390
+ failedDownloads,
391
+ writtenSkillNames,
392
+ );
393
+ const finalLocalSkills = await deps.scanLocalSkills(syncPaths);
394
+ const lastSyncedAt = pullResponse.last_synced_at || new Date().toISOString();
395
+
396
+ const relinkSkillNames = new Set(options.relinkSkillNames || []);
397
+ const failures = [...failedDownloads];
398
+ const verifiedLinks: Record<string, Partial<AgentTargets>> = {};
399
+ for (const skill of pullResponse.skills) {
400
+ const previous = previousState.skills[skill.name];
401
+ if (skill.updated_at && previous?.cloudId === skill.id && previous.cloudUpdatedAt === skill.updated_at) {
402
+ verifiedLinks[skill.name] = { ...previous.verifiedAgentLinks };
403
+ }
404
+ }
405
+ if (relinkSkillNames.size > 0) {
406
+ const relinked = await deps.syncSymlinks(
407
+ pullResponse.skills.filter((skill) => relinkSkillNames.has(skill.name)),
408
+ syncPaths.skillsDir,
409
+ { removeUndesired: false },
410
+ );
411
+ failures.push(...(relinked.failures ?? []).filter(
412
+ (failure) => !failedDownloads.some((download) => download.name === failure.name),
413
+ ));
414
+ for (const name of relinkSkillNames) {
415
+ verifiedLinks[name] = relinked.verifiedAgentLinks?.[name] ?? {};
416
+ }
417
+ }
418
+ for (const failure of failedDownloads) delete verifiedLinks[failure.name];
419
+
420
+ const materializedState = buildSyncState(
421
+ pullResponse, finalLocalSkills, lastSyncedAt, verifiedLinks,
422
+ new Set(failedDownloads.map(item => item.name)),
423
+ );
424
+ // Pull-only refresh is not an upload acknowledgement. Keep content baselines
425
+ // unless we actually wrote cloud content, and retain cloud-missing entries so
426
+ // the next two-way sync can delete them instead of uploading them as new.
427
+ for (const [name, entry] of Object.entries(materializedState.skills)) {
428
+ if (writtenSkillNames.has(name)) continue;
429
+ const previous = previousState.skills[name];
430
+ if (previous) {
431
+ entry.folderHash = previous.folderHash;
432
+ entry.cloudContentHash = previous.cloudContentHash;
433
+ } else {
434
+ delete materializedState.skills[name];
435
+ }
436
+ }
437
+ materializedState.skills = { ...previousState.skills, ...materializedState.skills };
438
+ await deps.writeSyncState(materializedState, syncPaths);
439
+
440
+ return {
441
+ materializedSkillNames: pullResponse.skills
442
+ .filter((skill) => finalLocalSkills.some((local) => local.name === skill.name)
443
+ && !failedDownloads.some((failure) => failure.name === skill.name))
444
+ .map((skill) => skill.name),
445
+ pulled: pullResponse.skills.length,
446
+ downloaded,
447
+ deleted: 0,
448
+ removed: 0,
449
+ lastSyncedAt,
450
+ ...(failures.length ? { failedLinks: failures } : {}),
451
+ };
452
+ }
453
+
454
+ /**
455
+ * When the user deletes a skill's symlink for a single agent (e.g. `rm ~/.claude/skills/<skill>`),
456
+ * honor that as "remove this skill from that agent" by deactivating it in the portal, instead of
457
+ * recreating the symlink on the next sync. The cloud `agent_targets` are mutated in place so the
458
+ * subsequent symlink reconciliation treats the link as undesired. Returns the number of
459
+ * (skill, agent) pairs deactivated.
460
+ */
461
+ async function deactivateDeletedAgentSkills(
462
+ serverUrl: string,
463
+ jwt: string,
464
+ pullResponse: SyncPullResponse,
465
+ previousState: NotisSyncState,
466
+ scopedState: NotisSyncState,
467
+ skillsDir: string,
468
+ deps: Pick<
469
+ RunSkillSyncDependencies,
470
+ "detectDeletedAgentSymlinks" | "updateAgentTargets" | "pullSkills"
471
+ >,
472
+ failures: SkillSyncFailure[],
473
+ ): Promise<number> {
474
+ // First sync (incl. legacy migration) has no reliable "we created this link" signal, so we
475
+ // cannot tell a user deletion apart from a never-created link — skip detection entirely.
476
+ if (isEmptySyncState(scopedState)) {
477
+ return 0;
478
+ }
479
+
480
+ const deletions = await deps.detectDeletedAgentSymlinks(
481
+ pullResponse.skills,
482
+ previousState,
483
+ skillsDir,
484
+ );
485
+ if (deletions.length === 0) {
486
+ return 0;
487
+ }
488
+
489
+ const agentsBySkill = new Map<string, { skillName: string; agents: Set<DeletedAgentSymlink["agent"]> }>();
490
+ for (const deletion of deletions) {
491
+ const entry = agentsBySkill.get(deletion.skillId) ?? {
492
+ skillName: deletion.skillName,
493
+ agents: new Set<DeletedAgentSymlink["agent"]>(),
494
+ };
495
+ entry.agents.add(deletion.agent);
496
+ agentsBySkill.set(deletion.skillId, entry);
497
+ }
498
+
499
+ const fresh = withoutBaseSkills(await deps.pullSkills(serverUrl, jwt));
500
+ assertSkillsPullAuthorized(fresh);
501
+ Object.assign(pullResponse, fresh);
502
+ let needsRefresh = false;
503
+ let deactivated = 0;
504
+ for (const [skillId, { skillName, agents }] of agentsBySkill) {
505
+ const skill = pullResponse.skills.find((item) => item.id === skillId);
506
+ const previous = previousState.skills[skillName];
507
+ if (!skill?.updated_at || previous?.cloudUpdatedAt !== skill.updated_at) continue;
508
+ const patch = Object.fromEntries([...agents].map((agent) => [agent, false]));
509
+ try {
510
+ const saved = await deps.updateAgentTargets(serverUrl, jwt, skillId, patch, skill.updated_at);
511
+ if (saved.success !== true || !saved.updated_at?.trim()
512
+ || saved.updated_at === skill.updated_at
513
+ || !['notis', 'claude_code', 'cursor', 'codex'].every((agent) =>
514
+ typeof saved.agent_targets?.[agent as keyof AgentTargets] === 'boolean')
515
+ || ![...agents].every((agent) => saved.agent_targets[agent] === false)) {
516
+ throw new Error('Assignment update did not return a verified saved revision');
517
+ }
518
+ skill.agent_targets = saved.agent_targets;
519
+ skill.updated_at = saved.updated_at;
520
+ deactivated += agents.size;
521
+ } catch (error) {
522
+ needsRefresh = true;
523
+ failures.push({ name: skillName, error: 'Could not save the local agent removal; refreshed saved assignments' });
524
+ console.warn(`[skill-sync] Assignment changed or could not be saved for "${skillName}"; refreshing before reconciliation.`, error);
525
+ }
526
+ }
527
+ if (needsRefresh) {
528
+ const refreshed = withoutBaseSkills(await deps.pullSkills(serverUrl, jwt));
529
+ assertSkillsPullAuthorized(refreshed);
530
+ Object.assign(pullResponse, refreshed);
531
+ }
532
+ return deactivated;
533
+ }
534
+
535
+ export async function runSkillSync(
536
+ serverUrl: string,
537
+ jwt: string,
538
+ dependencies: Partial<RunSkillSyncDependencies> = {},
539
+ options: RunSkillSyncOptions = {},
540
+ ): Promise<RunSkillSyncResult> {
541
+ const deps = {
542
+ ...DEFAULT_RUN_SKILL_SYNC_DEPS,
543
+ ...dependencies,
544
+ };
545
+ const syncSettings: SyncSettings = await deps.fetchSyncSettings(
546
+ serverUrl,
547
+ jwt,
548
+ );
549
+ // Supabase Desktop sessions use the auth-user id as JWT `sub`, while CLI
550
+ // OAuth credentials use the canonical Notis `users.user_id`. Trust the
551
+ // authenticated server response so both transports share one local mirror.
552
+ // The token fallback keeps the CLI compatible with an older server during
553
+ // rollout, where sync-settings did not yet return user_id.
554
+ const syncUserId = syncSettings.user_id?.trim() || decodeJwtSubject(jwt);
555
+ if (!syncUserId) {
556
+ throw new Error(
557
+ "Cannot sync skills without a server-verified account identity.",
558
+ );
559
+ }
560
+ const syncPaths = getSkillSyncPathsForUser(syncUserId);
561
+ const foreignLinksRemoved = await deps.removeForeignAccountSymlinks(
562
+ syncPaths.skillsDir,
563
+ );
564
+ if (options.honorSyncEnabled !== false && !syncSettings.sync_enabled) {
565
+ return {
566
+ syncEnabled: false,
567
+ pushed: 0,
568
+ pulled: 0,
569
+ downloaded: 0,
570
+ deleted: 0,
571
+ deactivated: 0,
572
+ linked: 0,
573
+ removed: foreignLinksRemoved,
574
+ skipped: 0,
575
+ lastSyncedAt: syncSettings.last_synced_at,
576
+ failedPushes: [],
577
+ };
578
+ }
579
+
580
+ let pullResponse = withoutBaseSkills(await deps.pullSkills(serverUrl, jwt));
581
+ assertSkillsPullAuthorized(pullResponse);
582
+
583
+ const cloudCuratedSkillNames = new Set(
584
+ pullResponse.skills
585
+ .filter((skill) => skill.source === "curated")
586
+ .map((skill) => skill.name),
587
+ );
588
+ const protectedSkillNames = new Set([...cloudCuratedSkillNames, ...BASE_SKILL_NAMES]);
589
+ const scopedState = withoutBaseSkillState(await deps.readSyncState(syncPaths));
590
+ const assignmentFailures: SkillSyncFailure[] = [];
591
+ const deactivated = syncSettings.agent_targets_conditional_updates === true
592
+ ? await deactivateDeletedAgentSkills(
593
+ serverUrl, jwt, pullResponse, scopedState, scopedState, syncPaths.skillsDir, deps, assignmentFailures,
594
+ )
595
+ : 0;
596
+ const authUserId = decodeJwtSubject(jwt);
597
+ let previousAuthState: NotisSyncState | null = null;
598
+ if (authUserId && authUserId !== syncUserId) {
599
+ const previousAuthPaths = getSkillSyncPathsForUser(authUserId);
600
+ previousAuthState = await deps.readSyncState(previousAuthPaths);
601
+ await deps.gatherTopLevelLocalSkills(syncPaths, {
602
+ sourceRoots: [{ label: "previous-auth-scope", root: previousAuthPaths.skillsDir }],
603
+ protectedSkillNames,
604
+ });
605
+ }
606
+ await deps.gatherTopLevelLocalSkills(syncPaths, {
607
+ protectedSkillNames,
608
+ });
609
+ const localSkills = (await deps.scanLocalSkills(syncPaths))
610
+ .filter((skill) => !BASE_SKILL_NAMES.has(skill.name));
611
+ const previousState = withoutBaseSkillState(applyLegacyFirstRunState(
612
+ localSkills,
613
+ scopedState,
614
+ isEmptySyncState(scopedState)
615
+ ? (!previousAuthState || isEmptySyncState(previousAuthState)
616
+ ? await deps.readLegacySyncState(syncPaths)
617
+ : previousAuthState)
618
+ : null,
619
+ ));
620
+ const gatheredSymlinkResult = await deps.syncSymlinks(
621
+ buildLocalSymlinkCandidates(pullResponse, localSkills, previousState),
622
+ syncPaths.skillsDir,
623
+ );
624
+ const pushCandidates = getPushCandidates(
625
+ localSkills,
626
+ previousState,
627
+ cloudCuratedSkillNames,
628
+ new Set(pullResponse.skills.map((skill) => skill.name)),
629
+ );
630
+
631
+ const failedPushes: SkillSyncFailure[] = [];
632
+ if (pushCandidates.length > 0) {
633
+ const pushResult = await deps.pushChangedSkills(serverUrl, jwt, pushCandidates);
634
+ if (Array.isArray(pushResult?.failed) && pushResult.failed.length > 0) {
635
+ failedPushes.push(...pushResult.failed);
636
+ console.warn(
637
+ `[skill-sync] ${pushResult.failed.length} skill(s) were rejected during push: ` +
638
+ pushResult.failed.map((f) => `${f.name} (${f.error})`).join("; "),
639
+ );
640
+ }
641
+ pullResponse = withoutBaseSkills(await deps.pullSkills(serverUrl, jwt));
642
+ assertSkillsPullAuthorized(pullResponse);
643
+ }
644
+
645
+ // Delete phase: remove skills that were previously synced but are no longer in the cloud
646
+ const cloudSkillNames = new Set(pullResponse.skills.map((s) => s.name));
647
+ let deleted = 0;
648
+ for (const skillName of Object.keys(previousState.skills)) {
649
+ if (!cloudSkillNames.has(skillName)) {
650
+ await deps.deleteLocalSkill(skillName, syncPaths);
651
+ await deps.removeAllSymlinksForSkill(skillName, syncPaths.skillsDir);
652
+ deleted += 1;
653
+ }
654
+ }
655
+
656
+ const failedDownloads: SkillSyncFailure[] = [];
657
+ const downloaded = await writePulledSkillsToScopedMirror(
658
+ pullResponse,
659
+ localSkills,
660
+ previousState,
661
+ syncPaths,
662
+ deps,
663
+ failedDownloads,
664
+ );
665
+
666
+ const finalLocalSkills = (await deps.scanLocalSkills(syncPaths))
667
+ .filter((skill) => !BASE_SKILL_NAMES.has(skill.name));
668
+ const symlinkResult = await deps.syncSymlinks(
669
+ buildLocalSymlinkCandidates(pullResponse, finalLocalSkills, previousState),
670
+ syncPaths.skillsDir,
671
+ );
672
+ const verifiedLinks = { ...(symlinkResult.verifiedAgentLinks ?? {}) };
673
+ for (const failure of failedDownloads) delete verifiedLinks[failure.name];
674
+ const lastSyncedAt = pullResponse.last_synced_at || new Date().toISOString();
675
+
676
+ await deps.writeSyncState(
677
+ buildSyncState(pullResponse, finalLocalSkills, lastSyncedAt, verifiedLinks, new Set(failedDownloads.map(item => item.name))),
678
+ syncPaths,
679
+ );
680
+
681
+ return {
682
+ syncEnabled: true,
683
+ pushed: pushCandidates.length,
684
+ pulled: pullResponse.skills.length,
685
+ downloaded,
686
+ deleted,
687
+ deactivated,
688
+ linked: gatheredSymlinkResult.linked + symlinkResult.linked,
689
+ removed: foreignLinksRemoved + gatheredSymlinkResult.removed + symlinkResult.removed,
690
+ skipped: symlinkResult.skipped,
691
+ failedLinks: [...assignmentFailures, ...failedDownloads, ...(symlinkResult.failures ?? []).filter(
692
+ (failure) => !failedDownloads.some((download) => download.name === failure.name),
693
+ )],
694
+ lastSyncedAt,
695
+ failedPushes,
696
+ };
697
+ }