phewsh 0.5.3 → 0.5.4

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.
package/bin/phewsh.js CHANGED
@@ -44,6 +44,7 @@ const COMMANDS = {
44
44
  link: () => require('../commands/link'),
45
45
  login: () => require('../commands/login'),
46
46
  ai: () => require('../commands/ai'),
47
+ style: () => require('../commands/style'),
47
48
  music: () => require('../commands/music'),
48
49
  sap: () => require('../commands/sap'),
49
50
  help: showHelp,
@@ -67,6 +68,7 @@ function showHelp() {
67
68
  console.log(` ${w('ai')} Run context-aware AI prompts (reads .intent/)`);
68
69
  console.log(` ${w('login')} Set up identity, API key, and cloud sync`);
69
70
  console.log(` ${w('sap')} Sustainable AI Protocol — usage and accountability`);
71
+ console.log(` ${w('style')} Build your style identity — ingest, profile, sync`);
70
72
  console.log(` ${w('music')} MBHD music engine`);
71
73
  console.log('');
72
74
  console.log(` ${b('Quick start')}`);
@@ -0,0 +1,320 @@
1
+ // phewsh style — build and manage your StyleTree identity
2
+ // Pipeline: ingest → extract features → rebuild profile → display
3
+
4
+ const fs = require('fs');
5
+ const path = require('path');
6
+ const os = require('os');
7
+ const readline = require('readline');
8
+ const { select, upsert, SUPABASE_URL, SUPABASE_ANON_KEY } = require('../lib/supabase');
9
+
10
+ const CONFIG_PATH = path.join(os.homedir(), '.phewsh', 'config.json');
11
+ const STYLE_CACHE_DIR = path.join(os.homedir(), '.phewsh', 'styletree');
12
+
13
+ // ── ANSI
14
+ const b = (s) => `\x1b[1m${s}\x1b[0m`;
15
+ const d = (s) => `\x1b[2m${s}\x1b[0m`;
16
+ const g = (s) => `\x1b[90m${s}\x1b[0m`;
17
+ const c = (s) => `\x1b[36m${s}\x1b[0m`;
18
+ const y = (s) => `\x1b[33m${s}\x1b[0m`;
19
+
20
+ function loadConfig() {
21
+ try { return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8')); } catch { return null; }
22
+ }
23
+
24
+ function ask(rl, q) {
25
+ return new Promise((resolve) => rl.question(q, (a) => resolve(a.trim())));
26
+ }
27
+
28
+ function ensureCacheDir() {
29
+ fs.mkdirSync(STYLE_CACHE_DIR, { recursive: true });
30
+ }
31
+
32
+ // ── Basic audio metadata via Node (no heavy deps — just file info for MVP)
33
+ function extractBasicFileInfo(filePath) {
34
+ try {
35
+ const stat = fs.statSync(filePath);
36
+ const ext = path.extname(filePath).toLowerCase();
37
+ const mediumMap = {
38
+ '.mp3': 'audio', '.wav': 'audio', '.flac': 'audio', '.aac': 'audio',
39
+ '.ogg': 'audio', '.m4a': 'audio', '.aiff': 'audio',
40
+ '.mid': 'midi', '.midi': 'midi',
41
+ '.txt': 'text', '.md': 'text',
42
+ };
43
+ return {
44
+ file_size_bytes: stat.size,
45
+ mime_type: ext,
46
+ medium: mediumMap[ext] || 'other',
47
+ };
48
+ } catch {
49
+ return { medium: 'other' };
50
+ }
51
+ }
52
+
53
+ // ── Save artifact + features locally (Tier 0)
54
+ function saveLocally(artifact, features) {
55
+ ensureCacheDir();
56
+ const localPath = path.join(STYLE_CACHE_DIR, 'artifacts.json');
57
+ let existing = [];
58
+ try { existing = JSON.parse(fs.readFileSync(localPath, 'utf-8')); } catch { /* empty */ }
59
+ existing.push({ artifact, features, savedAt: new Date().toISOString() });
60
+ fs.writeFileSync(localPath, JSON.stringify(existing, null, 2));
61
+ }
62
+
63
+ // ── Load local artifact cache
64
+ function loadLocal() {
65
+ try {
66
+ const localPath = path.join(STYLE_CACHE_DIR, 'artifacts.json');
67
+ return JSON.parse(fs.readFileSync(localPath, 'utf-8'));
68
+ } catch { return []; }
69
+ }
70
+
71
+ // ── Rebuild profile from local cache
72
+ function buildLocalProfile(entries) {
73
+ const tempos = entries.map(e => e.features?.tempo_bpm).filter(Boolean);
74
+ const keys = entries.map(e => e.features?.key_signature).filter(Boolean);
75
+ const vibes = entries.flatMap(e => e.features?.vibe || []).filter(Boolean);
76
+ const instruments = entries.flatMap(e => e.features?.instruments || []).filter(Boolean);
77
+ const energies = entries.map(e => e.features?.energy).filter(Boolean);
78
+
79
+ const freq = (arr) => {
80
+ const counts = {};
81
+ arr.forEach(v => counts[v] = (counts[v] || 0) + 1);
82
+ return Object.entries(counts).sort((a, b) => b[1] - a[1]).map(([k]) => k);
83
+ };
84
+
85
+ return {
86
+ artifact_count: entries.length,
87
+ tempo_range: tempos.length ? [Math.min(...tempos), Math.max(...tempos)] : null,
88
+ dominant_keys: [...new Set(keys)].slice(0, 3),
89
+ vibe_signature: freq(vibes).slice(0, 5),
90
+ instrument_palette: freq(instruments).slice(0, 6),
91
+ energy_avg: energies.length ? energies.reduce((a, b) => a + b, 0) / energies.length : null,
92
+ };
93
+ }
94
+
95
+ // ── Print style profile
96
+ function printProfile(profile, email) {
97
+ console.log('');
98
+ console.log(` ${b('your style')} ${g(email ? `· ${email}` : '')}`);
99
+ console.log(` ${d('─────────────────────────────')}`);
100
+
101
+ if (profile.artifact_count === 0) {
102
+ console.log(` ${g('no artifacts yet — run: phewsh style --ingest <file>')}`);
103
+ return;
104
+ }
105
+
106
+ console.log(` ${g('sessions ')}${profile.artifact_count}`);
107
+
108
+ if (profile.tempo_range) {
109
+ const [lo, hi] = profile.tempo_range;
110
+ const label = lo === hi ? `${lo} BPM` : `${Math.round(lo)}–${Math.round(hi)} BPM`;
111
+ console.log(` ${g('tempo ')}${label}`);
112
+ }
113
+
114
+ if (profile.dominant_keys?.length) {
115
+ console.log(` ${g('keys ')}${profile.dominant_keys.join(', ')}`);
116
+ }
117
+
118
+ if (profile.vibe_signature?.length) {
119
+ console.log(` ${g('vibe ')}${profile.vibe_signature.join(' · ')}`);
120
+ }
121
+
122
+ if (profile.instrument_palette?.length) {
123
+ console.log(` ${g('instruments ')}${profile.instrument_palette.join(', ')}`);
124
+ }
125
+
126
+ if (profile.energy_avg !== null && profile.energy_avg !== undefined) {
127
+ const energyLabel = profile.energy_avg > 0.7 ? 'high' : profile.energy_avg > 0.4 ? 'mid' : 'soft';
128
+ console.log(` ${g('dynamics ')}${energyLabel}`);
129
+ }
130
+
131
+ console.log('');
132
+ }
133
+
134
+ // ── Sync artifact + features to Supabase
135
+ async function syncToCloud(config, artifact, features) {
136
+ if (!config?.supabaseAccessToken) return null;
137
+
138
+ const headers = {
139
+ 'Content-Type': 'application/json',
140
+ 'apikey': SUPABASE_ANON_KEY,
141
+ 'Authorization': `Bearer ${config.supabaseAccessToken}`,
142
+ 'Prefer': 'resolution=merge-duplicates,return=representation',
143
+ };
144
+
145
+ // Insert artifact
146
+ const artifactRes = await fetch(`${SUPABASE_URL}/rest/v1/styletree_artifacts`, {
147
+ method: 'POST',
148
+ headers,
149
+ body: JSON.stringify({ ...artifact, user_id: config.supabaseUserId }),
150
+ });
151
+ if (!artifactRes.ok) return null;
152
+ const [savedArtifact] = await artifactRes.json();
153
+
154
+ // Insert features
155
+ await fetch(`${SUPABASE_URL}/rest/v1/styletree_features`, {
156
+ method: 'POST',
157
+ headers,
158
+ body: JSON.stringify({ ...features, artifact_id: savedArtifact.id, user_id: config.supabaseUserId }),
159
+ });
160
+
161
+ // Trigger profile rebuild via RPC
162
+ await fetch(`${SUPABASE_URL}/rest/v1/rpc/rebuild_styletree_profile`, {
163
+ method: 'POST',
164
+ headers,
165
+ body: JSON.stringify({ p_user_id: config.supabaseUserId }),
166
+ });
167
+
168
+ return savedArtifact.id;
169
+ }
170
+
171
+ // ── Main
172
+ async function main() {
173
+ const args = process.argv.slice(3);
174
+ const config = loadConfig();
175
+
176
+ // --status
177
+ if (args.includes('--status') || args.length === 0) {
178
+ const entries = loadLocal();
179
+ const profile = buildLocalProfile(entries);
180
+ printProfile(profile, config?.email);
181
+ if (!config?.supabaseUserId) {
182
+ console.log(` ${g('tip: run phewsh login to sync your style to the cloud')}`);
183
+ console.log('');
184
+ }
185
+ return;
186
+ }
187
+
188
+ // --ingest <file>
189
+ if (args.includes('--ingest')) {
190
+ const fileIdx = args.indexOf('--ingest');
191
+ const filePath = args[fileIdx + 1];
192
+
193
+ if (!filePath) {
194
+ console.error(`\n Usage: phewsh style --ingest <file>\n`);
195
+ process.exit(1);
196
+ }
197
+
198
+ const absPath = path.resolve(filePath);
199
+ if (!fs.existsSync(absPath)) {
200
+ console.error(`\n File not found: ${absPath}\n`);
201
+ process.exit(1);
202
+ }
203
+
204
+ const fileInfo = extractBasicFileInfo(absPath);
205
+ const fileName = path.basename(absPath);
206
+
207
+ console.log('');
208
+ console.log(` ${b('😮\u200d💨 ingesting')} ${c(fileName)}`);
209
+ console.log(` ${g('medium: ' + fileInfo.medium + ' · size: ' + (fileInfo.file_size_bytes ? Math.round(fileInfo.file_size_bytes / 1024) + 'kb' : 'unknown'))}`);
210
+ console.log('');
211
+
212
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
213
+
214
+ const title = await ask(rl, ` ${g('title')} (or enter to use filename)\n > `);
215
+ const tempoInput = await ask(rl, ` ${g('tempo')} BPM (leave blank if unknown)\n > `);
216
+ const keyInput = await ask(rl, ` ${g('key')} (e.g. C minor, F# major — blank to skip)\n > `);
217
+ const vibeInput = await ask(rl, ` ${g('vibe')} (e.g. dark chill driving — space-separated)\n > `);
218
+ const instrumentInput = await ask(rl, ` ${g('instruments')} (e.g. piano bass drums — space-separated)\n > `);
219
+
220
+ rl.close();
221
+ console.log('');
222
+
223
+ const artifact = {
224
+ title: title || fileName,
225
+ medium: fileInfo.medium,
226
+ file_path: absPath,
227
+ file_size_bytes: fileInfo.file_size_bytes || null,
228
+ mime_type: fileInfo.mime_type || null,
229
+ sync_tier: 0,
230
+ };
231
+
232
+ const features = {
233
+ tempo_bpm: tempoInput ? parseFloat(tempoInput) : null,
234
+ key_signature: keyInput || null,
235
+ mode: keyInput?.toLowerCase().includes('minor') ? 'minor'
236
+ : keyInput?.toLowerCase().includes('major') ? 'major'
237
+ : 'unknown',
238
+ vibe: vibeInput ? vibeInput.split(/\s+/).filter(Boolean) : [],
239
+ instruments: instrumentInput ? instrumentInput.split(/\s+/).filter(Boolean) : [],
240
+ };
241
+
242
+ // Always save locally first
243
+ saveLocally(artifact, features);
244
+ console.log(` ${c('✓')} saved locally`);
245
+
246
+ // Sync to cloud if logged in
247
+ if (config?.supabaseAccessToken) {
248
+ process.stdout.write(` ${g('syncing to cloud...')}`);
249
+ try {
250
+ const id = await syncToCloud(config, artifact, features);
251
+ if (id) {
252
+ process.stdout.write(`\r ${c('✓')} synced to cloud\n`);
253
+ } else {
254
+ process.stdout.write(`\r ${g('⚠ cloud sync skipped (run phewsh login --refresh)')}\n`);
255
+ }
256
+ } catch {
257
+ process.stdout.write(`\r ${g('⚠ cloud sync failed — local copy saved')}\n`);
258
+ }
259
+ } else {
260
+ console.log(` ${g('tip: run phewsh login to enable cloud sync')}`);
261
+ }
262
+
263
+ // Print updated profile
264
+ const entries = loadLocal();
265
+ const profile = buildLocalProfile(entries);
266
+ printProfile(profile, config?.email);
267
+ return;
268
+ }
269
+
270
+ // --sync
271
+ if (args.includes('--sync')) {
272
+ if (!config?.supabaseAccessToken) {
273
+ console.error(`\n Not logged in. Run: phewsh login\n`);
274
+ process.exit(1);
275
+ }
276
+ const entries = loadLocal();
277
+ if (!entries.length) {
278
+ console.log(`\n Nothing to sync. Run: phewsh style --ingest <file>\n`);
279
+ return;
280
+ }
281
+ console.log(`\n Syncing ${entries.length} artifact(s) to cloud...\n`);
282
+ let synced = 0;
283
+ for (const { artifact, features } of entries) {
284
+ try {
285
+ const id = await syncToCloud(config, artifact, features);
286
+ if (id) synced++;
287
+ } catch { /* skip */ }
288
+ }
289
+ console.log(` ${c('✓')} ${synced}/${entries.length} synced\n`);
290
+ return;
291
+ }
292
+
293
+ // --link-intent: mark that style should influence intent generation
294
+ if (args.includes('--link-intent')) {
295
+ const intentDir = path.join(process.cwd(), '.intent');
296
+ if (!fs.existsSync(intentDir)) {
297
+ console.error(`\n No .intent/ found here. Run: phewsh intent --init\n`);
298
+ process.exit(1);
299
+ }
300
+ const entries = loadLocal();
301
+ const profile = buildLocalProfile(entries);
302
+ const linkPath = path.join(intentDir, 'style.json');
303
+ fs.writeFileSync(linkPath, JSON.stringify(profile, null, 2));
304
+ console.log(`\n ${c('✓')} style profile linked to .intent/style.json`);
305
+ console.log(` ${g('phewsh ai will now include your style context automatically')}\n`);
306
+ return;
307
+ }
308
+
309
+ console.error(`\n Unknown style command. Try:\n`);
310
+ console.error(` phewsh style --ingest <file> ingest a new artifact`);
311
+ console.error(` phewsh style --status view your style profile`);
312
+ console.error(` phewsh style --sync push to cloud`);
313
+ console.error(` phewsh style --link-intent link style to current project\n`);
314
+ process.exit(1);
315
+ }
316
+
317
+ main().catch(err => {
318
+ console.error('\n Error:', err.message);
319
+ process.exit(1);
320
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "phewsh",
3
- "version": "0.5.3",
3
+ "version": "0.5.4",
4
4
  "description": "Turn intent into action. Structure your thinking, execute your next step.",
5
5
  "bin": {
6
6
  "phewsh": "bin/phewsh.js"