The design language that makes your AI harness better at design.
JavaScript
feat(skill): make bare /impeccable context-aware (re: #159)
Paul Bakaus5793e842922b
diff --git a/.agents/skills/impeccable/SKILL.md b/.agents/skills/impeccable/SKILL.mdindex f107ec6ca..ca57daafc 100644--- a/.agents/skills/impeccable/SKILL.md+++ b/.agents/skills/impeccable/SKILL.md@@ -148,7 +148,16 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be### Routing rules-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.+1. **No argument**: the user is asking "what should I do?" Make the menu context-aware instead of static. Setup has already run `context.mjs`; if that reported `NO_PRODUCT_MD` you are already in init (setup), so finish that and skip this. Otherwise run `node .agents/skills/impeccable/scripts/context-signals.mjs` once and read its JSON, then lead with the **2-3 highest-value next commands**, each with a one-line reason pulled from the signals, followed by the full menu (the table above, grouped by category). **Never auto-run a command; the recommendation is a suggestion the user confirms.**++ Reason over the signals; there is no score to obey:+ - `setup.hasDesign` false while `setup.hasCode` true → `document` (capture the visual system).+ - `critique.latest` with a low `score` or non-zero `p0` / `p1` → `polish` (it reads that snapshot as its backlog), or re-run `critique` if the snapshot looks stale.+ - `git.changedFiles` pointing at one surface → scope `audit` or `polish` to those files specifically, naming them.+ - `devServer.running` true → `live` is available for in-browser iteration; if false, don't lead with `live`.+ - Otherwise group by intent exactly as init's "Recommend starting points" step does (build new / improve what's there / iterate visually), tailored to `setup.register`.++ Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.diff --git a/.agents/skills/impeccable/scripts/context-signals.mjs b/.agents/skills/impeccable/scripts/context-signals.mjsnew file mode 100644index 000000000..cd54793af--- /dev/null+++ b/.agents/skills/impeccable/scripts/context-signals.mjs@@ -0,0 +1,187 @@+#!/usr/bin/env node+/**+ * Context-signals gatherer for the bare `{{command_prefix}}impeccable`+ * (no-argument) path. Collects cheap, deterministic signals about the current+ * project and emits them as JSON.+ *+ * It does NOT score or rank. The agent reasons over the raw signals using its+ * knowledge of the command catalog (see SKILL.md routing rule 1). Deliberately+ * light: no LLM calls, no detector run (`npx impeccable detect` is heavier and+ * opt-in), no file writes. Every probe is best-effort and never throws; the+ * output is always valid JSON.+ *+ * Signals:+ * - setup: PRODUCT.md / DESIGN.md presence, register, whether code exists+ * - critique: the latest cached critique score (.impeccable/critique)+ * - git: branch + files changed vs the default branch (a scope hint)+ * - devServer: whether a local dev server answers on a common port (gates live)+ */+import fs from 'node:fs';+import net from 'node:net';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFileSync } from 'node:child_process';+import { loadContext, extractRegister } from './context.mjs';+import { getCritiqueDir } from './impeccable-paths.mjs';++/** Is there code here at all, or just context files / an empty repo? */+function hasCode(cwd) {+ if (fs.existsSync(path.join(cwd, 'package.json'))) return true;+ for (const d of ['src', 'app', 'pages', 'site', 'public', 'components', 'lib']) {+ if (fs.existsSync(path.join(cwd, d))) return true;+ }+ return false;+}++/**+ * The most recent critique snapshot across all targets. Filenames are+ * timestamp-prefixed (`<iso>__<slug>.md`), so a lexical sort is chronological.+ * Parses the small frontmatter for score + P0/P1 counts.+ */+function latestCritique(cwd) {+ try {+ const dir = getCritiqueDir(cwd);+ if (!fs.existsSync(dir)) return null;+ const files = fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort();+ if (!files.length) return null;+ const newest = files[files.length - 1];+ const text = fs.readFileSync(path.join(dir, newest), 'utf-8');+ const front = text.split('---')[1] || '';+ const get = (k) => {+ const m = front.match(new RegExp(`^${k}:\\s*(.+)$`, 'm'));+ return m ? m[1].trim() : null;+ };+ const num = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+ };+ return {+ slug: get('slug'),+ score: num(get('score')),+ p0: num(get('p0')),+ p1: num(get('p1')),+ timestamp: get('timestamp'),+ file: path.relative(cwd, path.join(dir, newest)),+ };+ } catch {+ return null;+ }+}++/** Branch + a scope hint: files changed vs the default branch, else working tree. */+function gitSignals(cwd) {+ const run = (args, { trim = true } = {}) => {+ try {+ const out = execFileSync('git', args, {+ cwd,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'ignore'],+ });+ return trim ? out.trim() : out;+ } catch {+ return null;+ }+ };+ if (run(['rev-parse', '--is-inside-work-tree']) !== 'true') {+ return { isRepo: false, branch: null, base: null, changedFiles: [], changedCount: 0 };+ }+ const branch = run(['rev-parse', '--abbrev-ref', 'HEAD']);+ let base = null;+ for (const b of ['main', 'master']) {+ if (run(['rev-parse', '--verify', '--quiet', b]) !== null) {+ base = b;+ break;+ }+ }+ const diffBase = base && branch && branch !== base ? base : null;+ const fromDiff = diffBase ? run(['diff', '--name-only', `${diffBase}...HEAD`]) : null;+ // porcelain lines are `XY PATH`: a 2-char status + a space, then the path.+ // Don't trim the combined output — an unstaged-modified line starts with a+ // leading space (` M path`), and a global trim would eat the first line's+ // status column and shift the slice. Renames render as `old -> new`.+ const fromStatus = run(['-c', 'core.quotepath=false', 'status', '--porcelain'], { trim: false });+ let changed = [];+ if (fromDiff) {+ changed = fromDiff.split('\n').filter(Boolean);+ } else if (fromStatus) {+ changed = fromStatus.split(/\r?\n/).filter(Boolean).map((l) => {+ const p = l.slice(3);+ const arrow = p.indexOf(' -> ');+ return arrow === -1 ? p : p.slice(arrow + 4);+ });+ }+ return {+ isRepo: true,+ branch,+ base: diffBase,+ changedFiles: changed.slice(0, 50),+ changedCount: changed.length,+ };+}++const COMMON_DEV_PORTS = [4321, 3000, 5173, 5174, 8080, 8000, 4200];++function probePort(port, timeout = 250) {+ return new Promise((resolve) => {+ const sock = new net.Socket();+ let settled = false;+ const finish = (ok) => {+ if (settled) return;+ settled = true;+ try { sock.destroy(); } catch { /* ignore */ }+ resolve(ok);+ };+ sock.setTimeout(timeout);+ sock.once('connect', () => finish(true));+ sock.once('timeout', () => finish(false));+ sock.once('error', () => finish(false));+ sock.connect(port, '127.0.0.1');+ });+}++async function devServerSignals() {+ const open = [];+ await Promise.all(+ COMMON_DEV_PORTS.map(async (p) => {+ if (await probePort(p)) open.push(p);+ }),+ );+ open.sort((a, b) => a - b);+ return { running: open.length > 0, ports: open };+}++export async function gatherSignals(cwd = process.cwd()) {+ const ctx = loadContext(cwd);+ return {+ setup: {+ hasProduct: ctx.hasProduct,+ productPath: ctx.productPath,+ hasDesign: ctx.hasDesign,+ designPath: ctx.designPath,+ hasCode: hasCode(cwd),+ register: extractRegister(ctx.product),+ },+ critique: { latest: latestCritique(cwd) },+ git: gitSignals(cwd),+ devServer: await devServerSignals(),+ };+}++async function cli() {+ const signals = await gatherSignals(process.cwd());+ process.stdout.write(`${JSON.stringify(signals, null, 2)}\n`);+}++function invokedAsScript() {+ const arg = process.argv[1];+ if (!arg) return false;+ try {+ return fs.realpathSync(arg) === fs.realpathSync(fileURLToPath(import.meta.url));+ } catch {+ return false;+ }+}++if (invokedAsScript()) {+ cli();+}diff --git a/.agents/skills/impeccable/scripts/context.mjs b/.agents/skills/impeccable/scripts/context.mjsindex eb4000717..8725469bf 100644--- a/.agents/skills/impeccable/scripts/context.mjs+++ b/.agents/skills/impeccable/scripts/context.mjs@@ -94,7 +94,7 @@ function safeRead(p) {* for a `## Register` section and reading the first non-empty line that* follows it. Returns null when the file is legacy / register-less.*/-function extractRegister(product) {+export function extractRegister(product) {if (!product) return null;const lines = product.split('\n');for (let i = 0; i < lines.length; i++) {diff --git a/.claude/skills/impeccable/SKILL.md b/.claude/skills/impeccable/SKILL.mdindex 1edabd6d6..c61880528 100644--- a/.claude/skills/impeccable/SKILL.md+++ b/.claude/skills/impeccable/SKILL.md@@ -142,7 +142,16 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be### Routing rules-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.+1. **No argument**: the user is asking "what should I do?" Make the menu context-aware instead of static. Setup has already run `context.mjs`; if that reported `NO_PRODUCT_MD` you are already in init (setup), so finish that and skip this. Otherwise run `node .claude/skills/impeccable/scripts/context-signals.mjs` once and read its JSON, then lead with the **2-3 highest-value next commands**, each with a one-line reason pulled from the signals, followed by the full menu (the table above, grouped by category). **Never auto-run a command; the recommendation is a suggestion the user confirms.**++ Reason over the signals; there is no score to obey:+ - `setup.hasDesign` false while `setup.hasCode` true → `document` (capture the visual system).+ - `critique.latest` with a low `score` or non-zero `p0` / `p1` → `polish` (it reads that snapshot as its backlog), or re-run `critique` if the snapshot looks stale.+ - `git.changedFiles` pointing at one surface → scope `audit` or `polish` to those files specifically, naming them.+ - `devServer.running` true → `live` is available for in-browser iteration; if false, don't lead with `live`.+ - Otherwise group by intent exactly as init's "Recommend starting points" step does (build new / improve what's there / iterate visually), tailored to `setup.register`.++ Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.diff --git a/.claude/skills/impeccable/scripts/context-signals.mjs b/.claude/skills/impeccable/scripts/context-signals.mjsnew file mode 100644index 000000000..cd54793af--- /dev/null+++ b/.claude/skills/impeccable/scripts/context-signals.mjs@@ -0,0 +1,187 @@+#!/usr/bin/env node+/**+ * Context-signals gatherer for the bare `{{command_prefix}}impeccable`+ * (no-argument) path. Collects cheap, deterministic signals about the current+ * project and emits them as JSON.+ *+ * It does NOT score or rank. The agent reasons over the raw signals using its+ * knowledge of the command catalog (see SKILL.md routing rule 1). Deliberately+ * light: no LLM calls, no detector run (`npx impeccable detect` is heavier and+ * opt-in), no file writes. Every probe is best-effort and never throws; the+ * output is always valid JSON.+ *+ * Signals:+ * - setup: PRODUCT.md / DESIGN.md presence, register, whether code exists+ * - critique: the latest cached critique score (.impeccable/critique)+ * - git: branch + files changed vs the default branch (a scope hint)+ * - devServer: whether a local dev server answers on a common port (gates live)+ */+import fs from 'node:fs';+import net from 'node:net';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFileSync } from 'node:child_process';+import { loadContext, extractRegister } from './context.mjs';+import { getCritiqueDir } from './impeccable-paths.mjs';++/** Is there code here at all, or just context files / an empty repo? */+function hasCode(cwd) {+ if (fs.existsSync(path.join(cwd, 'package.json'))) return true;+ for (const d of ['src', 'app', 'pages', 'site', 'public', 'components', 'lib']) {+ if (fs.existsSync(path.join(cwd, d))) return true;+ }+ return false;+}++/**+ * The most recent critique snapshot across all targets. Filenames are+ * timestamp-prefixed (`<iso>__<slug>.md`), so a lexical sort is chronological.+ * Parses the small frontmatter for score + P0/P1 counts.+ */+function latestCritique(cwd) {+ try {+ const dir = getCritiqueDir(cwd);+ if (!fs.existsSync(dir)) return null;+ const files = fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort();+ if (!files.length) return null;+ const newest = files[files.length - 1];+ const text = fs.readFileSync(path.join(dir, newest), 'utf-8');+ const front = text.split('---')[1] || '';+ const get = (k) => {+ const m = front.match(new RegExp(`^${k}:\\s*(.+)$`, 'm'));+ return m ? m[1].trim() : null;+ };+ const num = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+ };+ return {+ slug: get('slug'),+ score: num(get('score')),+ p0: num(get('p0')),+ p1: num(get('p1')),+ timestamp: get('timestamp'),+ file: path.relative(cwd, path.join(dir, newest)),+ };+ } catch {+ return null;+ }+}++/** Branch + a scope hint: files changed vs the default branch, else working tree. */+function gitSignals(cwd) {+ const run = (args, { trim = true } = {}) => {+ try {+ const out = execFileSync('git', args, {+ cwd,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'ignore'],+ });+ return trim ? out.trim() : out;+ } catch {+ return null;+ }+ };+ if (run(['rev-parse', '--is-inside-work-tree']) !== 'true') {+ return { isRepo: false, branch: null, base: null, changedFiles: [], changedCount: 0 };+ }+ const branch = run(['rev-parse', '--abbrev-ref', 'HEAD']);+ let base = null;+ for (const b of ['main', 'master']) {+ if (run(['rev-parse', '--verify', '--quiet', b]) !== null) {+ base = b;+ break;+ }+ }+ const diffBase = base && branch && branch !== base ? base : null;+ const fromDiff = diffBase ? run(['diff', '--name-only', `${diffBase}...HEAD`]) : null;+ // porcelain lines are `XY PATH`: a 2-char status + a space, then the path.+ // Don't trim the combined output — an unstaged-modified line starts with a+ // leading space (` M path`), and a global trim would eat the first line's+ // status column and shift the slice. Renames render as `old -> new`.+ const fromStatus = run(['-c', 'core.quotepath=false', 'status', '--porcelain'], { trim: false });+ let changed = [];+ if (fromDiff) {+ changed = fromDiff.split('\n').filter(Boolean);+ } else if (fromStatus) {+ changed = fromStatus.split(/\r?\n/).filter(Boolean).map((l) => {+ const p = l.slice(3);+ const arrow = p.indexOf(' -> ');+ return arrow === -1 ? p : p.slice(arrow + 4);+ });+ }+ return {+ isRepo: true,+ branch,+ base: diffBase,+ changedFiles: changed.slice(0, 50),+ changedCount: changed.length,+ };+}++const COMMON_DEV_PORTS = [4321, 3000, 5173, 5174, 8080, 8000, 4200];++function probePort(port, timeout = 250) {+ return new Promise((resolve) => {+ const sock = new net.Socket();+ let settled = false;+ const finish = (ok) => {+ if (settled) return;+ settled = true;+ try { sock.destroy(); } catch { /* ignore */ }+ resolve(ok);+ };+ sock.setTimeout(timeout);+ sock.once('connect', () => finish(true));+ sock.once('timeout', () => finish(false));+ sock.once('error', () => finish(false));+ sock.connect(port, '127.0.0.1');+ });+}++async function devServerSignals() {+ const open = [];+ await Promise.all(+ COMMON_DEV_PORTS.map(async (p) => {+ if (await probePort(p)) open.push(p);+ }),+ );+ open.sort((a, b) => a - b);+ return { running: open.length > 0, ports: open };+}++export async function gatherSignals(cwd = process.cwd()) {+ const ctx = loadContext(cwd);+ return {+ setup: {+ hasProduct: ctx.hasProduct,+ productPath: ctx.productPath,+ hasDesign: ctx.hasDesign,+ designPath: ctx.designPath,+ hasCode: hasCode(cwd),+ register: extractRegister(ctx.product),+ },+ critique: { latest: latestCritique(cwd) },+ git: gitSignals(cwd),+ devServer: await devServerSignals(),+ };+}++async function cli() {+ const signals = await gatherSignals(process.cwd());+ process.stdout.write(`${JSON.stringify(signals, null, 2)}\n`);+}++function invokedAsScript() {+ const arg = process.argv[1];+ if (!arg) return false;+ try {+ return fs.realpathSync(arg) === fs.realpathSync(fileURLToPath(import.meta.url));+ } catch {+ return false;+ }+}++if (invokedAsScript()) {+ cli();+}diff --git a/.claude/skills/impeccable/scripts/context.mjs b/.claude/skills/impeccable/scripts/context.mjsindex eb4000717..8725469bf 100644--- a/.claude/skills/impeccable/scripts/context.mjs+++ b/.claude/skills/impeccable/scripts/context.mjs@@ -94,7 +94,7 @@ function safeRead(p) {* for a `## Register` section and reading the first non-empty line that* follows it. Returns null when the file is legacy / register-less.*/-function extractRegister(product) {+export function extractRegister(product) {if (!product) return null;const lines = product.split('\n');for (let i = 0; i < lines.length; i++) {diff --git a/.cursor/skills/impeccable/SKILL.md b/.cursor/skills/impeccable/SKILL.mdindex b4aaa698e..83dcdfbd9 100644--- a/.cursor/skills/impeccable/SKILL.md+++ b/.cursor/skills/impeccable/SKILL.md@@ -138,7 +138,16 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be### Routing rules-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.+1. **No argument**: the user is asking "what should I do?" Make the menu context-aware instead of static. Setup has already run `context.mjs`; if that reported `NO_PRODUCT_MD` you are already in init (setup), so finish that and skip this. Otherwise run `node .cursor/skills/impeccable/scripts/context-signals.mjs` once and read its JSON, then lead with the **2-3 highest-value next commands**, each with a one-line reason pulled from the signals, followed by the full menu (the table above, grouped by category). **Never auto-run a command; the recommendation is a suggestion the user confirms.**++ Reason over the signals; there is no score to obey:+ - `setup.hasDesign` false while `setup.hasCode` true → `document` (capture the visual system).+ - `critique.latest` with a low `score` or non-zero `p0` / `p1` → `polish` (it reads that snapshot as its backlog), or re-run `critique` if the snapshot looks stale.+ - `git.changedFiles` pointing at one surface → scope `audit` or `polish` to those files specifically, naming them.+ - `devServer.running` true → `live` is available for in-browser iteration; if false, don't lead with `live`.+ - Otherwise group by intent exactly as init's "Recommend starting points" step does (build new / improve what's there / iterate visually), tailored to `setup.register`.++ Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.diff --git a/.cursor/skills/impeccable/scripts/context-signals.mjs b/.cursor/skills/impeccable/scripts/context-signals.mjsnew file mode 100644index 000000000..cd54793af--- /dev/null+++ b/.cursor/skills/impeccable/scripts/context-signals.mjs@@ -0,0 +1,187 @@+#!/usr/bin/env node+/**+ * Context-signals gatherer for the bare `{{command_prefix}}impeccable`+ * (no-argument) path. Collects cheap, deterministic signals about the current+ * project and emits them as JSON.+ *+ * It does NOT score or rank. The agent reasons over the raw signals using its+ * knowledge of the command catalog (see SKILL.md routing rule 1). Deliberately+ * light: no LLM calls, no detector run (`npx impeccable detect` is heavier and+ * opt-in), no file writes. Every probe is best-effort and never throws; the+ * output is always valid JSON.+ *+ * Signals:+ * - setup: PRODUCT.md / DESIGN.md presence, register, whether code exists+ * - critique: the latest cached critique score (.impeccable/critique)+ * - git: branch + files changed vs the default branch (a scope hint)+ * - devServer: whether a local dev server answers on a common port (gates live)+ */+import fs from 'node:fs';+import net from 'node:net';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFileSync } from 'node:child_process';+import { loadContext, extractRegister } from './context.mjs';+import { getCritiqueDir } from './impeccable-paths.mjs';++/** Is there code here at all, or just context files / an empty repo? */+function hasCode(cwd) {+ if (fs.existsSync(path.join(cwd, 'package.json'))) return true;+ for (const d of ['src', 'app', 'pages', 'site', 'public', 'components', 'lib']) {+ if (fs.existsSync(path.join(cwd, d))) return true;+ }+ return false;+}++/**+ * The most recent critique snapshot across all targets. Filenames are+ * timestamp-prefixed (`<iso>__<slug>.md`), so a lexical sort is chronological.+ * Parses the small frontmatter for score + P0/P1 counts.+ */+function latestCritique(cwd) {+ try {+ const dir = getCritiqueDir(cwd);+ if (!fs.existsSync(dir)) return null;+ const files = fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort();+ if (!files.length) return null;+ const newest = files[files.length - 1];+ const text = fs.readFileSync(path.join(dir, newest), 'utf-8');+ const front = text.split('---')[1] || '';+ const get = (k) => {+ const m = front.match(new RegExp(`^${k}:\\s*(.+)$`, 'm'));+ return m ? m[1].trim() : null;+ };+ const num = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+ };+ return {+ slug: get('slug'),+ score: num(get('score')),+ p0: num(get('p0')),+ p1: num(get('p1')),+ timestamp: get('timestamp'),+ file: path.relative(cwd, path.join(dir, newest)),+ };+ } catch {+ return null;+ }+}++/** Branch + a scope hint: files changed vs the default branch, else working tree. */+function gitSignals(cwd) {+ const run = (args, { trim = true } = {}) => {+ try {+ const out = execFileSync('git', args, {+ cwd,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'ignore'],+ });+ return trim ? out.trim() : out;+ } catch {+ return null;+ }+ };+ if (run(['rev-parse', '--is-inside-work-tree']) !== 'true') {+ return { isRepo: false, branch: null, base: null, changedFiles: [], changedCount: 0 };+ }+ const branch = run(['rev-parse', '--abbrev-ref', 'HEAD']);+ let base = null;+ for (const b of ['main', 'master']) {+ if (run(['rev-parse', '--verify', '--quiet', b]) !== null) {+ base = b;+ break;+ }+ }+ const diffBase = base && branch && branch !== base ? base : null;+ const fromDiff = diffBase ? run(['diff', '--name-only', `${diffBase}...HEAD`]) : null;+ // porcelain lines are `XY PATH`: a 2-char status + a space, then the path.+ // Don't trim the combined output — an unstaged-modified line starts with a+ // leading space (` M path`), and a global trim would eat the first line's+ // status column and shift the slice. Renames render as `old -> new`.+ const fromStatus = run(['-c', 'core.quotepath=false', 'status', '--porcelain'], { trim: false });+ let changed = [];+ if (fromDiff) {+ changed = fromDiff.split('\n').filter(Boolean);+ } else if (fromStatus) {+ changed = fromStatus.split(/\r?\n/).filter(Boolean).map((l) => {+ const p = l.slice(3);+ const arrow = p.indexOf(' -> ');+ return arrow === -1 ? p : p.slice(arrow + 4);+ });+ }+ return {+ isRepo: true,+ branch,+ base: diffBase,+ changedFiles: changed.slice(0, 50),+ changedCount: changed.length,+ };+}++const COMMON_DEV_PORTS = [4321, 3000, 5173, 5174, 8080, 8000, 4200];++function probePort(port, timeout = 250) {+ return new Promise((resolve) => {+ const sock = new net.Socket();+ let settled = false;+ const finish = (ok) => {+ if (settled) return;+ settled = true;+ try { sock.destroy(); } catch { /* ignore */ }+ resolve(ok);+ };+ sock.setTimeout(timeout);+ sock.once('connect', () => finish(true));+ sock.once('timeout', () => finish(false));+ sock.once('error', () => finish(false));+ sock.connect(port, '127.0.0.1');+ });+}++async function devServerSignals() {+ const open = [];+ await Promise.all(+ COMMON_DEV_PORTS.map(async (p) => {+ if (await probePort(p)) open.push(p);+ }),+ );+ open.sort((a, b) => a - b);+ return { running: open.length > 0, ports: open };+}++export async function gatherSignals(cwd = process.cwd()) {+ const ctx = loadContext(cwd);+ return {+ setup: {+ hasProduct: ctx.hasProduct,+ productPath: ctx.productPath,+ hasDesign: ctx.hasDesign,+ designPath: ctx.designPath,+ hasCode: hasCode(cwd),+ register: extractRegister(ctx.product),+ },+ critique: { latest: latestCritique(cwd) },+ git: gitSignals(cwd),+ devServer: await devServerSignals(),+ };+}++async function cli() {+ const signals = await gatherSignals(process.cwd());+ process.stdout.write(`${JSON.stringify(signals, null, 2)}\n`);+}++function invokedAsScript() {+ const arg = process.argv[1];+ if (!arg) return false;+ try {+ return fs.realpathSync(arg) === fs.realpathSync(fileURLToPath(import.meta.url));+ } catch {+ return false;+ }+}++if (invokedAsScript()) {+ cli();+}diff --git a/.cursor/skills/impeccable/scripts/context.mjs b/.cursor/skills/impeccable/scripts/context.mjsindex eb4000717..8725469bf 100644--- a/.cursor/skills/impeccable/scripts/context.mjs+++ b/.cursor/skills/impeccable/scripts/context.mjs@@ -94,7 +94,7 @@ function safeRead(p) {* for a `## Register` section and reading the first non-empty line that* follows it. Returns null when the file is legacy / register-less.*/-function extractRegister(product) {+export function extractRegister(product) {if (!product) return null;const lines = product.split('\n');for (let i = 0; i < lines.length; i++) {diff --git a/.gemini/skills/impeccable/SKILL.md b/.gemini/skills/impeccable/SKILL.mdindex 9ae6bd7ae..2e753039f 100644--- a/.gemini/skills/impeccable/SKILL.md+++ b/.gemini/skills/impeccable/SKILL.md@@ -139,7 +139,16 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be### Routing rules-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.+1. **No argument**: the user is asking "what should I do?" Make the menu context-aware instead of static. Setup has already run `context.mjs`; if that reported `NO_PRODUCT_MD` you are already in init (setup), so finish that and skip this. Otherwise run `node .gemini/skills/impeccable/scripts/context-signals.mjs` once and read its JSON, then lead with the **2-3 highest-value next commands**, each with a one-line reason pulled from the signals, followed by the full menu (the table above, grouped by category). **Never auto-run a command; the recommendation is a suggestion the user confirms.**++ Reason over the signals; there is no score to obey:+ - `setup.hasDesign` false while `setup.hasCode` true → `document` (capture the visual system).+ - `critique.latest` with a low `score` or non-zero `p0` / `p1` → `polish` (it reads that snapshot as its backlog), or re-run `critique` if the snapshot looks stale.+ - `git.changedFiles` pointing at one surface → scope `audit` or `polish` to those files specifically, naming them.+ - `devServer.running` true → `live` is available for in-browser iteration; if false, don't lead with `live`.+ - Otherwise group by intent exactly as init's "Recommend starting points" step does (build new / improve what's there / iterate visually), tailored to `setup.register`.++ Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.diff --git a/.gemini/skills/impeccable/scripts/context-signals.mjs b/.gemini/skills/impeccable/scripts/context-signals.mjsnew file mode 100644index 000000000..cd54793af--- /dev/null+++ b/.gemini/skills/impeccable/scripts/context-signals.mjs@@ -0,0 +1,187 @@+#!/usr/bin/env node+/**+ * Context-signals gatherer for the bare `{{command_prefix}}impeccable`+ * (no-argument) path. Collects cheap, deterministic signals about the current+ * project and emits them as JSON.+ *+ * It does NOT score or rank. The agent reasons over the raw signals using its+ * knowledge of the command catalog (see SKILL.md routing rule 1). Deliberately+ * light: no LLM calls, no detector run (`npx impeccable detect` is heavier and+ * opt-in), no file writes. Every probe is best-effort and never throws; the+ * output is always valid JSON.+ *+ * Signals:+ * - setup: PRODUCT.md / DESIGN.md presence, register, whether code exists+ * - critique: the latest cached critique score (.impeccable/critique)+ * - git: branch + files changed vs the default branch (a scope hint)+ * - devServer: whether a local dev server answers on a common port (gates live)+ */+import fs from 'node:fs';+import net from 'node:net';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFileSync } from 'node:child_process';+import { loadContext, extractRegister } from './context.mjs';+import { getCritiqueDir } from './impeccable-paths.mjs';++/** Is there code here at all, or just context files / an empty repo? */+function hasCode(cwd) {+ if (fs.existsSync(path.join(cwd, 'package.json'))) return true;+ for (const d of ['src', 'app', 'pages', 'site', 'public', 'components', 'lib']) {+ if (fs.existsSync(path.join(cwd, d))) return true;+ }+ return false;+}++/**+ * The most recent critique snapshot across all targets. Filenames are+ * timestamp-prefixed (`<iso>__<slug>.md`), so a lexical sort is chronological.+ * Parses the small frontmatter for score + P0/P1 counts.+ */+function latestCritique(cwd) {+ try {+ const dir = getCritiqueDir(cwd);+ if (!fs.existsSync(dir)) return null;+ const files = fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort();+ if (!files.length) return null;+ const newest = files[files.length - 1];+ const text = fs.readFileSync(path.join(dir, newest), 'utf-8');+ const front = text.split('---')[1] || '';+ const get = (k) => {+ const m = front.match(new RegExp(`^${k}:\\s*(.+)$`, 'm'));+ return m ? m[1].trim() : null;+ };+ const num = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+ };+ return {+ slug: get('slug'),+ score: num(get('score')),+ p0: num(get('p0')),+ p1: num(get('p1')),+ timestamp: get('timestamp'),+ file: path.relative(cwd, path.join(dir, newest)),+ };+ } catch {+ return null;+ }+}++/** Branch + a scope hint: files changed vs the default branch, else working tree. */+function gitSignals(cwd) {+ const run = (args, { trim = true } = {}) => {+ try {+ const out = execFileSync('git', args, {+ cwd,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'ignore'],+ });+ return trim ? out.trim() : out;+ } catch {+ return null;+ }+ };+ if (run(['rev-parse', '--is-inside-work-tree']) !== 'true') {+ return { isRepo: false, branch: null, base: null, changedFiles: [], changedCount: 0 };+ }+ const branch = run(['rev-parse', '--abbrev-ref', 'HEAD']);+ let base = null;+ for (const b of ['main', 'master']) {+ if (run(['rev-parse', '--verify', '--quiet', b]) !== null) {+ base = b;+ break;+ }+ }+ const diffBase = base && branch && branch !== base ? base : null;+ const fromDiff = diffBase ? run(['diff', '--name-only', `${diffBase}...HEAD`]) : null;+ // porcelain lines are `XY PATH`: a 2-char status + a space, then the path.+ // Don't trim the combined output — an unstaged-modified line starts with a+ // leading space (` M path`), and a global trim would eat the first line's+ // status column and shift the slice. Renames render as `old -> new`.+ const fromStatus = run(['-c', 'core.quotepath=false', 'status', '--porcelain'], { trim: false });+ let changed = [];+ if (fromDiff) {+ changed = fromDiff.split('\n').filter(Boolean);+ } else if (fromStatus) {+ changed = fromStatus.split(/\r?\n/).filter(Boolean).map((l) => {+ const p = l.slice(3);+ const arrow = p.indexOf(' -> ');+ return arrow === -1 ? p : p.slice(arrow + 4);+ });+ }+ return {+ isRepo: true,+ branch,+ base: diffBase,+ changedFiles: changed.slice(0, 50),+ changedCount: changed.length,+ };+}++const COMMON_DEV_PORTS = [4321, 3000, 5173, 5174, 8080, 8000, 4200];++function probePort(port, timeout = 250) {+ return new Promise((resolve) => {+ const sock = new net.Socket();+ let settled = false;+ const finish = (ok) => {+ if (settled) return;+ settled = true;+ try { sock.destroy(); } catch { /* ignore */ }+ resolve(ok);+ };+ sock.setTimeout(timeout);+ sock.once('connect', () => finish(true));+ sock.once('timeout', () => finish(false));+ sock.once('error', () => finish(false));+ sock.connect(port, '127.0.0.1');+ });+}++async function devServerSignals() {+ const open = [];+ await Promise.all(+ COMMON_DEV_PORTS.map(async (p) => {+ if (await probePort(p)) open.push(p);+ }),+ );+ open.sort((a, b) => a - b);+ return { running: open.length > 0, ports: open };+}++export async function gatherSignals(cwd = process.cwd()) {+ const ctx = loadContext(cwd);+ return {+ setup: {+ hasProduct: ctx.hasProduct,+ productPath: ctx.productPath,+ hasDesign: ctx.hasDesign,+ designPath: ctx.designPath,+ hasCode: hasCode(cwd),+ register: extractRegister(ctx.product),+ },+ critique: { latest: latestCritique(cwd) },+ git: gitSignals(cwd),+ devServer: await devServerSignals(),+ };+}++async function cli() {+ const signals = await gatherSignals(process.cwd());+ process.stdout.write(`${JSON.stringify(signals, null, 2)}\n`);+}++function invokedAsScript() {+ const arg = process.argv[1];+ if (!arg) return false;+ try {+ return fs.realpathSync(arg) === fs.realpathSync(fileURLToPath(import.meta.url));+ } catch {+ return false;+ }+}++if (invokedAsScript()) {+ cli();+}diff --git a/.gemini/skills/impeccable/scripts/context.mjs b/.gemini/skills/impeccable/scripts/context.mjsindex eb4000717..8725469bf 100644--- a/.gemini/skills/impeccable/scripts/context.mjs+++ b/.gemini/skills/impeccable/scripts/context.mjs@@ -94,7 +94,7 @@ function safeRead(p) {* for a `## Register` section and reading the first non-empty line that* follows it. Returns null when the file is legacy / register-less.*/-function extractRegister(product) {+export function extractRegister(product) {if (!product) return null;const lines = product.split('\n');for (let i = 0; i < lines.length; i++) {diff --git a/.github/skills/impeccable/SKILL.md b/.github/skills/impeccable/SKILL.mdindex 2ea882afe..6ee98f389 100644--- a/.github/skills/impeccable/SKILL.md+++ b/.github/skills/impeccable/SKILL.md@@ -140,7 +140,16 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be### Routing rules-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.+1. **No argument**: the user is asking "what should I do?" Make the menu context-aware instead of static. Setup has already run `context.mjs`; if that reported `NO_PRODUCT_MD` you are already in init (setup), so finish that and skip this. Otherwise run `node .github/skills/impeccable/scripts/context-signals.mjs` once and read its JSON, then lead with the **2-3 highest-value next commands**, each with a one-line reason pulled from the signals, followed by the full menu (the table above, grouped by category). **Never auto-run a command; the recommendation is a suggestion the user confirms.**++ Reason over the signals; there is no score to obey:+ - `setup.hasDesign` false while `setup.hasCode` true → `document` (capture the visual system).+ - `critique.latest` with a low `score` or non-zero `p0` / `p1` → `polish` (it reads that snapshot as its backlog), or re-run `critique` if the snapshot looks stale.+ - `git.changedFiles` pointing at one surface → scope `audit` or `polish` to those files specifically, naming them.+ - `devServer.running` true → `live` is available for in-browser iteration; if false, don't lead with `live`.+ - Otherwise group by intent exactly as init's "Recommend starting points" step does (build new / improve what's there / iterate visually), tailored to `setup.register`.++ Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.diff --git a/.github/skills/impeccable/scripts/context-signals.mjs b/.github/skills/impeccable/scripts/context-signals.mjsnew file mode 100644index 000000000..cd54793af--- /dev/null+++ b/.github/skills/impeccable/scripts/context-signals.mjs@@ -0,0 +1,187 @@+#!/usr/bin/env node+/**+ * Context-signals gatherer for the bare `{{command_prefix}}impeccable`+ * (no-argument) path. Collects cheap, deterministic signals about the current+ * project and emits them as JSON.+ *+ * It does NOT score or rank. The agent reasons over the raw signals using its+ * knowledge of the command catalog (see SKILL.md routing rule 1). Deliberately+ * light: no LLM calls, no detector run (`npx impeccable detect` is heavier and+ * opt-in), no file writes. Every probe is best-effort and never throws; the+ * output is always valid JSON.+ *+ * Signals:+ * - setup: PRODUCT.md / DESIGN.md presence, register, whether code exists+ * - critique: the latest cached critique score (.impeccable/critique)+ * - git: branch + files changed vs the default branch (a scope hint)+ * - devServer: whether a local dev server answers on a common port (gates live)+ */+import fs from 'node:fs';+import net from 'node:net';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFileSync } from 'node:child_process';+import { loadContext, extractRegister } from './context.mjs';+import { getCritiqueDir } from './impeccable-paths.mjs';++/** Is there code here at all, or just context files / an empty repo? */+function hasCode(cwd) {+ if (fs.existsSync(path.join(cwd, 'package.json'))) return true;+ for (const d of ['src', 'app', 'pages', 'site', 'public', 'components', 'lib']) {+ if (fs.existsSync(path.join(cwd, d))) return true;+ }+ return false;+}++/**+ * The most recent critique snapshot across all targets. Filenames are+ * timestamp-prefixed (`<iso>__<slug>.md`), so a lexical sort is chronological.+ * Parses the small frontmatter for score + P0/P1 counts.+ */+function latestCritique(cwd) {+ try {+ const dir = getCritiqueDir(cwd);+ if (!fs.existsSync(dir)) return null;+ const files = fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort();+ if (!files.length) return null;+ const newest = files[files.length - 1];+ const text = fs.readFileSync(path.join(dir, newest), 'utf-8');+ const front = text.split('---')[1] || '';+ const get = (k) => {+ const m = front.match(new RegExp(`^${k}:\\s*(.+)$`, 'm'));+ return m ? m[1].trim() : null;+ };+ const num = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+ };+ return {+ slug: get('slug'),+ score: num(get('score')),+ p0: num(get('p0')),+ p1: num(get('p1')),+ timestamp: get('timestamp'),+ file: path.relative(cwd, path.join(dir, newest)),+ };+ } catch {+ return null;+ }+}++/** Branch + a scope hint: files changed vs the default branch, else working tree. */+function gitSignals(cwd) {+ const run = (args, { trim = true } = {}) => {+ try {+ const out = execFileSync('git', args, {+ cwd,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'ignore'],+ });+ return trim ? out.trim() : out;+ } catch {+ return null;+ }+ };+ if (run(['rev-parse', '--is-inside-work-tree']) !== 'true') {+ return { isRepo: false, branch: null, base: null, changedFiles: [], changedCount: 0 };+ }+ const branch = run(['rev-parse', '--abbrev-ref', 'HEAD']);+ let base = null;+ for (const b of ['main', 'master']) {+ if (run(['rev-parse', '--verify', '--quiet', b]) !== null) {+ base = b;+ break;+ }+ }+ const diffBase = base && branch && branch !== base ? base : null;+ const fromDiff = diffBase ? run(['diff', '--name-only', `${diffBase}...HEAD`]) : null;+ // porcelain lines are `XY PATH`: a 2-char status + a space, then the path.+ // Don't trim the combined output — an unstaged-modified line starts with a+ // leading space (` M path`), and a global trim would eat the first line's+ // status column and shift the slice. Renames render as `old -> new`.+ const fromStatus = run(['-c', 'core.quotepath=false', 'status', '--porcelain'], { trim: false });+ let changed = [];+ if (fromDiff) {+ changed = fromDiff.split('\n').filter(Boolean);+ } else if (fromStatus) {+ changed = fromStatus.split(/\r?\n/).filter(Boolean).map((l) => {+ const p = l.slice(3);+ const arrow = p.indexOf(' -> ');+ return arrow === -1 ? p : p.slice(arrow + 4);+ });+ }+ return {+ isRepo: true,+ branch,+ base: diffBase,+ changedFiles: changed.slice(0, 50),+ changedCount: changed.length,+ };+}++const COMMON_DEV_PORTS = [4321, 3000, 5173, 5174, 8080, 8000, 4200];++function probePort(port, timeout = 250) {+ return new Promise((resolve) => {+ const sock = new net.Socket();+ let settled = false;+ const finish = (ok) => {+ if (settled) return;+ settled = true;+ try { sock.destroy(); } catch { /* ignore */ }+ resolve(ok);+ };+ sock.setTimeout(timeout);+ sock.once('connect', () => finish(true));+ sock.once('timeout', () => finish(false));+ sock.once('error', () => finish(false));+ sock.connect(port, '127.0.0.1');+ });+}++async function devServerSignals() {+ const open = [];+ await Promise.all(+ COMMON_DEV_PORTS.map(async (p) => {+ if (await probePort(p)) open.push(p);+ }),+ );+ open.sort((a, b) => a - b);+ return { running: open.length > 0, ports: open };+}++export async function gatherSignals(cwd = process.cwd()) {+ const ctx = loadContext(cwd);+ return {+ setup: {+ hasProduct: ctx.hasProduct,+ productPath: ctx.productPath,+ hasDesign: ctx.hasDesign,+ designPath: ctx.designPath,+ hasCode: hasCode(cwd),+ register: extractRegister(ctx.product),+ },+ critique: { latest: latestCritique(cwd) },+ git: gitSignals(cwd),+ devServer: await devServerSignals(),+ };+}++async function cli() {+ const signals = await gatherSignals(process.cwd());+ process.stdout.write(`${JSON.stringify(signals, null, 2)}\n`);+}++function invokedAsScript() {+ const arg = process.argv[1];+ if (!arg) return false;+ try {+ return fs.realpathSync(arg) === fs.realpathSync(fileURLToPath(import.meta.url));+ } catch {+ return false;+ }+}++if (invokedAsScript()) {+ cli();+}diff --git a/.github/skills/impeccable/scripts/context.mjs b/.github/skills/impeccable/scripts/context.mjsindex eb4000717..8725469bf 100644--- a/.github/skills/impeccable/scripts/context.mjs+++ b/.github/skills/impeccable/scripts/context.mjs@@ -94,7 +94,7 @@ function safeRead(p) {* for a `## Register` section and reading the first non-empty line that* follows it. Returns null when the file is legacy / register-less.*/-function extractRegister(product) {+export function extractRegister(product) {if (!product) return null;const lines = product.split('\n');for (let i = 0; i < lines.length; i++) {diff --git a/.kiro/skills/impeccable/SKILL.md b/.kiro/skills/impeccable/SKILL.mdindex 47a323a3d..d0e6e0528 100644--- a/.kiro/skills/impeccable/SKILL.md+++ b/.kiro/skills/impeccable/SKILL.md@@ -138,7 +138,16 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be### Routing rules-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.+1. **No argument**: the user is asking "what should I do?" Make the menu context-aware instead of static. Setup has already run `context.mjs`; if that reported `NO_PRODUCT_MD` you are already in init (setup), so finish that and skip this. Otherwise run `node .kiro/skills/impeccable/scripts/context-signals.mjs` once and read its JSON, then lead with the **2-3 highest-value next commands**, each with a one-line reason pulled from the signals, followed by the full menu (the table above, grouped by category). **Never auto-run a command; the recommendation is a suggestion the user confirms.**++ Reason over the signals; there is no score to obey:+ - `setup.hasDesign` false while `setup.hasCode` true → `document` (capture the visual system).+ - `critique.latest` with a low `score` or non-zero `p0` / `p1` → `polish` (it reads that snapshot as its backlog), or re-run `critique` if the snapshot looks stale.+ - `git.changedFiles` pointing at one surface → scope `audit` or `polish` to those files specifically, naming them.+ - `devServer.running` true → `live` is available for in-browser iteration; if false, don't lead with `live`.+ - Otherwise group by intent exactly as init's "Recommend starting points" step does (build new / improve what's there / iterate visually), tailored to `setup.register`.++ Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.diff --git a/.kiro/skills/impeccable/scripts/context-signals.mjs b/.kiro/skills/impeccable/scripts/context-signals.mjsnew file mode 100644index 000000000..cd54793af--- /dev/null+++ b/.kiro/skills/impeccable/scripts/context-signals.mjs@@ -0,0 +1,187 @@+#!/usr/bin/env node+/**+ * Context-signals gatherer for the bare `{{command_prefix}}impeccable`+ * (no-argument) path. Collects cheap, deterministic signals about the current+ * project and emits them as JSON.+ *+ * It does NOT score or rank. The agent reasons over the raw signals using its+ * knowledge of the command catalog (see SKILL.md routing rule 1). Deliberately+ * light: no LLM calls, no detector run (`npx impeccable detect` is heavier and+ * opt-in), no file writes. Every probe is best-effort and never throws; the+ * output is always valid JSON.+ *+ * Signals:+ * - setup: PRODUCT.md / DESIGN.md presence, register, whether code exists+ * - critique: the latest cached critique score (.impeccable/critique)+ * - git: branch + files changed vs the default branch (a scope hint)+ * - devServer: whether a local dev server answers on a common port (gates live)+ */+import fs from 'node:fs';+import net from 'node:net';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFileSync } from 'node:child_process';+import { loadContext, extractRegister } from './context.mjs';+import { getCritiqueDir } from './impeccable-paths.mjs';++/** Is there code here at all, or just context files / an empty repo? */+function hasCode(cwd) {+ if (fs.existsSync(path.join(cwd, 'package.json'))) return true;+ for (const d of ['src', 'app', 'pages', 'site', 'public', 'components', 'lib']) {+ if (fs.existsSync(path.join(cwd, d))) return true;+ }+ return false;+}++/**+ * The most recent critique snapshot across all targets. Filenames are+ * timestamp-prefixed (`<iso>__<slug>.md`), so a lexical sort is chronological.+ * Parses the small frontmatter for score + P0/P1 counts.+ */+function latestCritique(cwd) {+ try {+ const dir = getCritiqueDir(cwd);+ if (!fs.existsSync(dir)) return null;+ const files = fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort();+ if (!files.length) return null;+ const newest = files[files.length - 1];+ const text = fs.readFileSync(path.join(dir, newest), 'utf-8');+ const front = text.split('---')[1] || '';+ const get = (k) => {+ const m = front.match(new RegExp(`^${k}:\\s*(.+)$`, 'm'));+ return m ? m[1].trim() : null;+ };+ const num = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+ };+ return {+ slug: get('slug'),+ score: num(get('score')),+ p0: num(get('p0')),+ p1: num(get('p1')),+ timestamp: get('timestamp'),+ file: path.relative(cwd, path.join(dir, newest)),+ };+ } catch {+ return null;+ }+}++/** Branch + a scope hint: files changed vs the default branch, else working tree. */+function gitSignals(cwd) {+ const run = (args, { trim = true } = {}) => {+ try {+ const out = execFileSync('git', args, {+ cwd,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'ignore'],+ });+ return trim ? out.trim() : out;+ } catch {+ return null;+ }+ };+ if (run(['rev-parse', '--is-inside-work-tree']) !== 'true') {+ return { isRepo: false, branch: null, base: null, changedFiles: [], changedCount: 0 };+ }+ const branch = run(['rev-parse', '--abbrev-ref', 'HEAD']);+ let base = null;+ for (const b of ['main', 'master']) {+ if (run(['rev-parse', '--verify', '--quiet', b]) !== null) {+ base = b;+ break;+ }+ }+ const diffBase = base && branch && branch !== base ? base : null;+ const fromDiff = diffBase ? run(['diff', '--name-only', `${diffBase}...HEAD`]) : null;+ // porcelain lines are `XY PATH`: a 2-char status + a space, then the path.+ // Don't trim the combined output — an unstaged-modified line starts with a+ // leading space (` M path`), and a global trim would eat the first line's+ // status column and shift the slice. Renames render as `old -> new`.+ const fromStatus = run(['-c', 'core.quotepath=false', 'status', '--porcelain'], { trim: false });+ let changed = [];+ if (fromDiff) {+ changed = fromDiff.split('\n').filter(Boolean);+ } else if (fromStatus) {+ changed = fromStatus.split(/\r?\n/).filter(Boolean).map((l) => {+ const p = l.slice(3);+ const arrow = p.indexOf(' -> ');+ return arrow === -1 ? p : p.slice(arrow + 4);+ });+ }+ return {+ isRepo: true,+ branch,+ base: diffBase,+ changedFiles: changed.slice(0, 50),+ changedCount: changed.length,+ };+}++const COMMON_DEV_PORTS = [4321, 3000, 5173, 5174, 8080, 8000, 4200];++function probePort(port, timeout = 250) {+ return new Promise((resolve) => {+ const sock = new net.Socket();+ let settled = false;+ const finish = (ok) => {+ if (settled) return;+ settled = true;+ try { sock.destroy(); } catch { /* ignore */ }+ resolve(ok);+ };+ sock.setTimeout(timeout);+ sock.once('connect', () => finish(true));+ sock.once('timeout', () => finish(false));+ sock.once('error', () => finish(false));+ sock.connect(port, '127.0.0.1');+ });+}++async function devServerSignals() {+ const open = [];+ await Promise.all(+ COMMON_DEV_PORTS.map(async (p) => {+ if (await probePort(p)) open.push(p);+ }),+ );+ open.sort((a, b) => a - b);+ return { running: open.length > 0, ports: open };+}++export async function gatherSignals(cwd = process.cwd()) {+ const ctx = loadContext(cwd);+ return {+ setup: {+ hasProduct: ctx.hasProduct,+ productPath: ctx.productPath,+ hasDesign: ctx.hasDesign,+ designPath: ctx.designPath,+ hasCode: hasCode(cwd),+ register: extractRegister(ctx.product),+ },+ critique: { latest: latestCritique(cwd) },+ git: gitSignals(cwd),+ devServer: await devServerSignals(),+ };+}++async function cli() {+ const signals = await gatherSignals(process.cwd());+ process.stdout.write(`${JSON.stringify(signals, null, 2)}\n`);+}++function invokedAsScript() {+ const arg = process.argv[1];+ if (!arg) return false;+ try {+ return fs.realpathSync(arg) === fs.realpathSync(fileURLToPath(import.meta.url));+ } catch {+ return false;+ }+}++if (invokedAsScript()) {+ cli();+}diff --git a/.kiro/skills/impeccable/scripts/context.mjs b/.kiro/skills/impeccable/scripts/context.mjsindex eb4000717..8725469bf 100644--- a/.kiro/skills/impeccable/scripts/context.mjs+++ b/.kiro/skills/impeccable/scripts/context.mjs@@ -94,7 +94,7 @@ function safeRead(p) {* for a `## Register` section and reading the first non-empty line that* follows it. Returns null when the file is legacy / register-less.*/-function extractRegister(product) {+export function extractRegister(product) {if (!product) return null;const lines = product.split('\n');for (let i = 0; i < lines.length; i++) {diff --git a/.opencode/skills/impeccable/SKILL.md b/.opencode/skills/impeccable/SKILL.mdindex 4445b6790..eea811708 100644--- a/.opencode/skills/impeccable/SKILL.md+++ b/.opencode/skills/impeccable/SKILL.md@@ -142,7 +142,16 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be### Routing rules-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.+1. **No argument**: the user is asking "what should I do?" Make the menu context-aware instead of static. Setup has already run `context.mjs`; if that reported `NO_PRODUCT_MD` you are already in init (setup), so finish that and skip this. Otherwise run `node .opencode/skills/impeccable/scripts/context-signals.mjs` once and read its JSON, then lead with the **2-3 highest-value next commands**, each with a one-line reason pulled from the signals, followed by the full menu (the table above, grouped by category). **Never auto-run a command; the recommendation is a suggestion the user confirms.**++ Reason over the signals; there is no score to obey:+ - `setup.hasDesign` false while `setup.hasCode` true → `document` (capture the visual system).+ - `critique.latest` with a low `score` or non-zero `p0` / `p1` → `polish` (it reads that snapshot as its backlog), or re-run `critique` if the snapshot looks stale.+ - `git.changedFiles` pointing at one surface → scope `audit` or `polish` to those files specifically, naming them.+ - `devServer.running` true → `live` is available for in-browser iteration; if false, don't lead with `live`.+ - Otherwise group by intent exactly as init's "Recommend starting points" step does (build new / improve what's there / iterate visually), tailored to `setup.register`.++ Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.diff --git a/.opencode/skills/impeccable/scripts/context-signals.mjs b/.opencode/skills/impeccable/scripts/context-signals.mjsnew file mode 100644index 000000000..cd54793af--- /dev/null+++ b/.opencode/skills/impeccable/scripts/context-signals.mjs@@ -0,0 +1,187 @@+#!/usr/bin/env node+/**+ * Context-signals gatherer for the bare `{{command_prefix}}impeccable`+ * (no-argument) path. Collects cheap, deterministic signals about the current+ * project and emits them as JSON.+ *+ * It does NOT score or rank. The agent reasons over the raw signals using its+ * knowledge of the command catalog (see SKILL.md routing rule 1). Deliberately+ * light: no LLM calls, no detector run (`npx impeccable detect` is heavier and+ * opt-in), no file writes. Every probe is best-effort and never throws; the+ * output is always valid JSON.+ *+ * Signals:+ * - setup: PRODUCT.md / DESIGN.md presence, register, whether code exists+ * - critique: the latest cached critique score (.impeccable/critique)+ * - git: branch + files changed vs the default branch (a scope hint)+ * - devServer: whether a local dev server answers on a common port (gates live)+ */+import fs from 'node:fs';+import net from 'node:net';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFileSync } from 'node:child_process';+import { loadContext, extractRegister } from './context.mjs';+import { getCritiqueDir } from './impeccable-paths.mjs';++/** Is there code here at all, or just context files / an empty repo? */+function hasCode(cwd) {+ if (fs.existsSync(path.join(cwd, 'package.json'))) return true;+ for (const d of ['src', 'app', 'pages', 'site', 'public', 'components', 'lib']) {+ if (fs.existsSync(path.join(cwd, d))) return true;+ }+ return false;+}++/**+ * The most recent critique snapshot across all targets. Filenames are+ * timestamp-prefixed (`<iso>__<slug>.md`), so a lexical sort is chronological.+ * Parses the small frontmatter for score + P0/P1 counts.+ */+function latestCritique(cwd) {+ try {+ const dir = getCritiqueDir(cwd);+ if (!fs.existsSync(dir)) return null;+ const files = fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort();+ if (!files.length) return null;+ const newest = files[files.length - 1];+ const text = fs.readFileSync(path.join(dir, newest), 'utf-8');+ const front = text.split('---')[1] || '';+ const get = (k) => {+ const m = front.match(new RegExp(`^${k}:\\s*(.+)$`, 'm'));+ return m ? m[1].trim() : null;+ };+ const num = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+ };+ return {+ slug: get('slug'),+ score: num(get('score')),+ p0: num(get('p0')),+ p1: num(get('p1')),+ timestamp: get('timestamp'),+ file: path.relative(cwd, path.join(dir, newest)),+ };+ } catch {+ return null;+ }+}++/** Branch + a scope hint: files changed vs the default branch, else working tree. */+function gitSignals(cwd) {+ const run = (args, { trim = true } = {}) => {+ try {+ const out = execFileSync('git', args, {+ cwd,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'ignore'],+ });+ return trim ? out.trim() : out;+ } catch {+ return null;+ }+ };+ if (run(['rev-parse', '--is-inside-work-tree']) !== 'true') {+ return { isRepo: false, branch: null, base: null, changedFiles: [], changedCount: 0 };+ }+ const branch = run(['rev-parse', '--abbrev-ref', 'HEAD']);+ let base = null;+ for (const b of ['main', 'master']) {+ if (run(['rev-parse', '--verify', '--quiet', b]) !== null) {+ base = b;+ break;+ }+ }+ const diffBase = base && branch && branch !== base ? base : null;+ const fromDiff = diffBase ? run(['diff', '--name-only', `${diffBase}...HEAD`]) : null;+ // porcelain lines are `XY PATH`: a 2-char status + a space, then the path.+ // Don't trim the combined output — an unstaged-modified line starts with a+ // leading space (` M path`), and a global trim would eat the first line's+ // status column and shift the slice. Renames render as `old -> new`.+ const fromStatus = run(['-c', 'core.quotepath=false', 'status', '--porcelain'], { trim: false });+ let changed = [];+ if (fromDiff) {+ changed = fromDiff.split('\n').filter(Boolean);+ } else if (fromStatus) {+ changed = fromStatus.split(/\r?\n/).filter(Boolean).map((l) => {+ const p = l.slice(3);+ const arrow = p.indexOf(' -> ');+ return arrow === -1 ? p : p.slice(arrow + 4);+ });+ }+ return {+ isRepo: true,+ branch,+ base: diffBase,+ changedFiles: changed.slice(0, 50),+ changedCount: changed.length,+ };+}++const COMMON_DEV_PORTS = [4321, 3000, 5173, 5174, 8080, 8000, 4200];++function probePort(port, timeout = 250) {+ return new Promise((resolve) => {+ const sock = new net.Socket();+ let settled = false;+ const finish = (ok) => {+ if (settled) return;+ settled = true;+ try { sock.destroy(); } catch { /* ignore */ }+ resolve(ok);+ };+ sock.setTimeout(timeout);+ sock.once('connect', () => finish(true));+ sock.once('timeout', () => finish(false));+ sock.once('error', () => finish(false));+ sock.connect(port, '127.0.0.1');+ });+}++async function devServerSignals() {+ const open = [];+ await Promise.all(+ COMMON_DEV_PORTS.map(async (p) => {+ if (await probePort(p)) open.push(p);+ }),+ );+ open.sort((a, b) => a - b);+ return { running: open.length > 0, ports: open };+}++export async function gatherSignals(cwd = process.cwd()) {+ const ctx = loadContext(cwd);+ return {+ setup: {+ hasProduct: ctx.hasProduct,+ productPath: ctx.productPath,+ hasDesign: ctx.hasDesign,+ designPath: ctx.designPath,+ hasCode: hasCode(cwd),+ register: extractRegister(ctx.product),+ },+ critique: { latest: latestCritique(cwd) },+ git: gitSignals(cwd),+ devServer: await devServerSignals(),+ };+}++async function cli() {+ const signals = await gatherSignals(process.cwd());+ process.stdout.write(`${JSON.stringify(signals, null, 2)}\n`);+}++function invokedAsScript() {+ const arg = process.argv[1];+ if (!arg) return false;+ try {+ return fs.realpathSync(arg) === fs.realpathSync(fileURLToPath(import.meta.url));+ } catch {+ return false;+ }+}++if (invokedAsScript()) {+ cli();+}diff --git a/.opencode/skills/impeccable/scripts/context.mjs b/.opencode/skills/impeccable/scripts/context.mjsindex eb4000717..8725469bf 100644--- a/.opencode/skills/impeccable/scripts/context.mjs+++ b/.opencode/skills/impeccable/scripts/context.mjs@@ -94,7 +94,7 @@ function safeRead(p) {* for a `## Register` section and reading the first non-empty line that* follows it. Returns null when the file is legacy / register-less.*/-function extractRegister(product) {+export function extractRegister(product) {if (!product) return null;const lines = product.split('\n');for (let i = 0; i < lines.length; i++) {diff --git a/.pi/skills/impeccable/SKILL.md b/.pi/skills/impeccable/SKILL.mdindex b41e0c61a..e4833e0fd 100644--- a/.pi/skills/impeccable/SKILL.md+++ b/.pi/skills/impeccable/SKILL.md@@ -140,7 +140,16 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be### Routing rules-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.+1. **No argument**: the user is asking "what should I do?" Make the menu context-aware instead of static. Setup has already run `context.mjs`; if that reported `NO_PRODUCT_MD` you are already in init (setup), so finish that and skip this. Otherwise run `node .pi/skills/impeccable/scripts/context-signals.mjs` once and read its JSON, then lead with the **2-3 highest-value next commands**, each with a one-line reason pulled from the signals, followed by the full menu (the table above, grouped by category). **Never auto-run a command; the recommendation is a suggestion the user confirms.**++ Reason over the signals; there is no score to obey:+ - `setup.hasDesign` false while `setup.hasCode` true → `document` (capture the visual system).+ - `critique.latest` with a low `score` or non-zero `p0` / `p1` → `polish` (it reads that snapshot as its backlog), or re-run `critique` if the snapshot looks stale.+ - `git.changedFiles` pointing at one surface → scope `audit` or `polish` to those files specifically, naming them.+ - `devServer.running` true → `live` is available for in-browser iteration; if false, don't lead with `live`.+ - Otherwise group by intent exactly as init's "Recommend starting points" step does (build new / improve what's there / iterate visually), tailored to `setup.register`.++ Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.diff --git a/.pi/skills/impeccable/scripts/context-signals.mjs b/.pi/skills/impeccable/scripts/context-signals.mjsnew file mode 100644index 000000000..cd54793af--- /dev/null+++ b/.pi/skills/impeccable/scripts/context-signals.mjs@@ -0,0 +1,187 @@+#!/usr/bin/env node+/**+ * Context-signals gatherer for the bare `{{command_prefix}}impeccable`+ * (no-argument) path. Collects cheap, deterministic signals about the current+ * project and emits them as JSON.+ *+ * It does NOT score or rank. The agent reasons over the raw signals using its+ * knowledge of the command catalog (see SKILL.md routing rule 1). Deliberately+ * light: no LLM calls, no detector run (`npx impeccable detect` is heavier and+ * opt-in), no file writes. Every probe is best-effort and never throws; the+ * output is always valid JSON.+ *+ * Signals:+ * - setup: PRODUCT.md / DESIGN.md presence, register, whether code exists+ * - critique: the latest cached critique score (.impeccable/critique)+ * - git: branch + files changed vs the default branch (a scope hint)+ * - devServer: whether a local dev server answers on a common port (gates live)+ */+import fs from 'node:fs';+import net from 'node:net';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFileSync } from 'node:child_process';+import { loadContext, extractRegister } from './context.mjs';+import { getCritiqueDir } from './impeccable-paths.mjs';++/** Is there code here at all, or just context files / an empty repo? */+function hasCode(cwd) {+ if (fs.existsSync(path.join(cwd, 'package.json'))) return true;+ for (const d of ['src', 'app', 'pages', 'site', 'public', 'components', 'lib']) {+ if (fs.existsSync(path.join(cwd, d))) return true;+ }+ return false;+}++/**+ * The most recent critique snapshot across all targets. Filenames are+ * timestamp-prefixed (`<iso>__<slug>.md`), so a lexical sort is chronological.+ * Parses the small frontmatter for score + P0/P1 counts.+ */+function latestCritique(cwd) {+ try {+ const dir = getCritiqueDir(cwd);+ if (!fs.existsSync(dir)) return null;+ const files = fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort();+ if (!files.length) return null;+ const newest = files[files.length - 1];+ const text = fs.readFileSync(path.join(dir, newest), 'utf-8');+ const front = text.split('---')[1] || '';+ const get = (k) => {+ const m = front.match(new RegExp(`^${k}:\\s*(.+)$`, 'm'));+ return m ? m[1].trim() : null;+ };+ const num = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+ };+ return {+ slug: get('slug'),+ score: num(get('score')),+ p0: num(get('p0')),+ p1: num(get('p1')),+ timestamp: get('timestamp'),+ file: path.relative(cwd, path.join(dir, newest)),+ };+ } catch {+ return null;+ }+}++/** Branch + a scope hint: files changed vs the default branch, else working tree. */+function gitSignals(cwd) {+ const run = (args, { trim = true } = {}) => {+ try {+ const out = execFileSync('git', args, {+ cwd,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'ignore'],+ });+ return trim ? out.trim() : out;+ } catch {+ return null;+ }+ };+ if (run(['rev-parse', '--is-inside-work-tree']) !== 'true') {+ return { isRepo: false, branch: null, base: null, changedFiles: [], changedCount: 0 };+ }+ const branch = run(['rev-parse', '--abbrev-ref', 'HEAD']);+ let base = null;+ for (const b of ['main', 'master']) {+ if (run(['rev-parse', '--verify', '--quiet', b]) !== null) {+ base = b;+ break;+ }+ }+ const diffBase = base && branch && branch !== base ? base : null;+ const fromDiff = diffBase ? run(['diff', '--name-only', `${diffBase}...HEAD`]) : null;+ // porcelain lines are `XY PATH`: a 2-char status + a space, then the path.+ // Don't trim the combined output — an unstaged-modified line starts with a+ // leading space (` M path`), and a global trim would eat the first line's+ // status column and shift the slice. Renames render as `old -> new`.+ const fromStatus = run(['-c', 'core.quotepath=false', 'status', '--porcelain'], { trim: false });+ let changed = [];+ if (fromDiff) {+ changed = fromDiff.split('\n').filter(Boolean);+ } else if (fromStatus) {+ changed = fromStatus.split(/\r?\n/).filter(Boolean).map((l) => {+ const p = l.slice(3);+ const arrow = p.indexOf(' -> ');+ return arrow === -1 ? p : p.slice(arrow + 4);+ });+ }+ return {+ isRepo: true,+ branch,+ base: diffBase,+ changedFiles: changed.slice(0, 50),+ changedCount: changed.length,+ };+}++const COMMON_DEV_PORTS = [4321, 3000, 5173, 5174, 8080, 8000, 4200];++function probePort(port, timeout = 250) {+ return new Promise((resolve) => {+ const sock = new net.Socket();+ let settled = false;+ const finish = (ok) => {+ if (settled) return;+ settled = true;+ try { sock.destroy(); } catch { /* ignore */ }+ resolve(ok);+ };+ sock.setTimeout(timeout);+ sock.once('connect', () => finish(true));+ sock.once('timeout', () => finish(false));+ sock.once('error', () => finish(false));+ sock.connect(port, '127.0.0.1');+ });+}++async function devServerSignals() {+ const open = [];+ await Promise.all(+ COMMON_DEV_PORTS.map(async (p) => {+ if (await probePort(p)) open.push(p);+ }),+ );+ open.sort((a, b) => a - b);+ return { running: open.length > 0, ports: open };+}++export async function gatherSignals(cwd = process.cwd()) {+ const ctx = loadContext(cwd);+ return {+ setup: {+ hasProduct: ctx.hasProduct,+ productPath: ctx.productPath,+ hasDesign: ctx.hasDesign,+ designPath: ctx.designPath,+ hasCode: hasCode(cwd),+ register: extractRegister(ctx.product),+ },+ critique: { latest: latestCritique(cwd) },+ git: gitSignals(cwd),+ devServer: await devServerSignals(),+ };+}++async function cli() {+ const signals = await gatherSignals(process.cwd());+ process.stdout.write(`${JSON.stringify(signals, null, 2)}\n`);+}++function invokedAsScript() {+ const arg = process.argv[1];+ if (!arg) return false;+ try {+ return fs.realpathSync(arg) === fs.realpathSync(fileURLToPath(import.meta.url));+ } catch {+ return false;+ }+}++if (invokedAsScript()) {+ cli();+}diff --git a/.pi/skills/impeccable/scripts/context.mjs b/.pi/skills/impeccable/scripts/context.mjsindex eb4000717..8725469bf 100644--- a/.pi/skills/impeccable/scripts/context.mjs+++ b/.pi/skills/impeccable/scripts/context.mjs@@ -94,7 +94,7 @@ function safeRead(p) {* for a `## Register` section and reading the first non-empty line that* follows it. Returns null when the file is legacy / register-less.*/-function extractRegister(product) {+export function extractRegister(product) {if (!product) return null;const lines = product.split('\n');for (let i = 0; i < lines.length; i++) {diff --git a/.qoder/skills/impeccable/SKILL.md b/.qoder/skills/impeccable/SKILL.mdindex 7f26e997b..a6fecfaf8 100644--- a/.qoder/skills/impeccable/SKILL.md+++ b/.qoder/skills/impeccable/SKILL.md@@ -142,7 +142,16 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be### Routing rules-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.+1. **No argument**: the user is asking "what should I do?" Make the menu context-aware instead of static. Setup has already run `context.mjs`; if that reported `NO_PRODUCT_MD` you are already in init (setup), so finish that and skip this. Otherwise run `node .qoder/skills/impeccable/scripts/context-signals.mjs` once and read its JSON, then lead with the **2-3 highest-value next commands**, each with a one-line reason pulled from the signals, followed by the full menu (the table above, grouped by category). **Never auto-run a command; the recommendation is a suggestion the user confirms.**++ Reason over the signals; there is no score to obey:+ - `setup.hasDesign` false while `setup.hasCode` true → `document` (capture the visual system).+ - `critique.latest` with a low `score` or non-zero `p0` / `p1` → `polish` (it reads that snapshot as its backlog), or re-run `critique` if the snapshot looks stale.+ - `git.changedFiles` pointing at one surface → scope `audit` or `polish` to those files specifically, naming them.+ - `devServer.running` true → `live` is available for in-browser iteration; if false, don't lead with `live`.+ - Otherwise group by intent exactly as init's "Recommend starting points" step does (build new / improve what's there / iterate visually), tailored to `setup.register`.++ Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.diff --git a/.qoder/skills/impeccable/scripts/context-signals.mjs b/.qoder/skills/impeccable/scripts/context-signals.mjsnew file mode 100644index 000000000..cd54793af--- /dev/null+++ b/.qoder/skills/impeccable/scripts/context-signals.mjs@@ -0,0 +1,187 @@+#!/usr/bin/env node+/**+ * Context-signals gatherer for the bare `{{command_prefix}}impeccable`+ * (no-argument) path. Collects cheap, deterministic signals about the current+ * project and emits them as JSON.+ *+ * It does NOT score or rank. The agent reasons over the raw signals using its+ * knowledge of the command catalog (see SKILL.md routing rule 1). Deliberately+ * light: no LLM calls, no detector run (`npx impeccable detect` is heavier and+ * opt-in), no file writes. Every probe is best-effort and never throws; the+ * output is always valid JSON.+ *+ * Signals:+ * - setup: PRODUCT.md / DESIGN.md presence, register, whether code exists+ * - critique: the latest cached critique score (.impeccable/critique)+ * - git: branch + files changed vs the default branch (a scope hint)+ * - devServer: whether a local dev server answers on a common port (gates live)+ */+import fs from 'node:fs';+import net from 'node:net';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFileSync } from 'node:child_process';+import { loadContext, extractRegister } from './context.mjs';+import { getCritiqueDir } from './impeccable-paths.mjs';++/** Is there code here at all, or just context files / an empty repo? */+function hasCode(cwd) {+ if (fs.existsSync(path.join(cwd, 'package.json'))) return true;+ for (const d of ['src', 'app', 'pages', 'site', 'public', 'components', 'lib']) {+ if (fs.existsSync(path.join(cwd, d))) return true;+ }+ return false;+}++/**+ * The most recent critique snapshot across all targets. Filenames are+ * timestamp-prefixed (`<iso>__<slug>.md`), so a lexical sort is chronological.+ * Parses the small frontmatter for score + P0/P1 counts.+ */+function latestCritique(cwd) {+ try {+ const dir = getCritiqueDir(cwd);+ if (!fs.existsSync(dir)) return null;+ const files = fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort();+ if (!files.length) return null;+ const newest = files[files.length - 1];+ const text = fs.readFileSync(path.join(dir, newest), 'utf-8');+ const front = text.split('---')[1] || '';+ const get = (k) => {+ const m = front.match(new RegExp(`^${k}:\\s*(.+)$`, 'm'));+ return m ? m[1].trim() : null;+ };+ const num = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+ };+ return {+ slug: get('slug'),+ score: num(get('score')),+ p0: num(get('p0')),+ p1: num(get('p1')),+ timestamp: get('timestamp'),+ file: path.relative(cwd, path.join(dir, newest)),+ };+ } catch {+ return null;+ }+}++/** Branch + a scope hint: files changed vs the default branch, else working tree. */+function gitSignals(cwd) {+ const run = (args, { trim = true } = {}) => {+ try {+ const out = execFileSync('git', args, {+ cwd,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'ignore'],+ });+ return trim ? out.trim() : out;+ } catch {+ return null;+ }+ };+ if (run(['rev-parse', '--is-inside-work-tree']) !== 'true') {+ return { isRepo: false, branch: null, base: null, changedFiles: [], changedCount: 0 };+ }+ const branch = run(['rev-parse', '--abbrev-ref', 'HEAD']);+ let base = null;+ for (const b of ['main', 'master']) {+ if (run(['rev-parse', '--verify', '--quiet', b]) !== null) {+ base = b;+ break;+ }+ }+ const diffBase = base && branch && branch !== base ? base : null;+ const fromDiff = diffBase ? run(['diff', '--name-only', `${diffBase}...HEAD`]) : null;+ // porcelain lines are `XY PATH`: a 2-char status + a space, then the path.+ // Don't trim the combined output — an unstaged-modified line starts with a+ // leading space (` M path`), and a global trim would eat the first line's+ // status column and shift the slice. Renames render as `old -> new`.+ const fromStatus = run(['-c', 'core.quotepath=false', 'status', '--porcelain'], { trim: false });+ let changed = [];+ if (fromDiff) {+ changed = fromDiff.split('\n').filter(Boolean);+ } else if (fromStatus) {+ changed = fromStatus.split(/\r?\n/).filter(Boolean).map((l) => {+ const p = l.slice(3);+ const arrow = p.indexOf(' -> ');+ return arrow === -1 ? p : p.slice(arrow + 4);+ });+ }+ return {+ isRepo: true,+ branch,+ base: diffBase,+ changedFiles: changed.slice(0, 50),+ changedCount: changed.length,+ };+}++const COMMON_DEV_PORTS = [4321, 3000, 5173, 5174, 8080, 8000, 4200];++function probePort(port, timeout = 250) {+ return new Promise((resolve) => {+ const sock = new net.Socket();+ let settled = false;+ const finish = (ok) => {+ if (settled) return;+ settled = true;+ try { sock.destroy(); } catch { /* ignore */ }+ resolve(ok);+ };+ sock.setTimeout(timeout);+ sock.once('connect', () => finish(true));+ sock.once('timeout', () => finish(false));+ sock.once('error', () => finish(false));+ sock.connect(port, '127.0.0.1');+ });+}++async function devServerSignals() {+ const open = [];+ await Promise.all(+ COMMON_DEV_PORTS.map(async (p) => {+ if (await probePort(p)) open.push(p);+ }),+ );+ open.sort((a, b) => a - b);+ return { running: open.length > 0, ports: open };+}++export async function gatherSignals(cwd = process.cwd()) {+ const ctx = loadContext(cwd);+ return {+ setup: {+ hasProduct: ctx.hasProduct,+ productPath: ctx.productPath,+ hasDesign: ctx.hasDesign,+ designPath: ctx.designPath,+ hasCode: hasCode(cwd),+ register: extractRegister(ctx.product),+ },+ critique: { latest: latestCritique(cwd) },+ git: gitSignals(cwd),+ devServer: await devServerSignals(),+ };+}++async function cli() {+ const signals = await gatherSignals(process.cwd());+ process.stdout.write(`${JSON.stringify(signals, null, 2)}\n`);+}++function invokedAsScript() {+ const arg = process.argv[1];+ if (!arg) return false;+ try {+ return fs.realpathSync(arg) === fs.realpathSync(fileURLToPath(import.meta.url));+ } catch {+ return false;+ }+}++if (invokedAsScript()) {+ cli();+}diff --git a/.qoder/skills/impeccable/scripts/context.mjs b/.qoder/skills/impeccable/scripts/context.mjsindex eb4000717..8725469bf 100644--- a/.qoder/skills/impeccable/scripts/context.mjs+++ b/.qoder/skills/impeccable/scripts/context.mjs@@ -94,7 +94,7 @@ function safeRead(p) {* for a `## Register` section and reading the first non-empty line that* follows it. Returns null when the file is legacy / register-less.*/-function extractRegister(product) {+export function extractRegister(product) {if (!product) return null;const lines = product.split('\n');for (let i = 0; i < lines.length; i++) {diff --git a/.rovodev/skills/impeccable/SKILL.md b/.rovodev/skills/impeccable/SKILL.mdindex b2b870e80..6a6619645 100644--- a/.rovodev/skills/impeccable/SKILL.md+++ b/.rovodev/skills/impeccable/SKILL.md@@ -142,7 +142,16 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be### Routing rules-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.+1. **No argument**: the user is asking "what should I do?" Make the menu context-aware instead of static. Setup has already run `context.mjs`; if that reported `NO_PRODUCT_MD` you are already in init (setup), so finish that and skip this. Otherwise run `node .rovodev/skills/impeccable/scripts/context-signals.mjs` once and read its JSON, then lead with the **2-3 highest-value next commands**, each with a one-line reason pulled from the signals, followed by the full menu (the table above, grouped by category). **Never auto-run a command; the recommendation is a suggestion the user confirms.**++ Reason over the signals; there is no score to obey:+ - `setup.hasDesign` false while `setup.hasCode` true → `document` (capture the visual system).+ - `critique.latest` with a low `score` or non-zero `p0` / `p1` → `polish` (it reads that snapshot as its backlog), or re-run `critique` if the snapshot looks stale.+ - `git.changedFiles` pointing at one surface → scope `audit` or `polish` to those files specifically, naming them.+ - `devServer.running` true → `live` is available for in-browser iteration; if false, don't lead with `live`.+ - Otherwise group by intent exactly as init's "Recommend starting points" step does (build new / improve what's there / iterate visually), tailored to `setup.register`.++ Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.diff --git a/.rovodev/skills/impeccable/scripts/context-signals.mjs b/.rovodev/skills/impeccable/scripts/context-signals.mjsnew file mode 100644index 000000000..cd54793af--- /dev/null+++ b/.rovodev/skills/impeccable/scripts/context-signals.mjs@@ -0,0 +1,187 @@+#!/usr/bin/env node+/**+ * Context-signals gatherer for the bare `{{command_prefix}}impeccable`+ * (no-argument) path. Collects cheap, deterministic signals about the current+ * project and emits them as JSON.+ *+ * It does NOT score or rank. The agent reasons over the raw signals using its+ * knowledge of the command catalog (see SKILL.md routing rule 1). Deliberately+ * light: no LLM calls, no detector run (`npx impeccable detect` is heavier and+ * opt-in), no file writes. Every probe is best-effort and never throws; the+ * output is always valid JSON.+ *+ * Signals:+ * - setup: PRODUCT.md / DESIGN.md presence, register, whether code exists+ * - critique: the latest cached critique score (.impeccable/critique)+ * - git: branch + files changed vs the default branch (a scope hint)+ * - devServer: whether a local dev server answers on a common port (gates live)+ */+import fs from 'node:fs';+import net from 'node:net';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFileSync } from 'node:child_process';+import { loadContext, extractRegister } from './context.mjs';+import { getCritiqueDir } from './impeccable-paths.mjs';++/** Is there code here at all, or just context files / an empty repo? */+function hasCode(cwd) {+ if (fs.existsSync(path.join(cwd, 'package.json'))) return true;+ for (const d of ['src', 'app', 'pages', 'site', 'public', 'components', 'lib']) {+ if (fs.existsSync(path.join(cwd, d))) return true;+ }+ return false;+}++/**+ * The most recent critique snapshot across all targets. Filenames are+ * timestamp-prefixed (`<iso>__<slug>.md`), so a lexical sort is chronological.+ * Parses the small frontmatter for score + P0/P1 counts.+ */+function latestCritique(cwd) {+ try {+ const dir = getCritiqueDir(cwd);+ if (!fs.existsSync(dir)) return null;+ const files = fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort();+ if (!files.length) return null;+ const newest = files[files.length - 1];+ const text = fs.readFileSync(path.join(dir, newest), 'utf-8');+ const front = text.split('---')[1] || '';+ const get = (k) => {+ const m = front.match(new RegExp(`^${k}:\\s*(.+)$`, 'm'));+ return m ? m[1].trim() : null;+ };+ const num = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+ };+ return {+ slug: get('slug'),+ score: num(get('score')),+ p0: num(get('p0')),+ p1: num(get('p1')),+ timestamp: get('timestamp'),+ file: path.relative(cwd, path.join(dir, newest)),+ };+ } catch {+ return null;+ }+}++/** Branch + a scope hint: files changed vs the default branch, else working tree. */+function gitSignals(cwd) {+ const run = (args, { trim = true } = {}) => {+ try {+ const out = execFileSync('git', args, {+ cwd,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'ignore'],+ });+ return trim ? out.trim() : out;+ } catch {+ return null;+ }+ };+ if (run(['rev-parse', '--is-inside-work-tree']) !== 'true') {+ return { isRepo: false, branch: null, base: null, changedFiles: [], changedCount: 0 };+ }+ const branch = run(['rev-parse', '--abbrev-ref', 'HEAD']);+ let base = null;+ for (const b of ['main', 'master']) {+ if (run(['rev-parse', '--verify', '--quiet', b]) !== null) {+ base = b;+ break;+ }+ }+ const diffBase = base && branch && branch !== base ? base : null;+ const fromDiff = diffBase ? run(['diff', '--name-only', `${diffBase}...HEAD`]) : null;+ // porcelain lines are `XY PATH`: a 2-char status + a space, then the path.+ // Don't trim the combined output — an unstaged-modified line starts with a+ // leading space (` M path`), and a global trim would eat the first line's+ // status column and shift the slice. Renames render as `old -> new`.+ const fromStatus = run(['-c', 'core.quotepath=false', 'status', '--porcelain'], { trim: false });+ let changed = [];+ if (fromDiff) {+ changed = fromDiff.split('\n').filter(Boolean);+ } else if (fromStatus) {+ changed = fromStatus.split(/\r?\n/).filter(Boolean).map((l) => {+ const p = l.slice(3);+ const arrow = p.indexOf(' -> ');+ return arrow === -1 ? p : p.slice(arrow + 4);+ });+ }+ return {+ isRepo: true,+ branch,+ base: diffBase,+ changedFiles: changed.slice(0, 50),+ changedCount: changed.length,+ };+}++const COMMON_DEV_PORTS = [4321, 3000, 5173, 5174, 8080, 8000, 4200];++function probePort(port, timeout = 250) {+ return new Promise((resolve) => {+ const sock = new net.Socket();+ let settled = false;+ const finish = (ok) => {+ if (settled) return;+ settled = true;+ try { sock.destroy(); } catch { /* ignore */ }+ resolve(ok);+ };+ sock.setTimeout(timeout);+ sock.once('connect', () => finish(true));+ sock.once('timeout', () => finish(false));+ sock.once('error', () => finish(false));+ sock.connect(port, '127.0.0.1');+ });+}++async function devServerSignals() {+ const open = [];+ await Promise.all(+ COMMON_DEV_PORTS.map(async (p) => {+ if (await probePort(p)) open.push(p);+ }),+ );+ open.sort((a, b) => a - b);+ return { running: open.length > 0, ports: open };+}++export async function gatherSignals(cwd = process.cwd()) {+ const ctx = loadContext(cwd);+ return {+ setup: {+ hasProduct: ctx.hasProduct,+ productPath: ctx.productPath,+ hasDesign: ctx.hasDesign,+ designPath: ctx.designPath,+ hasCode: hasCode(cwd),+ register: extractRegister(ctx.product),+ },+ critique: { latest: latestCritique(cwd) },+ git: gitSignals(cwd),+ devServer: await devServerSignals(),+ };+}++async function cli() {+ const signals = await gatherSignals(process.cwd());+ process.stdout.write(`${JSON.stringify(signals, null, 2)}\n`);+}++function invokedAsScript() {+ const arg = process.argv[1];+ if (!arg) return false;+ try {+ return fs.realpathSync(arg) === fs.realpathSync(fileURLToPath(import.meta.url));+ } catch {+ return false;+ }+}++if (invokedAsScript()) {+ cli();+}diff --git a/.rovodev/skills/impeccable/scripts/context.mjs b/.rovodev/skills/impeccable/scripts/context.mjsindex eb4000717..8725469bf 100644--- a/.rovodev/skills/impeccable/scripts/context.mjs+++ b/.rovodev/skills/impeccable/scripts/context.mjs@@ -94,7 +94,7 @@ function safeRead(p) {* for a `## Register` section and reading the first non-empty line that* follows it. Returns null when the file is legacy / register-less.*/-function extractRegister(product) {+export function extractRegister(product) {if (!product) return null;const lines = product.split('\n');for (let i = 0; i < lines.length; i++) {diff --git a/.trae-cn/skills/impeccable/SKILL.md b/.trae-cn/skills/impeccable/SKILL.mdindex c76f05c5b..e93bbdd3c 100644--- a/.trae-cn/skills/impeccable/SKILL.md+++ b/.trae-cn/skills/impeccable/SKILL.md@@ -140,7 +140,16 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be### Routing rules-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.+1. **No argument**: the user is asking "what should I do?" Make the menu context-aware instead of static. Setup has already run `context.mjs`; if that reported `NO_PRODUCT_MD` you are already in init (setup), so finish that and skip this. Otherwise run `node .trae-cn/skills/impeccable/scripts/context-signals.mjs` once and read its JSON, then lead with the **2-3 highest-value next commands**, each with a one-line reason pulled from the signals, followed by the full menu (the table above, grouped by category). **Never auto-run a command; the recommendation is a suggestion the user confirms.**++ Reason over the signals; there is no score to obey:+ - `setup.hasDesign` false while `setup.hasCode` true → `document` (capture the visual system).+ - `critique.latest` with a low `score` or non-zero `p0` / `p1` → `polish` (it reads that snapshot as its backlog), or re-run `critique` if the snapshot looks stale.+ - `git.changedFiles` pointing at one surface → scope `audit` or `polish` to those files specifically, naming them.+ - `devServer.running` true → `live` is available for in-browser iteration; if false, don't lead with `live`.+ - Otherwise group by intent exactly as init's "Recommend starting points" step does (build new / improve what's there / iterate visually), tailored to `setup.register`.++ Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.diff --git a/.trae-cn/skills/impeccable/scripts/context-signals.mjs b/.trae-cn/skills/impeccable/scripts/context-signals.mjsnew file mode 100644index 000000000..cd54793af--- /dev/null+++ b/.trae-cn/skills/impeccable/scripts/context-signals.mjs@@ -0,0 +1,187 @@+#!/usr/bin/env node+/**+ * Context-signals gatherer for the bare `{{command_prefix}}impeccable`+ * (no-argument) path. Collects cheap, deterministic signals about the current+ * project and emits them as JSON.+ *+ * It does NOT score or rank. The agent reasons over the raw signals using its+ * knowledge of the command catalog (see SKILL.md routing rule 1). Deliberately+ * light: no LLM calls, no detector run (`npx impeccable detect` is heavier and+ * opt-in), no file writes. Every probe is best-effort and never throws; the+ * output is always valid JSON.+ *+ * Signals:+ * - setup: PRODUCT.md / DESIGN.md presence, register, whether code exists+ * - critique: the latest cached critique score (.impeccable/critique)+ * - git: branch + files changed vs the default branch (a scope hint)+ * - devServer: whether a local dev server answers on a common port (gates live)+ */+import fs from 'node:fs';+import net from 'node:net';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFileSync } from 'node:child_process';+import { loadContext, extractRegister } from './context.mjs';+import { getCritiqueDir } from './impeccable-paths.mjs';++/** Is there code here at all, or just context files / an empty repo? */+function hasCode(cwd) {+ if (fs.existsSync(path.join(cwd, 'package.json'))) return true;+ for (const d of ['src', 'app', 'pages', 'site', 'public', 'components', 'lib']) {+ if (fs.existsSync(path.join(cwd, d))) return true;+ }+ return false;+}++/**+ * The most recent critique snapshot across all targets. Filenames are+ * timestamp-prefixed (`<iso>__<slug>.md`), so a lexical sort is chronological.+ * Parses the small frontmatter for score + P0/P1 counts.+ */+function latestCritique(cwd) {+ try {+ const dir = getCritiqueDir(cwd);+ if (!fs.existsSync(dir)) return null;+ const files = fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort();+ if (!files.length) return null;+ const newest = files[files.length - 1];+ const text = fs.readFileSync(path.join(dir, newest), 'utf-8');+ const front = text.split('---')[1] || '';+ const get = (k) => {+ const m = front.match(new RegExp(`^${k}:\\s*(.+)$`, 'm'));+ return m ? m[1].trim() : null;+ };+ const num = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+ };+ return {+ slug: get('slug'),+ score: num(get('score')),+ p0: num(get('p0')),+ p1: num(get('p1')),+ timestamp: get('timestamp'),+ file: path.relative(cwd, path.join(dir, newest)),+ };+ } catch {+ return null;+ }+}++/** Branch + a scope hint: files changed vs the default branch, else working tree. */+function gitSignals(cwd) {+ const run = (args, { trim = true } = {}) => {+ try {+ const out = execFileSync('git', args, {+ cwd,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'ignore'],+ });+ return trim ? out.trim() : out;+ } catch {+ return null;+ }+ };+ if (run(['rev-parse', '--is-inside-work-tree']) !== 'true') {+ return { isRepo: false, branch: null, base: null, changedFiles: [], changedCount: 0 };+ }+ const branch = run(['rev-parse', '--abbrev-ref', 'HEAD']);+ let base = null;+ for (const b of ['main', 'master']) {+ if (run(['rev-parse', '--verify', '--quiet', b]) !== null) {+ base = b;+ break;+ }+ }+ const diffBase = base && branch && branch !== base ? base : null;+ const fromDiff = diffBase ? run(['diff', '--name-only', `${diffBase}...HEAD`]) : null;+ // porcelain lines are `XY PATH`: a 2-char status + a space, then the path.+ // Don't trim the combined output — an unstaged-modified line starts with a+ // leading space (` M path`), and a global trim would eat the first line's+ // status column and shift the slice. Renames render as `old -> new`.+ const fromStatus = run(['-c', 'core.quotepath=false', 'status', '--porcelain'], { trim: false });+ let changed = [];+ if (fromDiff) {+ changed = fromDiff.split('\n').filter(Boolean);+ } else if (fromStatus) {+ changed = fromStatus.split(/\r?\n/).filter(Boolean).map((l) => {+ const p = l.slice(3);+ const arrow = p.indexOf(' -> ');+ return arrow === -1 ? p : p.slice(arrow + 4);+ });+ }+ return {+ isRepo: true,+ branch,+ base: diffBase,+ changedFiles: changed.slice(0, 50),+ changedCount: changed.length,+ };+}++const COMMON_DEV_PORTS = [4321, 3000, 5173, 5174, 8080, 8000, 4200];++function probePort(port, timeout = 250) {+ return new Promise((resolve) => {+ const sock = new net.Socket();+ let settled = false;+ const finish = (ok) => {+ if (settled) return;+ settled = true;+ try { sock.destroy(); } catch { /* ignore */ }+ resolve(ok);+ };+ sock.setTimeout(timeout);+ sock.once('connect', () => finish(true));+ sock.once('timeout', () => finish(false));+ sock.once('error', () => finish(false));+ sock.connect(port, '127.0.0.1');+ });+}++async function devServerSignals() {+ const open = [];+ await Promise.all(+ COMMON_DEV_PORTS.map(async (p) => {+ if (await probePort(p)) open.push(p);+ }),+ );+ open.sort((a, b) => a - b);+ return { running: open.length > 0, ports: open };+}++export async function gatherSignals(cwd = process.cwd()) {+ const ctx = loadContext(cwd);+ return {+ setup: {+ hasProduct: ctx.hasProduct,+ productPath: ctx.productPath,+ hasDesign: ctx.hasDesign,+ designPath: ctx.designPath,+ hasCode: hasCode(cwd),+ register: extractRegister(ctx.product),+ },+ critique: { latest: latestCritique(cwd) },+ git: gitSignals(cwd),+ devServer: await devServerSignals(),+ };+}++async function cli() {+ const signals = await gatherSignals(process.cwd());+ process.stdout.write(`${JSON.stringify(signals, null, 2)}\n`);+}++function invokedAsScript() {+ const arg = process.argv[1];+ if (!arg) return false;+ try {+ return fs.realpathSync(arg) === fs.realpathSync(fileURLToPath(import.meta.url));+ } catch {+ return false;+ }+}++if (invokedAsScript()) {+ cli();+}diff --git a/.trae-cn/skills/impeccable/scripts/context.mjs b/.trae-cn/skills/impeccable/scripts/context.mjsindex eb4000717..8725469bf 100644--- a/.trae-cn/skills/impeccable/scripts/context.mjs+++ b/.trae-cn/skills/impeccable/scripts/context.mjs@@ -94,7 +94,7 @@ function safeRead(p) {* for a `## Register` section and reading the first non-empty line that* follows it. Returns null when the file is legacy / register-less.*/-function extractRegister(product) {+export function extractRegister(product) {if (!product) return null;const lines = product.split('\n');for (let i = 0; i < lines.length; i++) {diff --git a/.trae/skills/impeccable/SKILL.md b/.trae/skills/impeccable/SKILL.mdindex 3e96fa2c7..d8316ae21 100644--- a/.trae/skills/impeccable/SKILL.md+++ b/.trae/skills/impeccable/SKILL.md@@ -140,7 +140,16 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be### Routing rules-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.+1. **No argument**: the user is asking "what should I do?" Make the menu context-aware instead of static. Setup has already run `context.mjs`; if that reported `NO_PRODUCT_MD` you are already in init (setup), so finish that and skip this. Otherwise run `node .trae/skills/impeccable/scripts/context-signals.mjs` once and read its JSON, then lead with the **2-3 highest-value next commands**, each with a one-line reason pulled from the signals, followed by the full menu (the table above, grouped by category). **Never auto-run a command; the recommendation is a suggestion the user confirms.**++ Reason over the signals; there is no score to obey:+ - `setup.hasDesign` false while `setup.hasCode` true → `document` (capture the visual system).+ - `critique.latest` with a low `score` or non-zero `p0` / `p1` → `polish` (it reads that snapshot as its backlog), or re-run `critique` if the snapshot looks stale.+ - `git.changedFiles` pointing at one surface → scope `audit` or `polish` to those files specifically, naming them.+ - `devServer.running` true → `live` is available for in-browser iteration; if false, don't lead with `live`.+ - Otherwise group by intent exactly as init's "Recommend starting points" step does (build new / improve what's there / iterate visually), tailored to `setup.register`.++ Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.diff --git a/.trae/skills/impeccable/scripts/context-signals.mjs b/.trae/skills/impeccable/scripts/context-signals.mjsnew file mode 100644index 000000000..cd54793af--- /dev/null+++ b/.trae/skills/impeccable/scripts/context-signals.mjs@@ -0,0 +1,187 @@+#!/usr/bin/env node+/**+ * Context-signals gatherer for the bare `{{command_prefix}}impeccable`+ * (no-argument) path. Collects cheap, deterministic signals about the current+ * project and emits them as JSON.+ *+ * It does NOT score or rank. The agent reasons over the raw signals using its+ * knowledge of the command catalog (see SKILL.md routing rule 1). Deliberately+ * light: no LLM calls, no detector run (`npx impeccable detect` is heavier and+ * opt-in), no file writes. Every probe is best-effort and never throws; the+ * output is always valid JSON.+ *+ * Signals:+ * - setup: PRODUCT.md / DESIGN.md presence, register, whether code exists+ * - critique: the latest cached critique score (.impeccable/critique)+ * - git: branch + files changed vs the default branch (a scope hint)+ * - devServer: whether a local dev server answers on a common port (gates live)+ */+import fs from 'node:fs';+import net from 'node:net';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFileSync } from 'node:child_process';+import { loadContext, extractRegister } from './context.mjs';+import { getCritiqueDir } from './impeccable-paths.mjs';++/** Is there code here at all, or just context files / an empty repo? */+function hasCode(cwd) {+ if (fs.existsSync(path.join(cwd, 'package.json'))) return true;+ for (const d of ['src', 'app', 'pages', 'site', 'public', 'components', 'lib']) {+ if (fs.existsSync(path.join(cwd, d))) return true;+ }+ return false;+}++/**+ * The most recent critique snapshot across all targets. Filenames are+ * timestamp-prefixed (`<iso>__<slug>.md`), so a lexical sort is chronological.+ * Parses the small frontmatter for score + P0/P1 counts.+ */+function latestCritique(cwd) {+ try {+ const dir = getCritiqueDir(cwd);+ if (!fs.existsSync(dir)) return null;+ const files = fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort();+ if (!files.length) return null;+ const newest = files[files.length - 1];+ const text = fs.readFileSync(path.join(dir, newest), 'utf-8');+ const front = text.split('---')[1] || '';+ const get = (k) => {+ const m = front.match(new RegExp(`^${k}:\\s*(.+)$`, 'm'));+ return m ? m[1].trim() : null;+ };+ const num = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+ };+ return {+ slug: get('slug'),+ score: num(get('score')),+ p0: num(get('p0')),+ p1: num(get('p1')),+ timestamp: get('timestamp'),+ file: path.relative(cwd, path.join(dir, newest)),+ };+ } catch {+ return null;+ }+}++/** Branch + a scope hint: files changed vs the default branch, else working tree. */+function gitSignals(cwd) {+ const run = (args, { trim = true } = {}) => {+ try {+ const out = execFileSync('git', args, {+ cwd,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'ignore'],+ });+ return trim ? out.trim() : out;+ } catch {+ return null;+ }+ };+ if (run(['rev-parse', '--is-inside-work-tree']) !== 'true') {+ return { isRepo: false, branch: null, base: null, changedFiles: [], changedCount: 0 };+ }+ const branch = run(['rev-parse', '--abbrev-ref', 'HEAD']);+ let base = null;+ for (const b of ['main', 'master']) {+ if (run(['rev-parse', '--verify', '--quiet', b]) !== null) {+ base = b;+ break;+ }+ }+ const diffBase = base && branch && branch !== base ? base : null;+ const fromDiff = diffBase ? run(['diff', '--name-only', `${diffBase}...HEAD`]) : null;+ // porcelain lines are `XY PATH`: a 2-char status + a space, then the path.+ // Don't trim the combined output — an unstaged-modified line starts with a+ // leading space (` M path`), and a global trim would eat the first line's+ // status column and shift the slice. Renames render as `old -> new`.+ const fromStatus = run(['-c', 'core.quotepath=false', 'status', '--porcelain'], { trim: false });+ let changed = [];+ if (fromDiff) {+ changed = fromDiff.split('\n').filter(Boolean);+ } else if (fromStatus) {+ changed = fromStatus.split(/\r?\n/).filter(Boolean).map((l) => {+ const p = l.slice(3);+ const arrow = p.indexOf(' -> ');+ return arrow === -1 ? p : p.slice(arrow + 4);+ });+ }+ return {+ isRepo: true,+ branch,+ base: diffBase,+ changedFiles: changed.slice(0, 50),+ changedCount: changed.length,+ };+}++const COMMON_DEV_PORTS = [4321, 3000, 5173, 5174, 8080, 8000, 4200];++function probePort(port, timeout = 250) {+ return new Promise((resolve) => {+ const sock = new net.Socket();+ let settled = false;+ const finish = (ok) => {+ if (settled) return;+ settled = true;+ try { sock.destroy(); } catch { /* ignore */ }+ resolve(ok);+ };+ sock.setTimeout(timeout);+ sock.once('connect', () => finish(true));+ sock.once('timeout', () => finish(false));+ sock.once('error', () => finish(false));+ sock.connect(port, '127.0.0.1');+ });+}++async function devServerSignals() {+ const open = [];+ await Promise.all(+ COMMON_DEV_PORTS.map(async (p) => {+ if (await probePort(p)) open.push(p);+ }),+ );+ open.sort((a, b) => a - b);+ return { running: open.length > 0, ports: open };+}++export async function gatherSignals(cwd = process.cwd()) {+ const ctx = loadContext(cwd);+ return {+ setup: {+ hasProduct: ctx.hasProduct,+ productPath: ctx.productPath,+ hasDesign: ctx.hasDesign,+ designPath: ctx.designPath,+ hasCode: hasCode(cwd),+ register: extractRegister(ctx.product),+ },+ critique: { latest: latestCritique(cwd) },+ git: gitSignals(cwd),+ devServer: await devServerSignals(),+ };+}++async function cli() {+ const signals = await gatherSignals(process.cwd());+ process.stdout.write(`${JSON.stringify(signals, null, 2)}\n`);+}++function invokedAsScript() {+ const arg = process.argv[1];+ if (!arg) return false;+ try {+ return fs.realpathSync(arg) === fs.realpathSync(fileURLToPath(import.meta.url));+ } catch {+ return false;+ }+}++if (invokedAsScript()) {+ cli();+}diff --git a/.trae/skills/impeccable/scripts/context.mjs b/.trae/skills/impeccable/scripts/context.mjsindex eb4000717..8725469bf 100644--- a/.trae/skills/impeccable/scripts/context.mjs+++ b/.trae/skills/impeccable/scripts/context.mjs@@ -94,7 +94,7 @@ function safeRead(p) {* for a `## Register` section and reading the first non-empty line that* follows it. Returns null when the file is legacy / register-less.*/-function extractRegister(product) {+export function extractRegister(product) {if (!product) return null;const lines = product.split('\n');for (let i = 0; i < lines.length; i++) {diff --git a/plugin/skills/impeccable/SKILL.md b/plugin/skills/impeccable/SKILL.mdindex 1edabd6d6..c61880528 100644--- a/plugin/skills/impeccable/SKILL.md+++ b/plugin/skills/impeccable/SKILL.md@@ -142,7 +142,16 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be### Routing rules-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.+1. **No argument**: the user is asking "what should I do?" Make the menu context-aware instead of static. Setup has already run `context.mjs`; if that reported `NO_PRODUCT_MD` you are already in init (setup), so finish that and skip this. Otherwise run `node .claude/skills/impeccable/scripts/context-signals.mjs` once and read its JSON, then lead with the **2-3 highest-value next commands**, each with a one-line reason pulled from the signals, followed by the full menu (the table above, grouped by category). **Never auto-run a command; the recommendation is a suggestion the user confirms.**++ Reason over the signals; there is no score to obey:+ - `setup.hasDesign` false while `setup.hasCode` true → `document` (capture the visual system).+ - `critique.latest` with a low `score` or non-zero `p0` / `p1` → `polish` (it reads that snapshot as its backlog), or re-run `critique` if the snapshot looks stale.+ - `git.changedFiles` pointing at one surface → scope `audit` or `polish` to those files specifically, naming them.+ - `devServer.running` true → `live` is available for in-browser iteration; if false, don't lead with `live`.+ - Otherwise group by intent exactly as init's "Recommend starting points" step does (build new / improve what's there / iterate visually), tailored to `setup.register`.++ Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.diff --git a/plugin/skills/impeccable/scripts/context-signals.mjs b/plugin/skills/impeccable/scripts/context-signals.mjsnew file mode 100644index 000000000..cd54793af--- /dev/null+++ b/plugin/skills/impeccable/scripts/context-signals.mjs@@ -0,0 +1,187 @@+#!/usr/bin/env node+/**+ * Context-signals gatherer for the bare `{{command_prefix}}impeccable`+ * (no-argument) path. Collects cheap, deterministic signals about the current+ * project and emits them as JSON.+ *+ * It does NOT score or rank. The agent reasons over the raw signals using its+ * knowledge of the command catalog (see SKILL.md routing rule 1). Deliberately+ * light: no LLM calls, no detector run (`npx impeccable detect` is heavier and+ * opt-in), no file writes. Every probe is best-effort and never throws; the+ * output is always valid JSON.+ *+ * Signals:+ * - setup: PRODUCT.md / DESIGN.md presence, register, whether code exists+ * - critique: the latest cached critique score (.impeccable/critique)+ * - git: branch + files changed vs the default branch (a scope hint)+ * - devServer: whether a local dev server answers on a common port (gates live)+ */+import fs from 'node:fs';+import net from 'node:net';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFileSync } from 'node:child_process';+import { loadContext, extractRegister } from './context.mjs';+import { getCritiqueDir } from './impeccable-paths.mjs';++/** Is there code here at all, or just context files / an empty repo? */+function hasCode(cwd) {+ if (fs.existsSync(path.join(cwd, 'package.json'))) return true;+ for (const d of ['src', 'app', 'pages', 'site', 'public', 'components', 'lib']) {+ if (fs.existsSync(path.join(cwd, d))) return true;+ }+ return false;+}++/**+ * The most recent critique snapshot across all targets. Filenames are+ * timestamp-prefixed (`<iso>__<slug>.md`), so a lexical sort is chronological.+ * Parses the small frontmatter for score + P0/P1 counts.+ */+function latestCritique(cwd) {+ try {+ const dir = getCritiqueDir(cwd);+ if (!fs.existsSync(dir)) return null;+ const files = fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort();+ if (!files.length) return null;+ const newest = files[files.length - 1];+ const text = fs.readFileSync(path.join(dir, newest), 'utf-8');+ const front = text.split('---')[1] || '';+ const get = (k) => {+ const m = front.match(new RegExp(`^${k}:\\s*(.+)$`, 'm'));+ return m ? m[1].trim() : null;+ };+ const num = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+ };+ return {+ slug: get('slug'),+ score: num(get('score')),+ p0: num(get('p0')),+ p1: num(get('p1')),+ timestamp: get('timestamp'),+ file: path.relative(cwd, path.join(dir, newest)),+ };+ } catch {+ return null;+ }+}++/** Branch + a scope hint: files changed vs the default branch, else working tree. */+function gitSignals(cwd) {+ const run = (args, { trim = true } = {}) => {+ try {+ const out = execFileSync('git', args, {+ cwd,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'ignore'],+ });+ return trim ? out.trim() : out;+ } catch {+ return null;+ }+ };+ if (run(['rev-parse', '--is-inside-work-tree']) !== 'true') {+ return { isRepo: false, branch: null, base: null, changedFiles: [], changedCount: 0 };+ }+ const branch = run(['rev-parse', '--abbrev-ref', 'HEAD']);+ let base = null;+ for (const b of ['main', 'master']) {+ if (run(['rev-parse', '--verify', '--quiet', b]) !== null) {+ base = b;+ break;+ }+ }+ const diffBase = base && branch && branch !== base ? base : null;+ const fromDiff = diffBase ? run(['diff', '--name-only', `${diffBase}...HEAD`]) : null;+ // porcelain lines are `XY PATH`: a 2-char status + a space, then the path.+ // Don't trim the combined output — an unstaged-modified line starts with a+ // leading space (` M path`), and a global trim would eat the first line's+ // status column and shift the slice. Renames render as `old -> new`.+ const fromStatus = run(['-c', 'core.quotepath=false', 'status', '--porcelain'], { trim: false });+ let changed = [];+ if (fromDiff) {+ changed = fromDiff.split('\n').filter(Boolean);+ } else if (fromStatus) {+ changed = fromStatus.split(/\r?\n/).filter(Boolean).map((l) => {+ const p = l.slice(3);+ const arrow = p.indexOf(' -> ');+ return arrow === -1 ? p : p.slice(arrow + 4);+ });+ }+ return {+ isRepo: true,+ branch,+ base: diffBase,+ changedFiles: changed.slice(0, 50),+ changedCount: changed.length,+ };+}++const COMMON_DEV_PORTS = [4321, 3000, 5173, 5174, 8080, 8000, 4200];++function probePort(port, timeout = 250) {+ return new Promise((resolve) => {+ const sock = new net.Socket();+ let settled = false;+ const finish = (ok) => {+ if (settled) return;+ settled = true;+ try { sock.destroy(); } catch { /* ignore */ }+ resolve(ok);+ };+ sock.setTimeout(timeout);+ sock.once('connect', () => finish(true));+ sock.once('timeout', () => finish(false));+ sock.once('error', () => finish(false));+ sock.connect(port, '127.0.0.1');+ });+}++async function devServerSignals() {+ const open = [];+ await Promise.all(+ COMMON_DEV_PORTS.map(async (p) => {+ if (await probePort(p)) open.push(p);+ }),+ );+ open.sort((a, b) => a - b);+ return { running: open.length > 0, ports: open };+}++export async function gatherSignals(cwd = process.cwd()) {+ const ctx = loadContext(cwd);+ return {+ setup: {+ hasProduct: ctx.hasProduct,+ productPath: ctx.productPath,+ hasDesign: ctx.hasDesign,+ designPath: ctx.designPath,+ hasCode: hasCode(cwd),+ register: extractRegister(ctx.product),+ },+ critique: { latest: latestCritique(cwd) },+ git: gitSignals(cwd),+ devServer: await devServerSignals(),+ };+}++async function cli() {+ const signals = await gatherSignals(process.cwd());+ process.stdout.write(`${JSON.stringify(signals, null, 2)}\n`);+}++function invokedAsScript() {+ const arg = process.argv[1];+ if (!arg) return false;+ try {+ return fs.realpathSync(arg) === fs.realpathSync(fileURLToPath(import.meta.url));+ } catch {+ return false;+ }+}++if (invokedAsScript()) {+ cli();+}diff --git a/plugin/skills/impeccable/scripts/context.mjs b/plugin/skills/impeccable/scripts/context.mjsindex eb4000717..8725469bf 100644--- a/plugin/skills/impeccable/scripts/context.mjs+++ b/plugin/skills/impeccable/scripts/context.mjs@@ -94,7 +94,7 @@ function safeRead(p) {* for a `## Register` section and reading the first non-empty line that* follows it. Returns null when the file is legacy / register-less.*/-function extractRegister(product) {+export function extractRegister(product) {if (!product) return null;const lines = product.split('\n');for (let i = 0; i < lines.length; i++) {diff --git a/skill/SKILL.src.md b/skill/SKILL.src.mdindex 019382b48..f82f70b7b 100644--- a/skill/SKILL.src.md+++ b/skill/SKILL.src.md@@ -161,7 +161,16 @@ Plus two management commands: `pin <command>` and `unpin <command>`, detailed be### Routing rules-1. **No argument**: render the table above as the user-facing command menu, grouped by category. Ask what they'd like to do.+1. **No argument**: the user is asking "what should I do?" Make the menu context-aware instead of static. Setup has already run `context.mjs`; if that reported `NO_PRODUCT_MD` you are already in init (setup), so finish that and skip this. Otherwise run `node {{scripts_path}}/context-signals.mjs` once and read its JSON, then lead with the **2-3 highest-value next commands**, each with a one-line reason pulled from the signals, followed by the full menu (the table above, grouped by category). **Never auto-run a command; the recommendation is a suggestion the user confirms.**++ Reason over the signals; there is no score to obey:+ - `setup.hasDesign` false while `setup.hasCode` true → `document` (capture the visual system).+ - `critique.latest` with a low `score` or non-zero `p0` / `p1` → `polish` (it reads that snapshot as its backlog), or re-run `critique` if the snapshot looks stale.+ - `git.changedFiles` pointing at one surface → scope `audit` or `polish` to those files specifically, naming them.+ - `devServer.running` true → `live` is available for in-browser iteration; if false, don't lead with `live`.+ - Otherwise group by intent exactly as init's "Recommend starting points" step does (build new / improve what's there / iterate visually), tailored to `setup.register`.++ Keep it to 2-3 pointed picks with the exact command to type. The menu stays the fallback; the recommendation is the lede.2. **First word matches a command**: load its reference file and follow its instructions. Everything after the command name is the target.3. **First word doesn't match, but the intent clearly maps to one command** (e.g. "fix the spacing" → `layout`, "rewrite this error message" → `clarify`, "the colors feel flat" → `colorize`): load that command's reference and proceed as if invoked. If two commands could fit, ask once which.4. **No clear command match**: general design invocation. Apply the setup steps, the General rules, and the loaded register reference, using the full argument as context.diff --git a/skill/scripts/context-signals.mjs b/skill/scripts/context-signals.mjsnew file mode 100644index 000000000..cd54793af--- /dev/null+++ b/skill/scripts/context-signals.mjs@@ -0,0 +1,187 @@+#!/usr/bin/env node+/**+ * Context-signals gatherer for the bare `{{command_prefix}}impeccable`+ * (no-argument) path. Collects cheap, deterministic signals about the current+ * project and emits them as JSON.+ *+ * It does NOT score or rank. The agent reasons over the raw signals using its+ * knowledge of the command catalog (see SKILL.md routing rule 1). Deliberately+ * light: no LLM calls, no detector run (`npx impeccable detect` is heavier and+ * opt-in), no file writes. Every probe is best-effort and never throws; the+ * output is always valid JSON.+ *+ * Signals:+ * - setup: PRODUCT.md / DESIGN.md presence, register, whether code exists+ * - critique: the latest cached critique score (.impeccable/critique)+ * - git: branch + files changed vs the default branch (a scope hint)+ * - devServer: whether a local dev server answers on a common port (gates live)+ */+import fs from 'node:fs';+import net from 'node:net';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { execFileSync } from 'node:child_process';+import { loadContext, extractRegister } from './context.mjs';+import { getCritiqueDir } from './impeccable-paths.mjs';++/** Is there code here at all, or just context files / an empty repo? */+function hasCode(cwd) {+ if (fs.existsSync(path.join(cwd, 'package.json'))) return true;+ for (const d of ['src', 'app', 'pages', 'site', 'public', 'components', 'lib']) {+ if (fs.existsSync(path.join(cwd, d))) return true;+ }+ return false;+}++/**+ * The most recent critique snapshot across all targets. Filenames are+ * timestamp-prefixed (`<iso>__<slug>.md`), so a lexical sort is chronological.+ * Parses the small frontmatter for score + P0/P1 counts.+ */+function latestCritique(cwd) {+ try {+ const dir = getCritiqueDir(cwd);+ if (!fs.existsSync(dir)) return null;+ const files = fs.readdirSync(dir).filter((f) => f.endsWith('.md')).sort();+ if (!files.length) return null;+ const newest = files[files.length - 1];+ const text = fs.readFileSync(path.join(dir, newest), 'utf-8');+ const front = text.split('---')[1] || '';+ const get = (k) => {+ const m = front.match(new RegExp(`^${k}:\\s*(.+)$`, 'm'));+ return m ? m[1].trim() : null;+ };+ const num = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+ };+ return {+ slug: get('slug'),+ score: num(get('score')),+ p0: num(get('p0')),+ p1: num(get('p1')),+ timestamp: get('timestamp'),+ file: path.relative(cwd, path.join(dir, newest)),+ };+ } catch {+ return null;+ }+}++/** Branch + a scope hint: files changed vs the default branch, else working tree. */+function gitSignals(cwd) {+ const run = (args, { trim = true } = {}) => {+ try {+ const out = execFileSync('git', args, {+ cwd,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'ignore'],+ });+ return trim ? out.trim() : out;+ } catch {+ return null;+ }+ };+ if (run(['rev-parse', '--is-inside-work-tree']) !== 'true') {+ return { isRepo: false, branch: null, base: null, changedFiles: [], changedCount: 0 };+ }+ const branch = run(['rev-parse', '--abbrev-ref', 'HEAD']);+ let base = null;+ for (const b of ['main', 'master']) {+ if (run(['rev-parse', '--verify', '--quiet', b]) !== null) {+ base = b;+ break;+ }+ }+ const diffBase = base && branch && branch !== base ? base : null;+ const fromDiff = diffBase ? run(['diff', '--name-only', `${diffBase}...HEAD`]) : null;+ // porcelain lines are `XY PATH`: a 2-char status + a space, then the path.+ // Don't trim the combined output — an unstaged-modified line starts with a+ // leading space (` M path`), and a global trim would eat the first line's+ // status column and shift the slice. Renames render as `old -> new`.+ const fromStatus = run(['-c', 'core.quotepath=false', 'status', '--porcelain'], { trim: false });+ let changed = [];+ if (fromDiff) {+ changed = fromDiff.split('\n').filter(Boolean);+ } else if (fromStatus) {+ changed = fromStatus.split(/\r?\n/).filter(Boolean).map((l) => {+ const p = l.slice(3);+ const arrow = p.indexOf(' -> ');+ return arrow === -1 ? p : p.slice(arrow + 4);+ });+ }+ return {+ isRepo: true,+ branch,+ base: diffBase,+ changedFiles: changed.slice(0, 50),+ changedCount: changed.length,+ };+}++const COMMON_DEV_PORTS = [4321, 3000, 5173, 5174, 8080, 8000, 4200];++function probePort(port, timeout = 250) {+ return new Promise((resolve) => {+ const sock = new net.Socket();+ let settled = false;+ const finish = (ok) => {+ if (settled) return;+ settled = true;+ try { sock.destroy(); } catch { /* ignore */ }+ resolve(ok);+ };+ sock.setTimeout(timeout);+ sock.once('connect', () => finish(true));+ sock.once('timeout', () => finish(false));+ sock.once('error', () => finish(false));+ sock.connect(port, '127.0.0.1');+ });+}++async function devServerSignals() {+ const open = [];+ await Promise.all(+ COMMON_DEV_PORTS.map(async (p) => {+ if (await probePort(p)) open.push(p);+ }),+ );+ open.sort((a, b) => a - b);+ return { running: open.length > 0, ports: open };+}++export async function gatherSignals(cwd = process.cwd()) {+ const ctx = loadContext(cwd);+ return {+ setup: {+ hasProduct: ctx.hasProduct,+ productPath: ctx.productPath,+ hasDesign: ctx.hasDesign,+ designPath: ctx.designPath,+ hasCode: hasCode(cwd),+ register: extractRegister(ctx.product),+ },+ critique: { latest: latestCritique(cwd) },+ git: gitSignals(cwd),+ devServer: await devServerSignals(),+ };+}++async function cli() {+ const signals = await gatherSignals(process.cwd());+ process.stdout.write(`${JSON.stringify(signals, null, 2)}\n`);+}++function invokedAsScript() {+ const arg = process.argv[1];+ if (!arg) return false;+ try {+ return fs.realpathSync(arg) === fs.realpathSync(fileURLToPath(import.meta.url));+ } catch {+ return false;+ }+}++if (invokedAsScript()) {+ cli();+}diff --git a/skill/scripts/context.mjs b/skill/scripts/context.mjsindex eb4000717..8725469bf 100644--- a/skill/scripts/context.mjs+++ b/skill/scripts/context.mjs@@ -94,7 +94,7 @@ function safeRead(p) {* for a `## Register` section and reading the first non-empty line that* follows it. Returns null when the file is legacy / register-less.*/-function extractRegister(product) {+export function extractRegister(product) {if (!product) return null;const lines = product.split('\n');for (let i = 0; i < lines.length; i++) {diff --git a/tests/context-signals.test.mjs b/tests/context-signals.test.mjsnew file mode 100644index 000000000..b44efb0c2--- /dev/null+++ b/tests/context-signals.test.mjs@@ -0,0 +1,123 @@+/**+ * Tests for context-signals.mjs — the signal gatherer behind the+ * context-aware bare `/impeccable` (no-argument) path.+ *+ * The script collects deterministic project signals and emits JSON; it does+ * not score or rank (the agent reasons over the raw signals). These tests+ * cover signal collection and the never-throw / always-valid-JSON contract.+ *+ * Each test runs in its own scratch dir under os.tmpdir().+ */+import { describe, it, beforeEach, afterEach } from 'node:test';+import assert from 'node:assert/strict';+import fs from 'node:fs';+import path from 'node:path';+import os from 'node:os';+import { fileURLToPath } from 'node:url';++import { gatherSignals } from '../skill/scripts/context-signals.mjs';++const SCRIPT_PATH = path.join(+ path.dirname(fileURLToPath(import.meta.url)),+ '..', 'skill', 'scripts', 'context-signals.mjs',+);++let scratch;+beforeEach(() => {+ scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'impeccable-signals-'));+});+afterEach(() => {+ fs.rmSync(scratch, { recursive: true, force: true });+});++function write(rel, body) {+ const abs = path.join(scratch, rel);+ fs.mkdirSync(path.dirname(abs), { recursive: true });+ fs.writeFileSync(abs, body);+}++describe('gatherSignals', () => {+ it('reports no setup context in an empty dir', async () => {+ const s = await gatherSignals(scratch);+ assert.equal(s.setup.hasProduct, false);+ assert.equal(s.setup.hasDesign, false);+ assert.equal(s.setup.register, null);+ assert.equal(s.setup.hasCode, false);+ assert.equal(s.critique.latest, null);+ });++ it('detects PRODUCT.md, register, and code presence', async () => {+ write('PRODUCT.md', '# Product\n\n## Register\n\nbrand\n');+ write('package.json', '{"name":"x"}');+ const s = await gatherSignals(scratch);+ assert.equal(s.setup.hasProduct, true);+ assert.equal(s.setup.register, 'brand');+ assert.equal(s.setup.hasCode, true);+ });++ it('flags missing DESIGN.md when code exists', async () => {+ write('PRODUCT.md', '# Product\n\n## Register\n\nproduct\n');+ write('src/App.tsx', 'export default 1;');+ const s = await gatherSignals(scratch);+ assert.equal(s.setup.hasProduct, true);+ assert.equal(s.setup.hasDesign, false);+ assert.equal(s.setup.hasCode, true);+ assert.equal(s.setup.register, 'product');+ });++ it('reads the newest critique snapshot score', async () => {+ write('.impeccable/critique/2026-05-01T10-00-00Z__home.md',+ '---\nslug: home\nscore: 6\np0: 1\np1: 3\ntimestamp: 2026-05-01T10-00-00Z\n---\nbody\n');+ write('.impeccable/critique/2026-05-02T10-00-00Z__home.md',+ '---\nslug: home\nscore: 8\np0: 0\np1: 1\ntimestamp: 2026-05-02T10-00-00Z\n---\nbody\n');+ const s = await gatherSignals(scratch);+ assert.equal(s.critique.latest.score, 8); // newest by timestamp prefix+ assert.equal(s.critique.latest.p0, 0);+ assert.equal(s.critique.latest.slug, 'home');+ });++ it('handles a non-git dir without throwing', async () => {+ const s = await gatherSignals(scratch);+ assert.equal(s.git.isRepo, false);+ assert.deepEqual(s.git.changedFiles, []);+ assert.equal(s.git.changedCount, 0);+ });++ it('reports working-tree changes with full, untruncated paths', async () => {+ const { execFileSync } = await import('node:child_process');+ const git = (...args) => execFileSync('git', args, { cwd: scratch, stdio: 'ignore' });+ git('init', '-q');+ git('config', 'user.email', '[email protected]');+ git('config', 'user.name', 'Test');+ write('site/styles/home.css', 'a{}\n');+ git('add', '.');+ git('commit', '-qm', 'init');+ // Modify it so it shows as ` M ...` (leading-space porcelain line) — the+ // exact shape that a naive global trim would truncate to "ite/...".+ write('site/styles/home.css', 'a{color:red}\n');+ const s = await gatherSignals(scratch);+ assert.equal(s.git.isRepo, true);+ assert.ok(+ s.git.changedFiles.includes('site/styles/home.css'),+ `expected full path, got: ${JSON.stringify(s.git.changedFiles)}`,+ );+ });++ it('always includes a well-formed devServer probe', async () => {+ const s = await gatherSignals(scratch);+ assert.equal(typeof s.devServer.running, 'boolean');+ assert.ok(Array.isArray(s.devServer.ports));+ });+});++describe('context-signals CLI', () => {+ it('emits valid JSON with all top-level signal groups', async () => {+ const { spawnSync } = await import('node:child_process');+ const res = spawnSync(process.execPath, [SCRIPT_PATH], { cwd: scratch, encoding: 'utf8' });+ assert.equal(res.status, 0);+ const parsed = JSON.parse(res.stdout);+ for (const k of ['setup', 'critique', 'git', 'devServer']) {+ assert.ok(k in parsed, `expected "${k}" in signals output`);+ }+ });+});