@venturewild/workspace 0.5.0 → 0.5.2

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 (56) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +112 -112
  3. package/package.json +85 -85
  4. package/server/bin/wild-workspace.mjs +1096 -1096
  5. package/server/src/account.mjs +114 -114
  6. package/server/src/agent-login.mjs +146 -146
  7. package/server/src/agent-readiness.mjs +200 -200
  8. package/server/src/agent.mjs +468 -468
  9. package/server/src/bazaar/core.mjs +790 -730
  10. package/server/src/bazaar/index.mjs +88 -88
  11. package/server/src/bazaar/mcp-server.mjs +417 -417
  12. package/server/src/bazaar/mock-tickup.mjs +97 -97
  13. package/server/src/bazaar/preview-server.mjs +95 -95
  14. package/server/src/bazaar/seed-recipes/customer-feedback-form/know-how.md +23 -23
  15. package/server/src/bazaar/seed-recipes/customer-feedback-form/recipe.json +24 -24
  16. package/server/src/bazaar/seed-recipes/landing-page-launch/know-how.md +29 -29
  17. package/server/src/bazaar/seed-recipes/landing-page-launch/recipe.json +25 -25
  18. package/server/src/bazaar/seed-recipes/personal-portfolio/know-how.md +21 -21
  19. package/server/src/bazaar/seed-recipes/personal-portfolio/recipe.json +24 -24
  20. package/server/src/bazaar/seed-recipes/receipt-sorter/know-how.md +31 -31
  21. package/server/src/bazaar/seed-recipes/receipt-sorter/recipe.json +25 -25
  22. package/server/src/bazaar/seed-recipes/tickup-hr-matching/know-how.md +79 -79
  23. package/server/src/bazaar/seed-recipes/tickup-hr-matching/recipe.json +40 -40
  24. package/server/src/canvas/core.mjs +446 -446
  25. package/server/src/canvas/index.mjs +42 -42
  26. package/server/src/canvas/mcp-server.mjs +253 -253
  27. package/server/src/canvas-rails.mjs +108 -108
  28. package/server/src/config.mjs +404 -404
  29. package/server/src/daemon-bin.mjs +110 -110
  30. package/server/src/daemon-supervisor.mjs +285 -285
  31. package/server/src/doctor.mjs +375 -375
  32. package/server/src/inbox.mjs +86 -86
  33. package/server/src/index.mjs +3279 -3181
  34. package/server/src/listings-rails.mjs +126 -0
  35. package/server/src/logpaths.mjs +98 -98
  36. package/server/src/observability.mjs +45 -45
  37. package/server/src/operator.mjs +92 -92
  38. package/server/src/pairing.mjs +137 -137
  39. package/server/src/service.mjs +515 -515
  40. package/server/src/session-reporter.mjs +201 -201
  41. package/server/src/settings.mjs +145 -145
  42. package/server/src/share.mjs +182 -182
  43. package/server/src/skills.mjs +213 -213
  44. package/server/src/supervisor.mjs +647 -647
  45. package/server/src/support-consent.mjs +133 -133
  46. package/server/src/sync.mjs +248 -248
  47. package/server/src/transcript.mjs +121 -121
  48. package/server/src/turn-mcp.mjs +46 -46
  49. package/server/src/usage.mjs +405 -405
  50. package/server/src/workspace-registry.mjs +295 -295
  51. package/server/src/workspaces.mjs +145 -135
  52. package/web/dist/assets/index-BXq-Irj8.js +131 -0
  53. package/web/dist/assets/index-CzUrGoMW.css +32 -0
  54. package/web/dist/index.html +2 -2
  55. package/web/dist/assets/index-DWNJ55qg.css +0 -32
  56. package/web/dist/assets/index-YlSTL4Wv.js +0 -131
@@ -1,730 +1,790 @@
1
- // Bazaar core — the shelf, search/ranking, and the transaction ledger.
2
- //
3
- // Faithful to UX §3.7: a *network* of producers' recipes that a consumer's agent
4
- // reaches onto, picks by "which actually works" (measured outcomes), absorbs, and
5
- // builds — recording a three-way transaction (consumer got it · producer earns ·
6
- // platform recorded it).
7
- //
8
- // State lives ENTIRELY under ~/.wild-workspace/bazaar/ (an absolute path OUTSIDE
9
- // the user's repo — CLAUDE.md rule #1). One module, imported by BOTH the main
10
- // server and the spawned MCP server, so there is a single source of truth and no
11
- // HTTP/port handshake between processes:
12
- // - events.jsonl append-only event log (use · service-call · publish). Append
13
- // is multi-writer safe (the MCP process writes use/publish; the
14
- // main process's preview server writes service-call).
15
- // - listings.json user-published listings (the flip side). MCP writes, main reads.
16
- // - preview.json the current preview target {dir,recipeId}. MCP writes, main reads.
17
- //
18
- // Seed recipes (our product content — the shelf) ship in-repo under seed-recipes/.
19
-
20
- import fs from 'node:fs';
21
- import path from 'node:path';
22
- import os from 'node:os';
23
- import crypto from 'node:crypto';
24
- import { fileURLToPath } from 'node:url';
25
-
26
- import { normalizeTheme } from '../canvas/core.mjs';
27
-
28
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
29
- const SEED_DIR = path.join(__dirname, 'seed-recipes');
30
-
31
- // Seed THEMES — the first cross-user marketplace artifact (a theme is a hex-token
32
- // bundle: pure data, zero execution risk, and its own preview). These ship as a
33
- // small network of "producers" so the bazaar's Themes shelf is populated out of
34
- // the box; a user's own published theme lands beside them (listings.json).
35
- export const SEED_THEMES = [
36
- {
37
- id: 'theme-midnight-cyan', kind: 'theme', source: 'theme',
38
- title: 'Midnight Cyan', pitch: 'The venturewild.llc night look — deep navy, electric cyan.',
39
- summary: 'A focused dark workspace: near-black navy with a bright cyan accent and cool slate cards.',
40
- tags: ['dark', 'cyan', 'focus'],
41
- producer: { name: 'VentureWild', handle: 'venturewild', kind: 'vendor' },
42
- theme: { mode: 'dark', accent: '#22d3ee', tokens: { bg: '#0a0c10', surface: '#11141a', text: '#e8eaed', textMuted: '#8b95a3', border: '#1f242d', canvas1: '#0b1620', canvas2: '#0c1320', canvas3: '#0a0f14' } },
43
- outcomeScore: 0.92, outcomeStats: { builds: 0, working: 0 }, safetyBadge: 'verified',
44
- rating: { stars: 5, count: 24 }, reward: { model: 'one-time', unit: 'per apply', oneTimeValue: 1.5, perUseValue: 0 },
45
- },
46
- {
47
- id: 'theme-sunset', kind: 'theme', source: 'theme',
48
- title: 'Warm Sunset', pitch: 'Dusty plum to amber — warm, low-glare, easy at night.',
49
- summary: 'A cosy dark theme: plum background fading to amber, with a glowing orange accent.',
50
- tags: ['dark', 'warm', 'orange'],
51
- producer: { name: 'Lina', handle: 'lina', kind: 'maker' },
52
- theme: { mode: 'dark', accent: '#ff7a3c', tokens: { bg: '#1a1014', surface: '#2a1a1f', text: '#fbeee6', textMuted: '#c7a89a', border: '#43292f', canvas1: '#2d1620', canvas2: '#5a2a2c', canvas3: '#b85c2e' } },
53
- outcomeScore: 0.84, outcomeStats: { builds: 0, working: 0 }, safetyBadge: 'verified',
54
- rating: { stars: 4, count: 11 }, reward: { model: 'one-time', unit: 'per apply', oneTimeValue: 1.5, perUseValue: 0 },
55
- },
56
- {
57
- id: 'theme-forest', kind: 'theme', source: 'theme',
58
- title: 'Forest Light', pitch: 'Soft sage & cream — a calm, bright daytime desk.',
59
- summary: 'A gentle light theme: sage-green wallpaper, cream cards, a deep forest accent.',
60
- tags: ['light', 'green', 'calm'],
61
- producer: { name: 'Mateo', handle: 'mateo', kind: 'maker' },
62
- theme: { mode: 'light', accent: '#15803d', tokens: { bg: '#fbfdfb', surface: '#ffffff', text: '#1a2b22', textMuted: '#5c7064', border: '#dde9e0', canvas1: '#e3f3e7', canvas2: '#eaf4ec', canvas3: '#fbfdf6' } },
63
- outcomeScore: 0.79, outcomeStats: { builds: 0, working: 0 }, safetyBadge: 'verified',
64
- rating: { stars: 4, count: 8 }, reward: { model: 'one-time', unit: 'per apply', oneTimeValue: 1.5, perUseValue: 0 },
65
- },
66
- {
67
- id: 'theme-mono', kind: 'theme', source: 'theme',
68
- title: 'Mono Slate', pitch: 'Greyscale, no distractions — one quiet blue accent.',
69
- summary: 'A neutral light theme for heads-down work: warm greys, a single muted-blue accent.',
70
- tags: ['light', 'minimal', 'mono'],
71
- producer: { name: 'Priya', handle: 'priya', kind: 'maker' },
72
- theme: { mode: 'light', accent: '#475569', tokens: { bg: '#fafafa', surface: '#ffffff', text: '#1e2530', textMuted: '#6b7280', border: '#e6e8ec', canvas1: '#eef0f3', canvas2: '#f3f4f6', canvas3: '#fafafa' } },
73
- outcomeScore: 0.74, outcomeStats: { builds: 0, working: 0 }, safetyBadge: 'verified',
74
- rating: { stars: 4, count: 6 }, reward: { model: 'one-time', unit: 'per apply', oneTimeValue: 1.5, perUseValue: 0 },
75
- },
76
- ];
77
-
78
- // ~/.wild-workspace/bazaar — mirrors logpaths.globalDir() but kept dependency-free
79
- // here so the MCP child can import this module standalone.
80
- export function defaultBazaarDir(env = process.env) {
81
- const base = env.WILD_WORKSPACE_GLOBAL_DIR || path.join(os.homedir(), '.wild-workspace');
82
- return path.join(base, 'bazaar');
83
- }
84
-
85
- function rid() {
86
- return crypto.randomUUID().slice(0, 12);
87
- }
88
-
89
- function readJsonSafe(file, fallback) {
90
- try {
91
- return JSON.parse(fs.readFileSync(file, 'utf8'));
92
- } catch {
93
- return fallback;
94
- }
95
- }
96
-
97
- function writeJsonAtomic(file, value) {
98
- const tmp = `${file}.${process.pid}.tmp`;
99
- fs.writeFileSync(tmp, JSON.stringify(value, null, 2));
100
- fs.renameSync(tmp, file); // Node rename replaces the destination on all platforms
101
- }
102
-
103
- // --- recipe loading -------------------------------------------------------
104
-
105
- function loadSeedRecipes(seedDir = SEED_DIR) {
106
- let entries = [];
107
- try {
108
- entries = fs.readdirSync(seedDir, { withFileTypes: true }).filter((e) => e.isDirectory());
109
- } catch {
110
- return [];
111
- }
112
- const recipes = [];
113
- for (const e of entries) {
114
- const dir = path.join(seedDir, e.name);
115
- const meta = readJsonSafe(path.join(dir, 'recipe.json'), null);
116
- if (!meta || !meta.id) continue;
117
- let knowHow = '';
118
- try {
119
- knowHow = fs.readFileSync(path.join(dir, 'know-how.md'), 'utf8');
120
- } catch {
121
- /* a recipe with no know-how file is still listable */
122
- }
123
- recipes.push({ ...meta, knowHow, source: 'seed' });
124
- }
125
- return recipes;
126
- }
127
-
128
- // --- search / ranking -----------------------------------------------------
129
- // The agent's pick signal is "which recipe actually works" (outcomeScore), NOT
130
- // marketing or stars (§3.7). Tag relevance gates the candidates; outcomeScore
131
- // breaks ties and floats proven recipes to the top of the shelf.
132
-
133
- function normalize(s) {
134
- return String(s || '')
135
- .toLowerCase()
136
- .replace(/[^a-z0-9]+/g, ' ')
137
- .trim();
138
- }
139
-
140
- function stem(word) {
141
- // ultra-light: drop a trailing plural 's' so "candidates" matches "candidate"
142
- return word.length > 3 && word.endsWith('s') ? word.slice(0, -1) : word;
143
- }
144
-
145
- export function scoreRecipe(recipe, need) {
146
- const needNorm = ` ${normalize(need)} `;
147
- const needWords = new Set(needNorm.trim().split(' ').filter(Boolean).map(stem));
148
- let score = 0;
149
- const matched = [];
150
- for (const tag of recipe.tags || []) {
151
- const tagNorm = normalize(tag);
152
- if (!tagNorm) continue;
153
- if (tagNorm.includes(' ')) {
154
- // multi-word tag: a phrase hit is a strong signal
155
- if (needNorm.includes(` ${tagNorm} `) || needNorm.includes(tagNorm)) {
156
- score += 3;
157
- matched.push(tag);
158
- }
159
- } else if (needWords.has(stem(tagNorm))) {
160
- score += 1;
161
- matched.push(tag);
162
- }
163
- }
164
- return { score, matched };
165
- }
166
-
167
- // --- Class-B auto-scan (B2) ------------------------------------------------
168
- // A conservative, pattern-based check that a published recipe carries no baked-in
169
- // secrets and no obviously destructive / remote-exec commands. It gates the FAST
170
- // lane (Class B self-attest), not a full audit — Class C/D get human review. High-
171
- // confidence patterns only, so a clean recipe is rarely false-flagged. Never throws.
172
- const UNSAFE_PATTERNS = [
173
- { kind: 'secret', note: 'private key', re: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
174
- { kind: 'secret', note: 'AWS access key', re: /\bAKIA[0-9A-Z]{16}\b/ },
175
- { kind: 'secret', note: 'API secret key', re: /\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\b/ },
176
- { kind: 'secret', note: 'GitHub token', re: /\bgh[pousr]_[A-Za-z0-9]{20,}\b/ },
177
- { kind: 'secret', note: 'hardcoded credential', re: /(?:api[_-]?key|secret|password|passwd|access[_-]?token)\s*[:=]\s*['"][^'"\s]{12,}['"]/i },
178
- { kind: 'destructive', note: 'recursive delete of a root/home path', re: /\brm\s+-[a-z]*r[a-z]*f?\s+[~/]/ },
179
- { kind: 'destructive', note: 'fork bomb', re: /:\(\)\s*\{\s*:\s*\|\s*:&\s*\}\s*;\s*:/ },
180
- { kind: 'exfiltrate', note: 'pipe a remote script straight into a shell', re: /\b(?:curl|wget)\b[^\n|]*\|\s*(?:sudo\s+)?(?:ba)?sh\b/i },
181
- ];
182
- export function scanForUnsafe(text) {
183
- const s = String(text || '');
184
- const findings = [];
185
- for (const p of UNSAFE_PATTERNS) {
186
- if (p.re.test(s)) findings.push({ kind: p.kind, note: p.note });
187
- }
188
- return { clean: findings.length === 0, findings };
189
- }
190
-
191
- // --- the bazaar instance --------------------------------------------------
192
-
193
- // Outcome score = a Bayesian-smoothed build success rate (B1). The recipe's
194
- // declared outcomeScore is the PRIOR mean; this many pseudo-builds give it weight,
195
- // so a brand-new listing or a thin sample isn't whipsawed by one result, while a
196
- // recipe with real volume converges on its true rate.
197
- const OUTCOME_PRIOR_K = 4;
198
-
199
- export function createBazaar({ baseDir, seedDir = SEED_DIR } = {}) {
200
- const dir = baseDir || defaultBazaarDir();
201
- const eventsFile = path.join(dir, 'events.jsonl');
202
- const listingsFile = path.join(dir, 'listings.json');
203
- const previewFile = path.join(dir, 'preview.json');
204
- // Self-seed drafts (cold-start, Producer #1): recipes the agent EXTRACTED from
205
- // the user's existing work, staged here for REVIEW. Nothing reaches the shelf
206
- // until the user approves a draft (publishDraft). The safety control is that a
207
- // draft holds only generalized know-how never client files/names/secrets.
208
- const draftsFile = path.join(dir, 'drafts.json');
209
-
210
- function ensureDir() {
211
- try {
212
- fs.mkdirSync(dir, { recursive: true });
213
- } catch {
214
- /* read-only fs degrades to no persistence */
215
- }
216
- }
217
-
218
- // --- live outcome telemetry (B1) ----------------------------------------
219
- // Real build-result events (recorded by record_build_result after a build lands
220
- // or fails) are the signal behind outcomeScore. Cached on the events file's
221
- // size+mtime so it stays correct even when the MCP child process appends.
222
- let _outcomeCache = null;
223
- let _outcomeCacheSig = null;
224
- function liveOutcomes() {
225
- let sig = '0';
226
- try { const st = fs.statSync(eventsFile); sig = `${st.size}:${st.mtimeMs}`; } catch { /* no file yet */ }
227
- if (_outcomeCache && _outcomeCacheSig === sig) return _outcomeCache;
228
- const map = {};
229
- for (const e of events()) {
230
- if (e.type !== 'build-result' || !e.recipeId) continue;
231
- const m = (map[e.recipeId] ??= { builds: 0, working: 0 });
232
- m.builds += 1;
233
- if (e.success) m.working += 1;
234
- }
235
- _outcomeCache = map;
236
- _outcomeCacheSig = sig;
237
- return map;
238
- }
239
- // The recipe's accumulated { builds, working }: its seed baseline (missing →
240
- // {0,0}, the migration for old listings) plus live build-results.
241
- function liveStats(r) {
242
- const base = r.outcomeStats && typeof r.outcomeStats === 'object' ? r.outcomeStats : { builds: 0, working: 0 };
243
- const live = liveOutcomes()[r.id] || { builds: 0, working: 0 };
244
- return { builds: (base.builds || 0) + live.builds, working: (base.working || 0) + live.working };
245
- }
246
- // Bayesian-smoothed success rate. Prior mean = the declared outcomeScore (0.7 for
247
- // an undeclared listing); with zero live results it equals the declared score, so
248
- // seed rankings stay stable until real outcomes accumulate.
249
- function liveScore(r) {
250
- const prior = typeof r.outcomeScore === 'number' ? r.outcomeScore : 0.7;
251
- const { builds, working } = liveStats(r);
252
- const score = (working + OUTCOME_PRIOR_K * prior) / (builds + OUTCOME_PRIOR_K);
253
- return Math.max(0, Math.min(1, Math.round(score * 1000) / 1000));
254
- }
255
- // The agent reports whether a build that used a recipe actually WORKED (B1) — the
256
- // real signal behind the outcome score. Appended to events.jsonl; liveScore reads
257
- // it on the next card render. Unknown recipe → a no-op error (keeps events clean).
258
- function recordBuildResult({ recipeId, success, reason = '' } = {}) {
259
- const r = getRecipe(recipeId);
260
- if (!r) return { ok: false, error: `no recipe "${recipeId}" on the shelf` };
261
- const evt = appendEvent({
262
- type: 'build-result',
263
- recipeId: r.id,
264
- title: r.title,
265
- success: !!success,
266
- reason: String(reason || '').slice(0, 200),
267
- });
268
- return { ok: true, event: evt, outcome: { ...liveStats(r), score: liveScore(r) } };
269
- }
270
-
271
- // --- trust & provenance (B2) --------------------------------------------
272
- // The §3 schema (docs/shelf-trust-provenance-design.md). riskClass is the spine:
273
- // A data (themes) · B local build-recipe · C connected-service · D executable-skill.
274
- // provenanceFor() also MIGRATES old records on read — a listing with the legacy
275
- // safetyBadge but no riskClass gets defaults by kind, and a free-text sourceNote
276
- // becomes a builtFrom[] entry so an existing listings.json never breaks.
277
- function riskClassOf(r) {
278
- if (['A', 'B', 'C', 'D'].includes(r.riskClass)) return r.riskClass;
279
- if (r.kind === 'theme') return 'A';
280
- if (r.service || r.hasService) return 'C';
281
- return 'B';
282
- }
283
- function normalizeBuiltFrom(r) {
284
- if (Array.isArray(r.builtFrom)) {
285
- return r.builtFrom.filter(Boolean).map((b) => ({ type: b.type || 'recipe', id: b.id ?? null, note: b.note || b.title || '' }));
286
- }
287
- if (r.builtFrom && (r.builtFrom.id || r.builtFrom.title)) {
288
- // the C2 remix pointer { id, title } → the schema's array form
289
- return [{ type: r.kind === 'theme' ? 'theme' : 'recipe', id: r.builtFrom.id ?? null, note: r.builtFrom.title || '' }];
290
- }
291
- if (r.sourceNote) return [{ type: 'scratch', id: null, note: String(r.sourceNote) }]; // migrate free-text
292
- return [];
293
- }
294
- function provenanceFor(r) {
295
- const riskClass = riskClassOf(r);
296
- const trusted = r.source === 'seed' || r.source === 'theme'; // VW-shipped pre-vetted
297
- const dataTouched = r.dataTouched || (riskClass === 'C'
298
- ? { egress: [], scope: 'external', paid: { model: r.reward?.perUseValue ? 'per-use' : 'none', note: '' } }
299
- : { egress: [], scope: 'in-workspace', paid: { model: 'none', note: '' } });
300
- const attestation = r.attestation || {
301
- privacy: riskClass === 'C' ? 'not-attested' : 'n/a',
302
- attestedBy: null,
303
- at: null,
304
- };
305
- const defaultVerdict =
306
- riskClass === 'A' ? 'auto'
307
- : riskClass === 'B' ? (trusted ? 'scanned' : 'unscanned')
308
- : riskClass === 'C' ? (trusted ? 'reviewed' : 'unvetted')
309
- : 'unvetted'; // D never auto-clears (enforcement deferred → own/teammate only)
310
- const vetting = r.vetting || { verdict: defaultVerdict, stakes: 'ordinary', signature: null, capabilities: null, findings: [] };
311
- return { riskClass, builtFrom: normalizeBuiltFrom(r), dataTouched, attestation, vetting };
312
- }
313
-
314
- function shelf() {
315
- const seed = loadSeedRecipes(seedDir);
316
- const listings = readJsonSafe(listingsFile, []);
317
- return [...seed, ...SEED_THEMES, ...(Array.isArray(listings) ? listings : [])];
318
- }
319
-
320
- function getRecipe(id) {
321
- return shelf().find((r) => r.id === id) || null;
322
- }
323
-
324
- // Public, agent-facing card for a recipe (no know-how dump until opened).
325
- function card(r, extra = {}) {
326
- return {
327
- id: r.id,
328
- kind: r.kind || 'recipe',
329
- title: r.title,
330
- pitch: r.pitch,
331
- producer: r.producer,
332
- summary: r.summary,
333
- vendorDescription: r.vendorDescription,
334
- outcomeScore: liveScore(r),
335
- outcomeStats: liveStats(r),
336
- safetyBadge: r.safetyBadge, // legacy field kept for back-compat; web derives from `vetting`
337
- ...provenanceFor(r), // B2: riskClass · builtFrom · dataTouched · attestation · vetting
338
- rating: r.rating,
339
- reward: r.reward,
340
- hasService: Boolean(r.service),
341
- buildDir: r.buildDir,
342
- // A theme card carries its own bundle — it IS its own preview (just hex), so
343
- // the storefront can render a live swatch and apply it without a fetch.
344
- ...(r.kind === 'theme' && r.theme ? { theme: r.theme } : {}),
345
- ...extra,
346
- };
347
- }
348
-
349
- function search(need, { limit = 4 } = {}) {
350
- const ranked = shelf()
351
- .map((r) => {
352
- const { score, matched } = scoreRecipe(r, need);
353
- return { r, score, matched };
354
- })
355
- .filter((x) => x.score > 0)
356
- .sort((a, b) => b.score - a.score || liveScore(b.r) - liveScore(a.r))
357
- .slice(0, limit);
358
- return ranked.map((x) => card(x.r, { relevance: x.score, matched: x.matched }));
359
- }
360
-
361
- function appendEvent(evt) {
362
- ensureDir();
363
- const enriched = { id: rid(), ts: Date.now(), ...evt };
364
- try {
365
- fs.appendFileSync(eventsFile, `${JSON.stringify(enriched)}\n`);
366
- } catch {
367
- /* persistence best-effort */
368
- }
369
- return enriched;
370
- }
371
-
372
- function events() {
373
- let raw = '';
374
- try {
375
- raw = fs.readFileSync(eventsFile, 'utf8');
376
- } catch {
377
- return [];
378
- }
379
- return raw
380
- .split('\n')
381
- .map((l) => l.trim())
382
- .filter(Boolean)
383
- .map((l) => {
384
- try {
385
- return JSON.parse(l);
386
- } catch {
387
- return null;
388
- }
389
- })
390
- .filter(Boolean);
391
- }
392
-
393
- // A consumer's agent absorbed a recipe and built it: the three-way moment.
394
- function recordUse({ recipeId, summary, consumer = 'you' }) {
395
- const r = getRecipe(recipeId);
396
- if (!r) return { ok: false, error: `no recipe "${recipeId}" on the shelf` };
397
- const recurring = r.reward?.perUseValue || 0;
398
- // A recurring SERVICE recipe (tool/API) earns per-use, NOT a build fee — so the
399
- // build itself credits 0, and the meter ticks up per match. This keeps the live
400
- // meter ("$X · N matches") reconciled with the "earns per match, ongoing" story.
401
- // Pure know-how recipes earn their one-time build-time slice here.
402
- const oneTime = r.service ? 0 : (r.reward?.oneTimeValue || 0);
403
- const evt = appendEvent({
404
- type: 'use',
405
- recipeId: r.id,
406
- title: r.title,
407
- producer: r.producer,
408
- consumer,
409
- summary: summary || r.title,
410
- value: oneTime,
411
- unit: r.service ? 'recurring-start' : 'one-time',
412
- });
413
- const threeWay = {
414
- you: `You got: ${summary || r.title}`,
415
- producer: r.service
416
- ? `${r.producer?.name || 'The producer'} just gained a customer — your site uses their matching on every candidate, ongoing.`
417
- : `${r.producer?.name || 'The producer'} earns a one-time share for the know-how you built on.`,
418
- platform: 'VentureWild matched you to a proven recipe — and recorded it.',
419
- };
420
- return {
421
- ok: true,
422
- event: evt,
423
- recipe: card(r),
424
- threeWay,
425
- credit: { producer: r.producer, oneTime, recurring, unit: r.reward?.unit },
426
- service: r.service || null,
427
- };
428
- }
429
-
430
- // TickUp's matching service ran once — recurring credit to the producer.
431
- function recordServiceCall({ recipeId, serviceId, matches = 0 }) {
432
- const r = getRecipe(recipeId) || shelf().find((x) => x.service?.id === serviceId);
433
- const per = r?.reward?.perUseValue || 0;
434
- return appendEvent({
435
- type: 'service-call',
436
- recipeId: r?.id || recipeId || null,
437
- serviceId: serviceId || r?.service?.id || null,
438
- producer: r?.producer || null,
439
- matches,
440
- value: per,
441
- unit: 'per-use',
442
- });
443
- }
444
-
445
- // The flip side (§3.7): the user's agent packaged a build into a listing.
446
- function publishListing({ id, title, pitch, summary, tags = [], knowHow = '', producer, buildDir, builtFrom = null }) {
447
- ensureDir();
448
- const listings = readJsonSafe(listingsFile, []);
449
- const arr = Array.isArray(listings) ? listings : [];
450
- const slug =
451
- id ||
452
- `${normalize(title).split(' ').slice(0, 4).join('-') || 'listing'}-${rid().slice(0, 4)}`;
453
- // Class-B vetting (B2): a recipe is local build know-how → self-attest + an
454
- // automated scan. A clean scan earns the 'scanned' verdict; a hit is recorded
455
- // (verdict 'flagged' + findings) so the badge tells the truth — publishing isn't
456
- // blocked here (single-user/local shelf), but the listing carries its verdict.
457
- const scan = scanForUnsafe(knowHow);
458
- const listing = {
459
- id: slug,
460
- title: title || 'Untitled',
461
- pitch: pitch || '',
462
- summary: summary || pitch || '',
463
- vendorDescription: summary || pitch || '',
464
- producer: producer || { name: 'You', handle: 'you', kind: 'maker' },
465
- tags,
466
- knowHow,
467
- buildDir: buildDir || null,
468
- outcomeScore: 0.7, // new listing: a starting, unproven score (earns its place by working)
469
- outcomeStats: { builds: 0, working: 0 },
470
- safetyBadge: 'new', // legacy field; the real signal is `vetting` below
471
- riskClass: 'B',
472
- ...(builtFrom && builtFrom.id ? { builtFrom: { id: String(builtFrom.id), title: String(builtFrom.title || '') } } : {}),
473
- dataTouched: { egress: [], scope: 'in-workspace', paid: { model: 'none', note: '' } },
474
- attestation: { privacy: 'n/a', attestedBy: (producer || {}).handle || 'you', at: new Date().toISOString() },
475
- vetting: {
476
- verdict: scan.clean ? 'scanned' : 'flagged',
477
- stakes: 'ordinary',
478
- signature: null,
479
- capabilities: null,
480
- findings: scan.findings,
481
- },
482
- rating: { stars: 0, count: 0 },
483
- reward: { model: 'one-time', unit: 'per build', perUseValue: 0, oneTimeValue: 5.0 },
484
- source: 'listing',
485
- createdAt: Date.now(),
486
- };
487
- // de-dupe by id (re-publish overwrites)
488
- const next = arr.filter((l) => l.id !== listing.id);
489
- next.push(listing);
490
- writeJsonAtomic(listingsFile, next);
491
- appendEvent({
492
- type: 'publish',
493
- recipeId: listing.id,
494
- title: listing.title,
495
- producer: listing.producer,
496
- });
497
- return {
498
- ok: true,
499
- listing: card(listing),
500
- earning: {
501
- model: listing.reward.model,
502
- oneTimeValue: listing.reward.oneTimeValue,
503
- note: 'Represented earnings you earn each time someone builds on this. (Money is for later.)',
504
- },
505
- };
506
- }
507
-
508
- // --- themes on the shelf (the safest cross-user artifact) -----------------
509
-
510
- // Publish a theme as a listing. The payload is a hex-token bundle (validated by
511
- // normalizeTheme same security boundary as set_theme: data, never CSS). It
512
- // lands in listings.json with kind:'theme' and shows on the Themes shelf.
513
- function publishTheme({ title, pitch, summary, tags = [], producer, theme, builtFrom = null } = {}) {
514
- ensureDir();
515
- const bundle = normalizeTheme(theme || {});
516
- const listings = readJsonSafe(listingsFile, []);
517
- const arr = Array.isArray(listings) ? listings : [];
518
- const slug = `theme-${normalize(title).split(' ').slice(0, 3).join('-') || 'custom'}-${rid().slice(0, 4)}`;
519
- // A remix records what it was tweaked from (the source theme on the shelf) so the
520
- // network shows lineage "built on each other's work", not a flat catalogue.
521
- const provenance =
522
- builtFrom && builtFrom.id
523
- ? { id: String(builtFrom.id), title: String(builtFrom.title || '') }
524
- : null;
525
- const listing = {
526
- id: slug,
527
- kind: 'theme',
528
- source: 'theme',
529
- title: title || bundle.name || 'Custom theme',
530
- pitch: pitch || '',
531
- summary: summary || pitch || `A ${bundle.mode} theme.`,
532
- vendorDescription: summary || pitch || '',
533
- producer: producer || { name: 'You', handle: 'you', kind: 'maker' },
534
- tags,
535
- theme: bundle,
536
- ...(provenance ? { builtFrom: provenance } : {}),
537
- outcomeScore: 0.7,
538
- outcomeStats: { builds: 0, working: 0 },
539
- safetyBadge: 'new',
540
- rating: { stars: 0, count: 0 },
541
- reward: { model: 'one-time', unit: 'per apply', oneTimeValue: 1.5, perUseValue: 0 },
542
- createdAt: Date.now(),
543
- };
544
- const next = arr.filter((l) => l.id !== listing.id);
545
- next.push(listing);
546
- writeJsonAtomic(listingsFile, next);
547
- appendEvent({ type: 'publish', recipeId: listing.id, title: listing.title, producer: listing.producer, ...(provenance ? { builtFrom: provenance } : {}) });
548
- return {
549
- ok: true,
550
- listing: card(listing),
551
- earning: { model: 'one-time', oneTimeValue: listing.reward.oneTimeValue, note: 'You earn each time someone applies it. (Money is for later.)' },
552
- };
553
- }
554
-
555
- // A consumer applied a theme from the shelf: record the three-way moment (they
556
- // got the look · the producer earns · platform recorded it) and hand back the
557
- // validated bundle for the browser to apply.
558
- function recordThemeApply({ themeId, consumer = 'you' } = {}) {
559
- const r = getRecipe(themeId);
560
- if (!r || r.kind !== 'theme') return { ok: false, error: `no theme "${themeId}" on the shelf` };
561
- const oneTime = r.reward?.oneTimeValue || 0;
562
- const evt = appendEvent({
563
- type: 'use',
564
- recipeId: r.id,
565
- title: r.title,
566
- producer: r.producer,
567
- consumer,
568
- summary: `Applied the "${r.title}" theme`,
569
- value: oneTime,
570
- unit: 'one-time',
571
- });
572
- return {
573
- ok: true,
574
- event: evt,
575
- theme: normalizeTheme(r.theme || {}),
576
- title: r.title,
577
- threeWay: {
578
- you: `Your workspace now wears "${r.title}".`,
579
- producer: `${r.producer?.name || 'The producer'} earns a one-time share for the look you adopted.`,
580
- platform: 'VentureWild matched you to a proven theme — and recorded it.',
581
- },
582
- credit: { producer: r.producer, oneTime, unit: r.reward?.unit },
583
- };
584
- }
585
-
586
- // --- self-seed drafts (review-gated) --------------------------------------
587
-
588
- function listDrafts() {
589
- const d = readJsonSafe(draftsFile, []);
590
- return Array.isArray(d) ? d : [];
591
- }
592
-
593
- function getDraft(id) {
594
- return listDrafts().find((d) => d.id === id) || null;
595
- }
596
-
597
- // Stage a recipe the agent extracted from the user's existing work does NOT
598
- // publish. `sourceNote` records (for the user's review) what it was generalized
599
- // from. Returns a review-shaped object the UI renders for approval.
600
- function stageDraft({ title, pitch, summary, tags = [], knowHow = '', sourceNote = '' }) {
601
- ensureDir();
602
- const drafts = listDrafts();
603
- const draft = {
604
- id: `draft-${rid()}`,
605
- title: title || 'Untitled',
606
- pitch: pitch || '',
607
- summary: summary || pitch || '',
608
- tags: Array.isArray(tags) ? tags : [],
609
- knowHow: knowHow || '',
610
- sourceNote: sourceNote || '',
611
- createdAt: Date.now(),
612
- };
613
- drafts.push(draft);
614
- writeJsonAtomic(draftsFile, drafts);
615
- return draft;
616
- }
617
-
618
- function discardDraft(id) {
619
- const drafts = listDrafts();
620
- const next = drafts.filter((d) => d.id !== id);
621
- writeJsonAtomic(draftsFile, next);
622
- return { ok: next.length !== drafts.length };
623
- }
624
-
625
- // Promote a reviewed draft onto the shelf — publishes EXACTLY what was reviewed
626
- // (you publish what you saw), then removes it from the draft queue.
627
- function publishDraft(id, { producer } = {}) {
628
- const draft = getDraft(id);
629
- if (!draft) return { ok: false, error: `no draft "${id}"` };
630
- const res = publishListing({
631
- title: draft.title,
632
- pitch: draft.pitch,
633
- summary: draft.summary,
634
- tags: draft.tags,
635
- knowHow: draft.knowHow,
636
- producer: producer || { name: 'You', handle: 'you', kind: 'maker' },
637
- });
638
- discardDraft(id);
639
- return res;
640
- }
641
-
642
- function setPreview({ dir: buildDir, recipeId, port = 4000 }) {
643
- ensureDir();
644
- const payload = { dir: buildDir, recipeId: recipeId || null, port, ts: Date.now() };
645
- writeJsonAtomic(previewFile, payload);
646
- return payload;
647
- }
648
-
649
- function getPreview() {
650
- return readJsonSafe(previewFile, null);
651
- }
652
-
653
- // Aggregate everything the UI needs: transactions, per-producer earnings,
654
- // per-service usage meters, and the user's own listings.
655
- function computeState() {
656
- const evs = events();
657
- const earnings = {}; // handle -> { name, total, uses, serviceCalls, matches }
658
- const meters = {}; // serviceId -> { calls, matches, value, producer }
659
- const transactions = [];
660
- for (const e of evs) {
661
- const h = e.producer?.handle || 'unknown';
662
- const bucket = (earnings[h] ??= {
663
- name: e.producer?.name || h,
664
- handle: h,
665
- total: 0,
666
- uses: 0,
667
- serviceCalls: 0,
668
- matches: 0,
669
- });
670
- if (e.type === 'use') {
671
- bucket.total += e.value || 0;
672
- bucket.uses += 1;
673
- transactions.push(e);
674
- } else if (e.type === 'service-call') {
675
- bucket.total += e.value || 0;
676
- bucket.serviceCalls += 1;
677
- bucket.matches += e.matches || 0;
678
- const sid = e.serviceId || 'service';
679
- const m = (meters[sid] ??= { calls: 0, matches: 0, value: 0, producer: e.producer || null });
680
- m.calls += 1;
681
- m.matches += e.matches || 0;
682
- m.value += e.value || 0;
683
- } else if (e.type === 'publish') {
684
- transactions.push(e);
685
- }
686
- }
687
- return {
688
- transactions: transactions.slice(-50),
689
- earnings: Object.values(earnings).sort((a, b) => b.total - a.total),
690
- meters,
691
- listings: (readJsonSafe(listingsFile, []) || []).map((l) => card(l)),
692
- totals: {
693
- events: evs.length,
694
- creditPaid: Object.values(earnings).reduce((s, b) => s + b.total, 0),
695
- },
696
- };
697
- }
698
-
699
- return {
700
- dir,
701
- eventsFile,
702
- listingsFile,
703
- previewFile,
704
- draftsFile,
705
- shelf,
706
- getRecipe,
707
- card,
708
- search,
709
- recordUse,
710
- recordBuildResult,
711
- recordServiceCall,
712
- publishListing,
713
- publishTheme,
714
- recordThemeApply,
715
- listDrafts,
716
- getDraft,
717
- stageDraft,
718
- discardDraft,
719
- publishDraft,
720
- setPreview,
721
- getPreview,
722
- computeState,
723
- events,
724
- };
725
- }
726
-
727
- function money(n) {
728
- const v = Number(n) || 0;
729
- return `$${v.toFixed(2)}`;
730
- }
1
+ // Bazaar core — the shelf, search/ranking, and the transaction ledger.
2
+ //
3
+ // Faithful to UX §3.7: a *network* of producers' recipes that a consumer's agent
4
+ // reaches onto, picks by "which actually works" (measured outcomes), absorbs, and
5
+ // builds — recording a three-way transaction (consumer got it · producer earns ·
6
+ // platform recorded it).
7
+ //
8
+ // State lives ENTIRELY under ~/.wild-workspace/bazaar/ (an absolute path OUTSIDE
9
+ // the user's repo — CLAUDE.md rule #1). One module, imported by BOTH the main
10
+ // server and the spawned MCP server, so there is a single source of truth and no
11
+ // HTTP/port handshake between processes:
12
+ // - events.jsonl append-only event log (use · service-call · publish). Append
13
+ // is multi-writer safe (the MCP process writes use/publish; the
14
+ // main process's preview server writes service-call).
15
+ // - listings.json user-published listings (the flip side). MCP writes, main reads.
16
+ // - preview.json the current preview target {dir,recipeId}. MCP writes, main reads.
17
+ //
18
+ // Seed recipes (our product content — the shelf) ship in-repo under seed-recipes/.
19
+
20
+ import fs from 'node:fs';
21
+ import path from 'node:path';
22
+ import os from 'node:os';
23
+ import crypto from 'node:crypto';
24
+ import { fileURLToPath } from 'node:url';
25
+
26
+ import { normalizeTheme } from '../canvas/core.mjs';
27
+
28
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
29
+ const SEED_DIR = path.join(__dirname, 'seed-recipes');
30
+
31
+ // Seed THEMES — the first cross-user marketplace artifact (a theme is a hex-token
32
+ // bundle: pure data, zero execution risk, and its own preview). These ship as a
33
+ // small network of "producers" so the bazaar's Themes shelf is populated out of
34
+ // the box; a user's own published theme lands beside them (listings.json).
35
+ export const SEED_THEMES = [
36
+ {
37
+ id: 'theme-midnight-cyan', kind: 'theme', source: 'theme',
38
+ title: 'Midnight Cyan', pitch: 'The venturewild.llc night look — deep navy, electric cyan.',
39
+ summary: 'A focused dark workspace: near-black navy with a bright cyan accent and cool slate cards.',
40
+ tags: ['dark', 'cyan', 'focus'],
41
+ producer: { name: 'VentureWild', handle: 'venturewild', kind: 'vendor' },
42
+ theme: { mode: 'dark', accent: '#22d3ee', tokens: { bg: '#0a0c10', surface: '#11141a', text: '#e8eaed', textMuted: '#8b95a3', border: '#1f242d', canvas1: '#0b1620', canvas2: '#0c1320', canvas3: '#0a0f14' } },
43
+ outcomeScore: 0.92, outcomeStats: { builds: 0, working: 0 }, safetyBadge: 'verified',
44
+ rating: { stars: 5, count: 24 }, reward: { model: 'one-time', unit: 'per apply', oneTimeValue: 1.5, perUseValue: 0 },
45
+ },
46
+ {
47
+ id: 'theme-sunset', kind: 'theme', source: 'theme',
48
+ title: 'Warm Sunset', pitch: 'Dusty plum to amber — warm, low-glare, easy at night.',
49
+ summary: 'A cosy dark theme: plum background fading to amber, with a glowing orange accent.',
50
+ tags: ['dark', 'warm', 'orange'],
51
+ producer: { name: 'Lina', handle: 'lina', kind: 'maker' },
52
+ theme: { mode: 'dark', accent: '#ff7a3c', tokens: { bg: '#1a1014', surface: '#2a1a1f', text: '#fbeee6', textMuted: '#c7a89a', border: '#43292f', canvas1: '#2d1620', canvas2: '#5a2a2c', canvas3: '#b85c2e' } },
53
+ outcomeScore: 0.84, outcomeStats: { builds: 0, working: 0 }, safetyBadge: 'verified',
54
+ rating: { stars: 4, count: 11 }, reward: { model: 'one-time', unit: 'per apply', oneTimeValue: 1.5, perUseValue: 0 },
55
+ },
56
+ {
57
+ id: 'theme-forest', kind: 'theme', source: 'theme',
58
+ title: 'Forest Light', pitch: 'Soft sage & cream — a calm, bright daytime desk.',
59
+ summary: 'A gentle light theme: sage-green wallpaper, cream cards, a deep forest accent.',
60
+ tags: ['light', 'green', 'calm'],
61
+ producer: { name: 'Mateo', handle: 'mateo', kind: 'maker' },
62
+ theme: { mode: 'light', accent: '#15803d', tokens: { bg: '#fbfdfb', surface: '#ffffff', text: '#1a2b22', textMuted: '#5c7064', border: '#dde9e0', canvas1: '#e3f3e7', canvas2: '#eaf4ec', canvas3: '#fbfdf6' } },
63
+ outcomeScore: 0.79, outcomeStats: { builds: 0, working: 0 }, safetyBadge: 'verified',
64
+ rating: { stars: 4, count: 8 }, reward: { model: 'one-time', unit: 'per apply', oneTimeValue: 1.5, perUseValue: 0 },
65
+ },
66
+ {
67
+ id: 'theme-mono', kind: 'theme', source: 'theme',
68
+ title: 'Mono Slate', pitch: 'Greyscale, no distractions — one quiet blue accent.',
69
+ summary: 'A neutral light theme for heads-down work: warm greys, a single muted-blue accent.',
70
+ tags: ['light', 'minimal', 'mono'],
71
+ producer: { name: 'Priya', handle: 'priya', kind: 'maker' },
72
+ theme: { mode: 'light', accent: '#475569', tokens: { bg: '#fafafa', surface: '#ffffff', text: '#1e2530', textMuted: '#6b7280', border: '#e6e8ec', canvas1: '#eef0f3', canvas2: '#f3f4f6', canvas3: '#fafafa' } },
73
+ outcomeScore: 0.74, outcomeStats: { builds: 0, working: 0 }, safetyBadge: 'verified',
74
+ rating: { stars: 4, count: 6 }, reward: { model: 'one-time', unit: 'per apply', oneTimeValue: 1.5, perUseValue: 0 },
75
+ },
76
+ ];
77
+
78
+ // ~/.wild-workspace/bazaar — mirrors logpaths.globalDir() but kept dependency-free
79
+ // here so the MCP child can import this module standalone.
80
+ export function defaultBazaarDir(env = process.env) {
81
+ const base = env.WILD_WORKSPACE_GLOBAL_DIR || path.join(os.homedir(), '.wild-workspace');
82
+ return path.join(base, 'bazaar');
83
+ }
84
+
85
+ function rid() {
86
+ return crypto.randomUUID().slice(0, 12);
87
+ }
88
+
89
+ function readJsonSafe(file, fallback) {
90
+ try {
91
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
92
+ } catch {
93
+ return fallback;
94
+ }
95
+ }
96
+
97
+ function writeJsonAtomic(file, value) {
98
+ const tmp = `${file}.${process.pid}.tmp`;
99
+ fs.writeFileSync(tmp, JSON.stringify(value, null, 2));
100
+ fs.renameSync(tmp, file); // Node rename replaces the destination on all platforms
101
+ }
102
+
103
+ // --- recipe loading -------------------------------------------------------
104
+
105
+ function loadSeedRecipes(seedDir = SEED_DIR) {
106
+ let entries = [];
107
+ try {
108
+ entries = fs.readdirSync(seedDir, { withFileTypes: true }).filter((e) => e.isDirectory());
109
+ } catch {
110
+ return [];
111
+ }
112
+ const recipes = [];
113
+ for (const e of entries) {
114
+ const dir = path.join(seedDir, e.name);
115
+ const meta = readJsonSafe(path.join(dir, 'recipe.json'), null);
116
+ if (!meta || !meta.id) continue;
117
+ let knowHow = '';
118
+ try {
119
+ knowHow = fs.readFileSync(path.join(dir, 'know-how.md'), 'utf8');
120
+ } catch {
121
+ /* a recipe with no know-how file is still listable */
122
+ }
123
+ recipes.push({ ...meta, knowHow, source: 'seed' });
124
+ }
125
+ return recipes;
126
+ }
127
+
128
+ // --- search / ranking -----------------------------------------------------
129
+ // The agent's pick signal is "which recipe actually works" (outcomeScore), NOT
130
+ // marketing or stars (§3.7). Tag relevance gates the candidates; outcomeScore
131
+ // breaks ties and floats proven recipes to the top of the shelf.
132
+
133
+ function normalize(s) {
134
+ return String(s || '')
135
+ .toLowerCase()
136
+ .replace(/[^a-z0-9]+/g, ' ')
137
+ .trim();
138
+ }
139
+
140
+ function stem(word) {
141
+ // ultra-light: drop a trailing plural 's' so "candidates" matches "candidate"
142
+ return word.length > 3 && word.endsWith('s') ? word.slice(0, -1) : word;
143
+ }
144
+
145
+ export function scoreRecipe(recipe, need) {
146
+ const needNorm = ` ${normalize(need)} `;
147
+ const needWords = new Set(needNorm.trim().split(' ').filter(Boolean).map(stem));
148
+ let score = 0;
149
+ const matched = [];
150
+ for (const tag of recipe.tags || []) {
151
+ const tagNorm = normalize(tag);
152
+ if (!tagNorm) continue;
153
+ if (tagNorm.includes(' ')) {
154
+ // multi-word tag: a phrase hit is a strong signal
155
+ if (needNorm.includes(` ${tagNorm} `) || needNorm.includes(tagNorm)) {
156
+ score += 3;
157
+ matched.push(tag);
158
+ }
159
+ } else if (needWords.has(stem(tagNorm))) {
160
+ score += 1;
161
+ matched.push(tag);
162
+ }
163
+ }
164
+ return { score, matched };
165
+ }
166
+
167
+ // --- Class-B auto-scan (B2) ------------------------------------------------
168
+ // A conservative, pattern-based check that a published recipe carries no baked-in
169
+ // secrets and no obviously destructive / remote-exec commands. It gates the FAST
170
+ // lane (Class B self-attest), not a full audit — Class C/D get human review. High-
171
+ // confidence patterns only, so a clean recipe is rarely false-flagged. Never throws.
172
+ const UNSAFE_PATTERNS = [
173
+ { kind: 'secret', note: 'private key', re: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
174
+ { kind: 'secret', note: 'AWS access key', re: /\bAKIA[0-9A-Z]{16}\b/ },
175
+ { kind: 'secret', note: 'API secret key', re: /\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\b/ },
176
+ { kind: 'secret', note: 'GitHub token', re: /\bgh[pousr]_[A-Za-z0-9]{20,}\b/ },
177
+ { kind: 'secret', note: 'hardcoded credential', re: /(?:api[_-]?key|secret|password|passwd|access[_-]?token)\s*[:=]\s*['"][^'"\s]{12,}['"]/i },
178
+ { kind: 'destructive', note: 'recursive delete of a root/home path', re: /\brm\s+-[a-z]*r[a-z]*f?\s+[~/]/ },
179
+ { kind: 'destructive', note: 'fork bomb', re: /:\(\)\s*\{\s*:\s*\|\s*:&\s*\}\s*;\s*:/ },
180
+ { kind: 'exfiltrate', note: 'pipe a remote script straight into a shell', re: /\b(?:curl|wget)\b[^\n|]*\|\s*(?:sudo\s+)?(?:ba)?sh\b/i },
181
+ ];
182
+ export function scanForUnsafe(text) {
183
+ const s = String(text || '');
184
+ const findings = [];
185
+ for (const p of UNSAFE_PATTERNS) {
186
+ if (p.re.test(s)) findings.push({ kind: p.kind, note: p.note });
187
+ }
188
+ return { clean: findings.length === 0, findings };
189
+ }
190
+
191
+ // --- the bazaar instance --------------------------------------------------
192
+
193
+ // Outcome score = a Bayesian-smoothed build success rate (B1). The recipe's
194
+ // declared outcomeScore is the PRIOR mean; this many pseudo-builds give it weight,
195
+ // so a brand-new listing or a thin sample isn't whipsawed by one result, while a
196
+ // recipe with real volume converges on its true rate.
197
+ const OUTCOME_PRIOR_K = 4;
198
+
199
+ export function createBazaar({ baseDir, seedDir = SEED_DIR, rails = null } = {}) {
200
+ const dir = baseDir || defaultBazaarDir();
201
+ const eventsFile = path.join(dir, 'events.jsonl');
202
+ const listingsFile = path.join(dir, 'listings.json');
203
+ const previewFile = path.join(dir, 'preview.json');
204
+ // The cross-user theme pool, cached locally (next push §N). The MAIN server
205
+ // periodically pulls the global pool from the rails and writes it here; BOTH
206
+ // this process and the spawned MCP child read it SYNCHRONOUSLY in shelf() the
207
+ // child has no rails access of its own, exactly the canvas "rails=truth → local
208
+ // cache below" model. `rails` (the ListingsRails client) is injected only into
209
+ // the main server's instance, for the immediate push on the human publish path;
210
+ // the MCP child's instance has none (the periodic reconcile pushes its writes).
211
+ const railsThemesFile = path.join(dir, 'rails-themes.json');
212
+ // Self-seed drafts (cold-start, Producer #1): recipes the agent EXTRACTED from
213
+ // the user's existing work, staged here for REVIEW. Nothing reaches the shelf
214
+ // until the user approves a draft (publishDraft). The safety control is that a
215
+ // draft holds only generalized know-how — never client files/names/secrets.
216
+ const draftsFile = path.join(dir, 'drafts.json');
217
+
218
+ function ensureDir() {
219
+ try {
220
+ fs.mkdirSync(dir, { recursive: true });
221
+ } catch {
222
+ /* read-only fs — degrades to no persistence */
223
+ }
224
+ }
225
+
226
+ // --- live outcome telemetry (B1) ----------------------------------------
227
+ // Real build-result events (recorded by record_build_result after a build lands
228
+ // or fails) are the signal behind outcomeScore. Cached on the events file's
229
+ // size+mtime so it stays correct even when the MCP child process appends.
230
+ let _outcomeCache = null;
231
+ let _outcomeCacheSig = null;
232
+ function liveOutcomes() {
233
+ let sig = '0';
234
+ try { const st = fs.statSync(eventsFile); sig = `${st.size}:${st.mtimeMs}`; } catch { /* no file yet */ }
235
+ if (_outcomeCache && _outcomeCacheSig === sig) return _outcomeCache;
236
+ const map = {};
237
+ for (const e of events()) {
238
+ if (e.type !== 'build-result' || !e.recipeId) continue;
239
+ const m = (map[e.recipeId] ??= { builds: 0, working: 0 });
240
+ m.builds += 1;
241
+ if (e.success) m.working += 1;
242
+ }
243
+ _outcomeCache = map;
244
+ _outcomeCacheSig = sig;
245
+ return map;
246
+ }
247
+ // The recipe's accumulated { builds, working }: its seed baseline (missing
248
+ // {0,0}, the migration for old listings) plus live build-results.
249
+ function liveStats(r) {
250
+ const base = r.outcomeStats && typeof r.outcomeStats === 'object' ? r.outcomeStats : { builds: 0, working: 0 };
251
+ const live = liveOutcomes()[r.id] || { builds: 0, working: 0 };
252
+ return { builds: (base.builds || 0) + live.builds, working: (base.working || 0) + live.working };
253
+ }
254
+ // Bayesian-smoothed success rate. Prior mean = the declared outcomeScore (0.7 for
255
+ // an undeclared listing); with zero live results it equals the declared score, so
256
+ // seed rankings stay stable until real outcomes accumulate.
257
+ function liveScore(r) {
258
+ const prior = typeof r.outcomeScore === 'number' ? r.outcomeScore : 0.7;
259
+ const { builds, working } = liveStats(r);
260
+ const score = (working + OUTCOME_PRIOR_K * prior) / (builds + OUTCOME_PRIOR_K);
261
+ return Math.max(0, Math.min(1, Math.round(score * 1000) / 1000));
262
+ }
263
+ // The agent reports whether a build that used a recipe actually WORKED (B1) — the
264
+ // real signal behind the outcome score. Appended to events.jsonl; liveScore reads
265
+ // it on the next card render. Unknown recipe → a no-op error (keeps events clean).
266
+ function recordBuildResult({ recipeId, success, reason = '' } = {}) {
267
+ const r = getRecipe(recipeId);
268
+ if (!r) return { ok: false, error: `no recipe "${recipeId}" on the shelf` };
269
+ const evt = appendEvent({
270
+ type: 'build-result',
271
+ recipeId: r.id,
272
+ title: r.title,
273
+ success: !!success,
274
+ reason: String(reason || '').slice(0, 200),
275
+ });
276
+ return { ok: true, event: evt, outcome: { ...liveStats(r), score: liveScore(r) } };
277
+ }
278
+
279
+ // --- trust & provenance (B2) --------------------------------------------
280
+ // The §3 schema (docs/shelf-trust-provenance-design.md). riskClass is the spine:
281
+ // A data (themes) · B local build-recipe · C connected-service · D executable-skill.
282
+ // provenanceFor() also MIGRATES old records on read — a listing with the legacy
283
+ // safetyBadge but no riskClass gets defaults by kind, and a free-text sourceNote
284
+ // becomes a builtFrom[] entry — so an existing listings.json never breaks.
285
+ function riskClassOf(r) {
286
+ if (['A', 'B', 'C', 'D'].includes(r.riskClass)) return r.riskClass;
287
+ if (r.kind === 'theme') return 'A';
288
+ if (r.service || r.hasService) return 'C';
289
+ return 'B';
290
+ }
291
+ function normalizeBuiltFrom(r) {
292
+ if (Array.isArray(r.builtFrom)) {
293
+ return r.builtFrom.filter(Boolean).map((b) => ({ type: b.type || 'recipe', id: b.id ?? null, note: b.note || b.title || '' }));
294
+ }
295
+ if (r.builtFrom && (r.builtFrom.id || r.builtFrom.title)) {
296
+ // the C2 remix pointer { id, title } the schema's array form
297
+ return [{ type: r.kind === 'theme' ? 'theme' : 'recipe', id: r.builtFrom.id ?? null, note: r.builtFrom.title || '' }];
298
+ }
299
+ if (r.sourceNote) return [{ type: 'scratch', id: null, note: String(r.sourceNote) }]; // migrate free-text
300
+ return [];
301
+ }
302
+ function provenanceFor(r) {
303
+ const riskClass = riskClassOf(r);
304
+ const trusted = r.source === 'seed' || r.source === 'theme'; // VW-shipped → pre-vetted
305
+ const dataTouched = r.dataTouched || (riskClass === 'C'
306
+ ? { egress: [], scope: 'external', paid: { model: r.reward?.perUseValue ? 'per-use' : 'none', note: '' } }
307
+ : { egress: [], scope: 'in-workspace', paid: { model: 'none', note: '' } });
308
+ const attestation = r.attestation || {
309
+ privacy: riskClass === 'C' ? 'not-attested' : 'n/a',
310
+ attestedBy: null,
311
+ at: null,
312
+ };
313
+ const defaultVerdict =
314
+ riskClass === 'A' ? 'auto'
315
+ : riskClass === 'B' ? (trusted ? 'scanned' : 'unscanned')
316
+ : riskClass === 'C' ? (trusted ? 'reviewed' : 'unvetted')
317
+ : 'unvetted'; // D never auto-clears (enforcement deferred own/teammate only)
318
+ const vetting = r.vetting || { verdict: defaultVerdict, stakes: 'ordinary', signature: null, capabilities: null, findings: [] };
319
+ return { riskClass, builtFrom: normalizeBuiltFrom(r), dataTouched, attestation, vetting };
320
+ }
321
+
322
+ // The cross-user theme pool from the local rails cache, RE-VALIDATED on read —
323
+ // never trust the pool blindly (spike 2: 15/15 hostile bundles neutralized by
324
+ // normalizeTheme). A tampered cache file degrades to a clean bundle, not exec.
325
+ function readRailsThemes() {
326
+ const raw = readJsonSafe(railsThemesFile, []);
327
+ if (!Array.isArray(raw)) return [];
328
+ return raw
329
+ .filter((r) => r && typeof r === 'object' && r.id && r.kind === 'theme')
330
+ .map((r) => ({ ...r, theme: normalizeTheme(r.theme || {}), source: 'rails' }));
331
+ }
332
+
333
+ // Overwrite the local cache of the global theme pool (called by the main
334
+ // server's periodic sync). Atomic; best-effort.
335
+ function writeRailsThemes(cards) {
336
+ ensureDir();
337
+ try {
338
+ writeJsonAtomic(railsThemesFile, Array.isArray(cards) ? cards : []);
339
+ } catch {
340
+ /* persistence best-effort */
341
+ }
342
+ }
343
+
344
+ function shelf() {
345
+ const seed = loadSeedRecipes(seedDir);
346
+ const listings = readJsonSafe(listingsFile, []);
347
+ const local = Array.isArray(listings) ? listings : [];
348
+ // Seeds + the user's OWN listings come first and SHADOW the pool: a theme the
349
+ // user published locally wins over its copy in the global pool (same id).
350
+ const base = [...seed, ...SEED_THEMES, ...local];
351
+ const seen = new Set(base.map((r) => r.id));
352
+ const pool = readRailsThemes().filter((r) => !seen.has(r.id));
353
+ return [...base, ...pool];
354
+ }
355
+
356
+ // The user's own theme listings, as public cards what the periodic sync
357
+ // reconciles up to the rails (catches themes the agent published via the MCP
358
+ // child, which has no rails of its own).
359
+ function ownThemeListings() {
360
+ const listings = readJsonSafe(listingsFile, []);
361
+ return (Array.isArray(listings) ? listings : [])
362
+ .filter((l) => l && l.kind === 'theme')
363
+ .map((l) => card(l));
364
+ }
365
+
366
+ function getRecipe(id) {
367
+ return shelf().find((r) => r.id === id) || null;
368
+ }
369
+
370
+ // Public, agent-facing card for a recipe (no know-how dump until opened).
371
+ function card(r, extra = {}) {
372
+ return {
373
+ id: r.id,
374
+ kind: r.kind || 'recipe',
375
+ // Provenance category: 'seed'|'theme' (VW-shipped) · 'listing' (own) · 'rails'
376
+ // (another user's, from the global pool). The shelf UI keys the Report action
377
+ // + the "from the community" labelling on this. Defaults to 'listing'.
378
+ source: r.source || 'listing',
379
+ title: r.title,
380
+ pitch: r.pitch,
381
+ producer: r.producer,
382
+ summary: r.summary,
383
+ vendorDescription: r.vendorDescription,
384
+ outcomeScore: liveScore(r),
385
+ outcomeStats: liveStats(r),
386
+ safetyBadge: r.safetyBadge, // legacy field kept for back-compat; web derives from `vetting`
387
+ ...provenanceFor(r), // B2: riskClass · builtFrom · dataTouched · attestation · vetting
388
+ rating: r.rating,
389
+ reward: r.reward,
390
+ hasService: Boolean(r.service),
391
+ buildDir: r.buildDir,
392
+ // A theme card carries its own bundle — it IS its own preview (just hex), so
393
+ // the storefront can render a live swatch and apply it without a fetch.
394
+ ...(r.kind === 'theme' && r.theme ? { theme: r.theme } : {}),
395
+ ...extra,
396
+ };
397
+ }
398
+
399
+ function search(need, { limit = 4 } = {}) {
400
+ const ranked = shelf()
401
+ .map((r) => {
402
+ const { score, matched } = scoreRecipe(r, need);
403
+ return { r, score, matched };
404
+ })
405
+ .filter((x) => x.score > 0)
406
+ .sort((a, b) => b.score - a.score || liveScore(b.r) - liveScore(a.r))
407
+ .slice(0, limit);
408
+ return ranked.map((x) => card(x.r, { relevance: x.score, matched: x.matched }));
409
+ }
410
+
411
+ function appendEvent(evt) {
412
+ ensureDir();
413
+ const enriched = { id: rid(), ts: Date.now(), ...evt };
414
+ try {
415
+ fs.appendFileSync(eventsFile, `${JSON.stringify(enriched)}\n`);
416
+ } catch {
417
+ /* persistence best-effort */
418
+ }
419
+ return enriched;
420
+ }
421
+
422
+ function events() {
423
+ let raw = '';
424
+ try {
425
+ raw = fs.readFileSync(eventsFile, 'utf8');
426
+ } catch {
427
+ return [];
428
+ }
429
+ return raw
430
+ .split('\n')
431
+ .map((l) => l.trim())
432
+ .filter(Boolean)
433
+ .map((l) => {
434
+ try {
435
+ return JSON.parse(l);
436
+ } catch {
437
+ return null;
438
+ }
439
+ })
440
+ .filter(Boolean);
441
+ }
442
+
443
+ // A consumer's agent absorbed a recipe and built it: the three-way moment.
444
+ function recordUse({ recipeId, summary, consumer = 'you' }) {
445
+ const r = getRecipe(recipeId);
446
+ if (!r) return { ok: false, error: `no recipe "${recipeId}" on the shelf` };
447
+ const recurring = r.reward?.perUseValue || 0;
448
+ // A recurring SERVICE recipe (tool/API) earns per-use, NOT a build fee — so the
449
+ // build itself credits 0, and the meter ticks up per match. This keeps the live
450
+ // meter ("$X · N matches") reconciled with the "earns per match, ongoing" story.
451
+ // Pure know-how recipes earn their one-time build-time slice here.
452
+ const oneTime = r.service ? 0 : (r.reward?.oneTimeValue || 0);
453
+ const evt = appendEvent({
454
+ type: 'use',
455
+ recipeId: r.id,
456
+ title: r.title,
457
+ producer: r.producer,
458
+ consumer,
459
+ summary: summary || r.title,
460
+ value: oneTime,
461
+ unit: r.service ? 'recurring-start' : 'one-time',
462
+ });
463
+ const threeWay = {
464
+ you: `You got: ${summary || r.title}`,
465
+ producer: r.service
466
+ ? `${r.producer?.name || 'The producer'} just gained a customer — your site uses their matching on every candidate, ongoing.`
467
+ : `${r.producer?.name || 'The producer'} earns a one-time share for the know-how you built on.`,
468
+ platform: 'VentureWild matched you to a proven recipe and recorded it.',
469
+ };
470
+ return {
471
+ ok: true,
472
+ event: evt,
473
+ recipe: card(r),
474
+ threeWay,
475
+ credit: { producer: r.producer, oneTime, recurring, unit: r.reward?.unit },
476
+ service: r.service || null,
477
+ };
478
+ }
479
+
480
+ // TickUp's matching service ran once — recurring credit to the producer.
481
+ function recordServiceCall({ recipeId, serviceId, matches = 0 }) {
482
+ const r = getRecipe(recipeId) || shelf().find((x) => x.service?.id === serviceId);
483
+ const per = r?.reward?.perUseValue || 0;
484
+ return appendEvent({
485
+ type: 'service-call',
486
+ recipeId: r?.id || recipeId || null,
487
+ serviceId: serviceId || r?.service?.id || null,
488
+ producer: r?.producer || null,
489
+ matches,
490
+ value: per,
491
+ unit: 'per-use',
492
+ });
493
+ }
494
+
495
+ // The flip side (§3.7): the user's agent packaged a build into a listing.
496
+ function publishListing({ id, title, pitch, summary, tags = [], knowHow = '', producer, buildDir, builtFrom = null }) {
497
+ ensureDir();
498
+ const listings = readJsonSafe(listingsFile, []);
499
+ const arr = Array.isArray(listings) ? listings : [];
500
+ const slug =
501
+ id ||
502
+ `${normalize(title).split(' ').slice(0, 4).join('-') || 'listing'}-${rid().slice(0, 4)}`;
503
+ // Class-B vetting (B2): a recipe is local build know-how self-attest + an
504
+ // automated scan. A clean scan earns the 'scanned' verdict; a hit is recorded
505
+ // (verdict 'flagged' + findings) so the badge tells the truth — publishing isn't
506
+ // blocked here (single-user/local shelf), but the listing carries its verdict.
507
+ const scan = scanForUnsafe(knowHow);
508
+ const listing = {
509
+ id: slug,
510
+ title: title || 'Untitled',
511
+ pitch: pitch || '',
512
+ summary: summary || pitch || '',
513
+ vendorDescription: summary || pitch || '',
514
+ producer: producer || { name: 'You', handle: 'you', kind: 'maker' },
515
+ tags,
516
+ knowHow,
517
+ buildDir: buildDir || null,
518
+ outcomeScore: 0.7, // new listing: a starting, unproven score (earns its place by working)
519
+ outcomeStats: { builds: 0, working: 0 },
520
+ safetyBadge: 'new', // legacy field; the real signal is `vetting` below
521
+ riskClass: 'B',
522
+ ...(builtFrom && builtFrom.id ? { builtFrom: { id: String(builtFrom.id), title: String(builtFrom.title || '') } } : {}),
523
+ dataTouched: { egress: [], scope: 'in-workspace', paid: { model: 'none', note: '' } },
524
+ attestation: { privacy: 'n/a', attestedBy: (producer || {}).handle || 'you', at: new Date().toISOString() },
525
+ vetting: {
526
+ verdict: scan.clean ? 'scanned' : 'flagged',
527
+ stakes: 'ordinary',
528
+ signature: null,
529
+ capabilities: null,
530
+ findings: scan.findings,
531
+ },
532
+ rating: { stars: 0, count: 0 },
533
+ reward: { model: 'one-time', unit: 'per build', perUseValue: 0, oneTimeValue: 5.0 },
534
+ source: 'listing',
535
+ createdAt: Date.now(),
536
+ };
537
+ // de-dupe by id (re-publish overwrites)
538
+ const next = arr.filter((l) => l.id !== listing.id);
539
+ next.push(listing);
540
+ writeJsonAtomic(listingsFile, next);
541
+ appendEvent({
542
+ type: 'publish',
543
+ recipeId: listing.id,
544
+ title: listing.title,
545
+ producer: listing.producer,
546
+ });
547
+ return {
548
+ ok: true,
549
+ listing: card(listing),
550
+ earning: {
551
+ model: listing.reward.model,
552
+ oneTimeValue: listing.reward.oneTimeValue,
553
+ note: 'Represented earnings — you earn each time someone builds on this. (Money is for later.)',
554
+ },
555
+ };
556
+ }
557
+
558
+ // --- themes on the shelf (the safest cross-user artifact) -----------------
559
+
560
+ // Publish a theme as a listing. The payload is a hex-token bundle (validated by
561
+ // normalizeTheme same security boundary as set_theme: data, never CSS). It
562
+ // lands in listings.json with kind:'theme' and shows on the Themes shelf.
563
+ function publishTheme({ title, pitch, summary, tags = [], producer, theme, builtFrom = null } = {}) {
564
+ ensureDir();
565
+ const bundle = normalizeTheme(theme || {});
566
+ const listings = readJsonSafe(listingsFile, []);
567
+ const arr = Array.isArray(listings) ? listings : [];
568
+ const slug = `theme-${normalize(title).split(' ').slice(0, 3).join('-') || 'custom'}-${rid().slice(0, 4)}`;
569
+ // A remix records what it was tweaked from (the source theme on the shelf) so the
570
+ // network shows lineage — "built on each other's work", not a flat catalogue.
571
+ const provenance =
572
+ builtFrom && builtFrom.id
573
+ ? { id: String(builtFrom.id), title: String(builtFrom.title || '') }
574
+ : null;
575
+ const listing = {
576
+ id: slug,
577
+ kind: 'theme',
578
+ source: 'theme',
579
+ title: title || bundle.name || 'Custom theme',
580
+ pitch: pitch || '',
581
+ summary: summary || pitch || `A ${bundle.mode} theme.`,
582
+ vendorDescription: summary || pitch || '',
583
+ producer: producer || { name: 'You', handle: 'you', kind: 'maker' },
584
+ tags,
585
+ theme: bundle,
586
+ ...(provenance ? { builtFrom: provenance } : {}),
587
+ outcomeScore: 0.7,
588
+ outcomeStats: { builds: 0, working: 0 },
589
+ safetyBadge: 'new',
590
+ rating: { stars: 0, count: 0 },
591
+ reward: { model: 'one-time', unit: 'per apply', oneTimeValue: 1.5, perUseValue: 0 },
592
+ createdAt: Date.now(),
593
+ };
594
+ const next = arr.filter((l) => l.id !== listing.id);
595
+ next.push(listing);
596
+ writeJsonAtomic(listingsFile, next);
597
+ appendEvent({ type: 'publish', recipeId: listing.id, title: listing.title, producer: listing.producer, ...(provenance ? { builtFrom: provenance } : {}) });
598
+ const publicCard = card(listing);
599
+ // Push to the GLOBAL pool (next push §N) so every VW user can discover it.
600
+ // Best-effort + fire-and-forget: a down rail (or the MCP child, which has no
601
+ // rails) NEVER fails the local publish — the periodic sync reconciles it up.
602
+ if (rails && typeof rails.publish === 'function') {
603
+ Promise.resolve(rails.publish(publicCard)).catch(() => {});
604
+ }
605
+ return {
606
+ ok: true,
607
+ listing: publicCard,
608
+ earning: { model: 'one-time', oneTimeValue: listing.reward.oneTimeValue, note: 'You earn each time someone applies it. (Money is for later.)' },
609
+ };
610
+ }
611
+
612
+ // A consumer applied a theme from the shelf: record the three-way moment (they
613
+ // got the look · the producer earns · platform recorded it) and hand back the
614
+ // validated bundle for the browser to apply.
615
+ function recordThemeApply({ themeId, consumer = 'you' } = {}) {
616
+ const r = getRecipe(themeId);
617
+ if (!r || r.kind !== 'theme') return { ok: false, error: `no theme "${themeId}" on the shelf` };
618
+ const oneTime = r.reward?.oneTimeValue || 0;
619
+ const evt = appendEvent({
620
+ type: 'use',
621
+ recipeId: r.id,
622
+ title: r.title,
623
+ producer: r.producer,
624
+ consumer,
625
+ summary: `Applied the "${r.title}" theme`,
626
+ value: oneTime,
627
+ unit: 'one-time',
628
+ });
629
+ return {
630
+ ok: true,
631
+ event: evt,
632
+ theme: normalizeTheme(r.theme || {}),
633
+ title: r.title,
634
+ threeWay: {
635
+ you: `Your workspace now wears "${r.title}".`,
636
+ producer: `${r.producer?.name || 'The producer'} earns a one-time share for the look you adopted.`,
637
+ platform: 'VentureWild matched you to a proven theme — and recorded it.',
638
+ },
639
+ credit: { producer: r.producer, oneTime, unit: r.reward?.unit },
640
+ };
641
+ }
642
+
643
+ // --- self-seed drafts (review-gated) --------------------------------------
644
+
645
+ function listDrafts() {
646
+ const d = readJsonSafe(draftsFile, []);
647
+ return Array.isArray(d) ? d : [];
648
+ }
649
+
650
+ function getDraft(id) {
651
+ return listDrafts().find((d) => d.id === id) || null;
652
+ }
653
+
654
+ // Stage a recipe the agent extracted from the user's existing work — does NOT
655
+ // publish. `sourceNote` records (for the user's review) what it was generalized
656
+ // from. Returns a review-shaped object the UI renders for approval.
657
+ function stageDraft({ title, pitch, summary, tags = [], knowHow = '', sourceNote = '' }) {
658
+ ensureDir();
659
+ const drafts = listDrafts();
660
+ const draft = {
661
+ id: `draft-${rid()}`,
662
+ title: title || 'Untitled',
663
+ pitch: pitch || '',
664
+ summary: summary || pitch || '',
665
+ tags: Array.isArray(tags) ? tags : [],
666
+ knowHow: knowHow || '',
667
+ sourceNote: sourceNote || '',
668
+ createdAt: Date.now(),
669
+ };
670
+ drafts.push(draft);
671
+ writeJsonAtomic(draftsFile, drafts);
672
+ return draft;
673
+ }
674
+
675
+ function discardDraft(id) {
676
+ const drafts = listDrafts();
677
+ const next = drafts.filter((d) => d.id !== id);
678
+ writeJsonAtomic(draftsFile, next);
679
+ return { ok: next.length !== drafts.length };
680
+ }
681
+
682
+ // Promote a reviewed draft onto the shelf — publishes EXACTLY what was reviewed
683
+ // (you publish what you saw), then removes it from the draft queue.
684
+ function publishDraft(id, { producer } = {}) {
685
+ const draft = getDraft(id);
686
+ if (!draft) return { ok: false, error: `no draft "${id}"` };
687
+ const res = publishListing({
688
+ title: draft.title,
689
+ pitch: draft.pitch,
690
+ summary: draft.summary,
691
+ tags: draft.tags,
692
+ knowHow: draft.knowHow,
693
+ producer: producer || { name: 'You', handle: 'you', kind: 'maker' },
694
+ });
695
+ discardDraft(id);
696
+ return res;
697
+ }
698
+
699
+ function setPreview({ dir: buildDir, recipeId, port = 4000 }) {
700
+ ensureDir();
701
+ const payload = { dir: buildDir, recipeId: recipeId || null, port, ts: Date.now() };
702
+ writeJsonAtomic(previewFile, payload);
703
+ return payload;
704
+ }
705
+
706
+ function getPreview() {
707
+ return readJsonSafe(previewFile, null);
708
+ }
709
+
710
+ // Aggregate everything the UI needs: transactions, per-producer earnings,
711
+ // per-service usage meters, and the user's own listings.
712
+ function computeState() {
713
+ const evs = events();
714
+ const earnings = {}; // handle -> { name, total, uses, serviceCalls, matches }
715
+ const meters = {}; // serviceId -> { calls, matches, value, producer }
716
+ const transactions = [];
717
+ for (const e of evs) {
718
+ const h = e.producer?.handle || 'unknown';
719
+ const bucket = (earnings[h] ??= {
720
+ name: e.producer?.name || h,
721
+ handle: h,
722
+ total: 0,
723
+ uses: 0,
724
+ serviceCalls: 0,
725
+ matches: 0,
726
+ });
727
+ if (e.type === 'use') {
728
+ bucket.total += e.value || 0;
729
+ bucket.uses += 1;
730
+ transactions.push(e);
731
+ } else if (e.type === 'service-call') {
732
+ bucket.total += e.value || 0;
733
+ bucket.serviceCalls += 1;
734
+ bucket.matches += e.matches || 0;
735
+ const sid = e.serviceId || 'service';
736
+ const m = (meters[sid] ??= { calls: 0, matches: 0, value: 0, producer: e.producer || null });
737
+ m.calls += 1;
738
+ m.matches += e.matches || 0;
739
+ m.value += e.value || 0;
740
+ } else if (e.type === 'publish') {
741
+ transactions.push(e);
742
+ }
743
+ }
744
+ return {
745
+ transactions: transactions.slice(-50),
746
+ earnings: Object.values(earnings).sort((a, b) => b.total - a.total),
747
+ meters,
748
+ listings: (readJsonSafe(listingsFile, []) || []).map((l) => card(l)),
749
+ totals: {
750
+ events: evs.length,
751
+ creditPaid: Object.values(earnings).reduce((s, b) => s + b.total, 0),
752
+ },
753
+ };
754
+ }
755
+
756
+ return {
757
+ dir,
758
+ eventsFile,
759
+ listingsFile,
760
+ previewFile,
761
+ draftsFile,
762
+ railsThemesFile,
763
+ writeRailsThemes,
764
+ ownThemeListings,
765
+ shelf,
766
+ getRecipe,
767
+ card,
768
+ search,
769
+ recordUse,
770
+ recordBuildResult,
771
+ recordServiceCall,
772
+ publishListing,
773
+ publishTheme,
774
+ recordThemeApply,
775
+ listDrafts,
776
+ getDraft,
777
+ stageDraft,
778
+ discardDraft,
779
+ publishDraft,
780
+ setPreview,
781
+ getPreview,
782
+ computeState,
783
+ events,
784
+ };
785
+ }
786
+
787
+ function money(n) {
788
+ const v = Number(n) || 0;
789
+ return `$${v.toFixed(2)}`;
790
+ }