screenhand 0.3.9 → 0.4.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.
package/README.md CHANGED
@@ -128,7 +128,7 @@ On Windows, use `npm run build:native:windows` instead.
128
128
 
129
129
  ## What It Does
130
130
 
131
- ScreenHand gives AI agents seven capabilities:
131
+ ScreenHand gives AI agents eight capabilities:
132
132
 
133
133
  ### Desktop Control — 19 tools
134
134
  Click buttons, type text, read UI trees, navigate menus, drag, scroll — all via native Accessibility APIs in ~50ms. Works with any app: Finder, Notes, VS Code, Xcode, System Settings, etc.
@@ -145,6 +145,9 @@ Gets smarter every session. Logs tool calls, saves winning strategies, tracks er
145
145
  ### App Mastery Map — automatic per-app spatial understanding
146
146
  Builds a persistent reverse-engineered blueprint of every app from normal tool usage. 8 features record automatically: page zones, navigation graph (BFS pathfinding), hierarchy, I/O contracts, state machine, element visibility, timing profiles, and ready signals. Mastery levels (beginner → pro → expert → grandmaster) honestly reflect how well ScreenHand knows each app. Maps stored at `~/.screenhand/app-maps/`.
147
147
 
148
+ ### Website Feature Discovery — real features, not generic ladders
149
+ `discover_features` fetches an app's official website and extracts real product features (headings, feature cards, definition lists). Assigns difficulty tiers automatically and generates value-add features only ScreenHand can provide: bulk operations, cross-app export, content summarization, auto-organize, and change monitoring. No LLM calls needed — pure rule-based extraction. Features merge into the reference file and enrich the mastery ladder.
150
+
148
151
  ### Jobs & Orchestration — 34 tools
149
152
  Queue multi-step jobs, run them via background worker daemon, coordinate multiple AI agents with session leases, detect stalls, auto-recover. Survives client restarts.
150
153
 
@@ -294,7 +297,7 @@ Accessibility: ~50ms. Chrome CDP: ~10ms (background, no focus needed). OCR: ~600
294
297
  ```bash
295
298
  git clone https://github.com/manushi4/screenhand.git
296
299
  cd screenhand && npm install && npm run build:native
297
- npm test # 1331 tests, 54 files
300
+ npm test # 1405 tests, 56 files
298
301
  ```
299
302
 
300
303
  ## Contact
@@ -69,6 +69,7 @@ import os from "node:os";
69
69
  import { MenuScanner } from "./src/ingestion/menu-scanner.js";
70
70
  import { DocParser } from "./src/ingestion/doc-parser.js";
71
71
  import { TutorialExtractor } from "./src/ingestion/tutorial-extractor.js";
72
+ import { extractFeaturesFromHTML } from "./src/ingestion/feature-extractor.js";
72
73
  import { CoverageAuditor } from "./src/ingestion/coverage-auditor.js";
73
74
  import { ReferenceMerger } from "./src/ingestion/reference-merger.js";
74
75
  import { PlaybookPublisher } from "./src/community/publisher.js";
@@ -280,6 +281,7 @@ coverage_report(bundleId, appName) → tells you exactly what ScreenHand knows
280
281
  - "0 selectors, 0 flows" → LEARN FIRST (Step 0a)
281
282
  - "Has selectors + flows" → GO (skip to Step 1)
282
283
  - "Has error patterns for your tool" → use *_with_fallback tools
284
+ - "Website features: 0" → run discover_features first (Step 0b)
283
285
 
284
286
  learning_status(bundleId) → tells you WHICH tools to use
285
287
  - AX score > 0.9 → use ui_press/ui_tree (fastest, ~50ms)
@@ -294,6 +296,16 @@ platform_guide("platform") → load curated selectors/flows/errors
294
296
  memory_recall("task description") → reuse past strategies
295
297
  Then go to Step 1.
296
298
 
299
+ ### Step 0b: DISCOVER FEATURES (if website features = 0)
300
+ discover_features(url, bundleId, appName) → fetch official app website, extract real features
301
+ → parses headings, feature cards, definition lists from HTML
302
+ → assigns levels: beginner/pro/expert/grandmaster
303
+ → generates value-add features: bulk ops, cross-app, summarize, organize, monitor
304
+ → merges into reference file, enriches the feature ladder
305
+ → coverage_report will now show real feature count
306
+ Priority: discover_features BEFORE scan_menu_bar (features give meaningful ladder)
307
+ Then continue to Step 0a or Step 1.
308
+
297
309
  ### Step 1: SEE
298
310
  perception_start() → turns on continuous monitoring (3 rates: AX 100ms, CDP 300ms, Vision 1s)
299
311
  world_state() → verify windows + controls are tracked
@@ -5277,6 +5289,16 @@ function getJobRunner() {
5277
5289
  const client = await CDPClient({ port });
5278
5290
  return { Runtime: client.Runtime, Input: client.Input, close: () => client.close() };
5279
5291
  });
5292
+ // Wire AppleScript runner into playbook engine for applescript steps
5293
+ playbookEngine.setAppleScriptRunner(async (script) => {
5294
+ if (process.platform === "win32")
5295
+ throw new Error("AppleScript is not supported on Windows");
5296
+ const { execSync } = await import("node:child_process");
5297
+ return execSync(`osascript -e '${script.replace(/'/g, "'\\''")}'`, {
5298
+ encoding: "utf-8",
5299
+ timeout: 15000,
5300
+ }).trim();
5301
+ });
5280
5302
  activeJobRunner = new JobRunner(bridge, jobManager, leaseManager, supervisor, (() => {
5281
5303
  const cfg = {
5282
5304
  hasCDP: cdpPort !== null,
@@ -6413,6 +6435,65 @@ server.tool("ingest_tutorial", "Extract structured playbook steps from a video t
6413
6435
  }],
6414
6436
  };
6415
6437
  });
6438
+ server.tool("discover_features", "Extract features from an app's official website and generate ScreenHand value-add features. Fetches the page, parses feature headings/cards/lists, assigns difficulty levels, and generates bulk/cross-app/intelligence/organization/monitoring value-adds. Merges into the reference file and enriches the feature ladder.", {
6439
+ url: z.string().url().describe("Official app website URL (e.g. https://www.apple.com/notes)"),
6440
+ bundleId: z.string().describe("macOS bundle ID (e.g. com.apple.Notes)"),
6441
+ appName: z.string().describe("Human-readable app name (e.g. Notes)"),
6442
+ }, async ({ url, bundleId, appName }) => {
6443
+ // SSRF protection: only allow http/https to public hosts
6444
+ const parsed = new URL(url);
6445
+ if (!["http:", "https:"].includes(parsed.protocol)) {
6446
+ throw new Error("Only http/https URLs are allowed");
6447
+ }
6448
+ const hostname = parsed.hostname.toLowerCase();
6449
+ if (hostname === "localhost" ||
6450
+ hostname === "metadata.google.internal" ||
6451
+ /^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|169\.254\.|0\.|0x|::1|\[::1\])/.test(hostname) ||
6452
+ /^\d+$/.test(hostname)) {
6453
+ throw new Error("URL points to internal/private network — blocked for security");
6454
+ }
6455
+ const MAX_HTML_BYTES = 5 * 1024 * 1024; // 5MB
6456
+ const resp = await fetch(url, {
6457
+ headers: { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" },
6458
+ signal: AbortSignal.timeout(15000),
6459
+ redirect: "follow",
6460
+ });
6461
+ if (!resp.ok)
6462
+ throw new Error(`Failed to fetch ${url}: ${resp.status}`);
6463
+ // Check Content-Length before buffering
6464
+ const contentLength = resp.headers.get("content-length");
6465
+ if (contentLength && parseInt(contentLength) > MAX_HTML_BYTES) {
6466
+ throw new Error(`Response too large: ${contentLength} bytes (max ${MAX_HTML_BYTES})`);
6467
+ }
6468
+ const html = await resp.text();
6469
+ if (html.length > MAX_HTML_BYTES) {
6470
+ throw new Error(`Response body too large: ${html.length} chars (max ${MAX_HTML_BYTES})`);
6471
+ }
6472
+ const result = extractFeaturesFromHTML(html, appName, url);
6473
+ const mergeResult = referenceMerger.mergeWebsiteFeatures(result, bundleId, appName);
6474
+ const lines = [
6475
+ `Feature discovery: ${appName} (${bundleId})`,
6476
+ `Source: ${url}`,
6477
+ `Website features: ${result.websiteFeatures.length}`,
6478
+ `Value-add features: ${result.valueAddFeatures.length}`,
6479
+ `Reference updated: ${mergeResult.filePath} (${mergeResult.added} new features added)`,
6480
+ "",
6481
+ ];
6482
+ if (result.websiteFeatures.length > 0) {
6483
+ lines.push("Website Features:");
6484
+ for (const f of result.websiteFeatures) {
6485
+ lines.push(` [${f.level}] ${f.name}: ${f.description.slice(0, 80)}`);
6486
+ }
6487
+ lines.push("");
6488
+ }
6489
+ if (result.valueAddFeatures.length > 0) {
6490
+ lines.push("ScreenHand Value-Adds:");
6491
+ for (const f of result.valueAddFeatures) {
6492
+ lines.push(` [${f.category}] ${f.name}: ${f.description}`);
6493
+ }
6494
+ }
6495
+ return { content: [{ type: "text", text: lines.join("\n") }] };
6496
+ });
6416
6497
  server.tool("coverage_report", "Check what ScreenHand knows about an app: shortcuts, selectors, flows, playbooks, error patterns, and stability %. Useful before complex workflows to decide strategy: learn first (if empty), go fast (if high coverage), or use fallback tools (if error patterns exist). Optional for quick actions.", {
6417
6498
  bundleId: z.string().describe("macOS bundle ID (e.g. com.blackmagic-design.DaVinciResolveLite)"),
6418
6499
  appName: z.string().describe("Human-readable app name"),
@@ -6435,6 +6516,7 @@ server.tool("coverage_report", "Check what ScreenHand knows about an app: shortc
6435
6516
  ` Flows: ${report.flowsKnown}`,
6436
6517
  ` Playbooks: ${report.playbooksAvailable}`,
6437
6518
  ` Error patterns: ${report.errorsDocumented}`,
6519
+ ` Website features: ${report.websiteFeaturesKnown}`,
6438
6520
  ];
6439
6521
  if (report.selectorStabilityScore > 0) {
6440
6522
  lines.push(` Selector stability: ${(report.selectorStabilityScore * 100).toFixed(0)}%`);
@@ -39,7 +39,7 @@ export class CoverageAuditor {
39
39
  */
40
40
  audit(bundleId, appName, menuScan) {
41
41
  const refs = this.loadReferences(bundleId);
42
- const playbooks = this.loadPlaybooks(bundleId);
42
+ const playbooks = this.loadPlaybooks(bundleId, appName);
43
43
  // Count what we know
44
44
  let shortcutsKnown = 0;
45
45
  let selectorsKnown = 0;
@@ -63,6 +63,13 @@ export class CoverageAuditor {
63
63
  errorsDocumented += ref.errors.length;
64
64
  }
65
65
  }
66
+ // Count website features
67
+ let websiteFeaturesKnown = 0;
68
+ for (const ref of refs) {
69
+ const wf = ref.websiteFeatures;
70
+ if (Array.isArray(wf))
71
+ websiteFeaturesKnown += wf.length;
72
+ }
66
73
  // Compare menu scan against reference shortcuts
67
74
  const menuPathsNotCovered = [];
68
75
  const shortcutsNotInReference = [];
@@ -153,6 +160,9 @@ export class CoverageAuditor {
153
160
  if (errorsDocumented === 0) {
154
161
  highValueGaps.push("No error patterns documented — errors will be learned automatically over time");
155
162
  }
163
+ if (websiteFeaturesKnown === 0) {
164
+ highValueGaps.push("No website features extracted — run discover_features to learn app capabilities from official website");
165
+ }
156
166
  if (workflowsWithNoPlaybook.length > 0) {
157
167
  highValueGaps.push(`Common workflows without playbooks: ${workflowsWithNoPlaybook.join(", ")}`);
158
168
  }
@@ -167,6 +177,7 @@ export class CoverageAuditor {
167
177
  flowsKnown,
168
178
  playbooksAvailable: playbooks.length,
169
179
  errorsDocumented,
180
+ websiteFeaturesKnown,
170
181
  menuPathsNotCovered: menuPathsNotCovered.slice(0, 50),
171
182
  shortcutsNotInReference: shortcutsNotInReference.slice(0, 50),
172
183
  workflowsWithNoPlaybook,
@@ -197,8 +208,12 @@ export class CoverageAuditor {
197
208
  catch { /* dir not found */ }
198
209
  return refs;
199
210
  }
200
- loadPlaybooks(bundleId) {
211
+ loadPlaybooks(bundleId, appName) {
201
212
  const playbooks = [];
213
+ // Derive short platform name from bundleId: "com.apple.Notes" → "notes"
214
+ const bundleParts = bundleId.split(".");
215
+ const shortName = (bundleParts[bundleParts.length - 1] ?? "").toLowerCase();
216
+ const appNameLower = appName.toLowerCase();
202
217
  try {
203
218
  const files = fs.readdirSync(this.playbooksDir);
204
219
  for (const file of files) {
@@ -207,7 +222,12 @@ export class CoverageAuditor {
207
222
  try {
208
223
  const raw = fs.readFileSync(path.join(this.playbooksDir, file), "utf-8");
209
224
  const pb = JSON.parse(raw);
210
- if (pb.bundleId === bundleId || pb.platform === bundleId) {
225
+ // Match by bundleId (exact), platform name (case-insensitive), or app name
226
+ const platformLower = (pb.platform ?? "").toLowerCase();
227
+ if (pb.bundleId === bundleId ||
228
+ platformLower === bundleId ||
229
+ platformLower === shortName ||
230
+ platformLower === appNameLower) {
211
231
  playbooks.push(pb);
212
232
  }
213
233
  }
@@ -0,0 +1,366 @@
1
+ // Copyright (C) 2025 Clazro Technology Private Limited
2
+ // SPDX-License-Identifier: AGPL-3.0-only
3
+ // ── Tier assignment keywords (F=entry, B=proficient, S=expert, SSS=grandmaster) ─
4
+ /** Single-word keywords checked individually */
5
+ const F_WORDS = new Set([
6
+ "basic", "create", "view", "share", "read",
7
+ "browse", "search", "home", "start", "launch", "write",
8
+ ]);
9
+ const B_WORDS = new Set([
10
+ "organize", "format", "customize", "template", "tag", "folder",
11
+ "sort", "filter", "pin", "archive", "move", "rename", "duplicate",
12
+ "favorites", "bookmark", "list", "table", "style", "font",
13
+ ]);
14
+ const S_WORDS = new Set([
15
+ "automate", "shortcut", "export", "import", "collaborate", "sync",
16
+ "scan", "link", "mention", "embed", "attachment", "password",
17
+ "encrypt", "lock", "version", "history", "recover", "backup",
18
+ ]);
19
+ const SSS_WORDS = new Set([
20
+ "api", "integrate", "plugin", "advanced", "workflow", "script",
21
+ "extension", "developer", "sdk", "automation", "pipeline", "webhook",
22
+ ]);
23
+ /** Multi-word phrases checked via substring match */
24
+ const SSS_PHRASES = [
25
+ "custom action", "get started",
26
+ ];
27
+ // ── HTML entity decoding ──────────────────────────────────────────
28
+ const HTML_ENTITIES = {
29
+ "&amp;": "&", "&lt;": "<", "&gt;": ">", "&quot;": '"',
30
+ "&#39;": "'", "&apos;": "'", "&nbsp;": " ",
31
+ "&#x27;": "'", "&#x2F;": "/",
32
+ };
33
+ function decodeHTMLEntities(text) {
34
+ let result = text;
35
+ for (const [entity, char] of Object.entries(HTML_ENTITIES)) {
36
+ result = result.replaceAll(entity, char);
37
+ }
38
+ // Numeric entities: &#123; or &#x1A;
39
+ // Only decode printable chars (>= 0x20), skip control chars
40
+ result = result.replace(/&#(\d+);/g, (orig, code) => {
41
+ const n = Number(code);
42
+ return n >= 0x20 && n !== 0x7F ? String.fromCharCode(n) : "";
43
+ });
44
+ result = result.replace(/&#x([0-9a-fA-F]+);/g, (orig, hex) => {
45
+ const n = parseInt(hex, 16);
46
+ return n >= 0x20 && n !== 0x7F ? String.fromCharCode(n) : "";
47
+ });
48
+ return result;
49
+ }
50
+ // ── Strip control characters ──────────────────────────────────────
51
+ function stripControlChars(text) {
52
+ // Remove ASCII control chars (0x00-0x08, 0x0B, 0x0C, 0x0E-0x1F, 0x7F)
53
+ // Preserve \t (0x09), \n (0x0A), \r (0x0D)
54
+ return text.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, "");
55
+ }
56
+ // ── Strip HTML tags — O(n) single-pass state machine ──────────────
57
+ function stripTags(html) {
58
+ let result = "";
59
+ let inTag = false;
60
+ for (let i = 0; i < html.length; i++) {
61
+ const ch = html[i];
62
+ if (ch === "<") {
63
+ inTag = true;
64
+ continue;
65
+ }
66
+ if (ch === ">") {
67
+ inTag = false;
68
+ continue;
69
+ }
70
+ if (!inTag)
71
+ result += ch;
72
+ }
73
+ return result.trim();
74
+ }
75
+ // ── Strip script and style blocks before processing ───────────────
76
+ function stripScriptsAndStyles(html) {
77
+ // Remove <script>...</script> and <style>...</style> blocks
78
+ // Use bounded match to prevent backtracking on malformed HTML
79
+ return html
80
+ .replace(/<script\b[^>]*>[\s\S]{0,100000}?<\/script>/gi, "")
81
+ .replace(/<style\b[^>]*>[\s\S]{0,100000}?<\/style>/gi, "")
82
+ .replace(/<!--[\s\S]{0,50000}?-->/g, "");
83
+ }
84
+ // ── Clean extracted text ──────────────────────────────────────────
85
+ function cleanText(rawHtml) {
86
+ return stripControlChars(decodeHTMLEntities(stripTags(rawHtml)));
87
+ }
88
+ // ── Normalize feature name to ID ──────────────────────────────────
89
+ function nameToId(name) {
90
+ return name
91
+ .toLowerCase()
92
+ .replace(/[^a-z0-9]+/g, "_")
93
+ .replace(/^_|_$/g, "")
94
+ .slice(0, 80);
95
+ }
96
+ // ── Assign level based on keywords ────────────────────────────────
97
+ function assignLevel(name, description) {
98
+ const text = `${name} ${description}`.toLowerCase();
99
+ const words = text.split(/\s+/);
100
+ // Check multi-word SSS phrases first
101
+ for (const phrase of SSS_PHRASES) {
102
+ if (text.includes(phrase))
103
+ return "SSS";
104
+ }
105
+ // Check single-word keywords
106
+ for (const w of words) {
107
+ if (SSS_WORDS.has(w))
108
+ return "SSS";
109
+ }
110
+ for (const w of words) {
111
+ if (S_WORDS.has(w))
112
+ return "S";
113
+ }
114
+ for (const w of words) {
115
+ if (B_WORDS.has(w))
116
+ return "B";
117
+ }
118
+ for (const w of words) {
119
+ if (F_WORDS.has(w))
120
+ return "F";
121
+ }
122
+ // Fallback: longer descriptions suggest complexity
123
+ if (description.length > 80)
124
+ return "B";
125
+ return "F";
126
+ }
127
+ // ── Main: Extract features from HTML ──────────────────────────────
128
+ export function extractFeaturesFromHTML(html, appName, url) {
129
+ const seen = new Map();
130
+ // Pre-process: strip scripts, styles, and comments to avoid content leakage
131
+ const cleanHtml = stripScriptsAndStyles(html);
132
+ // ── 1. Extract from headings (h2, h3, h4) ─────────────────────
133
+ const headingRegex = /<h([2-4])[^>]*>([\s\S]*?)<\/h\1>/gi;
134
+ let match;
135
+ while ((match = headingRegex.exec(cleanHtml)) !== null) {
136
+ const text = cleanText(match[2]).trim();
137
+ if (!text || text.length < 3 || text.length > 120)
138
+ continue;
139
+ // Skip navigation/generic headings
140
+ if (/^(menu|nav|footer|header|copyright|legal|privacy)$/i.test(text))
141
+ continue;
142
+ const id = nameToId(text);
143
+ if (!id || seen.has(id))
144
+ continue;
145
+ // Try to find a nearby paragraph for description
146
+ const afterHeading = cleanHtml.slice(match.index + match[0].length, match.index + match[0].length + 500);
147
+ const pMatch = afterHeading.match(/<p[^>]*>([\s\S]*?)<\/p>/i);
148
+ const description = pMatch
149
+ ? cleanText(pMatch[1]).trim().slice(0, 200)
150
+ : text;
151
+ seen.set(id, {
152
+ id,
153
+ name: text,
154
+ description,
155
+ sourceHeading: text,
156
+ level: assignLevel(text, description),
157
+ });
158
+ }
159
+ // ── 2. Extract from feature cards ──────────────────────────────
160
+ // Pattern: <div class="...feature..."> with a heading inside
161
+ // Bounded to 3000 chars to prevent backtracking on deeply nested divs
162
+ const cardRegex = /<div[^>]*class="[^"]*feature[^"]*"[^>]*>([\s\S]{0,3000}?)<\/div>/gi;
163
+ while ((match = cardRegex.exec(cleanHtml)) !== null) {
164
+ const cardHtml = match[1];
165
+ // Find heading inside card
166
+ const innerHeading = cardHtml.match(/<h[2-5][^>]*>([\s\S]*?)<\/h[2-5]>/i);
167
+ if (!innerHeading)
168
+ continue;
169
+ const name = cleanText(innerHeading[1]).trim();
170
+ if (!name || name.length < 3)
171
+ continue;
172
+ const id = nameToId(name);
173
+ if (seen.has(id))
174
+ continue;
175
+ // Description from paragraph
176
+ const pMatch = cardHtml.match(/<p[^>]*>([\s\S]*?)<\/p>/i);
177
+ const description = pMatch
178
+ ? cleanText(pMatch[1]).trim().slice(0, 200)
179
+ : name;
180
+ seen.set(id, {
181
+ id,
182
+ name,
183
+ description,
184
+ sourceHeading: name,
185
+ level: assignLevel(name, description),
186
+ });
187
+ }
188
+ // ── 3. Extract from list items (feature lists) ─────────────────
189
+ // Look for <ul> or <ol> near "feature" context
190
+ const listItemRegex = /<li[^>]*>([\s\S]*?)<\/li>/gi;
191
+ while ((match = listItemRegex.exec(cleanHtml)) !== null) {
192
+ const rawText = cleanText(match[1]).trim();
193
+ // Only accept list items that look like feature names (not too long, not too short)
194
+ if (!rawText || rawText.length < 5 || rawText.length > 100)
195
+ continue;
196
+ // Skip items that look like navigation
197
+ if (/^(home|about|contact|blog|pricing|sign up|log in|download)$/i.test(rawText))
198
+ continue;
199
+ // Skip items with too many sentences (likely paragraphs, not feature names)
200
+ if ((rawText.match(/\./g) ?? []).length > 2)
201
+ continue;
202
+ const id = nameToId(rawText);
203
+ if (seen.has(id))
204
+ continue;
205
+ // Only add if the surrounding context mentions "feature" (within 500 chars before)
206
+ const contextBefore = cleanHtml.slice(Math.max(0, match.index - 500), match.index).toLowerCase();
207
+ if (!contextBefore.includes("feature") && !contextBefore.includes("capability") && !contextBefore.includes("what you can"))
208
+ continue;
209
+ seen.set(id, {
210
+ id,
211
+ name: rawText,
212
+ description: rawText,
213
+ sourceHeading: rawText,
214
+ level: assignLevel(rawText, ""),
215
+ });
216
+ }
217
+ // ── 4. Extract from definition lists ───────────────────────────
218
+ const dtRegex = /<dt[^>]*>([\s\S]*?)<\/dt>\s*<dd[^>]*>([\s\S]*?)<\/dd>/gi;
219
+ while ((match = dtRegex.exec(cleanHtml)) !== null) {
220
+ const name = cleanText(match[1]).trim();
221
+ const desc = cleanText(match[2]).trim().slice(0, 200);
222
+ if (!name || name.length < 3)
223
+ continue;
224
+ const id = nameToId(name);
225
+ if (seen.has(id))
226
+ continue;
227
+ seen.set(id, {
228
+ id,
229
+ name,
230
+ description: desc || name,
231
+ sourceHeading: name,
232
+ level: assignLevel(name, desc),
233
+ });
234
+ }
235
+ const websiteFeatures = [...seen.values()];
236
+ // ── Generate value-add features ────────────────────────────────
237
+ const valueAddFeatures = generateValueAddFeatures(appName, websiteFeatures);
238
+ return {
239
+ appName,
240
+ url,
241
+ websiteFeatures,
242
+ valueAddFeatures,
243
+ extractedAt: new Date().toISOString(),
244
+ };
245
+ }
246
+ const VALUE_ADD_RULES = [
247
+ {
248
+ category: "bulk",
249
+ trigger: (fs) => fs.some((f) => /\b(creates?|adds?)\b/i.test(f.name)),
250
+ generate: (app) => ({
251
+ id: "bulk_create",
252
+ name: "Bulk Create",
253
+ description: `Create multiple ${app} items from a list or template`,
254
+ category: "bulk",
255
+ level: "B",
256
+ }),
257
+ },
258
+ {
259
+ category: "bulk",
260
+ trigger: (fs) => fs.some((f) => /\b(deletes?|removes?|trash)\b/i.test(f.name)),
261
+ generate: (app) => ({
262
+ id: "bulk_delete",
263
+ name: "Bulk Delete",
264
+ description: `Delete multiple ${app} items matching criteria`,
265
+ category: "bulk",
266
+ level: "B",
267
+ }),
268
+ },
269
+ {
270
+ category: "bulk",
271
+ trigger: (fs) => fs.some((f) => /\b(exports?|downloads?)\b/i.test(f.name)),
272
+ generate: (app) => ({
273
+ id: "bulk_export",
274
+ name: "Bulk Export",
275
+ description: `Export all ${app} items at once`,
276
+ category: "bulk",
277
+ level: "B",
278
+ }),
279
+ },
280
+ {
281
+ category: "organization",
282
+ trigger: (fs) => fs.some((f) => /\b(folders?|tags?|labels?|categor(?:y|ies))\b/i.test(f.name)),
283
+ generate: (app) => ({
284
+ id: "auto_organize",
285
+ name: "Auto-Organize",
286
+ description: `Sort and organize ${app} items by content, date, or type`,
287
+ category: "organization",
288
+ level: "S",
289
+ }),
290
+ },
291
+ {
292
+ category: "organization",
293
+ trigger: (fs) => fs.some((f) => /\b(search|finds?)\b/i.test(f.name)),
294
+ generate: (app) => ({
295
+ id: "smart_search",
296
+ name: "Smart Search",
297
+ description: `Search across all ${app} content with pattern matching`,
298
+ category: "organization",
299
+ level: "B",
300
+ }),
301
+ },
302
+ {
303
+ category: "intelligence",
304
+ trigger: () => true, // Always available
305
+ generate: (app) => ({
306
+ id: "summarize_all",
307
+ name: "Summarize",
308
+ description: `Read and summarize all ${app} content`,
309
+ category: "intelligence",
310
+ level: "S",
311
+ }),
312
+ },
313
+ {
314
+ category: "intelligence",
315
+ trigger: (fs) => fs.some((f) => /\b(duplicates?|similar)\b/i.test(f.name)),
316
+ generate: (app) => ({
317
+ id: "find_duplicates",
318
+ name: "Find Duplicates",
319
+ description: `Identify duplicate or near-duplicate ${app} items`,
320
+ category: "intelligence",
321
+ level: "S",
322
+ }),
323
+ },
324
+ {
325
+ category: "cross_app",
326
+ trigger: (fs) => fs.some((f) => /\b(shares?|exports?|sends?)\b/i.test(f.name)),
327
+ generate: (app) => ({
328
+ id: "cross_app_export",
329
+ name: "Cross-App Export",
330
+ description: `Export ${app} content to other apps automatically`,
331
+ category: "cross_app",
332
+ level: "S",
333
+ }),
334
+ },
335
+ {
336
+ category: "cross_app",
337
+ trigger: (fs) => fs.some((f) => /\bimports?\b/i.test(f.name)),
338
+ generate: (app) => ({
339
+ id: "cross_app_import",
340
+ name: "Cross-App Import",
341
+ description: `Import content from other apps into ${app}`,
342
+ category: "cross_app",
343
+ level: "S",
344
+ }),
345
+ },
346
+ {
347
+ category: "monitoring",
348
+ trigger: () => true, // Always available
349
+ generate: (app) => ({
350
+ id: "change_monitor",
351
+ name: "Change Monitor",
352
+ description: `Monitor ${app} for changes and notify`,
353
+ category: "monitoring",
354
+ level: "SSS",
355
+ }),
356
+ },
357
+ ];
358
+ export function generateValueAddFeatures(appName, websiteFeatures) {
359
+ const results = [];
360
+ for (const rule of VALUE_ADD_RULES) {
361
+ if (rule.trigger(websiteFeatures)) {
362
+ results.push(rule.generate(appName));
363
+ }
364
+ }
365
+ return results;
366
+ }
@@ -95,6 +95,23 @@ export class ReferenceMerger {
95
95
  const filePath = this.save(ref);
96
96
  return { filePath, added };
97
97
  }
98
+ /**
99
+ * Merge website-extracted features into the reference file.
100
+ */
101
+ mergeWebsiteFeatures(result, bundleId, appName) {
102
+ const ref = this.loadOrCreate(bundleId, appName);
103
+ const existing = ref.websiteFeatures;
104
+ const existingIds = new Set((existing ?? []).map((f) => f.id));
105
+ const newFeatures = result.websiteFeatures.filter((f) => !existingIds.has(f.id));
106
+ ref.websiteFeatures = [...(existing ?? []), ...newFeatures];
107
+ // Merge value-add features by id (don't overwrite existing)
108
+ const existingVA = ref.valueAddFeatures;
109
+ const existingVAIds = new Set((existingVA ?? []).map((f) => f.id));
110
+ const newVA = result.valueAddFeatures.filter((f) => !existingVAIds.has(f.id));
111
+ ref.valueAddFeatures = [...(existingVA ?? []), ...newVA];
112
+ const filePath = this.save(ref);
113
+ return { filePath, added: newFeatures.length };
114
+ }
98
115
  /**
99
116
  * Merge errors/solutions into reference.
100
117
  */
@@ -50,7 +50,7 @@ export function seedErrorsFromPlaybooks(playbooksDir) {
50
50
  for (const pb of playbooks) {
51
51
  const platform = pb.platform ?? pb.id ?? "unknown";
52
52
  // Extract from errors[]
53
- if (pb.errors) {
53
+ if (pb.errors && Array.isArray(pb.errors)) {
54
54
  for (const err of pb.errors) {
55
55
  const key = `${platform}::${err.error}`;
56
56
  if (seen.has(key))
@@ -20,6 +20,7 @@ const STEP_DELAY_MS = 300;
20
20
  export class PlaybookEngine {
21
21
  runtime;
22
22
  cdpConnect;
23
+ appleScriptRunner;
23
24
  /** Enable observer-based popup checks before each step */
24
25
  popupCheckEnabled = false;
25
26
  constructor(runtime) {
@@ -33,6 +34,10 @@ export class PlaybookEngine {
33
34
  setCDPConnect(factory) {
34
35
  this.cdpConnect = factory;
35
36
  }
37
+ /** Set AppleScript runner for applescript steps. Runner should execute the script and return stdout. */
38
+ setAppleScriptRunner(runner) {
39
+ this.appleScriptRunner = runner;
40
+ }
36
41
  /**
37
42
  * Execute a playbook against a live session.
38
43
  * Returns result with success/failure and which step broke.
@@ -284,6 +289,14 @@ export class PlaybookEngine {
284
289
  await client.close();
285
290
  }
286
291
  }
292
+ case "applescript": {
293
+ if (!step.script)
294
+ throw new Error("applescript step missing script");
295
+ if (!this.appleScriptRunner)
296
+ throw new Error("applescript requires runner — call setAppleScriptRunner() first");
297
+ const result = await this.appleScriptRunner(step.script);
298
+ return `applescript: ${result.substring(0, 200)}`;
299
+ }
287
300
  default:
288
301
  throw new Error(`Unknown action: ${step.action}`);
289
302
  }
@@ -312,6 +325,8 @@ export class PlaybookEngine {
312
325
  result.verify = sub(result.verify);
313
326
  if (result.menuPath)
314
327
  result.menuPath = result.menuPath.map(sub);
328
+ if (result.script)
329
+ result.script = sub(result.script);
315
330
  return result;
316
331
  }
317
332
  /**