Desktop app that records your on-screen work session and uses the GitHub Copilot SDK to reconstruct it as an intent + ordered steps, then builds a reusable Skill or Automation for Microsoft Autopilots like Scout, Microsoft Copilot Cowork, or Copilot Studio.
TypeScript agent-skillsai-agentsautomationcopilotcopilot-clicopilot-coworkcopilot-studioelectronmicrosoft-scoutscreen-recording
Editable read-first plan review for skill/automation builds (#17)
adileie2b53ad6c476
diff --git a/common/automation.ts b/common/automation.tsindex 9c163da..2e63032 100644--- a/common/automation.ts+++ b/common/automation.ts@@ -189,6 +189,22 @@ export function toBuiltAutomation(});}+/** Build an {@link AutomationSubmission} directly from a (user-edited) plan. The plan+ * fully determines the bundle, so create can skip a second agent turn and honor the+ * reviewed tiles exactly. Throws if the plan has no steps (a bundle needs ≥1). */+export function planToAutomationSubmission(plan: AutomationPlan): AutomationSubmission {+ return AutomationSubmissionSchema.parse({+ name: plan.name,+ description: plan.description,+ triggerType: plan.trigger.type,+ schedule: plan.trigger.schedule,+ condition: plan.trigger.condition,+ conditionCheckInterval: plan.trigger.conditionCheckInterval,+ model: plan.model,+ steps: plan.steps,+ });+}+/** The primary time of day for a schedule — the value Scout mirrors into the* schedule's top-level `hour`/`minute`. */function primaryTime(schedule: AutomationSchedule): TimeOfDay {diff --git a/common/ipc.ts b/common/ipc.tsindex 33a5b9a..7e1b465 100644--- a/common/ipc.ts+++ b/common/ipc.ts@@ -1,4 +1,4 @@-import type { Analysis, AnalysisFeedback, Confidence } from "./analysis";+import type { Analysis, AnalysisFeedback, AnalysisStep, Confidence } from "./analysis";import type { AutomationPlan, BuiltAutomation } from "./automation";import type { BuiltSkill, SkillArchitecture, SkillPlan } from "./skill";import type { RecorderState } from "./types";@@ -61,13 +61,16 @@ export interface AnalysisFeedbackInput extends AnalysisFeedback {sessionId: string;}-/** A direct text edit to the intent/title, applied without re-running the agent. */+/** A direct edit to the analysis, applied without re-running the agent. Any subset+ * of fields may be sent; the rest are left untouched. */export interface AnalysisEditInput {sessionId: string;/** New short label; empty string clears it (list falls back to the intent). */title?: string;/** New one-sentence goal; blank/whitespace is ignored (intent can't be emptied). */intent?: string;+ /** The full, user-edited ordered steps; replaces the current steps when present. */+ steps?: AnalysisStep[];}/* --- Skill Builder -------------------------------------------------------- */@@ -274,8 +277,12 @@ export interface SkillRecorderApi {* revise the current plan in the same multi-turn conversation.*/buildSkill(input: SkillBuildInput): Promise<SkillPlanResult>;- /** Finalize the proposed skill and export its SKILL.md into the target agent. */- createSkill(sessionId: string): Promise<SkillCreateResult>;+ /**+ * Finalize the (user-edited) skill plan and export its SKILL.md into the target+ * agent. The edited plan the user sees is authoritative — the body is written+ * from exactly these inputs and steps.+ */+ createSkill(sessionId: string, plan: SkillPlan): Promise<SkillCreateResult>;/** Load a previously built skill for a session, if any. */getSkill(sessionId: string): Promise<BuiltSkill | null>;/** Abort an in-flight build. */@@ -289,8 +296,9 @@ export interface SkillRecorderApi {* to revise the current plan in the same multi-turn conversation.*/buildAutomation(input: AutomationBuildInput): Promise<AutomationPlanResult>;- /** Finalize the proposed automation and export its importable bundle. */- createAutomation(sessionId: string): Promise<AutomationCreateResult>;+ /** Finalize the (user-edited) automation plan and export its importable bundle.+ * The edited plan is authoritative — the bundle is built from it verbatim. */+ createAutomation(sessionId: string, plan: AutomationPlan): Promise<AutomationCreateResult>;/** Load a previously built automation for a session, if any. */getAutomation(sessionId: string): Promise<BuiltAutomation | null>;/** Abort an in-flight automation build. */diff --git a/common/skill.ts b/common/skill.tsindex aa47984..65aa9db 100644--- a/common/skill.ts+++ b/common/skill.ts@@ -85,39 +85,67 @@ export const TARGETS: readonly BuildTarget[] = [] as const;/**- * Where a skill's input comes from at run time. Kept deliberately small:- * - **ask** — the skill asks the user for it when it runs (a path, URL, value).- * - **discover** — the agent finds it on the local OS with native file tools- * (e.g. "the most recent *.csv in ~/Downloads") instead of asking.- * - **constant** — a genuinely fixed value baked into the skill (e.g. one URL).+ * Where a skill's input comes from at run time — a small spectrum of "known now /+ * known at run time / found by the agent":+ * - **fixed** — a genuinely constant value baked into the skill: a canonical URL or+ * a specific file path that is the SAME on every run.+ * - **provided** — the skill asks the user for it when it runs (a path, URL, value).+ * - **locate** — the agent finds it on the device with native file tools (e.g. "the+ * most recent *.csv in ~/Downloads") because it varies run-to-run.*/-export const SkillInputSource = z.enum(["ask", "discover", "constant"]);+export const SkillInputSource = z.enum(["fixed", "provided", "locate"]);export type SkillInputSource = z.infer<typeof SkillInputSource>;+/** Source values from earlier builds (`ask/discover/constant`), mapped to current names. */+const LEGACY_INPUT_SOURCE: Record<string, SkillInputSource> = {+ ask: "provided",+ discover: "locate",+ constant: "fixed",+};++/** Accepts both current and legacy source strings, so older persisted plans/skills load. */+export const SkillInputSourceCompat = z.preprocess(+ (v) => (typeof v === "string" && v in LEGACY_INPUT_SOURCE ? LEGACY_INPUT_SOURCE[v] : v),+ SkillInputSource,+);+export const SkillInputSchema = z.object({/** Short name for the input, e.g. "records spreadsheet". */name: z.string(),/** What it is and how it's used in the task. */description: z.string().default(""),- source: SkillInputSource,+ source: SkillInputSourceCompat,/**- * Source-specific detail: the discovery instruction (for `discover`), the- * fixed value (for `constant`), or what to ask the user for (for `ask`).+ * Source-specific detail: the fixed value or path (for `fixed`), what to ask the+ * user for (for `provided`), or how to find it on the device (for `locate`).*/detail: z.string().default(""),});export type SkillInput = z.infer<typeof SkillInputSchema>;-/** One recorded action mapped to the native capability that will perform it. */-export const ToolMappingSchema = z.object({- /** What the recording showed, e.g. "Search a Teams chat". */- action: z.string(),- /** The native tool/skill chosen, e.g. "workiq_search_chats". */- tool: z.string(),- /** Why this tool (or how it replaces the UI step). */- note: z.string().default(""),-});-export type ToolMapping = z.infer<typeof ToolMappingSchema>;+/**+ * A generalized step is either a **calculation** (reads, derives, decides, or formats+ * — no external side effect) or an **action** (changes the world: submit, send, create,+ * delete). Splitting them keeps the plan honest about side effects; the actions are the+ * risky surface, and destructive/sending ones set {@link PlanStep.pausesForConfirmation}.+ */+export const PlanStepKind = z.enum(["calculation", "action"]);+export type PlanStepKind = z.infer<typeof PlanStepKind>;++export const PlanStepSchema = z.preprocess(+ // Earlier plans stored steps as bare strings; surface those as (visible) actions.+ (v) => (typeof v === "string" ? { kind: "action", text: v } : v),+ z.object({+ kind: PlanStepKind,+ /** Imperative, generalized description of the step. */+ text: z.string(),+ /** The native tool/skill this step uses, if any (e.g. "workiq_search_chats"). */+ tool: z.string().default(""),+ /** Actions that send/create/delete should pause for the user's OK before running. */+ pausesForConfirmation: z.boolean().default(false),+ }),+);+export type PlanStep = z.infer<typeof PlanStepSchema>;/*** The agent's proposed plan, shown to the user before any skill is written.@@ -137,9 +165,8 @@ export const SkillPlanSchema = z.object({/** How the recorded specifics are generalized (the loop/collection insight). */generalization: z.string().default(""),inputs: z.array(SkillInputSchema).default([]),- toolMapping: z.array(ToolMappingSchema).default([]),- /** The generalized procedure, as ordered plain-language steps. */- steps: z.array(z.string()).default([]),+ /** The generalized procedure as ordered, typed steps (calculations + actions). */+ steps: z.array(PlanStepSchema).default([]),/** Proposed `allowed-tools` frontmatter patterns, e.g. "Bash(git *)". */allowedTools: z.array(z.string()).default([]),});diff --git a/electron/automationbuilder/builder.ts b/electron/automationbuilder/builder.tsindex 88d3d75..3f6c20c 100644--- a/electron/automationbuilder/builder.ts+++ b/electron/automationbuilder/builder.ts@@ -5,7 +5,9 @@ import path from "node:path";import { approveAll, type CopilotSession } from "@github/copilot-sdk";import {+ AutomationPlanSchema,BuiltAutomationSchema,+ planToAutomationSubmission,renderAutomationJson,toBuiltAutomation,type AutomationPlan,@@ -32,10 +34,6 @@ const KICKOFF_PROMPT ="propose_automation_plan with how you'll generalize this task, a sensible default schedule, and the " +"generalized prompt-steps. Stop after propose_automation_plan so the user can review it.";-const CREATE_PROMPT =- "The user approved the plan. Now call submit_automation with the final name, description, trigger " +- "(triggerType + schedule), and the generalized ordered prompt-steps.";-const msg = (err: unknown) => (err instanceof Error ? err.message : String(err));/** Root folder automation bundles are exported into (overridable for dev/tests). */@@ -110,29 +108,29 @@ export class AutomationBuilder extends AgentBuilder<LiveBuild> {}}- /** Finalize the proposed plan into an automation bundle and export it. */- async create(sessionId: string): Promise<{ automation: BuiltAutomation; path: string }> {+ /** Finalize the user-edited plan into an automation bundle and export it. The plan+ * fully determines the bundle (trigger + ordered prompt-steps), so this builds it+ * directly — no extra agent turn — and the export matches the reviewed tiles exactly. */+ async create(sessionId: string, editedPlan?: AutomationPlan): Promise<{ automation: BuiltAutomation; path: string }> {if (this.active.has(sessionId)) throw new Error("Wait for the current step to finish.");- const live = this.live.get(sessionId);- if (!live) throw new Error("Propose a plan first, then create the automation.");- if (!live.lastPlan) throw new Error("There is no proposed plan to build from yet.");+ // Prefer the user's edited plan from the review tiles; fall back to the last+ // proposed plan for older callers that don't pass one.+ const plan = editedPlan ? AutomationPlanSchema.parse(editedPlan) : this.live.get(sessionId)?.lastPlan ?? null;+ if (!plan) throw new Error("There is no plan to build from yet.");this.active.add(sessionId);try {this.emit(sessionId, "drafting", "Writing the automation…");- live.holder.submission = undefined;+ let submission: AutomationSubmission;try {- await live.copilot.sendAndWait(CREATE_PROMPT, TURN_TIMEOUT_MS);- } catch (err) {- await live.copilot.abort().catch(() => undefined);- throw new Error(`Automation build failed: ${msg(err)}`);+ submission = planToAutomationSubmission(plan);+ } catch {+ throw new Error("Add at least one step before you create the automation.");}- const submission = live.holder.submission;- if (!submission) throw new Error("The agent finished without submitting an automation.");- const built = toBuiltAutomation(sessionId, live.architecture, submission, live.lastPlan);+ const built = toBuiltAutomation(sessionId, plan.architecture, submission, plan);const exportPath = this.exportAutomation(built);const finalAutomation: BuiltAutomation = { ...built, exportedPath: exportPath, exportedAt: Date.now() };- this.persist(live.sessionDir, finalAutomation);+ this.persist(sessionDir(sessionId), finalAutomation);this.emit(sessionId, "done", `Automation exported to ${exportPath}`);return { automation: finalAutomation, path: exportPath };} finally {diff --git a/electron/automationbuilder/instructions.ts b/electron/automationbuilder/instructions.tsindex 2bbc0e3..a6e0909 100644--- a/electron/automationbuilder/instructions.ts+++ b/electron/automationbuilder/instructions.ts@@ -72,8 +72,8 @@ Each step has a short **label** and a **prompt** — an imperative instruction tno API and no CLI). Write shell commands for the device OS (zsh/bash on macOS,PowerShell on Windows).- **Resolve inputs inside the prompt.** An automation runs unattended and can't stop to ask- a human, so tell the agent to DISCOVER inputs on the local OS / read them from M365, or- bake in a genuinely fixed value. Avoid "ask the user" inputs.+ a human, so tell the agent to LOCATE inputs on the device / read them from M365, or use a+ genuinely fixed value. Avoid inputs the user must provide at run time.- **No surprises.** Keep destructive or send/create actions explicit in their step so theuser sees them in the plan. The automation must do exactly what its description says.- Keep it to a few ordered steps (roughly 2–6); each prompt tight and imperative.@@ -81,7 +81,7 @@ Each step has a short **label** and a **prompt** — an imperative instruction t## Inputs (informational)List the things the task needs from outside in the plan's \`inputs\` with a likely source-(discover / constant / — avoid ask). These are for the user's awareness; the automation+(locate / fixed — avoid provided). These are for the user's awareness; the automationresolves them inside the step prompts.## Your toolsdiff --git a/electron/automationbuilder/scout-automation-catalog.ts b/electron/automationbuilder/scout-automation-catalog.tsindex 7744eb1..1275dd6 100644--- a/electron/automationbuilder/scout-automation-catalog.ts+++ b/electron/automationbuilder/scout-automation-catalog.ts@@ -42,9 +42,9 @@ in plain language.- Write prompts that GENERALIZE: if the recording acted on N specific items, the prompt tellsthe agent to handle every item of that kind, not the specific examples recorded.- Prompts should prefer Scout's native tools (below) over UI replay, and say briefly why.-- Resolve inputs inside the prompts: tell the agent to discover them on the local OS, read+- Resolve inputs inside the prompts: tell the agent to locate them on the device, readthem from M365, or (only if unavoidable) that they're fixed values. An unattended automation- can't stop to ask a human, so avoid "ask the user" inputs — discover or fix them instead.+ can't stop to ask a human, so avoid user-provided inputs — locate or fix them instead.- Keep destructive or send/create actions explicit so the user sees them in the plan.${SCOUT_NATIVE_CAPABILITIES}diff --git a/electron/automationbuilder/tools.ts b/electron/automationbuilder/tools.tsindex dcd0951..26470bf 100644--- a/electron/automationbuilder/tools.ts+++ b/electron/automationbuilder/tools.ts@@ -154,12 +154,12 @@ export function createAutomationBuilderTools(ctx: AutomationToolContext): Tool[]description: { type: "string" },source: {type: "string",- enum: ["ask", "discover", "constant"],- description: "Prefer discover/constant — an automation runs unattended and can't ask.",+ enum: ["fixed", "provided", "locate"],+ description: "Prefer locate/fixed — an automation runs unattended and can't ask the user.",},detail: {type: "string",- description: "For discover: how to find it. For constant: the value.",+ description: "For fixed: the value/path. For locate: how to find it.",},},required: ["name", "source"],diff --git a/electron/describer/describer.ts b/electron/describer/describer.tsindex de96eff..37f1cc1 100644--- a/electron/describer/describer.ts+++ b/electron/describer/describer.ts@@ -121,17 +121,22 @@ export class Describer {}/**- * Apply a direct text edit to the title and/or intent — a user correction, NOT a- * re-analysis. Steps and evidence are untouched; the agent is not invoked. Blank- * intent is ignored (a session always keeps a goal); the title may be cleared.+ * Apply a direct edit to the analysis — a user correction, NOT a re-analysis: the+ * agent is not invoked. Any subset of {title, intent, steps} may be patched; the+ * rest are untouched. Blank intent is ignored (a session always keeps a goal); the+ * title may be cleared. The edited steps become the source of truth downstream.*/- async edit(sessionId: string, patch: { title?: string; intent?: string }): Promise<Analysis> {+ async edit(+ sessionId: string,+ patch: { title?: string; intent?: string; steps?: Analysis["steps"] },+ ): Promise<Analysis> {if (this.active.has(sessionId)) throw new Error("Wait for the current analysis to finish before editing.");const prior = loadPersistedAnalysis(sessionId);if (!prior) throw new Error("There is no analysis to edit yet.");const next: Analysis = { ...prior };if (patch.title !== undefined) next.title = patch.title.trim();if (patch.intent !== undefined && patch.intent.trim()) next.intent = patch.intent.trim();+ if (patch.steps !== undefined) next.steps = patch.steps;this.persist(sessionDir(sessionId), next);return next;}diff --git a/electron/ipc.ts b/electron/ipc.tsindex 3df6990..6a4fbe2 100644--- a/electron/ipc.ts+++ b/electron/ipc.ts@@ -15,6 +15,8 @@ import type {StartOptions,} from "../common/ipc";import { IPC } from "../common/ipc";+import type { AutomationPlan } from "../common/automation";+import type { SkillPlan } from "../common/skill";import { AutomationBuilder, loadPersistedAutomation } from "./automationbuilder/builder";import { Describer, loadPersistedAnalysis } from "./describer/describer";import { runDoctor } from "./doctor";@@ -87,6 +89,7 @@ export function registerIpc(const analysis = await describer.edit(input.sessionId, {title: input.title,intent: input.intent,+ steps: input.steps,});return { ok: true, analysis };} catch (err) {@@ -146,10 +149,10 @@ export function registerIpc(}});- ipcMain.handle(IPC.createSkill, async (_event, sessionId: string): Promise<SkillCreateResult> => {+ ipcMain.handle(IPC.createSkill, async (_event, sessionId: string, plan?: SkillPlan): Promise<SkillCreateResult> => {if (!isValidSessionId(sessionId)) return { ok: false, error: "Unknown session." };try {- const { skill, path: file } = await builder.create(sessionId);+ const { skill, path: file } = await builder.create(sessionId, plan);return { ok: true, skill, path: file };} catch (err) {const error = err instanceof Error ? err.message : String(err);@@ -189,10 +192,10 @@ export function registerIpc(},);- ipcMain.handle(IPC.createAutomation, async (_event, sessionId: string): Promise<AutomationCreateResult> => {+ ipcMain.handle(IPC.createAutomation, async (_event, sessionId: string, plan?: AutomationPlan): Promise<AutomationCreateResult> => {if (!isValidSessionId(sessionId)) return { ok: false, error: "Unknown session." };try {- const { automation, path: file } = await automationBuilder.create(sessionId);+ const { automation, path: file } = await automationBuilder.create(sessionId, plan);return { ok: true, automation, path: file };} catch (err) {const error = err instanceof Error ? err.message : String(err);diff --git a/electron/preload.cjs b/electron/preload.cjsindex 648b0d4..82e2417 100644--- a/electron/preload.cjs+++ b/electron/preload.cjs@@ -57,7 +57,7 @@ contextBridge.exposeInMainWorld("skillRecorder", {listSessions: () => ipcRenderer.invoke(IPC.listSessions),deleteSession: (sessionId) => ipcRenderer.invoke(IPC.deleteSession, sessionId),buildSkill: (input) => ipcRenderer.invoke(IPC.buildSkill, input),- createSkill: (sessionId) => ipcRenderer.invoke(IPC.createSkill, sessionId),+ createSkill: (sessionId, plan) => ipcRenderer.invoke(IPC.createSkill, sessionId, plan),getSkill: (sessionId) => ipcRenderer.invoke(IPC.getSkill, sessionId),cancelSkill: (sessionId) => ipcRenderer.invoke(IPC.cancelSkill, sessionId),revealSkill: (sessionId) => ipcRenderer.invoke(IPC.revealSkill, sessionId),@@ -67,7 +67,7 @@ contextBridge.exposeInMainWorld("skillRecorder", {return () => ipcRenderer.removeListener(IPC.skillProgress, listener);},buildAutomation: (input) => ipcRenderer.invoke(IPC.buildAutomation, input),- createAutomation: (sessionId) => ipcRenderer.invoke(IPC.createAutomation, sessionId),+ createAutomation: (sessionId, plan) => ipcRenderer.invoke(IPC.createAutomation, sessionId, plan),getAutomation: (sessionId) => ipcRenderer.invoke(IPC.getAutomation, sessionId),cancelAutomation: (sessionId) => ipcRenderer.invoke(IPC.cancelAutomation, sessionId),revealAutomation: (sessionId) => ipcRenderer.invoke(IPC.revealAutomation, sessionId),diff --git a/electron/skillbuilder/builder.ts b/electron/skillbuilder/builder.tsindex f692c9f..93192c5 100644--- a/electron/skillbuilder/builder.ts+++ b/electron/skillbuilder/builder.ts@@ -7,6 +7,7 @@ import { approveAll, type CopilotSession } from "@github/copilot-sdk";import {BuiltSkillSchema,renderSkillMarkdown,+ SkillPlanSchema,slugifySkillName,toBuiltSkill,type BuiltSkill,@@ -30,12 +31,15 @@ const TURN_TIMEOUT_MS = 180_000;const KICKOFF_PROMPT ="Read get_analysis (and get_timeline where the tool mapping needs evidence), then call " +- "propose_plan with how you'll generalize this task, its inputs, and the native tools you'll use. " ++ "propose_plan with how you'll generalize this task, its inputs (fixed / provided / locate), and its " ++ "ordered calculation and action steps (each with the native tool it uses). " +"Stop after propose_plan so the user can review it.";const CREATE_PROMPT =- "The user approved the plan. Now call submit_skill with the final SKILL.md name, description, " +- "allowed-tools, and a generalized, native-tool-first instructions body.";+ "The user reviewed and edited the plan below. Build the SKILL.md from EXACTLY this plan — do not " ++ "add, drop, reorder, or rename its inputs or steps. Call submit_skill with a generalized, " ++ "native-tool-first instructions body that follows these inputs and steps faithfully (the name and " ++ "description are already decided — you may echo them).";const msg = (err: unknown) => (err instanceof Error ? err.message : String(err));@@ -111,26 +115,44 @@ export class SkillBuilder extends AgentBuilder<LiveBuild> {}}- /** Finalize the proposed plan into a SKILL.md and export it. */- async create(sessionId: string): Promise<{ skill: BuiltSkill; path: string }> {+ /** Finalize the user-edited plan into a SKILL.md and export it. The edited plan is+ * authoritative: its name/description/inputs/steps are used verbatim and only the+ * markdown body is written by the agent. */+ async create(sessionId: string, editedPlan?: SkillPlan): Promise<{ skill: BuiltSkill; path: string }> {if (this.active.has(sessionId)) throw new Error("Wait for the current step to finish.");- const live = this.live.get(sessionId);- if (!live) throw new Error("Propose a plan first, then create the skill.");- if (!live.lastPlan) throw new Error("There is no proposed plan to build from yet.");+ let held = this.live.get(sessionId);+ // Prefer the user's edited plan from the review tiles; fall back to the last+ // proposed plan for older callers that don't pass one.+ const plan = editedPlan ? SkillPlanSchema.parse(editedPlan) : held?.lastPlan ?? null;+ if (!plan) throw new Error("There is no plan to build from yet.");+ // The pool may have evicted the live conversation while the user edited the plan;+ // recreate one so export always works.+ if (!held) held = await this.createLive(sessionId, plan.architecture);+ const live = held;+ live.lastPlan = plan;this.active.add(sessionId);try {this.emit(sessionId, "drafting", "Writing the skill…");live.holder.submission = undefined;try {- await live.copilot.sendAndWait(CREATE_PROMPT, TURN_TIMEOUT_MS);+ await live.copilot.sendAndWait(`${CREATE_PROMPT}\n\n${renderPlanForPrompt(plan)}`, TURN_TIMEOUT_MS);} catch (err) {await live.copilot.abort().catch(() => undefined);throw new Error(`Skill build failed: ${msg(err)}`);}- const submission = live.holder.submission;+ const submission = live.holder.submission as SkillSubmission | undefined;if (!submission) throw new Error("The agent finished without submitting a skill.");- const built = toBuiltSkill(sessionId, live.architecture, submission, live.lastPlan);+ // The frontmatter comes from the edited plan (authoritative); only the body is+ // the agent's generated prose. allowed-tools may be tightened by the agent to the+ // final steps, but never emptied below what the plan declared.+ const finalSubmission: SkillSubmission = {+ name: plan.name,+ description: plan.description,+ allowedTools: submission.allowedTools.length ? submission.allowedTools : plan.allowedTools,+ body: submission.body,+ };+ const built = toBuiltSkill(sessionId, plan.architecture, finalSubmission, plan);const exportPath = this.exportSkill(built);const finalSkill: BuiltSkill = { ...built, exportedPath: exportPath, exportedAt: Date.now() };this.persist(live.sessionDir, finalSkill);@@ -242,6 +264,27 @@ export class SkillBuilder extends AgentBuilder<LiveBuild> {}}+/** Render the final, user-edited plan into a compact spec the create turn builds from. */+function renderPlanForPrompt(plan: SkillPlan): string {+ const lines = [`Title: ${plan.title}`, `Name: ${plan.name}`, `Description: ${plan.description}`];+ if (plan.generalization) lines.push(`Generalization: ${plan.generalization}`);+ if (plan.inputs.length) {+ lines.push("", "Inputs:");+ for (const i of plan.inputs) lines.push(`- ${i.name} [${i.source}]${i.detail ? `: ${i.detail}` : ""}`);+ }+ if (plan.steps.length) {+ lines.push("", "Steps (in order):");+ plan.steps.forEach((s, idx) => {+ const bits = [`${idx + 1}. (${s.kind}) ${s.text}`];+ if (s.tool) bits.push(`[tool: ${s.tool}]`);+ if (s.pausesForConfirmation) bits.push("[pause for confirmation]");+ lines.push(bits.join(" "));+ });+ }+ if (plan.allowedTools.length) lines.push("", `allowed-tools: ${plan.allowedTools.join(", ")}`);+ return lines.join("\n");+}+function renderRefinePrompt(feedback: string, prior: SkillPlan | null): string {const lines = ["The user reviewed your proposed plan and wants changes. Revise the plan and call",diff --git a/electron/skillbuilder/instructions.ts b/electron/skillbuilder/instructions.tsindex 81cef30..c4b1537 100644--- a/electron/skillbuilder/instructions.ts+++ b/electron/skillbuilder/instructions.ts@@ -5,8 +5,9 @@* the chosen agent, preferring that agent's native built-in tools over UI replay.** The flow is two-phase so the user stays in control:- * 1. **propose_plan** — infer the generalization + inputs + native-tool mapping- * and show it. The user may refine it in natural language (more turns).+ * 1. **propose_plan** — infer the generalization, the inputs, and the ordered+ * calculation/action steps (each with its native tool), and show it. The user+ * may refine it in natural language (more turns).* 2. **submit_skill** — only after the user approves, write the final SKILL.md.*/export const SKILL_BUILDER_INSTRUCTIONS = `@@ -43,12 +44,16 @@ native capabilities are described in the **catalogue below**.For each thing the task needs from outside (a file, a URL, a value), pick ONE sourceand record it in the plan's \`inputs\`. Use the fewest inputs that make it runnable.Sources (only these):-- **ask** — the skill asks the user for it at run time (a path, URL, or value).-- **discover** — the agent FINDS it on the local OS with native file tools instead- of asking, e.g. "read the most recent *.csv in ~/Downloads". Prefer this when the- recording clearly points at a discoverable local file.-- **constant** — bake in a genuinely fixed value (e.g. one specific URL the task- always uses).+- **fixed** — a value that is the SAME on every run, baked into the skill: a canonical+ URL, or a specific file path that never moves. Put the value/path in \`detail\`.+- **provided** — the skill asks the user for it at run time (a path, URL, or value).+- **locate** — the agent FINDS it on the device with native file tools, e.g. "read the+ most recent *.csv in ~/Downloads". Use this when the target varies run-to-run.++The rule: if the exact value/path is specified and never changes, it's **fixed**; if it+varies from run to run, it's **provided** or **locate**. Don't mark a file **fixed** just+because the recording used one path — if next run's file will differ, it's **locate** (or+**provided**) so the skill doesn't over-pin to one machine.Infer the most likely source for each input yourself and show it in the plan; theuser can override any of them in plain language.@@ -64,11 +69,24 @@ user can override any of them in plain language.UI-only steps (a web app with no API and no CLI). Gate the shell with \`allowed-tools\`(e.g. \`Bash(gh *)\`) and write commands for the device OS (zsh/bash on macOS,PowerShell on Windows).-- Record your choices in the plan's \`toolMapping\`, and set \`allowedTools\` to the+- Record the chosen tool on each step (the step's \`tool\`), and set \`allowedTools\` to thepatterns the skill actually needs.- Rely ONLY on the built-in tools and skills in the catalogue — never on a skill theuser might have added.+## Steps: separate calculations from actions++Break the generalized procedure into ordered **steps**, each tagged \`kind\`:+- **calculation** — reads, derives, filters, decides, or formats. No external side effect+ (e.g. "read the sheet", "keep the rows still open", "compute the total").+- **action** — changes the world: submits a form, sends a message, creates/edits/deletes a+ file or record, posts, pays. These are the risky surface — keep them explicit.++Put the native tool each step uses in its \`tool\`. For any action that sends, creates, or+deletes on the user's behalf — or is otherwise destructive — set \`pausesForConfirmation:+true\` so the skill checks with the user first. Order matters: interleave calculations and+actions in the real sequence the task runs.+## Write a good SKILL.md (authoring principles)You're authoring a skill another agent will load later, so write it the way a skill@@ -96,8 +114,10 @@ should be written, not as a transcript of this one recording:- **get_analysis** — the approved intent + ordered steps you're generalizing. Read first.- **get_timeline** — the deterministic timeline (apps, URLs, hosts, commands, clipboardcounts) behind those steps. Use it to ground the native-tool mapping in real evidence.-- **propose_plan({ name, title, description, summary, generalization, inputs, toolMapping,- steps, allowedTools })** — your reviewable plan. Call once per turn, then stop.+- **propose_plan({ name, title, description, summary, generalization, inputs, steps,+ allowedTools })** — your reviewable plan. Each input has a \`source\` (fixed / provided /+ locate); each step has a \`kind\` (calculation / action), its \`tool\`, and an optional+ \`pausesForConfirmation\`. Call once per turn, then stop.- **submit_skill({ name, description, allowedTools, body })** — the final skill. \`body\`is the SKILL.md instructions (imperative, generalized, native-tool-first). Call thisonly after the user approves the plan.diff --git a/electron/skillbuilder/scout-catalog.ts b/electron/skillbuilder/scout-catalog.tsindex 07c702d..ca75b9b 100644--- a/electron/skillbuilder/scout-catalog.ts+++ b/electron/skillbuilder/scout-catalog.ts@@ -110,7 +110,7 @@ ${SCOUT_NATIVE_CAPABILITIES}- Write a GENERALIZED procedure: if the recording acted on N specific items, the bodyloops over ALL items of that kind, not the specific examples that were recorded.-- Resolve each input via the plan (ask the user / discover on the local OS / constant).+- Resolve each input via the plan (a fixed value / the user provides it / the agent locates it on the device).- Prefer the native tools above; only use the browser for genuine UI-only steps.- Keep it concise and imperative. Include a short "When to use" and the ordered steps.`.trim();diff --git a/electron/skillbuilder/tools.ts b/electron/skillbuilder/tools.tsindex 5b7ea15..76114df 100644--- a/electron/skillbuilder/tools.ts+++ b/electron/skillbuilder/tools.ts@@ -33,7 +33,7 @@ export function createSkillBuilderTools(ctx: SkillToolContext): Tool[] {const proposePlan: Tool = {name: "propose_plan",description:- "Propose your reviewable plan for the skill: how you'll generalize the task, the inputs it needs and where each comes from, the native tools you'll use, the generalized steps, and the allowed-tools. Call this once per turn, then STOP so the user can review or refine it. Do NOT write the skill body yet.",+ "Propose your reviewable plan for the skill: how you'll generalize the task, the inputs it needs and where each comes from (fixed / provided / locate), the ordered steps tagged as calculations or actions (each with the native tool it uses), and the allowed-tools. Call this once per turn, then STOP so the user can review or refine it. Do NOT write the skill body yet.",parameters: {type: "object",properties: {@@ -58,37 +58,51 @@ export function createSkillBuilderTools(ctx: SkillToolContext): Tool[] {description: { type: "string" },source: {type: "string",- enum: ["ask", "discover", "constant"],- description: "ask the user / discover on the local OS / a baked-in constant.",+ enum: ["fixed", "provided", "locate"],+ description:+ "fixed = a URL/path/value that's the SAME every run; provided = ask the user at run time; locate = the agent finds it on the device (varies run-to-run).",},detail: {type: "string",description:- "For discover: how to find it. For constant: the value. For ask: what to ask for.",+ "For fixed: the value/path. For provided: what to ask for. For locate: how to find it.",},},required: ["name", "source"],additionalProperties: false,},},- toolMapping: {+ steps: {type: "array",+ description:+ "The generalized procedure as ordered, typed steps. Tag each as a calculation (reads/derives/decides/formats — no external side effect) or an action (changes the world: submit/send/create/delete).",items: {type: "object",properties: {- action: { type: "string", description: "What the recording showed." },- tool: { type: "string", description: "The native tool/skill chosen." },- note: { type: "string" },+ kind: {+ type: "string",+ enum: ["calculation", "action"],+ description: "calculation = no external effect; action = a side effect.",+ },+ text: {+ type: "string",+ description: "Imperative, generalized description of the step.",+ },+ tool: {+ type: "string",+ description:+ "The native tool/skill this step uses, e.g. \"workiq_search_chats\" or \"Bash(gh *)\".",+ },+ pausesForConfirmation: {+ type: "boolean",+ description:+ "For actions that send/create/delete: pause for the user's OK before running.",+ },},- required: ["action", "tool"],+ required: ["kind", "text"],additionalProperties: false,},},- steps: {- type: "array",- items: { type: "string" },- description: "The generalized procedure as ordered plain-language steps.",- },allowedTools: {type: "array",items: { type: "string" },diff --git a/evals/README.md b/evals/README.mdindex 51e4bae..3b715f3 100644--- a/evals/README.md+++ b/evals/README.md@@ -182,6 +182,40 @@ all `gh` — over the browser, platform-aware for zsh/bash vs PowerShell). Whenadd a describer scenario, add the matching builder scenario so the pair stays inlockstep.+## Skill builder evals (`evals/skillbuilder/`)++A sibling of the automation builder harness that guards the **`SkillBuilder`** —+the stage that turns an approved analysis into a reusable `SKILL.md` plan. Where+the automation harness scores free-text step prompts for native-tool choice, this+one scores the richer **plan structure** the builder now proposes.++```bash+npm run eval:skill # all skill scenarios+npm run eval:skill -- --only=price-tracker-skill+npm run eval:skill -- --keep # print the temp sessions dir+npm run eval:skill -- --model=<model-id> # override the builder model+```++Both builder harnesses share the same seeding (`evals/lib/seed.ts`): a fixed,+approved `Analysis` + a minimal `bundle.json` per scenario, so a failure points at+the builder, not the describer.++**Rubric** (`score.ts`) — beyond the `mustUseAny` / `forbidden` native-tool checks,+each scenario asserts the shape of the proposed `SkillPlan`:++- **input sources** — `expectInputSources` requires the plan to classify at least+ one input with each listed `source` (`fixed` / `provided` / `locate`), proving the+ vocabulary is applied, not just present.+- **typed steps** — `minCalculations` / `minActions` require the procedure to be+ split into `calculation` (no side effect) and `action` (changes the world) steps.+- **confirmation** — `requiresConfirmation` requires at least one action to set+ `pausesForConfirmation`, i.e. the send/create/delete surface pauses for the user.++**Coverage.** Two scenarios: `price-tracker-skill` (a canonical page URL → **fixed**+input, `web_fetch` + the `xlsx` skill, calculations then a confirmed append) and+`github-issue-triage-skill` (the gh-vs-browser case as a skill — must use `gh`,+forbid the browser, and gate the mutating comment/label actions).+## Mock pages (`evals/mocks/`)Static, self-contained HTML fixtures matching the scenarios (`pricing.html`,diff --git a/evals/builder/run.ts b/evals/builder/run.tsindex d5c5b5c..21d77ad 100644--- a/evals/builder/run.ts+++ b/evals/builder/run.ts@@ -20,13 +20,11 @@ import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";import os from "node:os";import path from "node:path";-import { toAnalysis, type Analysis } from "../../common/analysis";-import { SessionBundleSchema, type SessionBundle } from "../../common/bundle";import { AutomationBuilder } from "../../electron/automationbuilder/builder";import type { AutomationPlan } from "../../common/automation";+import { seedScenario } from "../lib/seed";import { builderScenarios } from "./scenarios";import { scoreBuilder, type BuilderScoreResult } from "./score";-import type { BuilderScenario } from "./scenario";interface Flags {only: Set<string> | null;@@ -54,73 +52,6 @@ interface Result {score?: BuilderScoreResult;}-/** Seed the scenario's fixed approved analysis so the builder can read it. */-function seed(root: string, scenario: BuilderScenario): void {- const dir = path.join(root, scenario.id);- mkdirSync(dir, { recursive: true });- const analysis: Analysis = {- ...toAnalysis(scenario.id, 1, scenario.analysis, []),- approved: true,- approvedAt: Date.now(),- };- writeFileSync(path.join(dir, "analysis.json"), JSON.stringify(analysis, null, 2));- writeFileSync(path.join(dir, "bundle.json"), JSON.stringify(toSeedBundle(scenario), null, 2));-}--const URL_RE = /https?:\/\/\S+/g;--/**- * A minimal but schema-valid timeline for the builder's `get_timeline` tool, built- * from the fixed analysis. It carries the device **platform** (so the builder knows- * it targets macOS or Windows) and each step's app + any URLs/hosts pulled from the- * analysis evidence — the same grounding the real bundle would provide.- */-function toSeedBundle(scenario: BuilderScenario): SessionBundle {- const now = Date.now();- const steps = scenario.analysis.steps.map((s, i) => {- const urls = (s.evidence.join(" ").match(URL_RE) ?? []).map((u) => u.replace(/[)"']+$/, ""));- const hosts = [...new Set(urls.map((u) => { try { return new URL(u).host; } catch { return ""; } }).filter(Boolean))];- const clipboardCount = s.evidence.filter((e) => e.toLowerCase().startsWith("clipboard")).length;- return {- index: i,- startMs: now + i * 1000,- endMs: now + (i + 1) * 1000,- durationMs: 1000,- boundary: (i === 0 ? "start" : "app-change") as SessionBundle["steps"][number]["boundary"],- app: s.apps[0],- titles: [],- hosts,- urls,- commands: [],- clipboardCount,- markers: [],- eventSeqs: [i],- frames: [],- summary: s.title,- };- });- return SessionBundleSchema.parse({- version: 1,- session: {- id: scenario.id,- startedAt: now,- stoppedAt: now + steps.length * 1000,- durationMs: steps.length * 1000,- platform: scenario.platform,- appVersion: "eval",- },- steps,- stats: {- eventCount: steps.length,- meaningfulEventCount: steps.length,- stepCount: steps.length,- frameCount: 0,- unexplainedFrameCount: 0,- silentEventCount: 0,- },- });-}-/** The actionable text we score: the ordered step labels + prompts. */function stepsText(plan: AutomationPlan): string {return plan.steps.map((s) => `${s.label}\n${s.prompt}`).join("\n\n");@@ -158,7 +89,7 @@ async function main(): Promise<void> {const started = Date.now();const res: Result = { id: scenario.id, title: scenario.title, ok: false, durationMs: 0 };try {- seed(root, scenario);+ seedScenario(root, scenario);const plan = await builder.build({ sessionId: scenario.id, architecture: scenario.architecture });res.plan = plan;res.score = scoreBuilder(stepsText(plan), scenario.rubric);diff --git a/evals/lib/seed.ts b/evals/lib/seed.tsnew file mode 100644index 0000000..d03857f--- /dev/null+++ b/evals/lib/seed.ts@@ -0,0 +1,90 @@+// Shared seeding for the builder evals (automation + skill).+//+// Both builder harnesses isolate the FINAL stage by freezing the describer's+// output: they write a fixed, approved `analysis.json` (plus a minimal but+// schema-valid `bundle.json`) into a temp sessions dir, then run the real builder+// against it. This module is the single source of that seed logic so the two+// harnesses stay in lockstep (see evals/README.md).++import { mkdirSync, writeFileSync } from "node:fs";+import path from "node:path";++import { toAnalysis, type Analysis, type AnalysisSubmission } from "../../common/analysis";+import { SessionBundleSchema, type SessionBundle } from "../../common/bundle";++/** The minimum a scenario must supply to be seeded to disk. */+export interface SeedInput {+ /** Slug used as the session id (a single path segment under the sessions root). */+ id: string;+ /** The device OS the built artifact will run on (drives the seeded bundle's platform). */+ platform: NodeJS.Platform;+ /** The approved analysis fed to the builder, exactly as the describer would emit it. */+ analysis: AnalysisSubmission;+}++/** Seed the scenario's fixed approved analysis + timeline so the builder can read them. */+export function seedScenario(root: string, scenario: SeedInput): void {+ const dir = path.join(root, scenario.id);+ mkdirSync(dir, { recursive: true });+ const analysis: Analysis = {+ ...toAnalysis(scenario.id, 1, scenario.analysis, []),+ approved: true,+ approvedAt: Date.now(),+ };+ writeFileSync(path.join(dir, "analysis.json"), JSON.stringify(analysis, null, 2));+ writeFileSync(path.join(dir, "bundle.json"), JSON.stringify(toSeedBundle(scenario), null, 2));+}++const URL_RE = /https?:\/\/\S+/g;++/**+ * A minimal but schema-valid timeline for the builder's `get_timeline` tool, built+ * from the fixed analysis. It carries the device **platform** (so the builder knows+ * it targets macOS or Windows) and each step's app + any URLs/hosts pulled from the+ * analysis evidence — the same grounding the real bundle would provide.+ */+export function toSeedBundle(scenario: SeedInput): SessionBundle {+ const now = Date.now();+ const steps = scenario.analysis.steps.map((s, i) => {+ const urls = (s.evidence.join(" ").match(URL_RE) ?? []).map((u) => u.replace(/[)"']+$/, ""));+ const hosts = [...new Set(urls.map((u) => { try { return new URL(u).host; } catch { return ""; } }).filter(Boolean))];+ const clipboardCount = s.evidence.filter((e) => e.toLowerCase().startsWith("clipboard")).length;+ return {+ index: i,+ startMs: now + i * 1000,+ endMs: now + (i + 1) * 1000,+ durationMs: 1000,+ boundary: (i === 0 ? "start" : "app-change") as SessionBundle["steps"][number]["boundary"],+ app: s.apps[0],+ titles: [],+ hosts,+ urls,+ commands: [],+ clipboardCount,+ markers: [],+ eventSeqs: [i],+ frames: [],+ summary: s.title,+ };+ });+ return SessionBundleSchema.parse({+ version: 1,+ session: {+ id: scenario.id,+ startedAt: now,+ stoppedAt: now + steps.length * 1000,+ durationMs: steps.length * 1000,+ platform: scenario.platform,+ appVersion: "eval",+ },+ steps,+ stats: {+ eventCount: steps.length,+ meaningfulEventCount: steps.length,+ stepCount: steps.length,+ frameCount: 0,+ unexplainedFrameCount: 0,+ silentEventCount: 0,+ },+ });+}diff --git a/evals/skillbuilder/run.ts b/evals/skillbuilder/run.tsnew file mode 100644index 0000000..1cc3b64--- /dev/null+++ b/evals/skillbuilder/run.ts@@ -0,0 +1,143 @@+// Skill builder eval harness: runs the real SkillBuilder against each fixed+// scenario and scores the PROPOSED PLAN's shape — the richer contract the builder+// now emits: typed inputs (each with a `source`), and an ordered list of typed+// steps (calculation vs action, each with its native tool and an optional+// confirmation pause).+//+// For every scenario it seeds the scenario's FIXED approved analysis (analysis.json)+// + a minimal timeline (bundle.json) into a temp sessions root, runs the real+// SkillBuilder.build (one turn → propose_plan), then scores the plan. No describer,+// no capture — this isolates the builder, the part with the variance we measure.+//+// Run:+// node --experimental-transform-types --import ./evals/register.mjs evals/skillbuilder/run.ts [flags]+// Flags:+// --only=slug,slug run a subset of scenarios+// --keep print the temp sessions dir (artifacts kept for inspection)+// --model=<id> override the builder model++import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";+import os from "node:os";+import path from "node:path";++import { SkillBuilder } from "../../electron/skillbuilder/builder";+import type { SkillPlan } from "../../common/skill";+import { seedScenario } from "../lib/seed";+import { skillScenarios } from "./scenarios";+import { scoreSkill, type SkillScoreResult } from "./score";++interface Flags {+ only: Set<string> | null;+ keep: boolean;+ model?: string;+}++function parseFlags(argv: string[]): Flags {+ const flags: Flags = { only: null, keep: false };+ for (const arg of argv) {+ if (arg.startsWith("--only=")) flags.only = new Set(arg.slice(7).split(",").map((s) => s.trim()).filter(Boolean));+ else if (arg === "--keep") flags.keep = true;+ else if (arg.startsWith("--model=")) flags.model = arg.slice(8);+ }+ return flags;+}++interface Result {+ id: string;+ title: string;+ ok: boolean;+ error?: string;+ durationMs: number;+ plan?: SkillPlan;+ score?: SkillScoreResult;+}++const bar = "─".repeat(64);++async function main(): Promise<void> {+ const flags = parseFlags(process.argv.slice(2));+ if (flags.model) process.env.SKILL_RECORDER_MODEL = flags.model;++ let root = process.env.SKILL_RECORDER_SESSIONS_DIR;+ if (!root) {+ root = mkdtempSync(path.join(os.tmpdir(), "sr-skill-evals-"));+ process.env.SKILL_RECORDER_SESSIONS_DIR = root;+ }++ const selected = skillScenarios.filter((s) => !flags.only || flags.only.has(s.id));+ if (selected.length === 0) {+ console.error("No scenarios matched", flags.only ? [...flags.only] : "");+ process.exit(2);+ }++ console.error(`\nSkill Recorder — skill builder evals`);+ console.error(`${selected.length} scenario(s) · sessions root: ${root}`);+ console.error(bar);++ const builder = new SkillBuilder((p) => {+ if (p.message) process.stderr.write(` · [${p.sessionId}] ${p.message}\n`);+ });++ const results: Result[] = [];+ for (const scenario of selected) {+ console.error(`\n▶ ${scenario.id} — ${scenario.title}`);+ const started = Date.now();+ const res: Result = { id: scenario.id, title: scenario.title, ok: false, durationMs: 0 };+ try {+ seedScenario(root, scenario);+ const plan = await builder.build({ sessionId: scenario.id, architecture: scenario.architecture });+ res.plan = plan;+ res.score = scoreSkill(plan, scenario.rubric);+ res.ok = res.score.pass;+ } catch (err) {+ res.error = err instanceof Error ? err.message : String(err);+ }+ res.durationMs = Date.now() - started;+ results.push(res);+ printResult(res);+ }++ await builder.dispose();++ const stamp = new Date().toISOString().replace(/[:.]/g, "-");+ const outFile = path.join(process.cwd(), "evals", "results", `skill-${stamp}.json`);+ mkdirSync(path.dirname(outFile), { recursive: true });+ writeFileSync(outFile, JSON.stringify({ at: stamp, root, results }, null, 2));++ console.error(`\n${bar}\nSummary`);+ const passed = results.filter((r) => r.ok).length;+ for (const r of results) {+ const pct = r.score ? `${Math.round(r.score.score * 100)}%` : " — ";+ const status = r.error ? "ERROR" : r.ok ? "PASS " : "FAIL ";+ console.error(` ${status} ${pct.padStart(4)} ${r.id}${r.error ? ` (${r.error})` : ""}`);+ }+ console.error(`\n ${passed}/${results.length} scenarios passed`);+ if (flags.keep) console.error(` artifacts: ${root}`);+ console.error(` results: ${path.relative(process.cwd(), outFile)}\n`);++ process.exit(passed === results.length ? 0 : 1);+}++function printResult(r: Result): void {+ if (r.error) {+ console.error(` ✗ error: ${r.error}`);+ return;+ }+ for (const inp of r.plan?.inputs ?? []) {+ console.error(` input · ${inp.name} [${inp.source}]`);+ }+ for (const [i, s] of (r.plan?.steps ?? []).entries()) {+ const tool = s.tool ? ` {${s.tool}}` : "";+ const gate = s.pausesForConfirmation ? " ⏸ confirm" : "";+ console.error(` ${i + 1}. [${s.kind}] ${s.text}${tool}${gate}`);+ }+ console.error(` score: ${Math.round((r.score?.score ?? 0) * 100)}% · ${r.ok ? "PASS" : "FAIL"} · ${(r.durationMs / 1000).toFixed(1)}s`);+ for (const c of r.score?.checks ?? []) {+ if (!c.pass) console.error(` ✗ ${c.name}${c.detail ? ` — ${c.detail}` : ""}`);+ }+}++main().catch((err) => {+ console.error("Harness crashed:", err);+ process.exit(3);+});diff --git a/evals/skillbuilder/scenario.ts b/evals/skillbuilder/scenario.tsnew file mode 100644index 0000000..9a3f894--- /dev/null+++ b/evals/skillbuilder/scenario.ts@@ -0,0 +1,55 @@+// Scenario model for the **skill builder** evals.+//+// A sibling of evals/builder/ (which guards the AutomationBuilder). This one guards+// the SkillBuilder — the stage that turns an approved analysis into a reusable+// SKILL.md plan. It exists to exercise the richer skill *plan* shape the builder now+// proposes: typed inputs (each with a `source`), and an ordered list of typed+// `steps` (calculation vs action, each with its native tool and an optional+// confirmation pause). Like the automation harness, each scenario ships a FIXED+// approved analysis so a failure points at the builder, not the describer.++import type { AnalysisSubmission } from "../../common/analysis";+import type { SkillArchitecture, SkillInputSource } from "../../common/skill";++/**+ * Deterministic rubric for a proposed SkillPlan. Beyond the native-tool check the+ * automation harness does, it asserts the plan's *structure* — that inputs are+ * classified with the right source vocabulary and that the procedure is split into+ * calculations and actions with confirmation on the risky ones.+ */+export interface SkillRubric {+ /**+ * Each group is a set of synonyms; the plan's steps (text + tool) or allowed-tools+ * must contain at least one member of every group (case-insensitive). Use it to+ * require the RIGHT native tool, e.g. [["gh "], ["gh issue", "gh api"]].+ */+ mustUseAny: string[][];+ /** None of these may appear in the steps or allowed-tools — signals of the WRONG tool. */+ forbidden: string[];+ /** Each listed source must be assigned to at least one input (proves the vocabulary is used). */+ expectInputSources?: SkillInputSource[];+ /** The plan must declare at least this many inputs. Default 1. */+ minInputs?: number;+ /** The plan must contain at least this many `calculation` steps. Default 1. */+ minCalculations?: number;+ /** The plan must contain at least this many `action` steps. Default 1. */+ minActions?: number;+ /** When true, at least one action step must set `pausesForConfirmation` (a send/create/delete). */+ requiresConfirmation?: boolean;+}++export interface SkillBuilderScenario {+ /** Slug used for the session id and result keys. */+ id: string;+ /** Human-readable title. */+ title: string;+ /** Which target agent's catalogue the builder generalizes against. */+ architecture: SkillArchitecture;+ /** The device OS the Scout skill will run on (macOS or Windows). */+ platform: NodeJS.Platform;+ /** Ground-truth description of the task (for docs + humans reading failures). */+ truth: string;+ /** The approved analysis fed to the builder, exactly as the describer would emit it. */+ analysis: AnalysisSubmission;+ rubric: SkillRubric;+}diff --git a/evals/skillbuilder/scenarios.ts b/evals/skillbuilder/scenarios.tsnew file mode 100644index 0000000..b8ae088--- /dev/null+++ b/evals/skillbuilder/scenarios.ts@@ -0,0 +1,177 @@+// Skill builder eval scenarios.+//+// Two fixed, approved analyses chosen to exercise the SkillBuilder's richer plan+// shape end to end:+//+// • price-tracker — a recurring read-from-one-page-then-record task. It should+// yield a **fixed** input (the canonical page URL), calculation steps (read the+// figure, compute the change) and an action step (append the row), reaching for+// web_fetch + the xlsx skill rather than driving the browser + a spreadsheet UI.+// • github-issue-triage — the gh-vs-browser case, as a skill. It should generalize+// to the `gh` CLI (never the browser), split "decide which issues qualify"+// (calculation) from "comment + label" (action), and gate the mutating action+// with a confirmation pause because it posts on the user's behalf.+//+// Together they assert the whole new contract: input `source` vocabulary, typed+// calculation/action steps, native-tool choice, and confirmation on the risky step.++import type { SkillBuilderScenario } from "./scenario";++/** Read one canonical page, compute a delta, append a dated row to a tracker sheet. */+const priceTracker: SkillBuilderScenario = {+ id: "price-tracker-skill",+ title: "Track a plan price over time in a spreadsheet",+ architecture: "scout",+ platform: "darwin",+ truth:+ "Every Monday the user opens the SAME public Acme pricing page in Chrome, reads the Pro " ++ "plan's monthly price, works out how much it changed since the last recorded figure, and " ++ "appends a new dated row (date, price, change) to their Pricing Tracker spreadsheet. " ++ "Generalized on a headless device the right tools are web_fetch (read the fixed public page) " ++ "and the xlsx skill (append the row) — the page URL is a fixed input, the change is a " ++ "calculation, and appending the row is the one action.",+ analysis: {+ title: "Record the weekly Pro plan price",+ intent:+ "Every week, read the Pro plan's current monthly price from the public Acme pricing page, " ++ "compute how much it changed since the last recorded value, and append a new dated row " ++ "(date, price, change vs last week) to the Pricing Tracker spreadsheet.",+ intentConfidence: "high",+ intentRationale:+ "The browser opened the same Acme pricing page URL; the Pro plan monthly price ($49 / month) " ++ "was read and a new dated row was added below the previous week's row in a Numbers sheet " ++ "titled 'Pricing Tracker'.",+ steps: [+ {+ id: "s1",+ title: "Open the Acme pricing page",+ detail:+ "Navigated in Chrome to the public Acme pricing page — the same canonical URL used every " ++ "week — to read the Pro plan's current monthly price.",+ apps: ["Google Chrome"],+ evidence: ["browser.url https://acme.example/pricing", "title 'Pricing — Acme'"],+ confidence: "high",+ },+ {+ id: "s2",+ title: "Read the Pro plan's monthly price",+ detail: "Read the Pro plan's monthly price ($49 / month) from the pricing table.",+ apps: ["Google Chrome"],+ evidence: ["clipboard '$49 / month'"],+ confidence: "high",+ },+ {+ id: "s3",+ title: "Work out the change since last week",+ detail:+ "Compared this week's price against the previous row's price in the tracker to work out " ++ "the change (this week $49 vs last week $45, so +$4).",+ apps: ["Numbers"],+ evidence: ["app Numbers 'Pricing Tracker — Numbers'"],+ confidence: "medium",+ },+ {+ id: "s4",+ title: "Append a dated row to the Pricing Tracker",+ detail:+ "Added a new row to the Pricing Tracker spreadsheet with today's date, the price, and the " ++ "change versus the previous week.",+ apps: ["Numbers"],+ evidence: ["app Numbers 'Pricing Tracker — Numbers'"],+ confidence: "medium",+ },+ ],+ },+ rubric: {+ mustUseAny: [["web_fetch"], ["xlsx"]],+ forbidden: [],+ expectInputSources: ["fixed"],+ minInputs: 1,+ minCalculations: 1,+ minActions: 1,+ requiresConfirmation: false,+ },+};++/** Triage bug issues recorded in the browser — should generalize to the gh CLI, and gate the mutating step. */+const githubIssueTriage: SkillBuilderScenario = {+ id: "github-issue-triage-skill",+ title: "Triage new bug issues on GitHub",+ architecture: "scout",+ platform: "darwin",+ truth:+ "In Chrome the user opened the acme/api repo's open issues filtered to label:bug with no " ++ "assignee, read a new report, posted a comment asking the reporter for exact reproduction " ++ "steps and their version, and applied the 'needs-info' label — a triage pass they repeat for " ++ "every new unassigned bug. The right generalization drives GitHub with the gh CLI (gh issue " ++ "list / gh issue comment / gh issue edit --add-label), not the browser UI; deciding which " ++ "issues qualify is a calculation, while commenting + labelling is a mutating action that " ++ "should pause for the user's confirmation because it posts on their behalf.",+ analysis: {+ title: "Triage new bug issues",+ intent:+ "Triage newly reported, unassigned bug issues in the acme/api GitHub repository: for each " ++ "open issue labeled 'bug' with no assignee, post a comment asking the reporter for exact " ++ "reproduction steps and their version, then add the 'needs-info' label.",+ intentConfidence: "high",+ intentRationale:+ "The browser stayed on github.com/acme/api issue pages throughout; the same comment text " ++ "and the same 'needs-info' label were applied to a bug issue.",+ steps: [+ {+ id: "s1",+ title: "Open the repo's open bug issues on GitHub",+ detail:+ "Navigated in Chrome to the acme/api issues list filtered to open bug issues with no " ++ "assignee to find reports that still need triage.",+ apps: ["Google Chrome"],+ evidence: [+ "browser.url https://github.com/acme/api/issues?q=is%3Aissue+is%3Aopen+label%3Abug+no%3Aassignee",+ "title 'Issues · acme/api'",+ ],+ confidence: "high",+ },+ {+ id: "s2",+ title: "Open a new bug report to read it",+ detail: "Opened issue #214 in Chrome to read the reported bug before triaging it.",+ apps: ["Google Chrome"],+ evidence: ["browser.url https://github.com/acme/api/issues/214"],+ confidence: "high",+ },+ {+ id: "s3",+ title: "Comment asking for reproduction steps",+ detail:+ "Typed a comment into the issue's comment box and submitted it, asking the reporter for " ++ "exact reproduction steps and the version they are on.",+ apps: ["Google Chrome"],+ evidence: [+ "clipboard 'Thanks for the report! Could you share exact reproduction steps and the version you're on?'",+ "browser.url https://github.com/acme/api/issues/214",+ ],+ confidence: "high",+ },+ {+ id: "s4",+ title: "Apply the needs-info label",+ detail:+ "Opened the Labels sidebar on the issue and applied the 'needs-info' label to mark it as " ++ "waiting on the reporter.",+ apps: ["Google Chrome"],+ evidence: ["browser.url https://github.com/acme/api/issues/214", "label 'needs-info'"],+ confidence: "medium",+ },+ ],+ },+ rubric: {+ mustUseAny: [["gh "], ["gh issue", "gh api"]],+ forbidden: ["playwright", "browser_", "click", "navigate to github", "github.com/acme"],+ minInputs: 1,+ minCalculations: 1,+ minActions: 1,+ requiresConfirmation: true,+ },+};++export const skillScenarios: SkillBuilderScenario[] = [priceTracker, githubIssueTriage];diff --git a/evals/skillbuilder/score.ts b/evals/skillbuilder/score.tsnew file mode 100644index 0000000..c5eaf50--- /dev/null+++ b/evals/skillbuilder/score.ts@@ -0,0 +1,105 @@+// Deterministic, LLM-free scoring for the skill builder evals.+//+// Where the automation scorer only checks native-tool choice over free-text step+// prompts, a SkillPlan is structured — so we score both the tool choice AND the+// shape the builder is now supposed to produce: inputs classified with the right+// `source`, an ordered procedure split into calculations and actions, and a+// confirmation pause on the risky ones. Each is a cheap, exact check so a run is+// repeatable and a failure names the missing piece.++import type { SkillPlan } from "../../common/skill";+import type { SkillRubric } from "./scenario";++export interface SkillCheck {+ name: string;+ pass: boolean;+ detail?: string;+}++export interface SkillScoreResult {+ pass: boolean;+ score: number;+ checks: SkillCheck[];+}++const has = (haystack: string, needle: string): boolean =>+ haystack.toLowerCase().includes(needle.toLowerCase());++/** All the text a native-tool check looks at: every step's text + tool, plus allowed-tools. */+function toolText(plan: SkillPlan): string {+ const steps = plan.steps.map((s) => `${s.text} ${s.tool}`).join("\n");+ return `${steps}\n${plan.allowedTools.join(" ")}`;+}++export function scoreSkill(plan: SkillPlan, rubric: SkillRubric): SkillScoreResult {+ const checks: SkillCheck[] = [];+ const text = toolText(plan);++ for (const group of rubric.mustUseAny) {+ const hit = group.find((k) => has(text, k));+ checks.push({+ name: `uses one of: ${group.map((k) => JSON.stringify(k)).join(", ")}`,+ pass: Boolean(hit),+ detail: hit ? `found ${JSON.stringify(hit)}` : "none of these appeared in the plan",+ });+ }++ for (const bad of rubric.forbidden) {+ const present = has(text, bad);+ checks.push({+ name: `avoids ${JSON.stringify(bad)}`,+ pass: !present,+ detail: present ? `forbidden token ${JSON.stringify(bad)} appeared in the plan` : undefined,+ });+ }++ // Inputs: at least N, and every expected source classified on at least one input.+ const minInputs = rubric.minInputs ?? 1;+ checks.push({+ name: `declares >= ${minInputs} input(s)`,+ pass: plan.inputs.length >= minInputs,+ detail: `found ${plan.inputs.length}`,+ });+ for (const source of rubric.expectInputSources ?? []) {+ const hit = plan.inputs.filter((i) => i.source === source);+ checks.push({+ name: `an input is source "${source}"`,+ pass: hit.length > 0,+ detail: hit.length+ ? `${hit.map((i) => JSON.stringify(i.name)).join(", ")}`+ : `sources present: ${[...new Set(plan.inputs.map((i) => i.source))].join(", ") || "none"}`,+ });+ }++ // Steps: split into calculations and actions.+ const calculations = plan.steps.filter((s) => s.kind === "calculation");+ const actions = plan.steps.filter((s) => s.kind === "action");+ const minCalculations = rubric.minCalculations ?? 1;+ const minActions = rubric.minActions ?? 1;+ checks.push({+ name: `has >= ${minCalculations} calculation step(s)`,+ pass: calculations.length >= minCalculations,+ detail: `found ${calculations.length}`,+ });+ checks.push({+ name: `has >= ${minActions} action step(s)`,+ pass: actions.length >= minActions,+ detail: `found ${actions.length}`,+ });++ // Confirmation on the risky surface: at least one action pauses for the user.+ if (rubric.requiresConfirmation) {+ const gated = actions.filter((s) => s.pausesForConfirmation);+ checks.push({+ name: "an action pauses for confirmation",+ pass: gated.length > 0,+ detail: gated.length ? `${gated.length} gated action(s)` : "no action set pausesForConfirmation",+ });+ }++ // A forbidden-token hit (wrong tool) fails outright; otherwise every check must pass.+ const forbiddenHit = checks.some((c) => c.name.startsWith("avoids ") && !c.pass);+ const passed = checks.filter((c) => c.pass).length;+ const score = checks.length ? passed / checks.length : 0;+ return { pass: !forbiddenHit && passed === checks.length, score, checks };+}diff --git a/package.json b/package.jsonindex 9009089..2a625d7 100644--- a/package.json+++ b/package.json@@ -15,6 +15,7 @@"typecheck:evals": "tsc --noEmit -p evals/tsconfig.json","eval": "node --experimental-transform-types --no-warnings --import ./evals/register.mjs evals/run.ts","eval:builder": "node --experimental-transform-types --no-warnings --import ./evals/register.mjs evals/builder/run.ts",+ "eval:skill": "node --experimental-transform-types --no-warnings --import ./evals/register.mjs evals/skillbuilder/run.ts","dist": "vite build && electron-builder","start": "electron ."},diff --git a/src/App.css b/src/App.cssindex fcf3923..0dbf8d2 100644--- a/src/App.css+++ b/src/App.css@@ -1665,78 +1665,145 @@ button:focus-visible,white-space: nowrap;}-.src-ask {+.src-provided {color: var(--brand-ink);background: var(--signal-dim);}-.src-discover {+.src-locate {color: var(--go);background: rgba(var(--go-rgb), 0.12);}-.src-constant {+.src-fixed {color: var(--muted);background: var(--surface-2);}+/* Per-input source switcher (skill plan) — a pill-shaped select tinted by source. */+.src-select {+ font-family: var(--mono);+ font-size: 10px;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ border: 1px solid var(--line);+ border-radius: 20px;+ padding: 2px 9px;+ white-space: nowrap;+ cursor: pointer;+ -webkit-appearance: none;+ appearance: none;+}++.src-select:disabled {+ opacity: 0.6;+ cursor: default;+}+.input-detail {font-size: 12.5px;line-height: 1.45;color: var(--muted);}-/* Steps */+/* Steps — ordered calculations + actions, each with its native tool. */.sb-steps {margin: 0;padding-left: 20px;display: flex;flex-direction: column;- gap: 6px;+ gap: 8px;}-.sb-steps li {+.step-row {font-size: 13.5px;line-height: 1.5;color: var(--text);}-/* Action → native tool mapping */-.sb-map {- list-style: none;- margin: 0;- padding: 0;+.step-main {display: flex;- flex-direction: column;- gap: 6px;+ align-items: baseline;+ gap: 8px;}-.map-row {- display: flex;- align-items: center;- gap: 10px;- font-size: 13px;+.step-kind {+ font-family: var(--mono);+ font-size: 9.5px;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ border-radius: 5px;+ padding: 1px 6px;+ flex: none;}-.map-action {- color: var(--text);+.step-kind-calculation {+ color: var(--muted);+ background: var(--surface-2);+}++.step-kind-action {+ color: var(--brand-ink);+ background: var(--signal-dim);+}++.step-text {flex: 1 1 auto;min-width: 0;}-.map-arrow {- color: var(--faint);+.step-adjust {flex: none;+ border: none;+ background: none;+ color: var(--muted);+ font-size: 11.5px;+ cursor: pointer;+ padding: 0 2px;+ opacity: 0;+ transition: opacity 0.12s ease;+}++.step-row:hover .step-adjust {+ opacity: 1;+}++.step-adjust:hover {+ color: var(--brand-ink);+ text-decoration: underline;+}++.step-adjust:disabled {+ cursor: default;+ opacity: 0;}-.map-tool {+.step-meta {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-top: 3px;+ padding-left: 2px;+}++.step-tool {font-family: var(--mono);font-size: 12px;color: var(--text);background: var(--surface-2);border-radius: 6px;padding: 2px 8px;- flex: none;+}++.step-confirm {+ font-family: var(--mono);+ font-size: 10px;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ color: var(--warn);+ border: 1px solid var(--warn);+ border-radius: 5px;+ padding: 1px 7px;}.sb-refine {@@ -1832,3 +1899,414 @@ button:focus-visible,color: var(--muted) !important;max-width: 460px;}++/* ==========================================================================+ Read-first review tiles (src/plan-edit.tsx). Each gate reads as a calm report+ of what Copilot proposed; a field becomes an input only when clicked. Controls+ (reorder / remove) are revealed on hover. No wall of text boxes by default.+ ========================================================================== */++.tiles {+ display: flex;+ flex-direction: column;+ gap: 6px;+}++.tile {+ display: flex;+ flex-direction: column;+ gap: 4px;+ background: var(--surface);+ border: 1px solid var(--line);+ border-radius: 10px;+ padding: 10px 12px;+}++/* Skill steps carry a quiet left accent by kind. */+.step-tile.step-action {+ border-left: 3px solid var(--brand);+}+.step-tile.step-calculation {+ border-left: 3px solid var(--line-strong);+}++.tile-head {+ display: flex;+ align-items: flex-start;+ gap: 8px;+}++.tile-num {+ flex: none;+ width: 22px;+ height: 22px;+ margin-top: 1px;+ border-radius: 50%;+ display: grid;+ place-items: center;+ background: var(--surface-2);+ color: var(--muted);+ font-family: var(--mono);+ font-size: 11px;+ font-weight: 600;+}++/* --- read mode: plain text that hints it's editable ---------------------- */+.ed-read {+ display: block;+ border: 1px solid transparent;+ border-radius: 6px;+ padding: 3px 6px;+ margin: -3px -6px; /* keep read + edit visually aligned (no jump on click) */+ color: var(--text);+ cursor: text;+ white-space: pre-wrap;+ overflow-wrap: anywhere;+ transition: background 0.1s ease, border-color 0.1s ease;+}++.ed-read:hover {+ background: var(--surface-2);+}++.ed-read:focus-visible {+ outline: none;+ border-color: var(--signal);+ background: var(--surface-2);+}++.ed-empty {+ color: var(--faint);+ font-style: italic;+}++/* Optional fields stay invisible until you hover the tile. */+.ed-hide {+ opacity: 0;+ transition: opacity 0.12s ease;+}+.tile:hover .ed-hide,+.ed-hide:focus-visible {+ opacity: 0.7;+}++/* Per-field read typography. */+.ed-name {+ flex: 1 1 auto;+ min-width: 0;+ font-weight: 600;+ font-size: 14px;+}+.ed-strong {+ flex: 1 1 auto;+ min-width: 0;+ font-size: 14px;+ line-height: 1.5;+ color: var(--text);+}+.ed-detail {+ font-size: 13px;+ line-height: 1.5;+ color: var(--muted);+}+.ed-tool {+ flex: none;+ font-family: var(--mono);+ font-size: 12px;+ color: var(--text);+}+.ed-title {+ font-size: 18px;+ font-weight: 620;+ letter-spacing: -0.012em;+}+.ed-desc {+ font-size: 14px;+ line-height: 1.5;+ color: var(--muted);+}++/* --- edit mode: the field is an input / textarea ------------------------- */+.ed-input {+ width: 100%;+ box-sizing: border-box;+ background: var(--deck);+ border: 1px solid var(--signal);+ border-radius: 6px;+ color: var(--text);+ font-family: inherit;+ font-size: 14px;+ line-height: 1.5;+ padding: 3px 6px;+ margin: -3px -6px;+ user-select: text;+}+.ed-input:focus {+ outline: none;+}+.ed-input-multi {+ resize: vertical;+ min-height: 44px;+}+.ed-input.ed-name,+.ed-input.ed-title {+ font-weight: 620;+}+.ed-input.ed-tool {+ font-family: var(--mono);+ font-size: 12px;+}++/* Header title/description sit flush with the plan header (no shift on click). */+.sb-title.ed-read,+.sb-desc.ed-read,+.sb-title.ed-input,+.sb-desc.ed-input {+ margin: 0;+ padding-left: 0;+ padding-right: 0;+}+.sb-title.ed-read:hover,+.sb-desc.ed-read:hover {+ background: transparent;+}+.sb-title.ed-read:focus-visible,+.sb-desc.ed-read:focus-visible {+ border-color: transparent;+ background: transparent;+ box-shadow: inset 0 -1px 0 var(--signal);+}+.sb-title.ed-input,+.sb-desc.ed-input {+ border-color: transparent;+ border-bottom-color: var(--signal);+ border-radius: 0;+ background: transparent;+}++/* --- pill button (source / kind), read → select on click ----------------- */+.pill-btn {+ flex: none;+ border: none;+ background: none;+ padding: 0;+ margin: 0;+ cursor: pointer;+ line-height: 1;+}++/* --- inline select (used by pills + schedule) ---------------------------- */+.tile-select {+ flex: none;+ background: var(--surface-2);+ border: 1px solid var(--line);+ border-radius: 7px;+ color: var(--text);+ font-family: inherit;+ font-size: 12.5px;+ padding: 5px 8px;+ cursor: pointer;+}+.tile-select:focus {+ outline: none;+ border-color: var(--signal);+}++/* --- reorder / remove, revealed on hover --------------------------------- */+.row-controls {+ flex: none;+ margin-left: auto;+ display: flex;+ gap: 3px;+ opacity: 0;+ transition: opacity 0.12s ease;+}+.tile:hover .row-controls,+.tile:focus-within .row-controls {+ opacity: 1;+}++.tile-btn {+ width: 24px;+ height: 24px;+ display: grid;+ place-items: center;+ border: 1px solid var(--line);+ border-radius: 6px;+ background: var(--surface);+ color: var(--muted);+ font-size: 13px;+ line-height: 1;+ cursor: pointer;+ transition: border-color 0.12s ease, color 0.12s ease, background 0.12s ease;+}+.tile-btn:not(:disabled):hover {+ border-color: var(--line-strong);+ color: var(--text);+}+.tile-btn:disabled {+ opacity: 0.32;+ cursor: default;+}+.tile-btn-del:not(:disabled):hover {+ border-color: var(--rec);+ color: var(--rec);+ background: rgba(var(--rec-rgb), 0.08);+}++/* --- skill-step foot: native tool + "asks first" toggle ------------------ */+.tile-foot {+ display: flex;+ align-items: center;+ gap: 10px;+ flex-wrap: wrap;+ padding-left: 2px;+}++.confirm-toggle {+ flex: none;+ border: 1px solid var(--line);+ border-radius: 20px;+ background: transparent;+ color: var(--faint);+ font-family: var(--mono);+ font-size: 10px;+ text-transform: uppercase;+ letter-spacing: 0.04em;+ padding: 2px 9px;+ cursor: pointer;+ opacity: 0;+ transition: opacity 0.12s ease, border-color 0.12s ease, color 0.12s ease, background 0.12s ease;+}+.tile:hover .confirm-toggle {+ opacity: 1;+}+.confirm-toggle.on {+ opacity: 1;+ color: var(--warn);+ border-color: var(--warn);+ background: rgba(240, 160, 30, 0.08);+}++/* --- "+ Add …" — a quiet, intentional affordance ------------------------- */+.tile-add {+ align-self: stretch;+ border: 1px dashed var(--line-strong);+ border-radius: 8px;+ background: transparent;+ color: var(--muted);+ font-family: inherit;+ font-size: 13px;+ padding: 7px 10px;+ cursor: pointer;+ transition: border-color 0.12s ease, color 0.12s ease, background 0.12s ease;+}+.tile-add:hover {+ border-color: var(--brand);+ color: var(--brand-ink);+ background: var(--signal-dim);+}++/* --- build-view header (read-first title + description) ------------------ */+.sb-planhead .ed-title {+ flex: 1 1 auto;+ min-width: 0;+}++/* --- schedule: reads as a sentence; "Edit" reveals controls -------------- */+.sched-read {+ display: flex;+ align-items: center;+ gap: 10px;+ background: var(--surface);+ border: 1px solid var(--line);+ border-radius: 9px;+ padding: 10px 12px;+}+.sched-when {+ flex: 1 1 auto;+ font-size: 14px;+ font-weight: 600;+ color: var(--text);+}+.sched-done {+ margin-left: auto;+}++.sched-edit {+ display: flex;+ flex-direction: column;+ gap: 10px;+ background: var(--surface);+ border: 1px solid var(--line);+ border-radius: 9px;+ padding: 12px;+}+.sched-row {+ display: flex;+ align-items: center;+ gap: 8px;+ flex-wrap: wrap;+}+.sched-times {+ display: flex;+ flex-direction: column;+ gap: 6px;+}+.sched-time-row {+ display: flex;+ align-items: center;+ gap: 6px;+}+.sched-days {+ display: flex;+ align-items: center;+ gap: 4px;+ flex-wrap: wrap;+}+.sched-lbl {+ font-size: 12.5px;+ color: var(--muted);+}+.sched-every {+ font-style: italic;+}++.tile-input {+ background: var(--deck);+ border: 1px solid var(--line);+ border-radius: 7px;+ color: var(--text);+ font-family: inherit;+ font-size: 13.5px;+ padding: 6px 9px;+}+.tile-input:focus {+ outline: none;+ border-color: var(--signal);+}+.tile-time {+ width: auto;+ flex: none;+}++.day-chip {+ min-width: 32px;+ padding: 4px 7px;+ border: 1px solid var(--line);+ border-radius: 6px;+ background: var(--surface);+ color: var(--muted);+ font-family: inherit;+ font-size: 11.5px;+ cursor: pointer;+ transition: border-color 0.12s ease, color 0.12s ease, background 0.12s ease;+}+.day-chip:hover {+ border-color: var(--line-strong);+}+.day-chip.on {+ border-color: var(--brand);+ color: var(--brand-ink);+ background: var(--signal-dim);+}diff --git a/src/Library.tsx b/src/Library.tsxindex 5d50619..07c94aa 100644--- a/src/Library.tsx+++ b/src/Library.tsx@@ -1,6 +1,6 @@import { useCallback, useEffect, useRef, useState } from "react";-import type { Analysis } from "../common/analysis";+import type { Analysis, AnalysisStep } from "../common/analysis";import type {AnalyzeProgress,AutomationBuildProgress,@@ -15,8 +15,15 @@ import type {} from "../common/skill";import { ARCHITECTURES, TARGETS } from "../common/skill";import type { AutomationPlan, BuiltAutomation } from "../common/automation";-import { describeSchedule } from "../common/automation";-import { formatDur, formatMs, formatWhen, shortLabel } from "./format";+import {+ AnalysisStepTiles,+ AutomationStepTiles,+ EditableText,+ InputTiles,+ ScheduleEditor,+ SkillStepTiles,+} from "./plan-edit";+import { formatDur, formatWhen, shortLabel } from "./format";export function Library() {const [sessions, setSessions] = useState<SessionSummary[]>([]);@@ -201,12 +208,6 @@ function SessionsList({/* --- Analysis workspace --------------------------------------------------- */-const STEP_CHIPS = ["Not accurate", "Not needed"] as const;-const CHIP_NOTE: Record<(typeof STEP_CHIPS)[number], string> = {- "Not accurate": "This isn't accurate.",- "Not needed": "This step isn't needed.",-};-function AnalysisWorkspace({summary,onChanged,@@ -220,12 +221,16 @@ function AnalysisWorkspace({const [analyzing, setAnalyzing] = useState(false);const [statusLine, setStatusLine] = useState("");const [error, setError] = useState<string | null>(null);- const [overall, setOverall] = useState("");- const [overallOpen, setOverallOpen] = useState(false);- const [notes, setNotes] = useState<Record<string, string>>({});const [editing, setEditing] = useState(false);const [draftTitle, setDraftTitle] = useState("");const [draftIntent, setDraftIntent] = useState("");+ // Directly-editable steps (the source of truth downstream); persisted on a short+ // debounce so typing stays instant. `stepsDirty` gates the persist so seeding from+ // a freshly loaded analysis never writes back.+ const [steps, setSteps] = useState<AnalysisStep[]>([]);+ const stepsDirty = useRef(false);+ const stepsRef = useRef<AnalysisStep[]>([]);+ stepsRef.current = steps;// The final stage: pick a target, then build a skill or an automation. A recording// that is already exactly one kind opens straight to it; otherwise it opens to the// analysis, where "Create…" starts the target picker.@@ -244,13 +249,44 @@ function AnalysisWorkspace({useEffect(() => {let live = true;void window.skillRecorder.getAnalysis(sessionId).then((a) => {- if (live) setAnalysis(a);+ if (!live) return;+ setAnalysis(a);+ setSteps(a?.steps ?? []);+ stepsDirty.current = false;});return () => {live = false;};}, [sessionId]);+ // Persist directly-edited steps on a short debounce (no agent, no re-analysis).+ useEffect(() => {+ if (!stepsDirty.current) return;+ const t = setTimeout(() => {+ stepsDirty.current = false;+ void window.skillRecorder.updateAnalysis({ sessionId, steps: stepsRef.current }).then((res) => {+ if (res.ok && res.analysis) setAnalysis(res.analysis);+ void onChanged();+ });+ }, 500);+ return () => clearTimeout(t);+ }, [steps, sessionId, onChanged]);++ // Flush any pending step edits when leaving this session, so nothing is lost.+ useEffect(() => {+ return () => {+ if (stepsDirty.current) {+ void window.skillRecorder.updateAnalysis({ sessionId, steps: stepsRef.current });+ stepsDirty.current = false;+ }+ };+ }, [sessionId]);++ const onStepsChange = useCallback((next: AnalysisStep[]) => {+ stepsDirty.current = true;+ setSteps(next);+ }, []);+// Single latest status line (no growing log).useEffect(() => {return window.skillRecorder.onAnalyzeProgress((p: AnalyzeProgress) => {@@ -266,8 +302,11 @@ function AnalysisWorkspace({setError(null);setStatusLine("Starting…");const res = await window.skillRecorder.analyze(sessionId);- if (res.ok && res.analysis) setAnalysis(res.analysis);- else if (!canceled.current) setError(res.error ?? "Analysis failed");+ if (res.ok && res.analysis) {+ setAnalysis(res.analysis);+ setSteps(res.analysis.steps);+ stepsDirty.current = false;+ } else if (!canceled.current) setError(res.error ?? "Analysis failed");setAnalyzing(false);void onChanged();}, [sessionId, onChanged]);@@ -279,35 +318,6 @@ function AnalysisWorkspace({setAnalyzing(false);}, [sessionId]);- const hasFeedback =- overall.trim().length > 0 || Object.values(notes).some((n) => n.trim().length > 0);-- const sendFeedback = useCallback(async () => {- const steps = Object.entries(notes)- .filter(([, note]) => note.trim())- .map(([stepId, note]) => ({ stepId, note: note.trim() }));- if (!overall.trim() && steps.length === 0) return;- canceled.current = false;- setAnalyzing(true);- setError(null);- setStatusLine("Re-analyzing with your feedback…");- const res = await window.skillRecorder.analyzeFeedback({- sessionId,- overall: overall.trim() || undefined,- steps,- });- if (res.ok && res.analysis) {- setAnalysis(res.analysis);- setOverall("");- setOverallOpen(false);- setNotes({});- } else if (!canceled.current) {- setError(res.error ?? "Re-analysis failed");- }- setAnalyzing(false);- void onChanged();- }, [notes, overall, sessionId, onChanged]);-const startEdit = useCallback(() => {if (!analysis) return;setDraftTitle(analysis.title ?? "");@@ -331,10 +341,6 @@ function AnalysisWorkspace({void onChanged();}, [sessionId, draftTitle, draftIntent, onChanged]);- const setNote = useCallback((stepId: string, note: string) => {- setNotes((prev) => ({ ...prev, [stepId]: note }));- }, []);-if (launch === "picker") {return (<TargetPicker@@ -385,11 +391,6 @@ function AnalysisWorkspace({<span className="eyebrow">Analysis</span><span className="ws-when">{formatWhen(summary.startedAt)}</span></div>- {analysis && !analyzing && (- <button className="ghost" onClick={run} title="Analyze this recording again from scratch">- Start over- </button>- )}</div><div className="ws-body">@@ -480,31 +481,12 @@ function AnalysisWorkspace({)}</div>- <ol className="story">- {analysis.steps.map((s, i) => (- <StepCard- key={s.id}- index={i}- step={s}- note={notes[s.id] ?? ""}- onNote={(v) => setNote(s.id, v)}- />- ))}- </ol>-- <div className="overall-zone">- {overallOpen || overall.trim() ? (- <textarea- className="overall-fb"- placeholder="Tell us what's off, or describe a step we missed…"- value={overall}- onChange={(e) => setOverall(e.target.value)}- />- ) : (- <button className="linky" onClick={() => setOverallOpen(true)}>- Something off, or did we miss a step?- </button>- )}+ <div className="story-edit">+ <div className="summary-head">+ <span className="eyebrow">Steps</span>+ <span className="edit-hint">Click any step to edit · reorder, add or remove — saved automatically</span>+ </div>+ <AnalysisStepTiles steps={steps} onChange={onStepsChange} /></div></div>)}@@ -514,11 +496,6 @@ function AnalysisWorkspace({<div className="ws-foot"><span className="foot-status">{launchFootStatus(summary)}</span><div className="ws-foot-actions">- {hasFeedback && (- <button className="secondary" onClick={sendFeedback}>- Send feedback & re-analyze- </button>- )}{summary.hasSkill && (<button className="secondary" onClick={() => setLaunch("skill")} title="Open the skill built from this recording">Open skill →@@ -536,12 +513,7 @@ function AnalysisWorkspace({<buttonclassName="record-cta"onClick={() => setLaunch("picker")}- disabled={hasFeedback}- title={- hasFeedback- ? "Send or clear your feedback first"- : "Turn this recording into a skill or an automation"- }+ title="Turn this recording into a skill or an automation">{summary.hasSkill || summary.hasAutomation ? "Create another →" : "Create…"}</button>@@ -611,12 +583,6 @@ function TargetPicker({type BuildPhase = "loading" | "ready" | "planning" | "plan" | "creating" | "done";-const SOURCE_LABEL: Record<SkillPlan["inputs"][number]["source"], string> = {- ask: "You provide it",- discover: "Found on this device",- constant: "Fixed value",-};-function SkillBuilderView({sessionId,architecture: initialArch,@@ -636,13 +602,16 @@ function SkillBuilderView({const [architecture, setArchitecture] = useState<SkillArchitecture>(initialArch);const [plan, setPlan] = useState<SkillPlan | null>(null);const [statusLine, setStatusLine] = useState("");- const [feedback, setFeedback] = useState("");const [error, setError] = useState<string | null>(null);const [exportedPath, setExportedPath] = useState("");const [builtName, setBuiltName] = useState("");const canceled = useRef(false);const inFlight = useRef(false);+ const updatePlan = useCallback((part: Partial<SkillPlan>) => {+ setPlan((prev) => (prev ? { ...prev, ...part } : prev));+ }, []);+// Leaving the builder (session switch or Close) discards an in-progress plan —// we don't save drafts — so stop any run that's still going in the background.useEffect(() => {@@ -678,34 +647,31 @@ function SkillBuilderView({});}, [sessionId]);- const runPlan = useCallback(- async (note?: string) => {- canceled.current = false;- inFlight.current = true;- setError(null);- setStatusLine(note ? "Refining the plan…" : "Planning the skill…");- setPhase("planning");- const res = await window.skillRecorder.buildSkill({ sessionId, architecture, feedback: note });- inFlight.current = false;- if (res.ok && res.plan) {- setPlan(res.plan);- setFeedback("");- setPhase("plan");- } else if (!canceled.current) {- setError(res.error ?? "Planning failed");- setPhase(note ? "plan" : "ready");- }- },- [sessionId, architecture],- );+ const runPlan = useCallback(async () => {+ canceled.current = false;+ inFlight.current = true;+ setError(null);+ setStatusLine("Planning the skill…");+ setPhase("planning");+ const res = await window.skillRecorder.buildSkill({ sessionId, architecture });+ inFlight.current = false;+ if (res.ok && res.plan) {+ setPlan(res.plan);+ setPhase("plan");+ } else if (!canceled.current) {+ setError(res.error ?? "Planning failed");+ setPhase("ready");+ }+ }, [sessionId, architecture]);const create = useCallback(async () => {+ if (!plan) return;canceled.current = false;inFlight.current = true;setError(null);setStatusLine("Writing the skill…");setPhase("creating");- const res = await window.skillRecorder.createSkill(sessionId);+ const res = await window.skillRecorder.createSkill(sessionId, plan);inFlight.current = false;if (res.ok && res.skill) {setBuiltName(res.skill.name);@@ -715,7 +681,7 @@ function SkillBuilderView({setError(res.error ?? "Could not create the skill");setPhase("plan");}- }, [sessionId]);+ }, [sessionId, plan]);const cancelRun = useCallback(async () => {canceled.current = true;@@ -776,77 +742,40 @@ function SkillBuilderView({{phase === "plan" && plan && (<div className="sb-plan"><div className="sb-planhead">- <h2 className="sb-title">{plan.title}</h2>+ <EditableText+ as="div"+ className="sb-title ed-title"+ value={plan.title}+ placeholder="Skill title"+ ariaLabel="Skill title"+ onChange={(v) => updatePlan({ title: v })}+ /><code className="sb-slug">{plan.name}</code></div>- <p className="sb-desc">{plan.description}</p>-- {(plan.summary || plan.generalization) && (- <div className="sb-sec">- <span className="eyebrow">How it generalizes</span>- {plan.summary && <p>{plan.summary}</p>}- {plan.generalization && <p className="sb-muted">{plan.generalization}</p>}- </div>- )}-- {plan.inputs.length > 0 && (- <div className="sb-sec">- <span className="eyebrow">Inputs</span>- <ul className="sb-inputs">- {plan.inputs.map((inp, i) => (- <li key={i} className="input-row">- <div className="input-main">- <span className="input-name">{inp.name}</span>- <span className={`src-badge src-${inp.source}`}>{SOURCE_LABEL[inp.source]}</span>- </div>- {(inp.detail || inp.description) && (- <span className="input-detail">{inp.detail || inp.description}</span>- )}- </li>- ))}- </ul>- </div>- )}-- {plan.steps.length > 0 && (- <div className="sb-sec">- <span className="eyebrow">What the skill will do</span>- <ol className="sb-steps">- {plan.steps.map((s, i) => (- <li key={i}>{s}</li>- ))}- </ol>- </div>- )}+ <EditableText+ as="p"+ multiline+ className="sb-desc ed-desc"+ value={plan.description}+ placeholder="One-line description of what this skill does"+ ariaLabel="Skill description"+ onChange={(v) => updatePlan({ description: v })}+ />- {plan.toolMapping.length > 0 && (- <div className="sb-sec">- <span className="eyebrow">Native tools it will use</span>- <ul className="sb-map">- {plan.toolMapping.map((m, i) => (- <li key={i} className="map-row">- <span className="map-action">{m.action}</span>- <span className="map-arrow" aria-hidden>- →- </span>- <code className="map-tool">{m.tool}</code>- </li>- ))}- </ul>- </div>- )}+ <div className="sb-sec">+ <span className="eyebrow">Inputs</span>+ <p className="sb-refine-hint">+ What the skill needs each run. Click a field to edit; set each as fixed, provided by you, or found by the agent.+ </p>+ <InputTiles inputs={plan.inputs} onChange={(inputs) => updatePlan({ inputs })} />+ </div>- <div className="sb-sec sb-refine">- <span className="eyebrow">Adjust the plan</span>+ <div className="sb-sec">+ <span className="eyebrow">What the skill will do</span><p className="sb-refine-hint">- Describe any change in plain language, then Refine to re-plan before you export.+ Click any step to edit. Reorder, add or remove as needed.</p>- <textarea- className="overall-fb"- placeholder="e.g. 'read the spreadsheet from Downloads instead of asking', or 'also fill in the Phone field'…"- value={feedback}- onChange={(e) => setFeedback(e.target.value)}- />+ <SkillStepTiles steps={plan.steps} onChange={(steps) => updatePlan({ steps })} /></div></div>)}@@ -869,14 +798,6 @@ function SkillBuilderView({<div className="ws-foot"><span className="foot-status" /><div className="ws-foot-actions">- <button- className="secondary"- onClick={() => void runPlan(feedback.trim())}- disabled={!feedback.trim()}- title={feedback.trim() ? "Apply your changes and re-plan" : "Type a change above to refine"}- >- Refine plan- </button><buttonclassName="record-cta"onClick={() => void create()}@@ -927,13 +848,16 @@ function AutomationBuilderView({const [architecture, setArchitecture] = useState<SkillArchitecture>(initialArch);const [plan, setPlan] = useState<AutomationPlan | null>(null);const [statusLine, setStatusLine] = useState("");- const [feedback, setFeedback] = useState("");const [error, setError] = useState<string | null>(null);const [exportedPath, setExportedPath] = useState("");const [builtName, setBuiltName] = useState("");const canceled = useRef(false);const inFlight = useRef(false);+ const updatePlan = useCallback((part: Partial<AutomationPlan>) => {+ setPlan((prev) => (prev ? { ...prev, ...part } : prev));+ }, []);+useEffect(() => {return () => {if (inFlight.current) void window.skillRecorder.cancelAutomation(sessionId);@@ -966,34 +890,31 @@ function AutomationBuilderView({});}, [sessionId]);- const runPlan = useCallback(- async (note?: string) => {- canceled.current = false;- inFlight.current = true;- setError(null);- setStatusLine(note ? "Refining the plan…" : "Planning the automation…");- setPhase("planning");- const res = await window.skillRecorder.buildAutomation({ sessionId, architecture, feedback: note });- inFlight.current = false;- if (res.ok && res.plan) {- setPlan(res.plan);- setFeedback("");- setPhase("plan");- } else if (!canceled.current) {- setError(res.error ?? "Planning failed");- setPhase(note ? "plan" : "ready");- }- },- [sessionId, architecture],- );+ const runPlan = useCallback(async () => {+ canceled.current = false;+ inFlight.current = true;+ setError(null);+ setStatusLine("Planning the automation…");+ setPhase("planning");+ const res = await window.skillRecorder.buildAutomation({ sessionId, architecture });+ inFlight.current = false;+ if (res.ok && res.plan) {+ setPlan(res.plan);+ setPhase("plan");+ } else if (!canceled.current) {+ setError(res.error ?? "Planning failed");+ setPhase("ready");+ }+ }, [sessionId, architecture]);const create = useCallback(async () => {+ if (!plan) return;canceled.current = false;inFlight.current = true;setError(null);setStatusLine("Writing the automation…");setPhase("creating");- const res = await window.skillRecorder.createAutomation(sessionId);+ const res = await window.skillRecorder.createAutomation(sessionId, plan);inFlight.current = false;if (res.ok && res.automation) {setBuiltName(res.automation.name);@@ -1003,7 +924,7 @@ function AutomationBuilderView({setError(res.error ?? "Could not create the automation");setPhase("plan");}- }, [sessionId]);+ }, [sessionId, plan]);const cancelRun = useCallback(async () => {canceled.current = true;@@ -1064,78 +985,54 @@ function AutomationBuilderView({{phase === "plan" && plan && (<div className="sb-plan"><div className="sb-planhead">- <h2 className="sb-title">{plan.title}</h2>+ <EditableText+ as="div"+ className="sb-title ed-title"+ value={plan.title}+ placeholder="Automation title"+ ariaLabel="Automation title"+ onChange={(v) => updatePlan({ title: v })}+ /><code className="sb-slug">{plan.name}</code></div>- <p className="sb-desc">{plan.description}</p>+ <EditableText+ as="p"+ multiline+ className="sb-desc ed-desc"+ value={plan.description}+ placeholder="One-line description of what this automation does"+ ariaLabel="Automation description"+ onChange={(v) => updatePlan({ description: v })}+ /><div className="sb-sec"><span className="eyebrow">When it runs</span>- <div className="sb-trigger">- <span className="trigger-when">{describeSchedule(plan.trigger.schedule)}</span>- {plan.trigger.type === "condition" && plan.trigger.condition && (- <span className="trigger-cond">Only when: {plan.trigger.condition}</span>- )}- </div><p className="sb-refine-hint">- A recording has no schedule of its own — this is a suggestion. Say e.g. “every- weekday at 8am” below to change it.+ A recording has no schedule of its own — set when this automation should run.</p>+ <ScheduleEditor+ schedule={plan.trigger.schedule}+ onChange={(schedule) => updatePlan({ trigger: { ...plan.trigger, schedule } })}+ />+ {plan.trigger.type === "condition" && plan.trigger.condition && (+ <span className="trigger-cond">Only when: {plan.trigger.condition}</span>+ )}</div>- {(plan.summary || plan.generalization) && (- <div className="sb-sec">- <span className="eyebrow">How it generalizes</span>- {plan.summary && <p>{plan.summary}</p>}- {plan.generalization && <p className="sb-muted">{plan.generalization}</p>}- </div>- )}-- {plan.inputs.length > 0 && (- <div className="sb-sec">- <span className="eyebrow">Inputs</span>- <ul className="sb-inputs">- {plan.inputs.map((inp, i) => (- <li key={i} className="input-row">- <div className="input-main">- <span className="input-name">{inp.name}</span>- <span className={`src-badge src-${inp.source}`}>{SOURCE_LABEL[inp.source]}</span>- </div>- {(inp.detail || inp.description) && (- <span className="input-detail">{inp.detail || inp.description}</span>- )}- </li>- ))}- </ul>- </div>- )}-- {plan.steps.length > 0 && (- <div className="sb-sec">- <span className="eyebrow">What the automation will do</span>- <ol className="sb-steps">- {plan.steps.map((s, i) => (- <li key={i}>- {s.label && <span className="sb-step-label">{s.label}</span>}- <span className="sb-step-prompt">{s.prompt}</span>- </li>- ))}- </ol>- </div>- )}+ <div className="sb-sec">+ <span className="eyebrow">Inputs</span>+ <p className="sb-refine-hint">+ What the automation needs each run. Click a field to edit; set each as fixed, provided by you, or found by the agent.+ </p>+ <InputTiles inputs={plan.inputs} onChange={(inputs) => updatePlan({ inputs })} />+ </div>- <div className="sb-sec sb-refine">- <span className="eyebrow">Adjust the plan</span>+ <div className="sb-sec">+ <span className="eyebrow">What the automation will do</span><p className="sb-refine-hint">- Describe any change in plain language — the schedule, the steps, anything — then- Refine to re-plan before you export.+ Click any step to edit. Reorder, add or remove as needed.</p>- <textarea- className="overall-fb"- placeholder="e.g. 'run every weekday at 8am', or 'add a step that emails me the summary'…"- value={feedback}- onChange={(e) => setFeedback(e.target.value)}- />+ <AutomationStepTiles steps={plan.steps} onChange={(steps) => updatePlan({ steps })} /></div></div>)}@@ -1161,14 +1058,6 @@ function AutomationBuilderView({<div className="ws-foot"><span className="foot-status" /><div className="ws-foot-actions">- <button- className="secondary"- onClick={() => void runPlan(feedback.trim())}- disabled={!feedback.trim()}- title={feedback.trim() ? "Apply your changes and re-plan" : "Type a change above to refine"}- >- Refine plan- </button><buttonclassName="record-cta"onClick={() => void create()}@@ -1198,94 +1087,3 @@ function AutomationBuilderView({</section>);}--/* --- One step, told as plain language ------------------------------------- */--function StepCard({- index,- step,- note,- onNote,-}: {- index: number;- step: Analysis["steps"][number];- note: string;- onNote: (value: string) => void;-}) {- const [showDetails, setShowDetails] = useState(false);- const [commenting, setCommenting] = useState(false);- const open = commenting || note.trim().length > 0;- const hasMeta = step.apps.length > 0 || step.startMs != null || step.evidence.length > 0;-- return (- <li className="story-step">- <div className="sstep-num">{index + 1}</div>- <div className="sstep-body">- <div className="sstep-title">{step.title}</div>- <p className="sstep-detail">{step.detail}</p>-- {step.confidence === "low" && (- <div className="sstep-flag">We're not fully sure about this one. Worth a check.</div>- )}-- <div className="sstep-tools">- {hasMeta && (- <button className="linky" onClick={() => setShowDetails((v) => !v)}>- {showDetails ? "Hide details" : "Details"}- </button>- )}- <button className="linky" onClick={() => setCommenting((v) => !v)}>- {open ? "Done" : "Suggest a change"}- </button>- </div>-- {showDetails && hasMeta && (- <div className="sstep-details">- {step.apps.length > 0 && (- <div className="drow">- <span className="dkey">App</span>- <span>{step.apps.join(", ")}</span>- </div>- )}- {step.startMs != null && (- <div className="drow">- <span className="dkey">At</span>- <span>{formatMs(step.startMs)}</span>- </div>- )}- {step.evidence.length > 0 && (- <div className="drow">- <span className="dkey">Signals</span>- <span className="dsignals">- {step.evidence.map((e, i) => (- <span className="sig" key={i}>- {e}- </span>- ))}- </span>- </div>- )}- </div>- )}-- {open && (- <div className="sstep-fb">- <div className="fb-chips">- {STEP_CHIPS.map((c) => (- <button key={c} className="fb-chip" onClick={() => onNote(CHIP_NOTE[c])}>- {c}- </button>- ))}- </div>- <input- className="fb-input"- placeholder="What should this say instead?"- value={note}- onChange={(e) => onNote(e.target.value)}- />- </div>- )}- </div>- </li>- );-}diff --git a/src/plan-edit.tsx b/src/plan-edit.tsxnew file mode 100644index 0000000..fc8d79c--- /dev/null+++ b/src/plan-edit.tsx@@ -0,0 +1,666 @@+import { useEffect, useRef, useState, type ReactNode } from "react";++import type { AnalysisStep } from "../common/analysis";+import {+ describeSchedule,+ type AutomationSchedule,+ type AutomationStepDraft,+ type TimeOfDay,+} from "../common/automation";+import type { PlanStep, SkillInput } from "../common/skill";++/* --- shared array helpers (pure) ----------------------------------------- */++export function replaceAt<T>(arr: T[], i: number, next: T): T[] {+ const out = arr.slice();+ out[i] = next;+ return out;+}+export function removeAt<T>(arr: T[], i: number): T[] {+ return arr.filter((_, idx) => idx !== i);+}+export function moveItem<T>(arr: T[], i: number, dir: -1 | 1): T[] {+ const j = i + dir;+ if (j < 0 || j >= arr.length) return arr;+ const out = arr.slice();+ [out[i], out[j]] = [out[j], out[i]];+ return out;+}++/* --- shared vocab (source + step-kind) ----------------------------------- */++export const SOURCE_LABEL: Record<SkillInput["source"], string> = {+ fixed: "Fixed value",+ provided: "You provide it",+ locate: "The agent finds it",+};++const SOURCE_OPTIONS: { value: SkillInput["source"]; label: string }[] = [+ { value: "fixed", label: "Fixed value" },+ { value: "provided", label: "You provide it" },+ { value: "locate", label: "The agent finds it" },+];++const SOURCE_HINT: Record<SkillInput["source"], string> = {+ fixed: "The exact URL / path / value, baked in",+ provided: "What to ask you for when it runs",+ locate: "How the agent should find it on your device",+};++const STEP_KIND_LABEL: Record<PlanStep["kind"], string> = {+ calculation: "Calculates",+ action: "Does",+};++const STEP_KIND_OPTIONS: { value: PlanStep["kind"]; label: string }[] = [+ { value: "calculation", label: "Calculates" },+ { value: "action", label: "Does" },+];++/* --- EditableText: reads as plain text, becomes an input on click --------- */++export function EditableText({+ value,+ onChange,+ placeholder = "",+ multiline = false,+ as = "span",+ className = "",+ rows = 2,+ hideEmpty = false,+ ariaLabel,+}: {+ value: string;+ onChange: (next: string) => void;+ placeholder?: string;+ multiline?: boolean;+ as?: "span" | "div" | "p";+ className?: string;+ rows?: number;+ /** When empty, stay invisible until the surrounding tile is hovered. */+ hideEmpty?: boolean;+ ariaLabel?: string;+}) {+ const [editing, setEditing] = useState(false);+ const [draft, setDraft] = useState(value);+ const ref = useRef<HTMLInputElement | HTMLTextAreaElement | null>(null);++ useEffect(() => {+ if (!editing) return;+ const el = ref.current;+ if (!el) return;+ el.focus();+ const end = el.value.length;+ el.setSelectionRange(end, end);+ }, [editing]);++ const begin = () => {+ setDraft(value);+ setEditing(true);+ };+ const commit = () => {+ setEditing(false);+ if (draft !== value) onChange(draft);+ };+ const cancel = () => {+ setDraft(value);+ setEditing(false);+ };++ if (editing) {+ const shared = {+ value: draft,+ "aria-label": ariaLabel ?? placeholder,+ onChange: (e: { target: { value: string } }) => setDraft(e.target.value),+ onBlur: commit,+ };+ return multiline ? (+ <textarea+ ref={ref as React.Ref<HTMLTextAreaElement>}+ className={`ed-input ed-input-multi ${className}`}+ rows={rows}+ onKeyDown={(e) => {+ if (e.key === "Escape") {+ e.preventDefault();+ cancel();+ } else if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {+ e.preventDefault();+ commit();+ }+ }}+ {...shared}+ />+ ) : (+ <input+ ref={ref as React.Ref<HTMLInputElement>}+ className={`ed-input ${className}`}+ onKeyDown={(e) => {+ if (e.key === "Escape") {+ e.preventDefault();+ cancel();+ } else if (e.key === "Enter") {+ e.preventDefault();+ commit();+ }+ }}+ {...shared}+ />+ );+ }++ const empty = value.trim().length === 0;+ const Tag = as;+ return (+ <Tag+ className={`ed-read ${multiline ? "ed-read-multi" : ""} ${empty ? "ed-empty" : ""} ${+ empty && hideEmpty ? "ed-hide" : ""+ } ${className}`}+ tabIndex={0}+ role="textbox"+ aria-label={ariaLabel ?? placeholder}+ title="Click to edit"+ onClick={begin}+ onKeyDown={(e) => {+ if (e.key === "Enter" || e.key === " ") {+ e.preventDefault();+ begin();+ }+ }}+ >+ {empty ? placeholder : value}+ </Tag>+ );+}++/* --- EditablePill: reads as a tinted pill, becomes a select on click ------ */++function EditablePill<T extends string>({+ value,+ options,+ onChange,+ pill,+ selectClassName = "",+}: {+ value: T;+ options: { value: T; label: string }[];+ onChange: (next: T) => void;+ pill: ReactNode;+ selectClassName?: string;+}) {+ const [editing, setEditing] = useState(false);+ const ref = useRef<HTMLSelectElement>(null);++ useEffect(() => {+ if (editing) ref.current?.focus();+ }, [editing]);++ if (editing) {+ return (+ <select+ ref={ref}+ className={`tile-select ${selectClassName}`}+ value={value}+ onChange={(e) => {+ onChange(e.target.value as T);+ setEditing(false);+ }}+ onBlur={() => setEditing(false)}+ >+ {options.map((o) => (+ <option key={o.value} value={o.value}>+ {o.label}+ </option>+ ))}+ </select>+ );+ }+ return (+ <button type="button" className="pill-btn" title="Click to change" onClick={() => setEditing(true)}>+ {pill}+ </button>+ );+}++/* --- reusable row controls (hover-revealed by CSS) ----------------------- */++function RowControls({+ index,+ count,+ onMove,+ onRemove,+}: {+ index: number;+ count: number;+ /** Omit to hide reorder arrows (e.g. for unordered inputs). */+ onMove?: (dir: -1 | 1) => void;+ onRemove: () => void;+}) {+ return (+ <div className="row-controls">+ {onMove && (+ <>+ <button+ type="button"+ className="tile-btn"+ title="Move up"+ disabled={index === 0}+ onClick={() => onMove(-1)}+ >+ ↑+ </button>+ <button+ type="button"+ className="tile-btn"+ title="Move down"+ disabled={index === count - 1}+ onClick={() => onMove(1)}+ >+ ↓+ </button>+ </>+ )}+ <button type="button" className="tile-btn tile-btn-del" title="Remove" onClick={onRemove}>+ ×+ </button>+ </div>+ );+}++function AddTile({ label, onAdd }: { label: string; onAdd: () => void }) {+ return (+ <button type="button" className="tile-add" onClick={onAdd}>+ + {label}+ </button>+ );+}++let uidCounter = 0;+function newId(prefix: string): string {+ uidCounter += 1;+ return `${prefix}${Date.now().toString(36)}${uidCounter.toString(36)}`;+}++/* --- Inputs (a SET — editable, add/remove, but NOT reorderable) ----------- */++export function InputTiles({+ inputs,+ onChange,+}: {+ inputs: SkillInput[];+ onChange: (next: SkillInput[]) => void;+}) {+ const patch = (i: number, part: Partial<SkillInput>) =>+ onChange(replaceAt(inputs, i, { ...inputs[i], ...part }));++ return (+ <div className="tiles">+ {inputs.map((inp, i) => (+ <div key={i} className="tile input-tile">+ <div className="tile-head">+ <EditableText+ className="ed-name"+ value={inp.name}+ placeholder="Input name"+ ariaLabel="Input name"+ onChange={(v) => patch(i, { name: v })}+ />+ <EditablePill+ value={inp.source}+ options={SOURCE_OPTIONS}+ onChange={(v) => patch(i, { source: v })}+ pill={<span className={`src-badge src-${inp.source}`}>{SOURCE_LABEL[inp.source]}</span>}+ />+ <RowControls index={i} count={inputs.length} onRemove={() => onChange(removeAt(inputs, i))} />+ </div>+ <EditableText+ as="p"+ multiline+ className="ed-detail"+ value={inp.detail}+ placeholder={SOURCE_HINT[inp.source]}+ ariaLabel="Input detail"+ hideEmpty+ onChange={(v) => patch(i, { detail: v })}+ />+ </div>+ ))}+ <AddTile+ label="Add input"+ onAdd={() => onChange([...inputs, { name: "", description: "", source: "provided", detail: "" }])}+ />+ </div>+ );+}++/* --- Skill steps (ordered; typed calculation / action) -------------------- */++export function SkillStepTiles({+ steps,+ onChange,+}: {+ steps: PlanStep[];+ onChange: (next: PlanStep[]) => void;+}) {+ const patch = (i: number, part: Partial<PlanStep>) =>+ onChange(replaceAt(steps, i, { ...steps[i], ...part }));++ return (+ <div className="tiles">+ {steps.map((s, i) => (+ <div key={i} className={`tile step-tile step-${s.kind}`}>+ <div className="tile-head">+ <EditablePill+ value={s.kind}+ options={STEP_KIND_OPTIONS}+ onChange={(v) => patch(i, { kind: v })}+ pill={<span className={`step-kind step-kind-${s.kind}`}>{STEP_KIND_LABEL[s.kind]}</span>}+ />+ <EditableText+ className="ed-strong"+ value={s.text}+ placeholder="What happens in this step?"+ ariaLabel="Step description"+ multiline+ onChange={(v) => patch(i, { text: v })}+ />+ <RowControls+ index={i}+ count={steps.length}+ onMove={(dir) => onChange(moveItem(steps, i, dir))}+ onRemove={() => onChange(removeAt(steps, i))}+ />+ </div>+ <div className="tile-foot">+ <EditableText+ className="ed-tool"+ value={s.tool}+ placeholder="+ native tool"+ ariaLabel="Native tool"+ hideEmpty+ onChange={(v) => patch(i, { tool: v })}+ />+ <button+ type="button"+ className={`confirm-toggle${s.pausesForConfirmation ? " on" : ""}`}+ title="Pause for your OK before running this step"+ onClick={() => patch(i, { pausesForConfirmation: !s.pausesForConfirmation })}+ >+ asks first+ </button>+ </div>+ </div>+ ))}+ <AddTile+ label="Add step"+ onAdd={() => onChange([...steps, { kind: "action", text: "", tool: "", pausesForConfirmation: false }])}+ />+ </div>+ );+}++/* --- Automation steps (ordered; label + NL prompt) ------------------------ */++export function AutomationStepTiles({+ steps,+ onChange,+}: {+ steps: AutomationStepDraft[];+ onChange: (next: AutomationStepDraft[]) => void;+}) {+ const patch = (i: number, part: Partial<AutomationStepDraft>) =>+ onChange(replaceAt(steps, i, { ...steps[i], ...part }));++ return (+ <div className="tiles">+ {steps.map((s, i) => (+ <div key={i} className="tile step-tile">+ <div className="tile-head">+ <span className="tile-num">{i + 1}</span>+ <EditableText+ className="ed-strong"+ value={s.label}+ placeholder="Step label"+ ariaLabel="Step label"+ onChange={(v) => patch(i, { label: v })}+ />+ <RowControls+ index={i}+ count={steps.length}+ onMove={(dir) => onChange(moveItem(steps, i, dir))}+ onRemove={() => onChange(removeAt(steps, i))}+ />+ </div>+ <EditableText+ as="p"+ multiline+ className="ed-detail"+ value={s.prompt}+ placeholder="The instruction the agent runs for this step"+ ariaLabel="Step instruction"+ onChange={(v) => patch(i, { prompt: v })}+ />+ </div>+ ))}+ <AddTile label="Add step" onAdd={() => onChange([...steps, { label: "", prompt: "" }])} />+ </div>+ );+}++/* --- Analysis steps (ordered; title + detail) ----------------------------- */++export function AnalysisStepTiles({+ steps,+ onChange,+}: {+ steps: AnalysisStep[];+ onChange: (next: AnalysisStep[]) => void;+}) {+ const patch = (i: number, part: Partial<AnalysisStep>) =>+ onChange(replaceAt(steps, i, { ...steps[i], ...part }));++ return (+ <div className="tiles">+ {steps.map((s, i) => (+ <div key={s.id} className="tile step-tile">+ <div className="tile-head">+ <span className="tile-num">{i + 1}</span>+ <EditableText+ className="ed-strong"+ value={s.title}+ placeholder="What you did"+ ariaLabel="Step title"+ onChange={(v) => patch(i, { title: v })}+ />+ <RowControls+ index={i}+ count={steps.length}+ onMove={(dir) => onChange(moveItem(steps, i, dir))}+ onRemove={() => onChange(removeAt(steps, i))}+ />+ </div>+ <EditableText+ as="p"+ multiline+ className="ed-detail"+ value={s.detail}+ placeholder="A little more detail"+ ariaLabel="Step detail"+ hideEmpty+ onChange={(v) => patch(i, { detail: v })}+ />+ </div>+ ))}+ <AddTile+ label="Add step"+ onAdd={() =>+ onChange([+ ...steps,+ { id: newId("u"), title: "", detail: "", apps: [], evidence: [], confidence: "medium" },+ ])+ }+ />+ </div>+ );+}++/* --- Automation schedule editor (read-first: sentence → controls) --------- */++const DAY_LABELS = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];+const INTERVAL_CHOICES = [15, 30, 60, 120, 180, 240, 360, 720];++function fmtTime(t: TimeOfDay): string {+ return `${String(t.hour).padStart(2, "0")}:${String(t.minute).padStart(2, "0")}`;+}+function parseTime(v: string): TimeOfDay {+ const [h, m] = v.split(":").map((n) => Number.parseInt(n, 10));+ return { hour: Number.isFinite(h) ? h : 0, minute: Number.isFinite(m) ? m : 0 };+}+function anchorOf(s: AutomationSchedule): TimeOfDay {+ if (s.kind === "single") return s.time;+ if (s.kind === "interval") return s.anchor;+ return s.times[0] ?? { hour: 9, minute: 0 };+}++/** Compact schedule editor. Reads as a plain-language sentence; "Edit" reveals the+ * structured controls. Structured edits clear `naturalLanguage` so the displayed+ * cadence always reflects the real firing rule. */+export function ScheduleEditor({+ schedule,+ onChange,+}: {+ schedule: AutomationSchedule;+ onChange: (next: AutomationSchedule) => void;+}) {+ const [editing, setEditing] = useState(false);++ if (!editing) {+ return (+ <div className="sched-read">+ <span className="sched-when">{describeSchedule(schedule)}</span>+ <button type="button" className="linky" onClick={() => setEditing(true)}>+ Edit+ </button>+ </div>+ );+ }++ const days = schedule.days;+ const toggleDay = (d: number) => {+ const next = days.includes(d) ? days.filter((x) => x !== d) : [...days, d].sort();+ onChange({ ...schedule, days: next, naturalLanguage: "" });+ };++ const changeKind = (kind: AutomationSchedule["kind"]) => {+ if (kind === schedule.kind) return;+ const anchor = anchorOf(schedule);+ if (kind === "single") onChange({ kind: "single", naturalLanguage: "", days, time: anchor });+ else if (kind === "interval")+ onChange({ kind: "interval", naturalLanguage: "", days, intervalMinutes: 60, anchor });+ else onChange({ kind: "multi", naturalLanguage: "", days, times: [anchor] });+ };++ return (+ <div className="sched-edit">+ <div className="sched-row">+ <select+ className="tile-select"+ value={schedule.kind}+ onChange={(e) => changeKind(e.target.value as AutomationSchedule["kind"])}+ >+ <option value="single">Once a day</option>+ <option value="interval">Every…</option>+ <option value="multi">A few times a day</option>+ </select>++ {schedule.kind === "single" && (+ <input+ type="time"+ className="tile-input tile-time"+ value={fmtTime(schedule.time)}+ onChange={(e) => onChange({ ...schedule, time: parseTime(e.target.value), naturalLanguage: "" })}+ />+ )}++ {schedule.kind === "interval" && (+ <>+ <select+ className="tile-select"+ value={schedule.intervalMinutes}+ onChange={(e) =>+ onChange({ ...schedule, intervalMinutes: Number.parseInt(e.target.value, 10), naturalLanguage: "" })+ }+ >+ {INTERVAL_CHOICES.map((m) => (+ <option key={m} value={m}>+ {m < 60 ? `${m} min` : `${m / 60} h`}+ </option>+ ))}+ </select>+ <span className="sched-lbl">from</span>+ <input+ type="time"+ className="tile-input tile-time"+ value={fmtTime(schedule.anchor)}+ onChange={(e) => onChange({ ...schedule, anchor: parseTime(e.target.value), naturalLanguage: "" })}+ />+ </>+ )}++ <button type="button" className="linky sched-done" onClick={() => setEditing(false)}>+ Done+ </button>+ </div>++ {schedule.kind === "multi" && (+ <div className="sched-times">+ {schedule.times.map((t, i) => (+ <div key={i} className="sched-time-row">+ <input+ type="time"+ className="tile-input tile-time"+ value={fmtTime(t)}+ onChange={(e) =>+ onChange({ ...schedule, times: replaceAt(schedule.times, i, parseTime(e.target.value)), naturalLanguage: "" })+ }+ />+ <button+ type="button"+ className="tile-btn tile-btn-del"+ title="Remove time"+ disabled={schedule.times.length <= 1}+ onClick={() => onChange({ ...schedule, times: removeAt(schedule.times, i), naturalLanguage: "" })}+ >+ ×+ </button>+ </div>+ ))}+ <button+ type="button"+ className="tile-add"+ onClick={() =>+ onChange({ ...schedule, times: [...schedule.times, anchorOf(schedule)], naturalLanguage: "" })+ }+ >+ + Add time+ </button>+ </div>+ )}++ <div className="sched-days">+ <span className="sched-lbl">On</span>+ {DAY_LABELS.map((lbl, d) => (+ <button+ key={d}+ type="button"+ className={`day-chip${days.length === 0 || days.includes(d) ? " on" : ""}`}+ title={days.length === 0 ? "Every day" : undefined}+ onClick={() => toggleDay(d)}+ >+ {lbl}+ </button>+ ))}+ {days.length === 0 && <span className="sched-lbl sched-every">every day</span>}+ </div>+ </div>+ );+}