Open-source SEO, GEO, and marketing skills for AI agents.
Resolve Claude plugin submission findings and retire NotFair CMO (#131)
Yuting Zhongf3ca1378948d
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex 86686ebc..3a486838 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -5,14 +5,14 @@},"metadata": {"description": "The official ads, analytics, SEO, and GEO plugin from NotFair.",- "version": "0.27.15"+ "version": "0.27.16"},"plugins": [{"name": "notfair","source": "./","description": "Operate Google, Meta, X, LinkedIn, Reddit, and TikTok Ads; WordPress and GoHighLevel; analyze Search Console and GA4; and run open-source SEO, GEO, and content workflows.",- "version": "0.27.15",+ "version": "0.27.16","author": {"name": "NotFair","url": "https://notfair.co"diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex f38f763a..19f74a9e 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,59 +1,68 @@{"name": "notfair",- "version": "0.27.15",+ "version": "0.27.16","description": "The official ads, analytics, SEO, and GEO plugin from NotFair. Operate Google, Meta, X, LinkedIn, Reddit, and TikTok Ads; WordPress and GoHighLevel; analyze Google Search Console and GA4; and run open-source search and content workflows from any compatible agent.","author": {"name": "NotFair","url": "https://notfair.co"},"skills": [- "./paid-ads/paid-ads",- "./paid-ads/paid-ads-guide",- "./paid-ads/paid-ads-setup",- "./paid-ads/paid-ads-integrations",- "./paid-ads/paid-ads-launch",- "./paid-ads/paid-ads-review",- "./paid-ads/paid-ads-optimize",- "./paid-ads/paid-ads-creative",- "./paid-ads/paid-ads-x",- "./paid-ads/paid-ads-linkedin",- "./paid-ads/paid-ads-reddit",- "./paid-ads/paid-ads-tiktok",- "./paid-ads/paid-ads-amazon",- "./paid-ads/paid-ads-chatgpt",- "./google-ads/manage",- "./google-ads/audit",- "./google-ads/copy",- "./google-ads/assets",- "./google-ads/landing",- "./meta-ads/manage",- "./meta-ads/audit",- "./meta-ads/creative",- "./analytics/google-analytics",- "./analytics/search-console",- "./wordpress",- "./gohighlevel",- "./seo/seo-analysis",- "./seo/content-writer",- "./seo/content-planner",- "./seo/keyword-research",- "./seo/meta-tags-optimizer",- "./seo/schema-markup-generator",- "./seo/setup-cms",- "./seo/seo-page",- "./seo/broken-link-checker",- "./seo/geo-optimizer",- "./seo/local-seo",- "./seo/hreflang-international",- "./seo/sitemap-audit",- "./seo/image-seo",- "./seo/ecommerce-seo",- "./seo/programmatic-seo",- "./seo/competitor-pages",- "./seo/sxo",- "./seo/seo-drift",- "./seo/backlink-audit",- "./notfair-upgrade-skill",- "./gemini"- ]+ "./skills/paid-ads",+ "./skills/paid-ads-guide",+ "./skills/paid-ads-setup",+ "./skills/paid-ads-integrations",+ "./skills/paid-ads-launch",+ "./skills/paid-ads-review",+ "./skills/paid-ads-optimize",+ "./skills/paid-ads-creative",+ "./skills/paid-ads-x",+ "./skills/paid-ads-linkedin",+ "./skills/paid-ads-reddit",+ "./skills/paid-ads-tiktok",+ "./skills/paid-ads-amazon",+ "./skills/paid-ads-chatgpt",+ "./skills/google-ads",+ "./skills/google-ads-audit",+ "./skills/google-ads-copy",+ "./skills/google-ads-assets",+ "./skills/google-ads-landing",+ "./skills/meta-ads",+ "./skills/meta-ads-audit",+ "./skills/meta-ads-creative",+ "./skills/google-analytics",+ "./skills/search-console",+ "./skills/wordpress",+ "./skills/gohighlevel",+ "./skills/seo-analysis",+ "./skills/content-writer",+ "./skills/content-planner",+ "./skills/keyword-research",+ "./skills/meta-tags-optimizer",+ "./skills/schema-markup-generator",+ "./skills/setup-cms",+ "./skills/seo-page",+ "./skills/broken-link-checker",+ "./skills/geo-optimizer",+ "./skills/local-seo",+ "./skills/hreflang-international",+ "./skills/sitemap-audit",+ "./skills/image-seo",+ "./skills/ecommerce-seo",+ "./skills/programmatic-seo",+ "./skills/competitor-pages",+ "./skills/sxo",+ "./skills/seo-drift",+ "./skills/backlink-audit",+ "./skills/upgrade",+ "./skills/gemini"+ ],+ "displayName": "NotFair",+ "homepage": "https://notfair.co",+ "repository": "https://github.com/nowork-studio/notfair-plugin",+ "license": "MIT",+ "icon": "./assets/notfair-icon.png",+ "documentationUrl": "https://github.com/nowork-studio/notfair-plugin#readme",+ "supportUrl": "https://notfair.co/contact",+ "privacyPolicyUrl": "https://notfair.co/privacy",+ "termsOfServiceUrl": "https://notfair.co/terms"}diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 9b345d9b..6765e7a2 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "notfair",- "version": "0.27.15",+ "version": "0.27.16","description": "The official ads, analytics, SEO, and GEO plugin from NotFair.","author": {"name": "NotFair",@@ -38,6 +38,7 @@],"brandColor": "#111827","logo": "./assets/notfair-icon.png",- "composerIcon": "./assets/notfair-icon.png"+ "composerIcon": "./assets/notfair-icon.png",+ "supportURL": "https://notfair.co/contact"}}diff --git a/.cursor-plugin/plugin.json b/.cursor-plugin/plugin.jsonindex fb701d2b..e540dfe7 100644--- a/.cursor-plugin/plugin.json+++ b/.cursor-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "notfair","displayName": "NotFair",- "version": "0.27.15",+ "version": "0.27.16","description": "One NotFair OAuth MCP for Google, Meta, X, LinkedIn, Reddit, and TikTok Ads, GA4, Search Console, GoHighLevel, and WordPress, plus open-source SEO, GEO, and content skills.","author": {"name": "Notfair",diff --git a/.gitattributes b/.gitattributesindex f59fc42b..afc65e64 100644--- a/.gitattributes+++ b/.gitattributes@@ -1,4 +1,4 @@*.sh text eol=lf-bin/notfair-change-watch text eol=lf-bin/notfair-config text eol=lf-bin/notfair-update-check text eol=lf+scripts/notfair-change-watch.sh text eol=lf+scripts/notfair-config.sh text eol=lf+scripts/notfair-update-check.sh text eol=lfdiff --git a/.github/workflows/npm-publish-nextjs-blog.yml b/.github/workflows/npm-publish-nextjs-blog.ymldeleted file mode 100644index ab2e516d..00000000--- a/.github/workflows/npm-publish-nextjs-blog.yml+++ /dev/null@@ -1,59 +0,0 @@-name: Publish notfair-nextjs-blog to npm--# Publishes the Next.js blog client when notfair-nextjs-blog/package.json-# lands on main with a version that isn't on the registry yet. Bump the-# version in a normal commit and push — no tags or releases to manage.-# Re-runs on an already-published version are a clean no-op.-on:- push:- branches: [main]- paths:- - "notfair-nextjs-blog/**"- workflow_dispatch:--concurrency:- group: npm-publish-nextjs-blog- cancel-in-progress: false--jobs:- publish:- # macos-14 matches the main notfair publish workflow — ubuntu-latest jobs- # were never acquired by a hosted runner in this org (see run 31127380316).- runs-on: macos-14- defaults:- run:- working-directory: notfair-nextjs-blog- steps:- - uses: actions/checkout@v4-- # registry-url makes setup-node write an ~/.npmrc that reads- # NODE_AUTH_TOKEN.- - uses: actions/setup-node@v4- with:- node-version: 24- registry-url: https://registry.npmjs.org-- - name: Skip if this version is already on npm- id: version- run: |- LOCAL=$(node -p "require('./package.json').version")- PUBLISHED=$(npm view notfair-nextjs-blog version 2>/dev/null || echo "none")- echo "local=$LOCAL published=$PUBLISHED"- echo "local=$LOCAL" >> "$GITHUB_OUTPUT"- if [ "$LOCAL" = "$PUBLISHED" ]; then- echo "skip=true" >> "$GITHUB_OUTPUT"- fi-- - name: Install- if: steps.version.outputs.skip != 'true'- run: npm install-- - name: Test and build- if: steps.version.outputs.skip != 'true'- run: npm test-- - name: Publish ${{ steps.version.outputs.local }}- if: steps.version.outputs.skip != 'true'- run: npm publish- env:- NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.ymldeleted file mode 100644index bd45a26e..00000000--- a/.github/workflows/npm-publish.yml+++ /dev/null@@ -1,73 +0,0 @@-name: Publish notfair to npm--# Publishes the app when notfair/package.json lands on main with a version-# that isn't on the registry yet. Bump the version in a normal commit and-# push — no tags or releases to manage. Re-runs on an already-published-# version are a clean no-op, so this is safe on every push to notfair/**.-on:- push:- branches: [main]- paths:- - "notfair/**"- workflow_dispatch:--concurrency:- group: npm-publish- cancel-in-progress: false--jobs:- publish:- # macOS ARM64 is load-bearing: the package declares darwin/arm64 and the- # standalone bundle ships native prebuilds (better-sqlite3, keytar).- # Building on Linux would publish binaries no supported machine can load.- runs-on: macos-14- defaults:- run:- working-directory: notfair- steps:- - uses: actions/checkout@v4-- - uses: pnpm/action-setup@v4- with:- version: 10-- # registry-url makes setup-node write an ~/.npmrc that reads- # NODE_AUTH_TOKEN — notfair/.npmrc is gitignored, so it cannot- # carry the auth wiring in CI.- - uses: actions/setup-node@v4- with:- node-version: 24- registry-url: https://registry.npmjs.org-- - name: Skip if this version is already on npm- id: version- run: |- LOCAL=$(node -p "require('./package.json').version")- PUBLISHED=$(npm view notfair version 2>/dev/null || echo "none")- echo "local=$LOCAL published=$PUBLISHED"- echo "local=$LOCAL" >> "$GITHUB_OUTPUT"- if [ "$LOCAL" = "$PUBLISHED" ]; then- echo "skip=true" >> "$GITHUB_OUTPUT"- fi-- - name: Install- if: steps.version.outputs.skip != 'true'- run: pnpm install --frozen-lockfile-- - name: Typecheck- if: steps.version.outputs.skip != 'true'- run: pnpm typecheck-- - name: Test- if: steps.version.outputs.skip != 'true'- run: pnpm test-- - name: Build- if: steps.version.outputs.skip != 'true'- run: pnpm build-- - name: Publish ${{ steps.version.outputs.local }}- if: steps.version.outputs.skip != 'true'- run: npm publish- env:- NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}diff --git a/AGENTS.md b/AGENTS.mdindex 08731ddd..e87f2437 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -4,6 +4,8 @@If you are an agent and a user mentions Google Ads, Meta Ads, SEO, GEO, or anything in the tables below, route to the named skill.+For repository maintenance, read [`docs/plugin-development.md`](docs/plugin-development.md). Installed workflow instructions live in the skills below.+---## How to use this file@@ -12,7 +14,7 @@ If you are an agent and a user mentions Google Ads, Meta Ads, SEO, GEO, or anyth2. **Read the named skill's `SKILL.md`** from the path shown.3. **Follow the procedure** in that SKILL.md exactly.-Skills under `seo/`, `paid-ads/`, `google-ads/`, `meta-ads/`, `analytics/`, `wordpress/`, `gohighlevel/`, `gemini/`, and `notfair-upgrade-skill/` are **host-agnostic** — they work the same on every supported agent host.+Skills under `skills/` are **host-agnostic**; each entry loads its full workflow from the corresponding category folder — they work the same on every supported agent host.---@@ -20,94 +22,94 @@ Skills under `seo/`, `paid-ads/`, `google-ads/`, `meta-ads/`, `analytics/`, `wor| Intent | Skill | Path ||---|---|---|-| Full-site SEO audit, traffic drop, GSC analysis, Core Web Vitals | `seo-analysis` | `seo/seo-analysis/SKILL.md` |-| Single-page deep audit (URL-specific) | `seo-page` | `seo/seo-page/SKILL.md` |-| Write or improve content (blog, landing, service page) | `content-writer` | `seo/content-writer/SKILL.md` |-| Plan content from GSC data, build a dated editorial calendar | `content-planner` | `seo/content-planner/SKILL.md` |-| Keyword discovery, topic clusters (seed → keyword universe) | `keyword-research` | `seo/keyword-research/SKILL.md` |-| Title tags, meta descriptions, Open Graph, CTR | `meta-tags-optimizer` | `seo/meta-tags-optimizer/SKILL.md` |-| JSON-LD / structured data (FAQ, Product, HowTo, etc.) | `schema-markup-generator` | `seo/schema-markup-generator/SKILL.md` |-| Broken-link / 404 / site-health crawl | `broken-link-checker` | `seo/broken-link-checker/SKILL.md` |-| Rank in ChatGPT / Perplexity / AI Overviews (GEO / AEO) | `geo-optimizer` | `seo/geo-optimizer/SKILL.md` |-| Local pack / Google Business Profile / Maps / NAP / "near me" | `local-seo` | `seo/local-seo/SKILL.md` |-| Hreflang, international / multilingual, multi-region targeting | `hreflang-international` | `seo/hreflang-international/SKILL.md` |-| XML sitemap audit, sitemap errors, crawl-coverage | `sitemap-audit` | `seo/sitemap-audit/SKILL.md` |-| Image SEO, alt text, Google Images, WebP, image schema | `image-seo` | `seo/image-seo/SKILL.md` |-| E-commerce SEO, product/category pages, faceted nav, product schema | `ecommerce-seo` | `seo/ecommerce-seo/SKILL.md` |-| Programmatic / templated pages at scale (pSEO) | `programmatic-seo` | `seo/programmatic-seo/SKILL.md` |-| Competitor page gap analysis, "why do they outrank me", SERP brief | `competitor-pages` | `seo/competitor-pages/SKILL.md` |-| Search Experience Optimization (SXO), CTR + on-page conversion | `sxo` | `seo/sxo/SKILL.md` |-| SEO drift / regression monitoring, baseline & compare over time | `seo-drift` | `seo/seo-drift/SKILL.md` |-| Backlink / off-page audit, anchor text, referring domains, disavow | `backlink-audit` | `seo/backlink-audit/SKILL.md` |-| Local Application-Password / `.env.local` CMS setup for SEO scripts (WordPress, Strapi, Contentful, or Ghost) | `setup-cms` | `seo/setup-cms/SKILL.md` |+| Full-site SEO audit, traffic drop, GSC analysis, Core Web Vitals | `seo-analysis` | `skills/seo-analysis/SKILL.md` |+| Single-page deep audit (URL-specific) | `seo-page` | `skills/seo-page/SKILL.md` |+| Write or improve content (blog, landing, service page) | `content-writer` | `skills/content-writer/SKILL.md` |+| Plan content from GSC data, build a dated editorial calendar | `content-planner` | `skills/content-planner/SKILL.md` |+| Keyword discovery, topic clusters (seed → keyword universe) | `keyword-research` | `skills/keyword-research/SKILL.md` |+| Title tags, meta descriptions, Open Graph, CTR | `meta-tags-optimizer` | `skills/meta-tags-optimizer/SKILL.md` |+| JSON-LD / structured data (FAQ, Product, HowTo, etc.) | `schema-markup-generator` | `skills/schema-markup-generator/SKILL.md` |+| Broken-link / 404 / site-health crawl | `broken-link-checker` | `skills/broken-link-checker/SKILL.md` |+| Rank in ChatGPT / Perplexity / AI Overviews (GEO / AEO) | `geo-optimizer` | `skills/geo-optimizer/SKILL.md` |+| Local pack / Google Business Profile / Maps / NAP / "near me" | `local-seo` | `skills/local-seo/SKILL.md` |+| Hreflang, international / multilingual, multi-region targeting | `hreflang-international` | `skills/hreflang-international/SKILL.md` |+| XML sitemap audit, sitemap errors, crawl-coverage | `sitemap-audit` | `skills/sitemap-audit/SKILL.md` |+| Image SEO, alt text, Google Images, WebP, image schema | `image-seo` | `skills/image-seo/SKILL.md` |+| E-commerce SEO, product/category pages, faceted nav, product schema | `ecommerce-seo` | `skills/ecommerce-seo/SKILL.md` |+| Programmatic / templated pages at scale (pSEO) | `programmatic-seo` | `skills/programmatic-seo/SKILL.md` |+| Competitor page gap analysis, "why do they outrank me", SERP brief | `competitor-pages` | `skills/competitor-pages/SKILL.md` |+| Search Experience Optimization (SXO), CTR + on-page conversion | `sxo` | `skills/sxo/SKILL.md` |+| SEO drift / regression monitoring, baseline & compare over time | `seo-drift` | `skills/seo-drift/SKILL.md` |+| Backlink / off-page audit, anchor text, referring domains, disavow | `backlink-audit` | `skills/backlink-audit/SKILL.md` |+| Local Application-Password / `.env.local` CMS setup for SEO scripts (WordPress, Strapi, Contentful, or Ghost) | `setup-cms` | `skills/setup-cms/SKILL.md` |## Paid Ads| Intent | Skill | Path ||---|---|---|-| Broad ads question, cross-channel strategy, budget, CPA/ROAS, or route to the right workflow | `paid-ads` | `paid-ads/paid-ads/SKILL.md` |-| How NotFair paid ads works, install, plan/limit, supported platforms, or product troubleshooting | `paid-ads-guide` | `paid-ads/paid-ads-guide/SKILL.md` |-| Connect an account, establish marketing context, or refresh a paid-media workspace | `paid-ads-setup` | `paid-ads/paid-ads-setup/SKILL.md` |-| Check connector access, tools, or supported platform capabilities | `paid-ads-integrations` | `paid-ads/paid-ads-integrations/SKILL.md` |-| Plan a new campaign or multi-channel experiment before it can spend | `paid-ads-launch` | `paid-ads/paid-ads-launch/SKILL.md` |-| Weekly/monthly performance report, scorecard, pacing, or tracking health | `paid-ads-review` | `paid-ads/paid-ads-review/SKILL.md` |-| Wasted spend, budget allocation, overspend, or safe optimization proposal | `paid-ads-optimize` | `paid-ads/paid-ads-optimize/SKILL.md` |-| Cross-channel copy, creative concepts, fatigue diagnosis, or test briefs | `paid-ads-creative` | `paid-ads/paid-ads-creative/SKILL.md` |-| X Ads performance, campaigns, line items, targeting, creative, or writes | `paid-ads-x` | `paid-ads/paid-ads-x/SKILL.md` |-| LinkedIn Ads performance, campaigns, targeting, leads, creative, or writes | `paid-ads-linkedin` | `paid-ads/paid-ads-linkedin/SKILL.md` |-| Reddit Ads performance, campaigns, ad groups, ads, targeting, audiences, or writes | `paid-ads-reddit` | `paid-ads/paid-ads-reddit/SKILL.md` |-| TikTok Ads performance, campaigns, creative, targeting, or writes | `paid-ads-tiktok` | `paid-ads/paid-ads-tiktok/SKILL.md` |-| Amazon Ads plan, ACoS review, ASIN targeting, or export-based review | `paid-ads-amazon` | `paid-ads/paid-ads-amazon/SKILL.md` |-| ChatGPT Ads experiment plan or verified-export review | `paid-ads-chatgpt` | `paid-ads/paid-ads-chatgpt/SKILL.md` |+| Broad ads question, cross-channel strategy, budget, CPA/ROAS, or route to the right workflow | `paid-ads` | `skills/paid-ads/SKILL.md` |+| How NotFair paid ads works, install, plan/limit, supported platforms, or product troubleshooting | `paid-ads-guide` | `skills/paid-ads-guide/SKILL.md` |+| Connect an account, establish marketing context, or refresh a paid-media workspace | `paid-ads-setup` | `skills/paid-ads-setup/SKILL.md` |+| Check connector access, tools, or supported platform capabilities | `paid-ads-integrations` | `skills/paid-ads-integrations/SKILL.md` |+| Plan a new campaign or multi-channel experiment before it can spend | `paid-ads-launch` | `skills/paid-ads-launch/SKILL.md` |+| Weekly/monthly performance report, scorecard, pacing, or tracking health | `paid-ads-review` | `skills/paid-ads-review/SKILL.md` |+| Wasted spend, budget allocation, overspend, or safe optimization proposal | `paid-ads-optimize` | `skills/paid-ads-optimize/SKILL.md` |+| Cross-channel copy, creative concepts, fatigue diagnosis, or test briefs | `paid-ads-creative` | `skills/paid-ads-creative/SKILL.md` |+| X Ads performance, campaigns, line items, targeting, creative, or writes | `paid-ads-x` | `skills/paid-ads-x/SKILL.md` |+| LinkedIn Ads performance, campaigns, targeting, leads, creative, or writes | `paid-ads-linkedin` | `skills/paid-ads-linkedin/SKILL.md` |+| Reddit Ads performance, campaigns, ad groups, ads, targeting, audiences, or writes | `paid-ads-reddit` | `skills/paid-ads-reddit/SKILL.md` |+| TikTok Ads performance, campaigns, creative, targeting, or writes | `paid-ads-tiktok` | `skills/paid-ads-tiktok/SKILL.md` |+| Amazon Ads plan, ACoS review, ASIN targeting, or export-based review | `paid-ads-amazon` | `skills/paid-ads-amazon/SKILL.md` |+| ChatGPT Ads experiment plan or verified-export review | `paid-ads-chatgpt` | `skills/paid-ads-chatgpt/SKILL.md` |## WordPress| Intent | Skill | Path ||---|---|---|-| Live WordPress content, media, comments, design, settings, plugins, themes, HTML files, or approved site changes through NotFair MCP | `wordpress` | `wordpress/SKILL.md` |+| Live WordPress content, media, comments, design, settings, plugins, themes, HTML files, or approved site changes through NotFair MCP | `wordpress` | `skills/wordpress/SKILL.md` |## CRM| Intent | Skill | Path ||---|---|---|-| GoHighLevel / HighLevel contacts, conversations, opportunities, calendars, pipelines, or approved CRM writes | `gohighlevel` | `gohighlevel/SKILL.md` |+| GoHighLevel / HighLevel contacts, conversations, opportunities, calendars, pipelines, or approved CRM writes | `gohighlevel` | `skills/gohighlevel/SKILL.md` |## Analytics| Intent | Skill | Path ||---|---|---|-| GA4 traffic, acquisition, engagement, conversions, realtime, or measurement configuration | `google-analytics` | `analytics/google-analytics/SKILL.md` |-| Live Search Console queries/pages, traffic changes, URL inspection, or sitemaps | `search-console` | `analytics/search-console/SKILL.md` |+| GA4 traffic, acquisition, engagement, conversions, realtime, or measurement configuration | `google-analytics` | `skills/google-analytics/SKILL.md` |+| Live Search Console queries/pages, traffic changes, URL inspection, or sitemaps | `search-console` | `skills/search-console/SKILL.md` |## Google Ads| Intent | Skill | Path ||---|---|---|-| First-time setup or account health check | `google-ads-audit` | `google-ads/audit/SKILL.md` |-| Performance, keywords, bids, budgets, negatives, experiments, bulk ops | `google-ads` | `google-ads/manage/SKILL.md` |-| Write ad copy, RSA headlines/descriptions, A/B variants | `google-ads-copy` | `google-ads/copy/SKILL.md` |-| Google Ads assets, extensions, sitelinks, callouts, image assets, PMax asset briefs | `google-ads-assets` | `google-ads/assets/SKILL.md` |-| Landing-page quality, ad-to-page match, LPX diagnosis | `google-ads-landing` | `google-ads/landing/SKILL.md` |+| First-time setup or account health check | `google-ads-audit` | `skills/google-ads-audit/SKILL.md` |+| Performance, keywords, bids, budgets, negatives, experiments, bulk ops | `google-ads` | `skills/google-ads/SKILL.md` |+| Write ad copy, RSA headlines/descriptions, A/B variants | `google-ads-copy` | `skills/google-ads-copy/SKILL.md` |+| Google Ads assets, extensions, sitelinks, callouts, image assets, PMax asset briefs | `google-ads-assets` | `skills/google-ads-assets/SKILL.md` |+| Landing-page quality, ad-to-page match, LPX diagnosis | `google-ads-landing` | `skills/google-ads-landing/SKILL.md` |## Meta Ads| Intent | Skill | Path ||---|---|---|-| First-time Meta setup or account health check | `meta-ads-audit` | `meta-ads/audit/SKILL.md` |-| Facebook/Instagram performance, ROAS, CPM, creative fatigue, audience overlap | `meta-ads` | `meta-ads/manage/SKILL.md` |-| Facebook/Instagram ad creative, copy angles, UGC concepts, asset briefs, creative refreshes | `meta-ads-creative` | `meta-ads/creative/SKILL.md` |+| First-time Meta setup or account health check | `meta-ads-audit` | `skills/meta-ads-audit/SKILL.md` |+| Facebook/Instagram performance, ROAS, CPM, creative fatigue, audience overlap | `meta-ads` | `skills/meta-ads/SKILL.md` |+| Facebook/Instagram ad creative, copy angles, UGC concepts, asset briefs, creative refreshes | `meta-ads-creative` | `skills/meta-ads-creative/SKILL.md` |## Cross-model review| Intent | Skill | Path ||---|---|---|-| Second opinion / review / challenge / consult via Google Gemini | `gemini` | `gemini/SKILL.md` |+| Second opinion / review / challenge / consult via Google Gemini | `gemini` | `skills/gemini/SKILL.md` |## Plugin maintenance| Intent | Skill | Path ||---|---|---|-| Upgrade NotFair to the latest version | `upgrade` | `notfair-upgrade-skill/SKILL.md` |+| Upgrade NotFair to the latest version | `upgrade` | `skills/upgrade/SKILL.md` |## External dependenciesdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex af2fc8b2..f52c0f21 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,21 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).## [Unreleased]+## [0.27.16] — 2026-10-08++### Removed++- Retired the optional NotFair CMO goal-loop application, its npm publishing workflow, and its dashboard screenshot. The marketing plugin and hosted MCP connection remain available.++- Moved the Next.js blog client and its release tooling to [nowork-studio/notfair-nextjs-blog](https://github.com/nowork-studio/notfair-nextjs-blog), preserving its package name and runtime exports while keeping it outside the AI-agent plugin.++### Fixed++- All hosts now register the same 48 entry points under `skills/`. Each entry loads one full workflow in its category folder, avoiding duplicate Claude skill names without copying workflow code.+- Added Claude directory icon, documentation, support, privacy-policy, and terms links. Existing OpenAI and Cursor manifests retain their identity and MCP connection.+- Removed blanket shell and file-write pre-approvals from CMS setup and upgrade. Upgrades use the host's plugin manager instead of resetting checkouts, rewriting installation records, and deleting caches.+- Bundled helpers are readable shell and Python source under `scripts/`, invoked explicitly through an interpreter. Repository development guidance is separate from installed plugin context.+## [0.27.15] — 2026-09-30### Fixed@@ -52,7 +67,7 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).### Changed-- **Cursor marketplace listing.** Commit a 512×512 PNG plugin logo at `assets/notfair-icon.png` and point `.cursor-plugin/plugin.json` at it so marketplace cards can render the NotFair mark (GitHub serves committed SVGs as plain text). Refresh Cursor and Agent Plugins listing copy to name the current one-OAuth MCP surfaces — Google, Meta, X, LinkedIn, Reddit, and TikTok Ads, GA4, Search Console, GoHighLevel, and WordPress — plus open-source SEO, GEO, and content skills.+- **Cursor marketplace listing.** Commit a 512×512 PNG plugin logo in the assets folder and point `.cursor-plugin/plugin.json` at it so marketplace cards can render the NotFair mark (GitHub serves committed SVGs as plain text). Refresh Cursor and Agent Plugins listing copy to name the current one-OAuth MCP surfaces — Google, Meta, X, LinkedIn, Reddit, and TikTok Ads, GA4, Search Console, GoHighLevel, and WordPress — plus open-source SEO, GEO, and content skills.## [0.27.8] — 2026-09-16@@ -335,7 +350,7 @@ reflects that. CHANGELOG entries below this one are unchanged.`openclaw cron remove "Toprank OpenClaw Scheduler"` and equivalent foreach per-site weekly review job before re-installing.- **Hooks pointing at `bin/toprank-change-watch`** in `~/.claude/settings.json`- must be updated to `bin/notfair-change-watch` after reinstall.+ must be updated to `scripts/notfair-change-watch.sh` after reinstall.---diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex edb5892e..5bec141f 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -13,9 +13,9 @@ Please be respectful and professional in all your interactions with the communitEach skill lives in its own folder under a category directory (e.g., `seo/`, `google-ads/`).1. **Create the Skill Directory**: `mkdir seo/your-new-skill`-2. **Add `SKILL.md`**: This is the heart of the skill. It must contain frontmatter with `name` and `description`.+2. **Add `WORKFLOW.md`**: Put the full instructions and frontmatter with `name` and `description` in the category directory. Create one `skills/<name>/SKILL.md` entry with the same frontmatter that loads the workflow. Only this entry is registered as a skill across hosts.3. **Optional Scripts/References**: Add any supporting Python scripts in a `scripts/` folder and reference documents in a `references/` folder within your skill directory.-4. **Register the Skill**: Add the path to your skill (relative to the repo root) to the `skills` array in `.claude-plugin/plugin.json`.+4. **Register the Skill**: Add `./skills/<name>` to the `skills` array in `.claude-plugin/plugin.json` and the entry point to `AGENTS.md`.5. **Bump Versions**: Update the version in:* `.claude-plugin/plugin.json`* `.claude-plugin/marketplace.json`@@ -24,7 +24,7 @@ Each skill lives in its own folder under a category directory (e.g., `seo/`, `go### 2. Improving Existing Skills-* Refine prompts in `SKILL.md` for better accuracy.+* Refine prompts in `WORKFLOW.md` for better accuracy and synchronize its frontmatter with the skill entry.* Add more robust error handling to scripts.* Update reference documentation.diff --git a/INSTALL_FOR_AGENTS.md b/INSTALL_FOR_AGENTS.mdindex 7197c899..69429446 100644--- a/INSTALL_FOR_AGENTS.md+++ b/INSTALL_FOR_AGENTS.md@@ -102,7 +102,7 @@ Do **not** invent credentials. If a skill needs auth that isn't present, surface## Step 5 — Verify and hand back1. Confirm `AGENTS.md` is readable from the working directory.-2. Confirm at least one canonical skill (e.g., `seo/seo-analysis/SKILL.md`) is readable.+2. Confirm at least one entry point (e.g., `skills/seo-analysis/SKILL.md`) and its full workflow (`seo/seo-analysis/WORKFLOW.md`) is readable.3. Tell the user: "NotFair is installed. Try `/notfair:google-ads-audit` for ads or `/notfair:seo-analysis` for SEO."---diff --git a/README.md b/README.mdindex 78fcdeda..9a90dce6 100644--- a/README.md+++ b/README.md@@ -7,7 +7,7 @@The NotFair Plugin gives Claude Code, Codex, Hermes, and other compatible agents practical marketing workflows they can follow—not another generic prompt collection. Use it to audit a site, investigate a traffic drop, analyze GA4 and Search Console, find wasted ad spend across Google, Meta, X, LinkedIn, Reddit, and TikTok, operate connected WordPress and GoHighLevel accounts, build campaign plans, and make reviewable changes.-Every skill is built in the open as a readable `SKILL.md`, with supporting references, scripts, and evals where needed. Inspect it, adapt it, or contribute a better workflow.+Each skill has one discoverable `skills/<name>/SKILL.md` entry point. It loads a readable `WORKFLOW.md` in the category folder, with supporting references, scripts, and evals where needed. Inspect it, adapt it, or contribute a better workflow.## What your agent can do@@ -248,7 +248,29 @@ Supported account operations come from the live connection. Changes must stay wi## Privacy and support+The plugin connects to the declared NotFair MCP endpoint through browser OAuth.+Requested tool arguments go to NotFair and results from connected providers return+to your authorized AI client. See the privacy policy for storage, retention, and+deletion details. Connect only the workspace and platform accounts you intend to use.++Optional local workflows run readable Python or shell scripts. Crawlers request+the URLs you supply; direct Search Console scripts use your explicitly authorized+Google Cloud login; CMS scripts use the site credentials you configure through+`setup-cms`. Gemini review sends the selected review context to Google's Gemini+CLI after its authentication setup. Choose these workflows explicitly, keep+credentials out of reports and commits, and use the OAuth MCP for live platform+work when it is available. There are no automatic plugin hooks or local MCP servers.+The calendar viewer serves local planning data on loopback, and the optional+update checker reads the public version file from GitHub.++The separate [NotFair Next.js blog library](https://github.com/nowork-studio/notfair-nextjs-blog)+now lives in its own public repository and is distributed through its GitHub+releases. Its source and publishing workflow are no longer bundled in this+AI-agent plugin. The retired NotFair CMO application is also no longer included.+- [Privacy Policy](https://notfair.co/privacy)+- [Terms of Service](https://notfair.co/terms)+- [Product and integration support](https://notfair.co/contact)- [Support and community](https://discord.gg/gVJCRczpps)- [Issue tracker](https://github.com/nowork-studio/notfair-plugin/issues)@@ -269,28 +291,18 @@ notfair-plugin/├── seo/ # SEO, GEO, content, and technical-search skills├── gemini/ # cross-model review├── test/ # unit and LLM-judge evals-└── notfair/ # optional local goal-loop application+└── skills/ # shared entry points for every agent host```[`AGENTS.md`](AGENTS.md) is the universal entry point. It maps user intent to the canonical `SKILL.md` and documents the external dependency each workflow requires.-## Optional: run recurring marketing goals locally--This repository also includes a local application for turning a measurable marketing outcome into a recurring agent loop. It is a companion to the skill library, not a requirement for using the skills.--```bash-npx notfair@latest-```--The app runs on your machine with Codex or Claude Code, stores state locally, and can track a verified metric over time. See [`notfair/README.md`](notfair/README.md) for setup, architecture, and operating details.-## ContributingEach skill lives in its own category folder:```textseo/your-skill-name/-├── SKILL.md # required instructions and frontmatter+├── WORKFLOW.md # full instructions and frontmatter├── references/ # optional supporting knowledge└── scripts/ # optional deterministic tooling```@@ -298,11 +310,11 @@ seo/your-skill-name/When adding or changing a skill:1. Keep the workflow focused on one clear marketing job.-2. Use imperative, testable instructions in `SKILL.md`.+2. Use imperative, testable instructions in `WORKFLOW.md`, and keep the entry point under `skills/` in sync.3. Add or update eval coverage.4. Update [`AGENTS.md`](AGENTS.md), the plugin manifest, [`VERSION`](VERSION), and [`CHANGELOG.md`](CHANGELOG.md).-Open a pull request with one skill or one coherent improvement. For application contributions, see [`notfair/CONTRIBUTING.md`](notfair/CONTRIBUTING.md) and [`notfair/ARCHITECTURE.md`](notfair/ARCHITECTURE.md).+Open a pull request with one skill or one coherent improvement. See [plugin development](docs/plugin-development.md) for repository conventions.## Communitydiff --git a/VERSION b/VERSIONindex 828d05b1..f9da9ab2 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-0.27.15+0.27.16diff --git a/analytics/google-analytics/SKILL.md b/analytics/google-analytics/WORKFLOW.mdsimilarity index 100%rename from analytics/google-analytics/SKILL.mdrename to analytics/google-analytics/WORKFLOW.mddiff --git a/analytics/search-console/SKILL.md b/analytics/search-console/WORKFLOW.mdsimilarity index 100%rename from analytics/search-console/SKILL.mdrename to analytics/search-console/WORKFLOW.mddiff --git a/bin/preamble.md b/bin/preamble.mddeleted file mode 100755index 0545997a..00000000--- a/bin/preamble.md+++ /dev/null@@ -1,14 +0,0 @@-## Preamble (run first)--```bash-_UPD_BIN=$(ls ~/.claude/plugins/cache/nowork-studio/notfair/*/bin/notfair-update-check 2>/dev/null | head -1)-[ -n "$_UPD_BIN" ] && _UPD=$("$_UPD_BIN" 2>/dev/null || true) || _UPD=""-[ -n "$_UPD" ] && echo "$_UPD" || true-```--If the output contains `UPGRADE_AVAILABLE <old> <new>`: immediately follow the inline upgrade flow in the `/notfair:upgrade` skill (Step 1 onward) to auto-upgrade, then return here and continue.--If the output contains `JUST_UPGRADED <old> <new>`: mention "NotFair upgraded from v{old} to v{new}" briefly, then continue.------diff --git a/docs/claude-submission-readiness.md b/docs/claude-submission-readiness.mdnew file mode 100644index 00000000..7e3a167b--- /dev/null+++ b/docs/claude-submission-readiness.md@@ -0,0 +1,60 @@+# Claude submission preparation — 0.27.16++Checked on October 8, 2026 against the existing NotFair submission and Anthropic's+[pre-submission checklist](https://claude.com/docs/plugins/pre-submission-checklist).+The repository root remains the shared plugin source for Claude, OpenAI, and+Cursor. A separate generated plugin directory is unnecessary after retiring CMO.++## Findings and source changes++| Portal finding on 0.27.15 | Change in 0.27.16 |+| --- | --- |+| Files the validator could not inspect | Removed the 388-file CMO application and its publishing workflow and screenshot. The tracked plugin is below 512 files; text files stay below 256 KiB. |+| Ships executable files | Helpers are readable `.sh` and `.py` sources under `scripts/`, with non-executable file modes and explicit interpreter calls. No `bin/` or compiled application ships. |+| Broad shell access and unscoped writes | Removed `allowed-tools` grants from CMS setup and upgrade, in both workflow and entry point. |+| Duplicate skill names | Only `skills/<name>/SKILL.md` entries register. Category files are `WORKFLOW.md`; their content and relative reference locations remain the source of truth. All hosts discover the same 48 names. |+| No privacy-policy URL | Added the Claude-native `privacyPolicyUrl`, alongside documentation, support, and terms URLs. |+| No icon | Added the Claude-native `icon` referencing the existing 512-pixel PNG. |+| Root CLAUDE.md is not loaded | Moved contributor guidance to `docs/plugin-development.md`; the resolver links it for repository maintenance. Installed instructions stay in the skills. |+| Image paths treated as code | Removed CMO design documents and screenshot and removed the historical code-formatted logo path. The only bundled image is the listing icon, with its SVG source. |+| Credential reads from CMO | Removed CMO, its publisher, and its credential-handling source. Moved the separate blog library and its publisher to their dedicated public repository. Optional local credential workflows remain disclosed. |++The root Agent Plugins manifest is intentionally retained for OpenAI and other+portable hosts. Claude's note that it ignores this manifest is informational.++## Verified locally++- Claude strict plugin and marketplace manifest validation.+- All 48 entry points resolve to contained workflow files, with matching+ frontmatter, unique names, and unchanged platform placeholders.+- Installer, local script, host-manifest, package-limit, and icon checks.+- The shared OAuth MCP endpoint and its public discovery contract.++The portal's **This plugin collects or transmits user data** setting was changed+to **on** and read back, matching the declared hosted MCP connection and published+privacy policy. The existing review was preserved.++## Still requires destination verification++The portal is still reviewing the previously submitted version. Local validation+does not establish that Anthropic has scanned or approved 0.27.16. After the source+change reaches the tracked default branch, use **Check for new commits**, then+inspect that exact commit in Versions. Do not withdraw or recreate the submission+just to refresh it.++The blog library and its publishing workflow were moved to+[notfair-nextjs-blog](https://github.com/nowork-studio/notfair-nextjs-blog).+Neither is included in this plugin. Optional local CMS and Google Cloud+workflows, Gemini CLI authentication, and eval harness credentials may still+draw credential-use review findings. The README discloses these paths; none is+an automatic hook or a credential header on the declared OAuth MCP server.+Only a new portal report establishes which findings remain.++The existing Listing tab records the publisher's avatar as its icon. The portal+warns that adding an icon after first submission does not update that recorded+image automatically. Verify the live listing image after review and use the+portal's supported correction process if it still shows the avatar.++Keep legal acknowledgements and submission/publication decisions with the+authorized developer. Retain the existing plugin, repository, root path,+publisher, platform selections, and MCP endpoint.diff --git a/docs/goal-screen.png b/docs/goal-screen.pngdeleted file mode 100644index 84813ba9..00000000Binary files a/docs/goal-screen.png and /dev/null differdiff --git a/CLAUDE.md b/docs/plugin-development.mdsimilarity index 90%rename from CLAUDE.mdrename to docs/plugin-development.mdindex a6784595..94999e69 100644--- a/CLAUDE.md+++ b/docs/plugin-development.md@@ -20,7 +20,7 @@ NotFair is a host-agnostic plugin providing SEO, Google Ads, and Meta Ads skills- **`AGENTS.md`** — the universal skill resolver. Every host reads this to route user intents to the right skill. Update it whenever a skill is added, removed, or its purpose changes.- **`INSTALL_FOR_AGENTS.md`** — the single paste-URL target that walks an AI agent through host detection and install.-- **`skills/`** — Codex's portable wrapper index into the canonical skill directories. Each wrapper preserves the canonical frontmatter and forwards to the full workflow; keep both in parity with `.claude-plugin/plugin.json`.+- **`skills/`** — Codex's portable wrapper index into the canonical `WORKFLOW.md` files in category directories. Each wrapper preserves the canonical frontmatter and forwards to the full workflow; keep both in parity with `.claude-plugin/plugin.json`.- **`install/README.md`** — convention for adding per-host install adapters (Codex, Hermes, etc.) without duplicating skills.## Working style: brutal honesty, relentless quality@@ -52,10 +52,10 @@ The product is **NotFair**. All user-facing text, documentation, skill descripti## When adding or modifying a skill-1. Create/edit the skill directory under the appropriate category (`google-ads/`, `seo/`, etc.) with a `SKILL.md` containing valid frontmatter.+1. Create/edit the skill directory under the appropriate category (`google-ads/`, `seo/`, etc.) with a `WORKFLOW.md` containing the complete workflow and valid frontmatter.2. **Register it in `AGENTS.md`** under the matching intent table. A skill that isn't in `AGENTS.md` is invisible to Codex, Hermes, and any non-Claude host.-3. **Register it in `.claude-plugin/plugin.json`** under the `skills` array. A skill that exists on disk but isn't listed here will NOT appear in the installed Claude Code plugin — this has already bitten us once with `ads-landing`.-4. **Link it under `skills/`** using the skill's frontmatter name so Codex discovers the same canonical source without duplication.+3. **Register it in `.claude-plugin/plugin.json`** under the `skills` array, pointing at `./skills/<name>`. A skill that exists on disk but isn't registered will NOT appear in the installed Claude Code plugin — this has already bitten us once with `ads-landing`.+4. **Create its entry under `skills/`** using the workflow's frontmatter name. Copy only the frontmatter, then link to the full `WORKFLOW.md`; every host uses this same entry. Do not create symlinks.5. Bump the version in all manifests so upgrades propagate:- `.claude-plugin/plugin.json` → `version`- `.codex-plugin/plugin.json` → `version`diff --git a/gemini-extension.json b/gemini-extension.jsonindex 20d564ea..e35efc23 100644--- a/gemini-extension.json+++ b/gemini-extension.json@@ -1,6 +1,6 @@{"name": "notfair",- "version": "0.27.15",+ "version": "0.27.16","description": "Operate ads and analytics, and run open-source SEO, GEO, and content workflows with NotFair.","contextFileName": "AGENTS.md","mcpServers": {diff --git a/gemini/SKILL.md b/gemini/WORKFLOW.mdsimilarity index 100%rename from gemini/SKILL.mdrename to gemini/WORKFLOW.mddiff --git a/gohighlevel/SKILL.md b/gohighlevel/WORKFLOW.mdsimilarity index 100%rename from gohighlevel/SKILL.mdrename to gohighlevel/WORKFLOW.mddiff --git a/google-ads/assets/SKILL.md b/google-ads/assets/WORKFLOW.mdsimilarity index 100%rename from google-ads/assets/SKILL.mdrename to google-ads/assets/WORKFLOW.mddiff --git a/google-ads/audit/SKILL.md b/google-ads/audit/WORKFLOW.mdsimilarity index 100%rename from google-ads/audit/SKILL.mdrename to google-ads/audit/WORKFLOW.mddiff --git a/google-ads/copy/SKILL.md b/google-ads/copy/WORKFLOW.mdsimilarity index 100%rename from google-ads/copy/SKILL.mdrename to google-ads/copy/WORKFLOW.mddiff --git a/google-ads/landing/SKILL.md b/google-ads/landing/WORKFLOW.mdsimilarity index 100%rename from google-ads/landing/SKILL.mdrename to google-ads/landing/WORKFLOW.mddiff --git a/google-ads/manage/SKILL.md b/google-ads/manage/WORKFLOW.mdsimilarity index 100%rename from google-ads/manage/SKILL.mdrename to google-ads/manage/WORKFLOW.mddiff --git a/google-ads/manage/references/change-tracking.md b/google-ads/manage/references/change-tracking.mdindex 6bb57a51..b3d3add3 100644--- a/google-ads/manage/references/change-tracking.md+++ b/google-ads/manage/references/change-tracking.md@@ -42,12 +42,15 @@ Append to the `changes` array:Users shouldn't have to remember to come back. Two complementary mechanisms:-1. **SessionStart hook** — `bin/notfair-change-watch` scans every account's `change-log.json` and prints any entry whose `reviewAfter` has passed and `reviewed == false`. Wire it in `~/.claude/settings.json`:+1. **SessionStart hook** — `bash scripts/notfair-change-watch.sh` scans every account's `change-log.json` and prints any entry whose `reviewAfter` has passed and `reviewed == false`. If the user asks to enable the reminder, resolve the script+ from the installed plugin and substitute its actual absolute path in+ `~/.claude/settings.json`. A global user hook does not receive a plugin-root+ environment variable. For example:```json{"hooks": {"SessionStart": [- { "hooks": [ { "type": "command", "command": "/home/user/notfair/bin/notfair-change-watch" } ] }+ { "hooks": [ { "type": "command", "command": "bash \"/absolute/path/to/notfair-plugin/scripts/notfair-change-watch.sh\"" } ] }]}}@@ -56,6 +59,6 @@ Users shouldn't have to remember to come back. Two complementary mechanisms:2. **Calendar (.ics) reminder** — after logging a change, offer to generate a calendar invite the user can drop into any calendar app:```- notfair-change-watch ics <account_id> <change_id> > ~/review-<change_id>.ics+ bash "/absolute/path/to/notfair-plugin/scripts/notfair-change-watch.sh" ics <account_id> <change_id> > ~/review-<change_id>.ics```The .ics file includes a 9-hour-before alarm so the user gets notified on review day. Cross-platform, no cloud dependency, works offline.diff --git a/install/README.md b/install/README.mdindex 42c7b0b4..6ebc1be8 100644--- a/install/README.md+++ b/install/README.md@@ -1,6 +1,6 @@# Per-host install adapters-This directory is the home for **thin install adapters** that wire NotFair into a specific AI agent host. Each adapter registers the *same* host-agnostic skills (under `seo/`, `google-ads/`, `meta-ads/`, `gemini/` at the repo root) into the host's expected layout.+This directory is the home for **thin install adapters** that wire NotFair into a specific AI agent host. Each adapter registers the *same* `skills/` entry points, which load host-agnostic workflows (under `seo/`, `google-ads/`, `meta-ads/`, `gemini/` at the repo root) into the host's expected layout.## Why this existsdiff --git a/meta-ads/audit/SKILL.md b/meta-ads/audit/WORKFLOW.mdsimilarity index 100%rename from meta-ads/audit/SKILL.mdrename to meta-ads/audit/WORKFLOW.mddiff --git a/meta-ads/creative/SKILL.md b/meta-ads/creative/WORKFLOW.mdsimilarity index 100%rename from meta-ads/creative/SKILL.mdrename to meta-ads/creative/WORKFLOW.mddiff --git a/meta-ads/manage/SKILL.md b/meta-ads/manage/WORKFLOW.mdsimilarity index 100%rename from meta-ads/manage/SKILL.mdrename to meta-ads/manage/WORKFLOW.mddiff --git a/notfair-nextjs-blog/.gitignore b/notfair-nextjs-blog/.gitignoredeleted file mode 100644index e7289959..00000000--- a/notfair-nextjs-blog/.gitignore+++ /dev/null@@ -1,3 +0,0 @@-dist/-node_modules/-*.tgzdiff --git a/notfair-nextjs-blog/README.md b/notfair-nextjs-blog/README.mddeleted file mode 100644index 53ccda19..00000000--- a/notfair-nextjs-blog/README.md+++ /dev/null@@ -1,283 +0,0 @@-# notfair-nextjs-blog--Render your [NotFair SEO](https://notfair.co/seo) exchange posts on-a Next.js (App Router) blog. Pull model: your site fetches published posts-server-side from the NotFair content API with a private key — nothing is ever-pushed to your infrastructure.--## Setup--1. Install the package and the server-side HTML sanitizer:--```bash-npm install notfair-nextjs-blog sanitize-html-npm install --save-dev @types/sanitize-html-```--2. In the NotFair SEO dashboard, create a **Next.js / headless**- integration and copy the site API key (shown once).-3. Add it to your environment — server-side only, never `NEXT_PUBLIC_`:--```bash-NOTFAIR_SEO_API_KEY=nfbl_...-```--4. Allow NotFair-hosted article images through Next.js image optimization.- Preserve your existing `next.config.js` or `next.config.ts` and append the- following entry to `images.remotePatterns`:--```js-images: {- remotePatterns: [- // ...your existing image patterns,- {- protocol: "https",- hostname: "notfair.co",- pathname: "/api/seo/**",- },- ],-},-```--5. Publish NotFair posts under `/blog/{slug}`. The dashboard derives the- verification URL automatically. If `/blog` already exists, merge NotFair- into it as an additional source rather than replacing the route.--## Minimal app/blog--### Required safe article renderer--`content_html` is remote HTML. Do not render it directly or rely on browser-defaults for its typography: Tailwind's base reset removes heading hierarchy and-list markers unless the host site styles those elements explicitly. Keep the-presentation in the host app so it can match the existing blog design.--Create `src/lib/notfair-article.ts`:--```ts-import sanitizeHtml from "sanitize-html";--export function sanitizeNotFairArticleHtml(html: string) {- return sanitizeHtml(html, {- allowedTags: [- ...sanitizeHtml.defaults.allowedTags,- "figure", "figcaption", "h1", "h2", "h3", "h4", "img", "nav",- "table", "thead", "tbody", "tr", "th", "td",- ],- allowedAttributes: {- ...sanitizeHtml.defaults.allowedAttributes,- a: ["href", "title", "target", "rel"],- div: ["class"],- h1: ["id"], h2: ["id"], h3: ["id"], h4: ["id"],- img: ["src", "alt", "title", "width", "height", "loading"],- li: ["class"],- nav: ["aria-label", "class"],- p: ["class"],- },- allowedClasses: {- div: ["nf-tablewrap"],- li: ["nf-toc-l2", "nf-toc-l3"],- nav: ["nf-toc"],- p: ["nf-attribution", "nf-toc-title"],- },- allowedSchemes: ["http", "https", "mailto"],- allowedSchemesByTag: { img: ["https"] },- transformTags: {- a: sanitizeHtml.simpleTransform("a", { rel: "noopener noreferrer" }, true),- },- });-}-```--Create `app/blog/notfair-article.module.css`, then adapt the values to the-existing design system. Keep these selectors: they restore semantic hierarchy,-mobile table behavior, and NotFair's stable structural hooks.--```css-.articleContent { color: inherit; font-size: 1.0625rem; line-height: 1.75; }-.articleContent > * + * { margin-top: 1.25rem; }--.articleContent h1,-.articleContent h2,-.articleContent h3,-.articleContent h4 {- font-weight: 600;- letter-spacing: -0.01em;- scroll-margin-top: 6rem;-}--.articleContent h2 { margin-top: 3rem; font-size: 1.5rem; line-height: 1.25; }-.articleContent h3 { margin-top: 2.25rem; font-size: 1.25rem; line-height: 1.35; }-.articleContent ul,-.articleContent ol { padding-left: 1.5rem; }-.articleContent ul { list-style: disc; }-.articleContent ol { list-style: decimal; }-.articleContent li + li { margin-top: 0.5rem; }-.articleContent a { color: var(--notfair-article-link, currentColor); text-decoration: underline; text-underline-offset: 0.2em; }-.articleContent blockquote { border-left: 3px solid var(--notfair-article-accent, currentColor); padding-left: 1rem; }--.articleContent :global(.nf-toc) {- border: 1px solid var(--notfair-article-border, currentColor);- border-radius: 0.5rem;- padding: 1rem 1.25rem;-}-.articleContent :global(.nf-toc) ul { list-style: none; padding-left: 0; }-.articleContent :global(.nf-toc-l3) { padding-left: 1rem; }-.articleContent :global(.nf-toc-title) { font-weight: 600; }-.articleContent :global(.nf-tablewrap) { overflow-x: auto; }--.articleContent table { width: 100%; border-collapse: collapse; }-.articleContent th,-.articleContent td {- border: 1px solid var(--notfair-article-border, currentColor);- min-width: 11rem;- padding: 0.75rem 1rem;- text-align: left;- vertical-align: top;-}-.articleContent :global(.nf-attribution) { font-size: 0.875rem; opacity: 0.75; }-```--The `nf-*` classes are a small, stable semantic contract:--- `nf-toc`, `nf-toc-title`, `nf-toc-l2`, and `nf-toc-l3` describe the table of contents.-- `nf-tablewrap` enables horizontal scrolling for wide tables on mobile.-- `nf-attribution` identifies the disclosure line.--Do not let the content generator emit your app's Tailwind utility classes. Use-the scoped CSS module above, or adapt the same selectors to the site's existing-article renderer. Tailwind Typography is optional only when it is already part-of the host application's design system.--`app/blog/page.tsx`:--```tsx-import Image from "next/image";-import Link from "next/link";-import { getSeoPosts } from "notfair-nextjs-blog";--export default async function BlogIndex() {- const posts = await getSeoPosts();- return (- <main>- <h1>Blog</h1>- {posts.map((p) => (- <article key={p.slug}>- <Image src={p.image_url} alt={p.title} width={1600} height={900} />- <Link href={`/blog/${p.slug}`}>{p.title}</Link>- </article>- ))}- </main>- );-}-```--`app/blog/[slug]/page.tsx`:--```tsx-import { notFound } from "next/navigation";-import { getSeoPost } from "notfair-nextjs-blog";-import { NotFairPostHero } from "notfair-nextjs-blog/react";-import { sanitizeNotFairArticleHtml } from "@/lib/notfair-article";-import styles from "../notfair-article.module.css";--export default async function BlogPost({- params,-}: {- params: Promise<{ slug: string }>;-}) {- const { slug } = await params;- const post = await getSeoPost(slug);- if (!post) notFound();- return (- <article>- <NotFairPostHero post={post} />- <div- className={styles.articleContent}- dangerouslySetInnerHTML={{- __html: sanitizeNotFairArticleHtml(post.content_html),- }}- />- </article>- );-}-```--`NotFairPostHero` is an optional, image-first Server Component exported from-`notfair-nextjs-blog/react`. It renders the generated 16:9 cover before the-article `<h1>` and accepts `className`, `imageClassName`, and `titleClassName`-for the host design system. Existing data-client imports and page templates are-unchanged when upgrading; adopt the component when you want the canonical-header.--Responses revalidate hourly by default (`{ revalidate }` option to change).--## Existing `/blog`--Keep your current blog queries, components, metadata, and styling. Native posts-win slug collisions; NotFair fills only the remaining index entries and slugs.--For the index, fetch both sources in parallel and merge them without reshaping-your existing post type:--```tsx-import { getSeoPosts, mergeBlogPosts } from "notfair-nextjs-blog";--const [existingPosts, seoPosts] = await Promise.all([- getExistingPosts(),- getSeoPosts(),-]);-const posts = mergeBlogPosts(existingPosts, seoPosts);--// Branch on item.source and render each source with the site's existing cards.-// Every item still links to /blog/${item.post.slug}.-```--For `app/blog/[slug]/page.tsx`, resolve the existing source first and call-NotFair only as a fallback:--```tsx-import { notFound } from "next/navigation";-import { getBlogPostWithSeoFallback } from "notfair-nextjs-blog";-import { NotFairPostHero } from "notfair-nextjs-blog/react";--const result = await getBlogPostWithSeoFallback(slug, getExistingPost);-if (!result) notFound();--if (result.source === "existing") {- return <ExistingPost post={result.post} />;-}--return (- <article>- <NotFairPostHero post={result.post} />- <div- className={styles.articleContent}- dangerouslySetInnerHTML={{- __html: sanitizeNotFairArticleHtml(result.post.content_html),- }}- />- </article>-);-```--Apply the same native-first lookup in `generateMetadata`. Do not call-`notFound()` until both sources return no post.--## Verify before marking setup complete--Deploy a real NotFair post and check both desktop and mobile. Confirm the-featured image loads, headings are visually distinct, list markers are visible,-wide tables scroll horizontally, table-of-contents links jump to their-headings, and the attribution remains visible. Published pages must be publicly-reachable at the configured `/blog/{slug}` URL for link verification.--## API--- `getSeoPosts({ revalidate? })` → summaries including `image_url`, tags, and timestamps-- `getSeoPost(slug, { revalidate? })` → adds `content_html`, or `null`-- `mergeBlogPosts(existing, seo)` → discriminated list; existing slugs win-- `getBlogPostWithSeoFallback(slug, getExistingPost, { revalidate? })` →- `{ source, post }`, or `null`-- `NotFairPostHero` from `notfair-nextjs-blog/react` → optional image-first- article cover and title; existing renderers remain compatiblediff --git a/notfair-nextjs-blog/package.json b/notfair-nextjs-blog/package.jsondeleted file mode 100644index b003a4b0..00000000--- a/notfair-nextjs-blog/package.json+++ /dev/null@@ -1,52 +0,0 @@-{- "name": "notfair-nextjs-blog",- "version": "0.4.0",- "description": "Render your NotFair SEO exchange posts on a Next.js blog — server-side content pulls with your private site API key.",- "license": "MIT",- "type": "module",- "main": "dist/index.js",- "types": "dist/index.d.ts",- "exports": {- ".": {- "types": "./dist/index.d.ts",- "import": "./dist/index.js"- },- "./react": {- "types": "./dist/react.d.ts",- "import": "./dist/react.js"- }- },- "sideEffects": false,- "files": [- "dist",- "README.md"- ],- "scripts": {- "build": "tsc -p tsconfig.json",- "test": "npm run build && node --test test/*.test.mjs && next build test/next-app --webpack",- "prepublishOnly": "tsc -p tsconfig.json"- },- "keywords": [- "notfair",- "backlinks",- "nextjs",- "next",- "blog",- "seo"- ],- "homepage": "https://notfair.co/backlinks",- "repository": {- "type": "git",- "url": "git+https://github.com/nowork-studio/notfair-plugin.git",- "directory": "notfair-nextjs-blog"- },- "peerDependencies": {- "next": ">=14",- "react": ">=18"- },- "devDependencies": {- "typescript": "^5.6.0",- "@types/node": "^22.0.0",- "@types/react": "^19.0.0"- }-}diff --git a/notfair-nextjs-blog/src/index.ts b/notfair-nextjs-blog/src/index.tsdeleted file mode 100644index f432c79b..00000000--- a/notfair-nextjs-blog/src/index.ts+++ /dev/null@@ -1,112 +0,0 @@-/**- * notfair-nextjs-blog — server-side client for the NotFair SEO- * content API (the "Next.js / headless" integration).- *- * Usage: set NOTFAIR_SEO_API_KEY in your environment (server-only —- * never expose it to the client bundle), then call these from Server- * Components or route handlers. See README.md for a copy-paste app/blog.- */--const API_BASE = process.env.NOTFAIR_SEO_API_URL ?? "https://notfair.co/api/seo/content";--export type SeoPostSummary = {- id: number;- title: string;- slug: string;- meta_description: string | null;- tags: string[];- /** Generated 16:9 title-card image — article hero, thumbnail, and og:image. */- image_url: string;- reading_time_minutes: number | null;- published_at: string | null;- created_at: string;-};--export type SeoPost = SeoPostSummary & { content_html: string };--export type SeoFetchOptions = { revalidate?: number };--/** A collision-safe union for rendering an existing blog index alongside- * NotFair posts without forcing either source into the other's data shape. */-export type MergedBlogPost<T> =- | { source: "existing"; post: T }- | { source: "notfair"; post: SeoPostSummary };--/** Merge NotFair summaries into an existing blog. Existing posts keep their- * order and win duplicate slugs; NotFair-only posts follow in API order. */-export function mergeBlogPosts<T extends { slug: string }>(- existingPosts: readonly T[],- seoPosts: readonly SeoPostSummary[],-): MergedBlogPost<T>[] {- const existingSlugs = new Set(existingPosts.map((post) => post.slug));- return [- ...existingPosts.map((post) => ({ source: "existing" as const, post })),- ...seoPosts- .filter((post) => !existingSlugs.has(post.slug))- .map((post) => ({ source: "notfair" as const, post })),- ];-}--export type ResolvedBlogPost<T> =- | { source: "existing"; post: T }- | { source: "notfair"; post: SeoPost };--function apiKey(): string {- const key = process.env.NOTFAIR_SEO_API_KEY;- if (!key) {- throw new Error(- "notfair-nextjs-blog: NOTFAIR_SEO_API_KEY is not set. Create the key in your NotFair SEO dashboard (Integrations → Next.js).",- );- }- return key;-}--/** Next.js extends fetch's RequestInit with `next` — typed locally so the- * package builds standalone without Next's global type augmentation. */-type NextFetchInit = RequestInit & { next?: { revalidate: number } };--async function contentFetch(path: string, revalidate: number): Promise<Response> {- const init: NextFetchInit = {- headers: { authorization: `Bearer ${apiKey()}` },- // Cached server-side; posts publish on a schedule, hourly is plenty.- next: { revalidate },- };- return fetch(`${API_BASE}${path}`, init);-}--/** List published exchange posts (no bodies — cheap for blog indexes). */-export async function getSeoPosts(- opts: SeoFetchOptions = {},-): Promise<SeoPostSummary[]> {- const res = await contentFetch("", opts.revalidate ?? 3600);- if (!res.ok) return [];- const body = (await res.json().catch(() => null)) as { posts?: SeoPostSummary[] } | null;- return body?.posts ?? [];-}--/** Fetch one published post with its full HTML body. Returns null if the- * slug doesn't exist or isn't published. */-export async function getSeoPost(- slug: string,- opts: SeoFetchOptions = {},-): Promise<SeoPost | null> {- const res = await contentFetch(`?slug=${encodeURIComponent(slug)}`, opts.revalidate ?? 3600);- if (!res.ok) return null;- const body = (await res.json().catch(() => null)) as { post?: SeoPost } | null;- return body?.post ?? null;-}--/** Resolve a dynamic /blog/[slug] route without shadowing the site's native- * posts. The existing loader always runs first; NotFair is queried only when- * it returns null or undefined. */-export async function getBlogPostWithSeoFallback<T>(- slug: string,- getExistingPost: (slug: string) => T | null | undefined | Promise<T | null | undefined>,- opts: SeoFetchOptions = {},-): Promise<ResolvedBlogPost<T> | null> {- const existing = await getExistingPost(slug);- if (existing != null) return { source: "existing", post: existing };-- const post = await getSeoPost(slug, opts);- return post ? { source: "notfair", post } : null;-}diff --git a/notfair-nextjs-blog/src/react.tsx b/notfair-nextjs-blog/src/react.tsxdeleted file mode 100644index d84abe28..00000000--- a/notfair-nextjs-blog/src/react.tsx+++ /dev/null@@ -1,50 +0,0 @@-import Image from "next/image.js";-import type { CSSProperties } from "react";-import type { SeoPostSummary } from "./index.js";--export type NotFairPostHeroProps = {- /** A full post or summary returned by notfair-nextjs-blog. */- post: Pick<SeoPostSummary, "image_url" | "title">;- className?: string;- imageClassName?: string;- titleClassName?: string;- /** Above-the-fold article heroes should keep the default eager priority. */- priority?: boolean;- /** Responsive image hint passed to next/image. */- sizes?: string;- imageStyle?: CSSProperties;-};--/**- * Canonical NotFair article header. It deliberately owns only the cover and- * title so host apps retain control of their typography and sanitized article- * body. The cover is always the first visible element.- *- * Import from `notfair-nextjs-blog/react`; the root data-client export remains- * UI-free and fully backward compatible.- */-export function NotFairPostHero({- post,- className,- imageClassName,- titleClassName,- priority = true,- sizes = "(max-width: 768px) 100vw, 1200px",- imageStyle,-}: NotFairPostHeroProps) {- return (- <header className={className}>- <Image- src={post.image_url}- alt={post.title}- width={1600}- height={900}- sizes={sizes}- priority={priority}- className={imageClassName}- style={{ width: "100%", height: "auto", ...imageStyle }}- />- <h1 className={titleClassName}>{post.title}</h1>- </header>- );-}diff --git a/notfair-nextjs-blog/test/compatibility.test.mjs b/notfair-nextjs-blog/test/compatibility.test.mjsdeleted file mode 100644index 14f0603e..00000000--- a/notfair-nextjs-blog/test/compatibility.test.mjs+++ /dev/null@@ -1,19 +0,0 @@-import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";-import { fileURLToPath } from "node:url";-import test from "node:test";--const packageJson = JSON.parse(- await readFile(fileURLToPath(new URL("../package.json", import.meta.url)), "utf8"),-);-const rootClient = await readFile(- fileURLToPath(new URL("../dist/index.js", import.meta.url)),- "utf8",-);--test("the existing root data client remains UI-free", () => {- assert.deepEqual(Object.keys(packageJson.exports), [".", "./react"]);- assert.equal(packageJson.exports["."].import, "./dist/index.js");- assert.equal(packageJson.exports["./react"].import, "./dist/react.js");- assert.doesNotMatch(rootClient, /next\/image|react\/jsx-runtime|NotFairPostHero/);-});diff --git a/notfair-nextjs-blog/test/merge.test.mjs b/notfair-nextjs-blog/test/merge.test.mjsdeleted file mode 100644index 44735a7f..00000000--- a/notfair-nextjs-blog/test/merge.test.mjs+++ /dev/null@@ -1,64 +0,0 @@-import assert from "node:assert/strict";-import test from "node:test";-import {- getBlogPostWithSeoFallback,- mergeBlogPosts,-} from "../dist/index.js";--const seoPost = {- id: 1,- title: "NotFair post",- slug: "shared-slug",- meta_description: null,- tags: [],- image_url: "https://example.com/image.png",- reading_time_minutes: 2,- published_at: null,- created_at: "2026-08-09T00:00:00.000Z",-};--test("mergeBlogPosts preserves native posts on slug collisions", () => {- const existing = [{ slug: "shared-slug", title: "Native post" }];- const seoOnly = { ...seoPost, id: 2, slug: "seo-only" };-- assert.deepEqual(mergeBlogPosts(existing, [seoPost, seoOnly]), [- { source: "existing", post: existing[0] },- { source: "notfair", post: seoOnly },- ]);-});--test("getBlogPostWithSeoFallback does not fetch NotFair when a native post exists", async () => {- const originalFetch = globalThis.fetch;- globalThis.fetch = async () => {- throw new Error("NotFair should not be fetched");- };-- try {- const native = { slug: "native", title: "Native post" };- const result = await getBlogPostWithSeoFallback("native", async () => native);- assert.deepEqual(result, { source: "existing", post: native });- } finally {- globalThis.fetch = originalFetch;- }-});--test("getBlogPostWithSeoFallback returns a NotFair post after a native miss", async () => {- const originalFetch = globalThis.fetch;- const originalKey = process.env.NOTFAIR_SEO_API_KEY;- process.env.NOTFAIR_SEO_API_KEY = "nfbl_test";- globalThis.fetch = async () =>- new Response(JSON.stringify({ post: { ...seoPost, content_html: "<p>Body</p>" } }), {- status: 200,- headers: { "content-type": "application/json" },- });-- try {- const result = await getBlogPostWithSeoFallback("shared-slug", async () => null);- assert.equal(result?.source, "notfair");- assert.equal(result?.post.slug, "shared-slug");- } finally {- globalThis.fetch = originalFetch;- if (originalKey === undefined) delete process.env.NOTFAIR_SEO_API_KEY;- else process.env.NOTFAIR_SEO_API_KEY = originalKey;- }-});diff --git a/notfair-nextjs-blog/test/next-app/.gitignore b/notfair-nextjs-blog/test/next-app/.gitignoredeleted file mode 100644index 6f92be1a..00000000--- a/notfair-nextjs-blog/test/next-app/.gitignore+++ /dev/null@@ -1,3 +0,0 @@-.next/-next-env.d.ts-tsconfig.jsondiff --git a/notfair-nextjs-blog/test/next-app/app/layout.tsx b/notfair-nextjs-blog/test/next-app/app/layout.tsxdeleted file mode 100644index e53180ee..00000000--- a/notfair-nextjs-blog/test/next-app/app/layout.tsx+++ /dev/null@@ -1,9 +0,0 @@-import type { ReactNode } from "react";--export default function RootLayout({ children }: { children: ReactNode }) {- return (- <html lang="en">- <body>{children}</body>- </html>- );-}diff --git a/notfair-nextjs-blog/test/next-app/app/page.tsx b/notfair-nextjs-blog/test/next-app/app/page.tsxdeleted file mode 100644index c40b03d7..00000000--- a/notfair-nextjs-blog/test/next-app/app/page.tsx+++ /dev/null@@ -1,14 +0,0 @@-import { NotFairPostHero } from "notfair-nextjs-blog/react";--export default function Page() {- return (- <main>- <NotFairPostHero- post={{- title: "A practical resource guide",- image_url: "https://notfair.co/api/seo/og?postId=32",- }}- />- </main>- );-}diff --git a/notfair-nextjs-blog/test/next-app/next.config.mjs b/notfair-nextjs-blog/test/next-app/next.config.mjsdeleted file mode 100644index 79e1c57f..00000000--- a/notfair-nextjs-blog/test/next-app/next.config.mjs+++ /dev/null@@ -1,14 +0,0 @@-/** @type {import("next").NextConfig} */-const nextConfig = {- images: {- remotePatterns: [- {- protocol: "https",- hostname: "notfair.co",- pathname: "/api/seo/**",- },- ],- },-};--export default nextConfig;diff --git a/notfair-nextjs-blog/test/react.test.mjs b/notfair-nextjs-blog/test/react.test.mjsdeleted file mode 100644index 05ce3773..00000000--- a/notfair-nextjs-blog/test/react.test.mjs+++ /dev/null@@ -1,37 +0,0 @@-import assert from "node:assert/strict";-import test from "node:test";--import { NotFairPostHero } from "../dist/react.js";--const post = {- title: "A practical resource guide",- image_url: "https://notfair.co/api/seo/og?postId=32",-};--test("NotFairPostHero always renders the cover before the article title", () => {- const hero = NotFairPostHero({ post });- const [cover, title] = hero.props.children;-- assert.equal(title.type, "h1");- assert.equal(cover.props.src, post.image_url);- assert.equal(cover.props.alt, post.title);- assert.equal(cover.props.width, 1600);- assert.equal(cover.props.height, 900);- assert.equal(title.props.children, post.title);-});--test("NotFairPostHero keeps host styling hooks optional", () => {- const hero = NotFairPostHero({- post,- className: "article-header",- imageClassName: "article-cover",- titleClassName: "article-title",- priority: false,- });- const [cover, title] = hero.props.children;-- assert.equal(hero.props.className, "article-header");- assert.equal(cover.props.className, "article-cover");- assert.equal(title.props.className, "article-title");- assert.equal(cover.props.priority, false);-});diff --git a/notfair-nextjs-blog/test/readme.test.mjs b/notfair-nextjs-blog/test/readme.test.mjsdeleted file mode 100644index 2fb4216e..00000000--- a/notfair-nextjs-blog/test/readme.test.mjs+++ /dev/null@@ -1,26 +0,0 @@-import assert from "node:assert/strict";-import { readFile } from "node:fs/promises";-import { fileURLToPath } from "node:url";--import test from "node:test";--const readme = await readFile(- fileURLToPath(new URL("../README.md", import.meta.url)),- "utf8",-);--test("README requires sanitized, scoped NotFair article rendering", () => {- assert.match(readme, /sanitizeNotFairArticleHtml/);- assert.match(readme, /notfair-article\.module\.css/);- assert.match(readme, /:global\(\.nf-toc\)/);- assert.match(readme, /:global\(\.nf-tablewrap\)/);- assert.match(readme, /list-style: disc/);- assert.match(readme, /from "\.\.\/notfair-article\.module\.css"/);- assert.doesNotMatch(readme, /dangerouslySetInnerHTML=\{\{ __html: post\.content_html \}\}/);-});--test("README uses the canonical image-first article hero", () => {- assert.match(readme, /NotFairPostHero/);- assert.match(readme, /notfair-nextjs-blog\/react/);- assert.doesNotMatch(readme, /<h1>\{post\.title\}<\/h1>\s*<Image src=\{post\.image_url\}/);-});diff --git a/notfair-nextjs-blog/tsconfig.json b/notfair-nextjs-blog/tsconfig.jsondeleted file mode 100644index 8f1190b2..00000000--- a/notfair-nextjs-blog/tsconfig.json+++ /dev/null@@ -1,17 +0,0 @@-{- "compilerOptions": {- "target": "ES2022",- "module": "ESNext",- "moduleResolution": "bundler",- "jsx": "react-jsx",- "lib": ["ES2022", "DOM"],- "strict": true,- "declaration": true,- "outDir": "dist",- "rootDir": "src",- "skipLibCheck": true,- "esModuleInterop": true,- "forceConsistentCasingInFileNames": true- },- "include": ["src"]-}diff --git a/notfair-upgrade-skill/SKILL.md b/notfair-upgrade-skill/SKILL.mddeleted file mode 100644index 899499fd..00000000--- a/notfair-upgrade-skill/SKILL.md+++ /dev/null@@ -1,189 +0,0 @@-----name: upgrade-argument-hint: "<or just run '/notfair:upgrade'>"-description: >- Upgrade the NotFair plugin to the latest version. Updates the marketplace repo,- installs the new version to the plugin cache, and updates installed_plugins.json.- Use when asked to "upgrade notfair", "update notfair", or "get latest version".- Also handles inline upgrade prompts when a skill detects UPGRADE_AVAILABLE at startup.-allowed-tools:- - Bash- - Read- - AskUserQuestion------# /notfair:upgrade--Upgrade the NotFair plugin to the latest version and show what's new.--## Key paths--| What | Path |-|------|------|-| Marketplace repo | `~/.claude/plugins/marketplaces/nowork-studio/` |-| Plugin cache | `~/.claude/plugins/cache/nowork-studio/notfair/<version>/` |-| Installed plugins | `~/.claude/plugins/installed_plugins.json` |-| Update state | `~/.toprank/` (intentionally preserved — see CHANGELOG 0.24.0) |-------## Inline upgrade flow--This section is used when a skill preamble outputs `UPGRADE_AVAILABLE`.--### Step 1: Auto-upgrade--Log "Upgrading NotFair v{old} → v{new}..." and proceed to Step 2.-------### Step 2: Detect current install--First check for dev symlink (see "Dev symlink detection" section). If detected, stop — do not upgrade.--```bash-# Find the currently installed plugin path-INSTALLED_DIR=$(ls -d ~/.claude/plugins/cache/nowork-studio/notfair/*/ 2>/dev/null | grep -v '.bak' | head -1)-if [ -z "$INSTALLED_DIR" ]; then- echo "ERROR: NotFair plugin not found in cache"; exit 1-fi-MARKETPLACE_DIR="$HOME/.claude/plugins/marketplaces/nowork-studio"-if [ ! -d "$MARKETPLACE_DIR/.git" ]; then- echo "ERROR: marketplace repo not found at $MARKETPLACE_DIR"; exit 1-fi-echo "Current install: $INSTALLED_DIR"-echo "Marketplace repo: $MARKETPLACE_DIR"-```--### Step 3: Save old version--```bash-OLD_VERSION=$(cat "$INSTALLED_DIR/VERSION" 2>/dev/null | tr -d '[:space:]' || echo "unknown")-```--### Step 4: Update marketplace repo and install--```bash-cd "$MARKETPLACE_DIR"-git fetch origin-git reset --hard origin/main-NEW_VERSION=$(cat VERSION | tr -d '[:space:]')-GIT_SHA=$(git rev-parse HEAD)--# Create new versioned cache directory-NEW_CACHE_DIR="$HOME/.claude/plugins/cache/nowork-studio/notfair/$NEW_VERSION"-if [ -d "$NEW_CACHE_DIR" ]; then- rm -rf "$NEW_CACHE_DIR"-fi-mkdir -p "$NEW_CACHE_DIR"--# Copy plugin files (exclude .git to save space)-rsync -a --exclude='.git' "$MARKETPLACE_DIR/" "$NEW_CACHE_DIR/"-```--If the copy fails, warn: "Upgrade failed — the old version is still active. Run `/notfair:upgrade` manually." and stop.--### Step 5: Update installed_plugins.json--Read `~/.claude/plugins/installed_plugins.json`, then update the `notfair@nowork-studio` entry:--```bash-python3 -c "-import json, os-from datetime import datetime, timezone--path = os.path.expanduser('~/.claude/plugins/installed_plugins.json')-with open(path) as f:- data = json.load(f)--data['plugins']['notfair@nowork-studio'] = [{- 'scope': 'user',- 'installPath': os.path.expanduser('~/.claude/plugins/cache/nowork-studio/notfair/$NEW_VERSION'),- 'version': '$NEW_VERSION',- 'installedAt': data['plugins'].get('notfair@nowork-studio', [{}])[0].get('installedAt', datetime.now(timezone.utc).isoformat()),- 'lastUpdated': datetime.now(timezone.utc).isoformat(),- 'gitCommitSha': '$GIT_SHA'-}]--with open(path, 'w') as f:- json.dump(data, f, indent=4)-print('Updated installed_plugins.json: notfair@nowork-studio -> v$NEW_VERSION')-"-```--### Step 6: Clean up old cache versions--Remove old versioned cache directories (keep only the new one). Never remove a `dev` symlink:--```bash-for dir in ~/.claude/plugins/cache/nowork-studio/notfair/*/; do- ver=$(basename "$dir")- if [ "$ver" != "$NEW_VERSION" ] && [ "$ver" != "dev" ]; then- rm -rf "$dir"- echo "Removed old cache: $ver"- fi-done-```--### Step 7: Write marker + clear update state--```bash-mkdir -p ~/.toprank-echo "$OLD_VERSION" > ~/.toprank/just-upgraded-from-rm -f ~/.toprank/last-update-check-rm -f ~/.toprank/update-snoozed-```--### Step 8: Show What's New--Read `$NEW_CACHE_DIR/CHANGELOG.md`. Find all version entries between the old version and the new version. Summarize as 3-7 bullets grouped by theme — focus on user-facing changes, skip internal refactors.--Format:-```-NotFair v{new} — upgraded from v{old}!--What's new:-- [bullet 1]-- [bullet 2]-- ...--The new version will be fully active on your next Claude Code session.-```--### Step 9: Continue--After showing What's New, continue with whatever skill the user originally invoked.-------## Dev symlink detection--Before upgrading, check if the installed cache directory is a symlink named `dev`:--```bash-CACHE_DIR=$(ls -d ~/.claude/plugins/cache/nowork-studio/notfair/*/ 2>/dev/null | head -1)-if [ -L "${CACHE_DIR%/}" ] && [ "$(basename "$CACHE_DIR")" = "dev" ]; then- echo "DEV_SYMLINK"-fi-```--If `DEV_SYMLINK`: tell the user "NotFair is installed as a dev symlink — it always points to your local source (v$(cat "$CACHE_DIR/VERSION" 2>/dev/null | tr -d '[:space:]')). No upgrade needed." and **stop**. Do not proceed with Steps 2–8.-------## Standalone usage--When invoked directly as `/notfair:upgrade`:--1. Check for dev symlink (see "Dev symlink detection" above). If detected, stop.--2. Force a fresh update check (bypass cache and snooze):-```bash-_UPD_BIN=$(ls ~/.claude/plugins/cache/nowork-studio/notfair/*/bin/notfair-update-check 2>/dev/null | head -1)-[ -n "$_UPD_BIN" ] && _UPD=$("$_UPD_BIN" --force 2>/dev/null || true) || _UPD=""-echo "$_UPD"-```--3. If `UPGRADE_AVAILABLE <old> <new>`: follow Steps 2–8 above.--4. If no `UPGRADE_AVAILABLE` output: tell the user "You're already on the latest version (v{LOCAL})."diff --git a/notfair-upgrade-skill/WORKFLOW.md b/notfair-upgrade-skill/WORKFLOW.mdnew file mode 100644index 00000000..1fc5b5d7--- /dev/null+++ b/notfair-upgrade-skill/WORKFLOW.md@@ -0,0 +1,58 @@+---+name: upgrade+argument-hint: "<or just run '/notfair:upgrade'>"+description: >+ Upgrade the NotFair plugin to the latest version. Updates the marketplace repo,+ installs the new version to the plugin cache, and updates installed_plugins.json.+ Use when asked to "upgrade notfair", "update notfair", or "get latest version".+ Also handles inline upgrade prompts when a skill detects UPGRADE_AVAILABLE at startup.+---++# /notfair:upgrade++Update NotFair through the current host's plugin manager, then show what changed.+Retain the installed plugin identity, scope, OAuth connection, and user settings.+Follow the host's permission prompts; this skill does not pre-approve shell access.++## Detect the installation++Identify the host and the actual installed NotFair entry before running an update.+Read its version and installation source if the host exposes them. A workspace+checkout or development symlink is source-controlled: do not replace it with a+marketplace copy, reset its branch, or delete local changes.++## Update with the host++- **Claude Code marketplace install (`notfair@nowork-studio`)**: run+ `claude plugin update notfair@nowork-studio`. If the host requires a marketplace+ refresh, follow its returned instructions and retry the update.+- **Claude directory install (`notfair@synced`, Claude web, desktop, or Cowork)**:+ use the installed plugin's update controls. Directory versions are reviewed and+ can lag the source repository; don't overwrite them with unreviewed files.+- **Codex**: use the documented native update flow:+ `codex plugin marketplace upgrade nowork-studio --json`, then+ `codex plugin add notfair@nowork-studio --json`.+- **Cursor, Gemini CLI, or another host**: use that host's current native update+ instructions. Inspect its help or official documentation if the command is+ unknown; do not guess cache paths or edit host registry files.+- **Workspace checkout**: inspect Git status and the configured remote first.+ Fetch the remote and report any pending update. Preserve local work; if the+ checkout is clean and a fast-forward is available, use `git pull --ff-only`.+ If it diverges, explain the conflict and ask for the desired resolution.++If the update fails, report the host's error and keep the working installation.+Do not edit `installed_plugins.json`, reset a marketplace checkout, or delete old+cache versions manually. The host owns installation and cache management.++## Verify and report++Read the installed version again through the host. An update command succeeding+is insufficient if the installed version cannot be confirmed. If the host says+no newer version is available, state that without claiming it matches the latest+GitHub commit. A development checkout is not proof of a published release.++Read the installed `CHANGELOG.md` and summarize the user-facing changes since the+old version. Start a fresh host session or reload plugins as the host directs.+Retain one NotFair MCP connection and reauthorize only if the host requests it;+follow `../docs/mcp-connection.md`. Continue the user's original workflow after+the updated installation is confirmed.diff --git a/notfair/.claude/scheduled_tasks.lock b/notfair/.claude/scheduled_tasks.lockdeleted file mode 100644index a4869c86..00000000--- a/notfair/.claude/scheduled_tasks.lock+++ /dev/null@@ -1 +0,0 @@-{"sessionId":"e8325c83-a66d-464a-90bf-308fee3cc0bd","pid":24772,"procStart":"Sun May 17 21:33:18 2026","acquiredAt":1779257395997}\ No newline at end of filediff --git a/notfair/.github/workflows/ci.yml b/notfair/.github/workflows/ci.ymldeleted file mode 100644index c01006a0..00000000--- a/notfair/.github/workflows/ci.yml+++ /dev/null@@ -1,42 +0,0 @@-name: CI--on:- push:- branches: [main]- pull_request:- branches: [main]--permissions:- contents: read--jobs:- build:- name: typecheck + build (node ${{ matrix.node }})- runs-on: ubuntu-latest- strategy:- fail-fast: false- matrix:- node: ['20', '22', '24']- steps:- - uses: actions/checkout@v4-- - uses: pnpm/action-setup@v4- with:- version: 10-- - uses: actions/setup-node@v4- with:- node-version: ${{ matrix.node }}- cache: 'pnpm'-- - name: Install- run: pnpm install --frozen-lockfile-- - name: Approve native module builds- run: pnpm approve-builds --all || true-- - name: Typecheck- run: pnpm typecheck-- - name: Build- run: pnpm builddiff --git a/notfair/.github/workflows/release.yml b/notfair/.github/workflows/release.ymldeleted file mode 100644index b008e15e..00000000--- a/notfair/.github/workflows/release.yml+++ /dev/null@@ -1,42 +0,0 @@-name: Release--on:- push:- tags:- - 'v[0-9]+.[0-9]+.[0-9]+'- - 'v[0-9]+.[0-9]+.[0-9]+-*'--permissions:- contents: read- id-token: write # required for npm provenance--jobs:- publish:- name: Build + publish to npm- runs-on: ubuntu-latest- steps:- - uses: actions/checkout@v4-- - uses: pnpm/action-setup@v4- with:- version: 10-- - uses: actions/setup-node@v4- with:- node-version: '22'- registry-url: 'https://registry.npmjs.org'- cache: 'pnpm'-- - name: Install- run: pnpm install --frozen-lockfile-- - name: Typecheck- run: pnpm typecheck-- - name: Build- run: pnpm build-- - name: Publish to npm with provenance- run: pnpm publish --no-git-checks --provenance --access public- env:- NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}diff --git a/notfair/.gitignore b/notfair/.gitignoredeleted file mode 100644index 5870f452..00000000--- a/notfair/.gitignore+++ /dev/null@@ -1,25 +0,0 @@-node_modules/-.next/-.env-.env.local-.env*.local-.npmrc-*.log-.DS_Store-.turbo/-dist/-out/-tsconfig.tsbuildinfo-*.tsbuildinfo-coverage/--# OS / editor-.vscode/-.idea/-.zed/--# Local data dir if symlinked into repo for dev-.notfair-dev/--# npm pack artifacts (release.yml builds these in CI; not for git)-*.tgzdiff --git a/notfair/ARCHITECTURE.md b/notfair/ARCHITECTURE.mddeleted file mode 100644index 6e6f1cb1..00000000--- a/notfair/ARCHITECTURE.md+++ /dev/null@@ -1,119 +0,0 @@-# Architecture--> Single-user local app. No auth, no multi-tenancy, no hosted backend.-> One idea: **agent = goal**, and a disciplined loop moves the number.--## The model--```-project ──▶ agents (user mints as many as they have goals)- │ 1:1- ▼- goal ──▶ metric (executable MCP query, server-verified)- │- ▼ heartbeat (cron cadence)- tick: measure → review past moves → ≤1 new move → diary row-```--- **Goal lifecycle**: `intake → proposed → active ⇄ paused → achieved | failed | killed`.- Defined conversationally in the agent's chat via MCP tools:- `define_goal` (record the ambition) → `propose_goal_metric` (agent authors +- tests a query; the platform re-runs it server-side and stores the baseline)- → `activate_goal` (only after the user explicitly confirms the target).-- **Measurement discipline**: every mutation is logged *before* execution- (`log_goal_action`) with a falsifiable expected effect and an observation- window (`review_after`); its resources are untouchable until the window- closes, and expired actions must be scored (`review_goal_action`) before- any new move. The platform measures the metric mechanically each tick —- the agent never self-reports the number it is judged on.-- **Autonomy**: no approvals. Controls are the spend envelope on the goal,- the observation-window gate, and the user's pause/close buttons. Every- move is on the record (actions log + tick diary + full transcripts).-- **Context**: shared workspace context (`PROJECT.md`, synced into every- agent identity, writable via `set_shared_context`) + per-agent memory- (the `goal_learnings` ledger + the agent's own workspace files). All- connected MCPs are registered to every agent.--## Process layout--```-USER'S MACHINE-┌────────────────────────────────────────────────────────────────────┐-│ NotFair (Next.js, `npx notfair` → localhost:3327) │-│ │-│ UI: goals index (project root) · per-agent goal dashboard + chat │-│ + files/skills/cron/settings tabs · crons · connections │-│ │-│ Runtime services (SQLite + Node, no external daemon): │-│ · goals/actions/snapshots/learnings/ticks tables │-│ · 30s scheduler interval → due goal ticks + cron jobs │-│ · sessions + transcript_events (chat + tick transcripts) │-│ · MCP token vault (AES-256-GCM, OS-keychain master key) │-│ · MCP servers served as Next routes: │-│ /api/mcp/orchestration (goal tools, shared context, cron) │-│ /api/mcp/browser (shared workspace Chrome) │-│ │-│ Harness adapters spawn a turn as a subprocess: │-│ claude-code-local (claude CLI) · codex-local (codex CLI) │-│ per-agent workspace at ~/.notfair/agents/<id>/ with IDENTITY.md │-│ mirrored to the harness's native files │-└────────────────────────────────────────────────────────────────────┘-```--## A tick, end to end--1. `src/server/scheduler/tick.ts` (30s interval, started from- `src/instrumentation.ts`) calls `runDueGoalTicks()`.-2. `src/server/goals/tick.ts` claims the tick (advances `next_tick_at`- first — double-fire guard), executes the goal's stored metric query- against the catalog MCP via `src/server/mcp/rpc.ts` (token refresh +- SSE/JSON parsing handled there), and snapshots the value.-3. `buildTickMessage` composes the brief purely from DB state: fresh- metric, stop-condition flags, actions due for review vs. still gated,- recent learnings, last tick summary. The agent's context window is- disposable; the DB is the loop's memory.-4. One adapter turn runs on a `tick-<n>` session; every event persists to- `transcript_events`; the result lands as a `goal_ticks` diary row the- dashboard renders. Opening that row resumes the same chat session, so a- completed check remains available for follow-up turns in its original context.--Chat turns hit the same agent through `/api/chat` — same identity, same-rules; anything decided in chat that future ticks must know is written to-the learnings ledger by the agent.--## Distribution--- npm package (`notfair` bin); Next.js standalone build started by- `bin/cli.mjs`. Runtime requires Node 20+ and at least one harness CLI- (`claude` or `codex`) installed + authenticated.-- Data at `~/.notfair/` (override `NOTFAIR_DATA_DIR`): `db.sqlite`,- `agents/<id>/`, `projects/<slug>/PROJECT.md`, `mcp-server-secret`.--## Module map (orientation, not exhaustive)--```-src/server/goals/ the loop: identity.ts (prompt), tick.ts (runner),- metric.ts (server-side MCP measurement),- handlers.ts (MCP tool handlers), provision.ts-src/server/db/goals.ts goal state machine + actions/snapshots/learnings/ticks-src/server/mcp-server/ orchestration + browser MCP servers (Next routes)-src/server/adapters/ HarnessAdapter contract + claude/codex implementations-src/server/scheduler/ scheduled_jobs + the shared 30s interval-src/server/mcp/ catalog MCP tokens, OAuth refresh, JSON-RPC client-src/app/(app)/[project]/ goals index (root), agents/[agent]/ (dashboard,- chat, files, skills, cron, settings), crons,- connections, settings-```--## Why this shape--- **Loop state lives in SQLite, not context windows.** Contexts rotate;- `get_goal` re-anchors an agent from the DB in one call.-- **The metric is executable, not descriptive.** Storing the exact tool- call lets the platform measure before the agent wakes and verify- metrics at intake — trust comes from reproducibility.-- **No org chart.** There is exactly one kind of agent. Coordination- across agents happens through the shared workspace context, not- through delegation machinery.-- **Don't rebuild the wheels.** Harness CLIs bring the LLM runtime and- login; NotFair adds the loop, the bookkeeping, and the UI.diff --git a/notfair/CHANGELOG.md b/notfair/CHANGELOG.mddeleted file mode 100644index 51cbc855..00000000--- a/notfair/CHANGELOG.md+++ /dev/null@@ -1,433 +0,0 @@-# NotFair--## 0.9.19 — 2026-07-30--**Remote control brings the full NotFair workspace to your phone.** Activate it from the sidebar to create a temporary Cloudflare URL protected by a private fragment-to-cookie sign-in; unauthenticated public traffic stays blocked, and stopping the session invalidates the link. Mobile navigation now exposes the same control from the workspace drawer.--## 0.9.18 — 2026-07-22--**Streaming replies now stay visually quiet.** While the agent writes, chat shows only the animated **Writing the response** label—without a spinner, goal name, timer, tool subtitle, or activity history—so the status no longer competes with the response itself.--## 0.9.17 — 2026-07-22--**Completed goals now get the celebration they deserve.** Achievements stay visible in the sidebar with a sparkling **Completed** badge until you open the congratulations experience, where you can set a more ambitious next milestone or archive the goal without losing its chat, checks, metrics, or evidence.--**Background NotFair servers can reliably launch Codex.** Codex discovery no longer depends entirely on an interactive shell’s `PATH`; chat execution, health checks, login, and usage status now find standard installations and the executable bundled with the ChatGPT desktop app while still honoring `NOTFAIR_CODEX_BIN`.--## 0.9.16 — 2026-07-22--**NotFair now starts with the Node.js runtime that matches its installed native database module.** Global installs no longer land on a server-error page when the shell and npm installation use different Node.js versions.--**Interrupted checks recover safely after a restart.** Finished turns are reconciled from their stored transcript, genuinely interrupted work is marked failed instead of running forever, and checks owned by another live NotFair process are left untouched.--**Finished tool activity no longer keeps shimmering.** Missing tool-result events are closed at terminal turn boundaries and retain the correct success or failure state.--## 0.9.15 — 2026-07-21--**Background updates no longer modify a running installation.** NotFair now downloads the exact npm release into its local update cache without installing it; only clicking **Update to v…** performs the global install, immediately restarts a managed server, and reloads the app. This removes the live-file replacement window that could leave Chrome requesting chunks from two different builds.--## 0.9.14 — 2026-07-21--**Goal chat now reflects Codex’s real model defaults and reasoning controls.** The model menu no longer duplicates the configured default, and each provider-supported reasoning effort can be selected per goal and carried safely through the chat API to the Codex CLI.--**Every check exposes the prompt that started it.** The trigger appears as a normal user-style message, expands into fully rendered Markdown, and stays contained within the transcript so long activity labels cannot make the whole workspace scroll.--**Updates download before you ask to apply them.** When a release is available, NotFair downloads it automatically; the visible update button then restarts the managed server and applies the release immediately instead of presenting a second restart step.--## 0.9.13 — 2026-07-21--**Adding a server now opens the connector catalog immediately.** The Connections page and onboarding’s **More tools** tile skip the extra menu and go straight to **Browse connectors**, where **Add custom connector** is always the final option—even when every trusted connector is already connected.--**The goal sidebar is quieter and easier to control.** Goal rows no longer carry redundant status dots, group rows match the same visual style with an inline disclosure chevron instead of a count, nested action menus align with their parent, and hovering one goal reveals only that goal’s actions.--## 0.9.12 — 2026-07-21--**All goals now opens as a grouped metrics dashboard.** Every goal card leads with its live value, target or hold threshold, health, recent history, and check freshness; groups structure the page, pinned and live goals stay prominent, and every card opens the selected goal's full dashboard and chat. The layout works from mobile through wide desktop and refreshes active goal data automatically.--**Expanded tool activity is calmer and easier to scan.** Tool groups summarize work in plain language, keep their disclosure control stable through streaming updates, and expand into a compact, scrollable activity list without nested result boxes or layout jumps.--**Metric history renders at the requested size.** Goal sparklines now honor their height in both measured and empty states, keeping dashboard cards aligned while readings arrive.--## 0.9.11 — 2026-07-21--**Needs You requests now open the conversation that raised them.** Every escalation includes a **Details** link to its originating check, where completed checks remain fully conversational so you can ask follow-up questions or give the agent more work in the right context.--**The Checks rail now owns its schedule and trigger context.** The next-check countdown (or running state) lives in the section heading, while manual and heartbeat checks use compact, accessible icons with full labels on hover or keyboard focus.--**Long chats keep repeated messages and tool activity stable.** Transcript merging now deduplicates only by durable event IDs, and reused harness tool IDs receive occurrence-aware UI keys, preventing dropped repeated turns, key collisions, and tool-list flicker.--## 0.9.10 — 2026-07-21--**Fresh installs now start cleanly on every supported Node.js version.** The CLI refreshes Next.js's bundled `better-sqlite3` copies from npm's locally built dependency before each server start, so installing a release built with Node 24 no longer produces a database-module error when the user's active runtime is Node 20, 22, 25, or 26.--## 0.9.9 — 2026-07-21--**Sidebar upgrades no longer fail with `npm exited with code 7`.** NotFair now launches npm and its restart helper from the user's stable home directory, so rebuilding or replacing the standalone app cannot strand the updater inside a directory that no longer exists.--**Restarting after an upgrade uses the correct native database binary.** Before offering **Restart now**, the updater synchronizes Next.js's traced `better-sqlite3` copies with the dependency npm built for the user's active Node.js version. This prevents the upgraded app from landing on a server-error screen when the release builder and local Node versions use different native ABIs.--## 0.9.8 — 2026-07-21--**Completed checks stay fully conversational.** Opening a finished check from the goal rail now keeps its composer and model picker active, so you can ask follow-up questions or give the agent more work in that check's original context instead of being sent back to the main goal chat.--**The goal rail is easier to scan and control.** The goal statement and primary metric now have explicit **Goal** and **Main metric** headings, and every right-rail section can be collapsed independently without losing its internal state.--**Tool activity no longer flashes open and shut.** Live tool groups stay quietly collapsed by default, keep a stable identity while streaming results settle into the transcript, and preserve the user's manual expanded state through completion.--## 0.9.7 — 2026-07-21--**`notfair update` — one command from "there's a newer version" to running it.** Checks npm, installs globally, and restarts whatever is running: launchd-managed servers restart through the (freshly rewritten) LaunchAgent, background daemons are stopped and relaunched on the same port and data dir, and source checkouts are pointed at `git pull && pnpm build` instead of being paved over.--**In-app updates actually work now — and finish with one click.** The sidebar's update check had been dead since the rebrand: it asked the npm registry for `NotFair`, but the registry is case-sensitive and the package is `notfair`, so the "update available" button never appeared. Fixed — and upgraded: after installing an update, background and launchd-managed servers now show **Restart now**, restart themselves, and reload the page on the new version. No more "go restart it in your terminal" (that note remains only for foreground/dev runs, which the app never kills).--**Search Console setup now handles accounts with no reachable properties.** Empty `sites` and `siteEntry` responses are valid and render as an empty property list instead of being rejected as malformed. The test suite now covers 80%+ of executable statements and lines, with enforced coverage thresholds to prevent regression.--## 0.9.6 — 2026-07-21--**NotFair now runs in the background — and survives reboots.** `notfair` (or `notfair start`) detaches the server, waits for it to answer, and opens the UI; your terminal stays free and closing it no longer kills the loop. New lifecycle commands: `notfair status` (pid, port, uptime, health), `notfair stop` (finally implemented), and `notfair logs -f` (server log lives at `~/.notfair/logs/server.log`). `notfair autostart enable` installs a macOS LaunchAgent that starts NotFair at login and restarts it if it crashes — launchd becomes the single owner, so `start`/`stop` delegate to it instead of racing it for the port, the agent captures your shell's PATH so `claude`/`codex` stay reachable at login, and `start` self-heals the entry when an upgrade moves the package on disk. `--foreground` keeps the old attached behavior.--## 0.9.5 — 2026-07-21--**The "Needs you" panel is now the single source of truth for repeated asks.** Agents were told to repeat user-action asks in every check summary, but nothing told them when an ask was closed — so asks you'd already handled kept echoing from summary to summary forever. Every tick brief now mirrors the panel's live list of open escalations: the agent repeats exactly those, and only those. A handled-but-still-broken problem comes back as a fresh escalation with new evidence, so the panel and the diary can never drift apart again.--## 0.9.4 — 2026-07-20--**The working indicator's status text is visible again.** The shimmer gradient referenced a CSS token that doesn't exist, which invalidated the whole background — and with `background-clip: text` in play, the headline ("Calling the model", "Thinking", "Using N tools") rendered fully transparent, leaving a blank gap next to the spinner. The same undefined-token sweep restores the metric card's active-segment fill, the context dialog's content wells, chip hover colors, and the "Needs you" badge count.--**Linux gets a native folder picker.** The Browse button now works on Linux desktops via zenity (GTK) with a kdialog (KDE/Plasma) fallback, and reports a clear error when neither is installed. Contributed by @RohithVangalla1 (#77), ported to the renamed app tree.--## 0.9.3 — 2026-07-20--**Tagline refined.** "Goal-driven, loop-powered marketing agents that crush your business goals 24/7" — the identity and the hustle in one line, across npm, CLI `--help`, and the READMEs. First release published by the new auto-publish GitHub Action.--## 0.9.2 — 2026-07-20--**New one-liner everywhere it counts.** npm description, CLI `--help`, and both READMEs now lead with what NotFair actually is: marketing agents that chase your goals 24/7, on your own machine. No code changes.--## 0.9.1 — 2026-07-20--**Confirming the plan in chat starts the loop — the START button is gone.** Intake used to double-confirm: agree the plan in chat, then press START on the Goal tab. Now your confirmation in chat IS the consent moment — the moment the agent records the agreed target (`propose_target`), the goal goes active and the first check runs immediately.--**Check diary rows show what changed.** Each check on the Checks rail now carries write badges — MCP writes classified from the check's own tool calls ("Campaign budget updated"), plus agent-labeled action badges for logged mutations. The "Action taken" filter keys off real writes, so read-only checks stay out of the way.--**CLI: relative `--data-dir` no longer strands your database in the npm cache.** The path is resolved to absolute before it reaches the server; previously `--data-dir ./data` validated one directory and wrote `db.sqlite` into another (inside the npx cache, for `npx notfair` runs). The `pnpm cli` script now points at the real CLI entry, and the `--help` text no longer references a long-dead runtime.--**Codex account and model state now match the local CLI.** The sidebar reads authentication independently from usage availability, shows the correct ChatGPT Pro label, keeps authenticated users signed in when a rate-limit window is absent, and offers a working manual sign-in button when Codex is actually logged out. The chat model selector now names the configured Codex model instead of showing an opaque “Default” label.--**Completed checks stop looking active.** A harness final event now renders as a static “Turn complete” state with no spinner, heartbeat, shimmer, or increasing timer. Read-only check logs also explain that follow-up belongs in the goal chat instead of implying the agent is still working forever.--**Code changes go through pull requests — and the loop tracks them natively.** Goals whose levers live in your website's code (SEO above all) now have a sanctioned, governed channel: the agent may change code only inside the workspace's **Codebase folder** (new Settings card, validated + editable any time), only on a `notfair/…` branch, and only via a PR it registers with the new `register_pull_request` tool — never a direct push, never merging its own PR. You review and merge on GitHub, exactly like any teammate's PR. PR state syncs through your authenticated `gh` CLI via a centralized freshness sweep on the 30-second scheduler: every open PR carries its own adaptive `next_sync_at` (checks every 2 minutes right after activity, decaying to hourly for long-quiet PRs, resetting on any observed change; merged/closed PRs leave the schedule forever), with tick-time and goal-page-view syncs kept as correctness/UX guarantees and a single-flight guard so triggers coalesce. Each tick brief therefore carries the live truth: changes requested → the agent addresses your review comments that tick; awaiting review → your Goal tab and the goals index show a "PR needs your review" badge; merged → the observation window measures from there; closed unmerged → the agent scores the action as rejected and learns. Open PRs also pin the heartbeat to its normal cadence (no smart-sleep past a pending review). Without a codebase folder set, code stays off-limits and agents log recommendations instead.--**Goal creation gets a platform focus — dynamic per workspace.** The goal form (goals index and a new onboarding step 3, "First goal") shows one focus chip per connected platform — Google Ads, Meta Ads, SEO (Search Console), X Ads, Analytics — plus "Other". Picking a focus swaps in platform-appropriate placeholder text and tap-to-fill example statements, and the choice rides along to the agent's intake kickoff so it explores the right platform even when the statement is ambiguous. Connect Search Console and SEO goals are one tap away — without auto-flooding the index with machine-proposed goals (the audited X Ads suggestions remain the only auto-generated ones). Onboarding now ends by minting that first goal instead of dropping you on an empty index; skippable, and the workspace form is identical.--**Pick which account each connection targets — right where you connect.** Multi-account MCPs (Google Ads, Meta Ads, Search Console) now resolve their workspace account/property on the Connections page, not just in onboarding. Finishing OAuth auto-keeps a still-valid selection, silently persists the only reachable account, and otherwise opens a picker dialog listing what the new token can reach. Each card carries one action tracking its setup state — **Connect** → **Choose account/property** → a quiet **Switch account/property** — with the persisted selection shown on the card (`Search Console property: sc-domain:example.com`) and Disconnect / Remove tucked into the ⋯ menu, so switching accounts never requires reconnecting. Selections persist on the workspace row and feed every goal agent's identity, keeping each workspace's agents on exactly one account per platform. Onboarding's connect step now renders the same `McpCard` rows and picker dialog as the Connections page — its bespoke connector tiles and three full-page picker steps are gone, so the Connect → Choose → Switch lifecycle is identical on both surfaces, and the picker's rows use the design system's elevated surfaces instead of borders. The account-selection layer is covered by the repo's first vitest suite (`pnpm test`).--## 0.9.0 — 2026-07-10--**Renamed: notfair-cmo is now just NotFair — and the CMO is gone.** The product pivoted from "a CMO delegating to platform specialists" to **agent = goal**: you mint an agent per goal, define the goal by chatting with it, and it runs a disciplined improvement loop until the number says done. npm package `notfair-cmo` → `notfair` (bin: `notfair`), data dir `~/.notfair-cmo` → `~/.notfair` (auto-migrated on first start, merging safely with any plugin config already there), env vars `NOTFAIR_CMO_*` → `NOTFAIR_*`.--**Conversational goal intake with server-verified metrics.** A fresh agent's goal is empty; the chat defines it: the agent records the ambition (`define_goal`), explores your connected platforms, authors + tests ONE query that returns a single number, and submits it (`propose_goal_metric`) — the platform re-runs the exact call server-side and only a reproducible number, with its measured baseline, moves the goal forward. The loop starts only after you explicitly confirm the target in chat (`activate_goal` rejects targets on the wrong side of the baseline).--**Heartbeat ticks with measurement discipline.** On your cadence, the platform measures the metric mechanically — agents never self-report the number they're judged on — and wakes the agent with a tick brief: current reading, actions due for review vs. still gated, memory, stop-condition flags. Mutations must be logged before execution with a falsifiable expected effect and an observation window that gates their resources until review; expired actions must be scored against their predictions before any new move; "achieved" is rejected by the server unless the measured metric meets the target. One mutation per tick, hard stop.--**Everything legacy is deleted, not deprecated.** The CMO and platform-specialist agents, the task board/kanban, the approvals inbox + policies, the questions system, the activity log, and the delegation machinery are all gone — UI, MCP tools, server modules, and tests. Agents run autonomously inside a spend envelope; your controls are the envelope, the observation-window gate, and pause/close. The MCP surface is now 12 tools: the goal lifecycle + loop bookkeeping, `get_project`, `set_shared_context`, and `schedule_recurring_work`.--**Shared context + private memory.** `PROJECT.md` is the workspace brief every agent carries in its identity (any agent updates it via `set_shared_context`, which re-renders all agent identities); each agent keeps its own learnings ledger (`log_learning` / `search_learnings`) and workspace files. All connected MCPs register to every agent automatically.--**New surfaces.** The project root is the goals index (one row per agent: status, statement, live metric); each agent's page is its goal dashboard — sparkline vs. target, tick diary linking to full transcripts, open actions with review dates, memory — with Chat/Files/Skills/Cron/Settings tabs. Onboarding is two steps (name workspace → connect sources) and drops you at the goals index. Sidebar: Goals + Crons/Connections/Settings.--**Goals are the only identity.** No agent personas: the sidebar and every page label goals by an agent-written `short_label` ("Wasted X spend → $0"); the machinery behind a goal is "this goal's agent", full stop. Routes live under `/goals/…`, creation is statement-first (type the ambition, land inside the already-streaming kickoff thread), and platform-generated briefs render as compact system lines, not fake user bubbles.--**Consent + control are platform-enforced.** The agent can propose everything but start nothing: `propose_target` records the plan, the user's START click begins the loop and fires the first tick immediately. Live goals are amendable in chat (`amend_goal`); per-action spend is logged and totaled against the envelope in every tick brief; other agents' observation-gated resources appear in each brief; idle-gated loops sleep until the earliest review date. Two goal modes: **achieve** (complete at target) and **maintain** (hold the number forever — target met is the steady state, and the loop never self-closes).--**Progress you can see.** Each goal's rail carries a time-true progress chart: the metric line with target/baseline references, every agent mutation as a hoverable marker (predicted vs. observed effect), observation windows shaded, deadline flagged, crosshair tooltips. New `backfill_metric_history` tool lets the agent reconstruct ~30 days of per-day history at setup (platform-verified like the metric), so the chart has context from day one. Maintain goals lead with a streak — "held at target for N days" — plus a per-check strip (held / intervened / drifted); the workspace index gains mini sparklines and 7-day deltas per goal. (Migration 022.)--**One screen per goal, one scheduler.** The goal page unifies chat + status rail (metric, sparkline, checks with full logs, open actions, memory) — the Goal/Chat/Files/Settings tabs, chat-thread management, and the entire Crons surface (page, tool, engine) are gone. The heartbeat is the only recurring thing in the product, and the nav is: your goals, Connections, Settings.--Schema: migrations 017–021 (goal tables; one live goal per agent; per-action spend; short labels; goal mode). Eval suite `goal-tick.eval.ts` locks the loop's three invariants (stop at target, review first, respect the gate).--## 0.8.0 — 2026-07-07--**Slack-style "needs you" badges.** When an agent asks a question or requests an approval, a red badge with the count appears next to that agent in the sidebar — visible from every page — and on the blocked task's row in the task rail. Clicking the agent deep-links straight into the decision space (the blocked task with the question/approval card ready to answer) instead of Chat. Badges ride the existing 2–8 s liveness poll and clear the moment you answer. The green in-flight indicator on agent rows was removed — the red badge is the only signal, by design.--**Task rail simplified.** One flat list (no more Working/Blocked/Done section headers), no "All quiet." status line, no per-row age counters. Each row is now two lines — task id on top, title below clamped to two lines with an ellipsis — with uniform row heights, sidebar-matching spacing (`gap-1`), and the same rounded selection treatment the agent sidebar uses.--**Onboarding connect step reworked.** The "Required for <X> agent" pills are gone; each tile's description now reads "Gives the <X> agent the ability to …" so the MCP→agent dependency is plain language. Google Analytics moved out of the recommended tiles into the "More tools" browse dialog (it powers no specialist agent); a connected GA shows up as an extras row.--**Agents can no longer "restart" terminal tasks into the void.** `submit_task_status` on a cancelled/done/failed task used to be a silent success no-op — an agent asked to "restart the task" would rerun the work, get success back, and narrate progress the DB never recorded. It now returns an instructive error naming the terminal status and pointing the agent at `create_task` for redos.--**Fixes.** Files tab's file list now uses the theme sidebar token instead of a hardcoded near-white, so dark mode renders correctly. Removed the stray divider under the chat thread-selector header row.--## 0.7.1 — 2026-06-06--**Sidebar shows the installed version + a one-click Upgrade button.** The sidebar footer now always displays `NotFair v<x.y.z>`. When the npm registry has a newer release, an `v<x.y.z> available` button appears next to it — click runs `npm i -g notfair@latest` via a new `/api/upgrade` endpoint and surfaces "Restart to apply" on success. Latest-version lookup is cached 1 hour in-process so the sidebar polling doesn't pound `registry.npmjs.org`.--When `npm` isn't discoverable on the user's PATH (rare but real on minimal shells), `/api/upgrade` returns the command string instead and the client copies `npm i -g notfair@latest` to the clipboard so the user can run it themselves.--## 0.7.0 — 2026-06-06--**Browser tools split into their own standalone MCP server.** The 11 `browser_*` tools moved out of `notfair-orchestration` into a new `notfair-browser` MCP at `/api/mcp/browser`. The orchestration surface drops from 32 tools to 21 (task / approval / project / cron only); each MCP server now has one clear job. Codex / Claude Code configs gain a second internal entry automatically on next project visit — no manual reconfig.--**Tool descriptions sharpened to fight plugin collisions.** Real failure observed where a Codex-hosted CMO asked to "launch your browser" found OpenAI's bundled `browser-use` plugin first, then fell back to `open -a "Google Chrome"` (wrong profile, no shared cookies). Following Hermes' convention, every browser tool description now does explicit tool routing: `browser_open` claims the "launch the browser / open a page / go to <URL>" intent up front and names the wrong choices to ignore (browser-use plugin, `open -a`, AppleScript, xdg-open, `start chrome`). The orchestration skill loaded into every agent's IDENTITY/AGENTS.md gains a `CRITICAL: which "browser" tool to use` section enumerating the same anti-fallbacks.--**Multi-agent safety: `browser_shutdown` removed from the agent surface.** With multiple agents sharing one workspace Chrome, any agent calling shutdown would kill the browser mid-task for the others. Browser lifecycle is now user-owned (Settings → Stop) and process-exit-owned only.--**5-minute idle auto-shutdown.** A 30s background tick stops any workspace browser with no activity in the last 5 minutes (override via `NOTFAIR_BROWSER_IDLE_TIMEOUT_MS`). Settings card surfaces the countdown as `auto-stops in 258s if idle` alongside uptime.--**Hidden Codex env-var bug fixed.** The Codex spawn loop only injected the orchestration bearer; for `notfair-browser` (and any future internal MCP), Codex saw the config entry but had no token, so tool discovery silently excluded the tools. Now both internal MCPs share the same machine secret via env injection.--E2E verified: fresh Codex chat turn — Greg (CMO) asked to open https://example.org chose `notfair_notfairco__notfair_browser.browser_open` directly, no shell fallback, no plugin attempts.--## 0.6.0 — 2026-06-05--**Workspace browser tool — agents can drive real Chrome.** One managed Chrome instance per workspace at `~/.notfair/projects/<slug>/browser/user-data/`, shared by every agent in that project via labeled tabs. The user signs into Google / Meta / Search Console once (Settings → Workspace browser → Launch + Open <service>), cookies persist in the workspace profile, and every agent inherits the session on subsequent runs.--The agent surface is 11 small typed MCP tools — `browser_status`, `browser_tabs`, `browser_open`, `browser_close`, `browser_navigate`, `browser_snapshot`, `browser_click`, `browser_type`, `browser_press`, `browser_scroll`, `browser_back` — matching the granularity of the rest of the `notfair-orchestration` MCP. `browser_shutdown` is intentionally NOT exposed to agents: with multiple agents sharing one workspace Chrome, any agent calling shutdown would kill the browser mid-task for the others. Browser lifecycle is user-owned (Settings → Stop) and process-exit-owned.--Agents are taught the snapshot-before-act discipline and the `label=<agent_id>` convention via the shared orchestration skill so multi-agent runs at 9am (CMO + Google Ads + Meta + SEO crons firing together) don't race — each agent only acts on its own tab.--**Idle auto-shutdown.** A 30s background tick stops any workspace browser with no agent activity in the last 5 minutes (override via `NOTFAIR_BROWSER_IDLE_TIMEOUT_MS`). Settings card surfaces the countdown as "auto-stops in 258s if idle" alongside uptime.--**Settings → Workspace browser card.** Live status (running / not running, port, uptime, idle countdown), Launch / Stop, sign-in shortcuts for Google / Meta / Search Console, and a list of open tabs. Verified end-to-end in dev: launching from Settings spawns Chrome with the workspace `--user-data-dir`, status flips to running, Stop tears it down cleanly.--Under the hood: Chrome lifecycle (binary discovery, `SingletonLock` cleanup, deterministic CDP port allocation in 19000-19099) borrowed from openclaw; Playwright (CDP-attach mode, via `playwright-core`) for the actual page driving. No bundled browser — uses system Chrome. SSRF/loopback hardening from openclaw was intentionally NOT ported: NotFair is single-user localhost-only, and the MCP server already requires bearer auth.--## 0.5.0 — 2026-06-03--**Multi-MCP onboarding + per-MCP specialist agents.** The connect step in onboarding is now a four-tile picker: Google Ads, Meta Ads, Google Search Console, and a "More" overflow modal. Each recommended tile is OAuth-wired to its own NotFair MCP and, on successful connect, triggers provisioning of the matching specialist agent — `meta_ads` (Mia) and `gsc` (Sasha) join the existing `cmo` (Greg) and `google_ads` (Ana) templates. CMO is the only template that ships unconditionally; specialists are gated on the user actually connecting their MCP.--After each OAuth callback the user lands back on the connect step so they can wire up the next tool. When a connected MCP exposes more than one account/property, the matching account picker (Meta `act_*` ad accounts, GSC `sc-domain:` / URL properties) auto-selects when only one is reachable and otherwise shows a Google-Ads-style picker. Selections persist as `projects.meta_ads_account_id` and `projects.gsc_property_id` (migration 015) so specialists always target the right entity.--Skip → "Done adding MCPs — next step" once at least one MCP is wired. The setup screen still waits for `ensureProjectAgents` (CMO + any specialists provisioned by the connect-time hooks) before routing the user into the CMO task workspace.--Agent pages now render a **"Connect <Platform> MCP"** blocker in place of the chat/tasks UI when a specialist's required MCP token is missing — both before initial connect and after a later disconnect. The predicate is colocated in `src/server/onboarding/agent-mcp-blocker.ts` for unit-test coverage; the card lives at `src/components/agent-mcp-blocker-card.tsx`.--The trusted-connectors registry promotes Meta Ads and Google Search Console to first-class `MCP_CATALOG_PRESETS` so they're always visible on the Connections page even when not yet connected. The "More" modal on the onboarding step hides the recommended trio (they have first-class tiles already) via a new `hideKeys` prop on `BrowseConnectorsDialog`. **Heads-up:** the GSC MCP listing tool is best-guessed as `listSites` (Search Console API's native term); if the deployed MCP uses a different method name, swap the `GSC_LIST_TOOL` constant in `src/server/onboarding/accounts.ts` — the failure surface is a clean "method not found" RPC error.--## 0.4.4 — 2026-06-03--**Cron jobs actually run now.** The Crons calendar was rendering future occurrences from the cron expression and creating `scheduled_jobs` rows, but the tick loop that actually dispatches due jobs was never starting. `ensureSchedulerRunning()` was defined in `src/server/scheduler/tick.ts` and imported from nowhere — no layout, no instrumentation, no CLI. Net effect: clicking a past occurrence on the calendar showed no status badge and the Result section had nothing to render, because `scheduled_job_runs` stayed empty forever.--New `src/instrumentation.ts` registers a `nodejs`-runtime hook that calls `ensureSchedulerRunning()` once per server boot. Verified live: a test cron inserted at 16:45 UTC fired ~25s later, Codex returned a short reply, the green-check badge appeared on the calendar chip, and the detail dialog rendered the captured summary with duration (7.6s).--**Run summaries are captured and shown.** `loadCronRuns()` used to hardcode `summary: ""` even though the Result section in the detail dialog rendered from that field — so every completed run, no matter what the adapter produced, displayed "Run finished with no summary." `dispatchJob` now accumulates the adapter's final-text event (or concatenated delta chunks, capped at 4000 chars) and `finishJobRun` persists it to a new `summary` column on `scheduled_job_runs` (migration 014). The calendar's detail dialog now shows what the agent actually said.--**Failed-run badge fix.** The calendar's status glyph maps "ok" → green check and "error" → red badge, but `loadCronRuns` was returning `"failed"` for failed runs — they rendered as a neutral gray dot. `normalizeRunStatus` now maps `done → ok` and `failed → error` at the read boundary so the destructive badge fires correctly. Same helper applies to `jobToDisplay`'s `last_status` so the per-cron summary row matches.--## 0.4.3 — 2026-06-02--**Humanized tool-call rendering in the chat transcript.** The chat used to show every shell call as the raw command — long `/bin/zsh -lc "rg --files ..."` lines splatted right under the assistant's reasoning, with both the tool group's `name` and `label` rendering the same incantation. Visually noisy and didn't tell the user anything they couldn't infer from the prose above it.--The transcript now leads with the *intent*. A new `humanizeTool` helper unwraps `bash -lc`-style shell wrappers, inspects the leading binary, and maps it to a verb phrase: `rg`/`grep` → "Searched files", `git status` → "Ran git status", `cat`/`head`/`tail` → "Read file", `pwd` → "Checked working directory", and so on. Built-in tools (Read/Write/Edit/fetch) and MCP tool names (`mcp__notfair-googleads__listAdAccounts` → "Called list ad accounts") get the same treatment. The raw command stays in the expandable body for power users; the small mono identifier (`shell`, `runScript`, etc.) lives on the row as a debug tag.--Codex `command_execution` items are also re-tagged from `name: "<first line of command>"` to `name: "shell"`, so icon lookup hits Terminal correctly and the working indicator stops reading "Calling /bin/zsh -lc …".--**MCP tool calls now stream into the transcript at all.** Codex 0.132+ surfaces MCP invocations as a distinct `mcp_tool_call` item type (separate from `command_execution` and `tool_call`), and our parser was only handling the older two. Net effect: every MCP call the CMO and Google Ads agents fired was silently dropped from the chat — the conversation jumped straight from "I'll query the account" to the prose summary with nothing visible in between. Parser now consumes `mcp_tool_call` (and `mcp_call` / `function_call` for completeness) and emits a `<server>.<tool>` name so the catalog matcher can resolve the brand.--**MCP brand favicons next to tool calls.** When a tool name resolves to a known MCP server in the project's catalog — matched via Claude Code's `mcp__<key>__<tool>` namespace, Codex's `notfair_<proj>__<server>__<tool>` namespace, or the `mcp_tool_call` `<namespaced-server>.<tool>` shape (the matcher peels the `notfair_<proj>__` prefix to find the bare server key) — the row renders the server's brand favicon (via `t3.gstatic.com/faviconV2`) instead of the generic Wrench icon. Falls back gracefully to Wrench when the favicon misses or the catalog has no match.--The chat page and the per-agent task workspace both forward the project's catalog to `LiveTranscript`; `agent-task-workspace` gained a `mcpCatalog` prop that passes straight through.--## 0.4.2 — 2026-06-01--**TTL cache on MCP probe results.** Every server render of `/connections` (and the chat thread page's notfair-googleads banner) used to fan out one `initialize` JSON-RPC call per connector to verify liveness. With six connectors that was six round-trips on every page load — fine for one user dogfooding, rude to upstreams as usage grows.--New `mcp/probe-cache.ts` wraps `getMcpStatus` with an in-process TTL cache keyed by `(project_slug, catalog_key)`. State-aware TTLs:-- `connected` → 60 s (access tokens live for hours; staleness within a minute is invisible)-- `unreachable` → 10 s (recover quickly when the provider comes back)-- `stale_token` / `not_configured` / `configured_no_token` → no cache (user-actionable states where instant feedback matters)--Invalidated explicitly in `setMcpBearer` (after fresh OAuth callback) and `disconnectMcp` so reconnects show updated state on the very next render rather than waiting out the TTL. Pinned to `globalThis` so Next.js HMR doesn't drop the cache on every code edit.--Tradeoff: the status badge can be up to 60 s out of date if you revoke an OAuth grant from the provider's dashboard. Acceptable for a local single-user tool.--## 0.4.1 — 2026-06-01--**Silent OAuth refresh for MCP connections.** The Connections page stopped flapping to "token expired" every hour for providers with short-lived access tokens (Stripe, Mixpanel, Supabase, PostHog). The MCP OAuth callback used to discard the `refresh_token`, `expires_in`, and `scope` fields from the token-endpoint response and store only the access token — so when the upstream rotated it (~1h for most providers), the only recovery path was a manual "Reconnect" click.--The callback now captures the full token envelope and persists the token endpoint + DCR-issued `client_id` / `client_secret` alongside it (new migration `013`). A new `mcpRpcAutoRefresh` wrapper proactively swaps an expiring access token (within 60s) and reactively retries once on HTTP 401, rotating the stored pair when the provider issues a new refresh token (RFC 6749 §6).--Existing token rows (created before this release) have no refresh token captured, so they continue to fall through to the existing reconnect-on-401 UX. After one fresh reconnect they pick up silent refresh.--**Probe + tool-list + onboarding's account picker** now route through `mcpRpcAutoRefresh`, so the status badge, the View tools dialog, and Google Ads account selection all stay green across the access-token TTL boundary instead of flashing stale_token between refreshes.--**Stripe (and any AS that gates refresh tokens on client capability) now issues one.** Dynamic client registration now advertises `grant_types: ["authorization_code", "refresh_token"]` per [SEP-2207](https://modelcontextprotocol.io/seps/2207-oidc-refresh-token-guidance). Without it, Stripe's MCP authorization server returned only an access token at consent time — forcing a manual reconnect every ~1h. After this change, reconnecting Stripe captures a refresh token alongside the access token, and silent rotation works the same as it does for Supabase and Mixpanel.--## 0.4.0 — 2026-05-31--Redesigned Connections page + curated "Browse connectors" UX. The catalog now ships with a small directory of trusted MCPs you opt into; clicking a tile adds it to the project and starts OAuth in one step. The page itself was rebuilt as an editorial list with a top-right "Add server" menu.--**Connections page redesign.** Cards became list rows inside a single bordered container; sharper typographic hierarchy (eyebrow + large H1 + mono section labels); status communicated via small colored dot + small-caps mono label instead of pill backgrounds; the "Add server" affordance moved to the header.--**Browse connectors.** New dropdown menu on the header splits "Browse connectors" (curated grid of NotFair Google Ads, NotFair Meta Ads, Stripe, PostHog, Supabase, Mixpanel) and "Add custom connector" (paste-a-URL form). Tile click chains `addUserMcpServerAction` → `startMcpConnect` → browser redirect — no second click. Tiles for connectors already connected in the project render non-clickable with a green "connected" lozenge.--**Preset connectors are now removable.** New migration `012` adds `projects.hidden_mcp_preset_keys_json`. Removing a preset (e.g. NotFair Google Ads) hides it from the project's catalog and clears its token + adapter wiring; re-adding from Browse unhides it.--**OAuth fidelity fixes that shook out during dogfooding:**-- RFC 8414 §3.1 inserted form for AS metadata. Stripe's issuer `https://access.stripe.com/mcp` only resolves via the inserted variant.-- `client_secret_post` fallback when an AS doesn't advertise `none` as a token-endpoint auth method (Supabase). DCR registers as a confidential client; the callback already forwards `client_secret` at token exchange.-- `MCP-Protocol-Version: 2025-06-18` on every JSON-RPC call. Some servers (Supabase) 400 without it.-- Status probe uses spec-mandated `initialize` instead of `tools/list`. Tool count moves to on-demand fetch via the Tools dialog.-- `localhost` → `127.0.0.1` normalization on the redirect URI. RFC 8252 §7.3.-- HTTP-error response body is captured + surfaced in the unreachable message instead of just "HTTP 400".-- AS-metadata candidate-URL probing (RFC 8414 inserted, OIDC inserted, appended fallbacks).--**Idempotent add + URL-based dedup.** `addUserMcpServerAction` now accepts a canonical `key` override (used by Browse so "NotFair Google Ads" hits the preset key `notfair-googleads` instead of slugifying into a different identifier). The action also detects "this same MCP server URL is already in the project" and returns the existing key instead of writing a duplicate.--**Trusted connectors curated.** Vercel and Supabase were each verified end-to-end:-- Stripe, PostHog, Mixpanel: kept after URL corrections (most live at `/mcp`, not `/`).-- Supabase: kept after the `client_secret_post` fallback landed.-- Vercel: omitted. Their DCR endpoint silently returns a single fixed `client_id` and the authorize endpoint rejects every loopback redirect URI — only their first-party integrations work today.--**New components:** `browse-connectors-dialog`, `mcp-icon` (shared brand favicon via Google's faviconV2 service, subdomain-stripped to the registrable domain), `add-mcp-server-card` (now a `AddMcpServerMenu` dropdown trigger; the custom-URL dialog moved inside).--## 0.3.1 — 2026-05-31--User-configurable MCP catalog. The Connections page is no longer limited to the curated preset list — users can register any OAuth-2.0 MCP server (Stripe, Vercel, Supabase, or their own) by pasting a resource URL. The portal probes RFC 9728 protected-resource discovery + RFC 8414 AS metadata before persisting, so only servers that actually support dynamic client registration get past the form.--- New `user_mcp_servers` SQLite table (migration `011`), project-scoped, joined with `MCP_CATALOG_PRESETS` by the new `getMcpCatalog(project_slug)` helper.-- `mcpSpecByKey` is now project-scoped (`(project_slug, key)`); all call sites updated.-- New server actions: `probeMcpDiscovery`, `addUserMcpServerAction`, `removeUserMcpServerAction`.-- New "Add an MCP server" card on the Connections page; user-added cards get a "Remove server" affordance presets don't have.-- `cascadeDeleteProjectArtifacts` cleans up `user_mcp_servers` rows on project deletion and unregisters the adapter rows for both presets and user-added entries.--## 0.3.0 — 2026-06-01--End-to-end wiring + reliability pass on top of the 0.2.0 harness-agnostic rewrite. Every surface in the app is now driven by a real, persisted code path; no more half-finished stubs.--### Agents can actually use the tools they're given--- **`schedule_recurring_work` MCP tool** — agents create real rows in `scheduled_jobs` instead of shelling out to a CLI that no longer exists. Skill prompt rewritten to teach the tool; the dead `openclaw cron add` block is gone.-- **Codex MCP auth fixed** — Codex 0.132+ rejects raw `headers.Authorization` rows as `Auth: Unsupported`. Registration now writes `bearer_token_env_var`; spawn injects one env var per server. Orchestration keeps its dedicated `NOTFAIR_ORCHESTRATION_BEARER` for backward compat.-- **Codex sandbox bypass** — adapter spawns Codex with `--dangerously-bypass-approvals-and-sandbox` so MCP tool calls aren't silently cancelled and loopback to the local orchestration server actually works.-- **External MCPs reach agents on OAuth complete** — `setMcpBearer` now also calls `registerCatalogMcpForProject`, wiring the new bearer into every agent's harness config. New agents provisioned later also inherit existing project tokens.-- **Per-server env var scheme** (`NOTFAIR_MCP_BEARER__<SERVER>`) so multiple MCPs can coexist with different bearers in the same Codex spawn.--### Live transcript: paperclip-style pub/sub--- In-process `EventEmitter` keyed by `session_id`. `appendTranscriptEvent` publishes after every INSERT.-- SSE bridge (`/api/agents/.../live`) subscribes instead of polling. Sub-millisecond push latency for chat / tool / lifecycle events.-- Reattach is race-free: backfill from `cursor=0` runs *after* the subscription is attached, with events buffered during the backfill and dedup-by-seq on flush.-- Verified end-to-end via curl SSE alongside the chat composer: each new event arrives in its own SSE frame, in order.--### Recover from agent silence--- New "abandoned task" state surfaced when the harness turn ends cleanly but the agent forgot to call `submit_task_status`. Previously this stranded the task in `working` with an infinite "Wrapping up" spinner.-- Recovery card with three explicit actions:- - **Resume** — flip back to `proposed` and re-fire the kickoff (transcript preserved).- - **Mark done** — close the task manually.- - **Cancel** — terminate.-- New `resumeBlockedTaskAction` and `markTaskDoneAction` server actions.-- Working indicator gets a `mood: "ended"` palette so the spinner doesn't lie during the parked state.--### Sidebar no longer flickers--- Replaced `router.refresh()`-driven badge updates with a client `LiveCountsProvider` polling `/api/in-flight-counts` and pushing fresh numbers through React Context.-- Sidebar's server-rendered structure never reconciles between polls — only the badge nodes flip. Zero flicker across multiple polling cycles.-- `GlobalLivenessPoller` removed entirely; superseded by the context provider.-- `startTransition` wraps remaining `router.refresh()` calls in the task workspace + start-all flows.--### Bug fixes--- **Project delete FK violation** — `deleteProjectRow` and `changeProjectSlug` were missing `questions`, `mcp_tokens`, `scheduled_jobs`, `sessions` in their child-table lists. Added; regression test now seeds every FK-bearing table.-- **Reattach session-mismatch** — chat composer sends `sessionId` matching the URL UUID, but the chat route read `body.thread` and fell back to `"main"`. Now honors both fields with `sessionId` as the canonical thread label.-- **Project isolation: agent-prefix collision** — `listProjectAgents` matched dirs by string prefix; project "acme" leaked agents from "acme-q4". Now filtered by the sidecar's `project_slug` field. Test asserts the cross-leak no longer happens.-- **Session lookup scoped to project** — `findSessionBySessionId` now requires `project_slug` to close the same prefix-collision class of bugs.-- **Files tab dedup** — `PROJECT.md` was appearing twice from a legacy augment step. Removed; field shape on `AgentFileEntry` aligned to UI expectations.--### Removed user-visible "OpenClaw" copy--- Home page, agents page, crons header / error, agent cron header / error, skills header / error, mcp-card, schedule-cron-dialog, create-agent-dialog, danger-zone, agent-danger-zone — all rewritten to describe what's actually running (workspace dirs, scheduled jobs, harness adapters).--### Internal--- `NotFair doctor` drops the OpenClaw / gateway / LLM-config probes; now checks Claude Code + Codex per adapter, requires at least one.-- `agents/files.ts` simplified — fs reader returns every workspace file in one pass.-- 870 tests, 73 test files. Adapter parsers, MCP config writers (Claude Code + Codex), pub/sub emitter, scheduler tool, project delete cascade, sidebar live-counts context, abandoned-task UI flows all covered.--### Migrating from 0.2.0--No DB migration required (the schema landed in 0.2.0). The OAuth callback now auto-registers the catalog MCP with every agent — if you previously connected an MCP that wasn't visible to your agents, just **disconnect and reconnect** from `/<project>/connections` and Greg / Ana will pick it up.--## 0.2.0 — 2026-05-31--### Harness-agnostic rewrite--NotFair is no longer coupled to OpenClaw. Agents run through pluggable-harness adapters — Claude Code (default) and Codex ship as the first two-supported options, and the architecture is open for more.--**Architecture**--- `HarnessAdapter` interface + adapter registry + UI display registry under- `src/server/adapters/`. Mirrors paperclip's adapter pattern.-- Two adapters fully implemented:- - `claude-code-local` — spawns `claude --output-format stream-json`,- parses events, writes workspace `IDENTITY.md`/`CLAUDE.md`, and registers- MCP servers via `.mcp.json`.- - `codex-local` — spawns `codex exec --json`, writes workspace- `IDENTITY.md`/`AGENTS.md`, registers MCP servers in- `~/.codex/config.toml`.-- Migration `010_harness_adapter.sql` adds `projects.harness_adapter` plus- five new tables (`mcp_tokens`, `scheduled_jobs`, `scheduled_job_runs`,- `sessions`, `transcript_events`).-- Native runtime services replace every OpenClaw dependency:- - **Sessions / transcripts**: `src/server/sessions/` — SQLite rows backed- by `transcript_events`, plus `view.ts` for the thread dropdown and- `transcript-tail.ts` for the live SSE bridge.- - **Scheduler**: `src/server/scheduler/` — cron-parser tick loop, schedule- rows in `scheduled_jobs`, runs in `scheduled_job_runs`. The tick loop- dispatches due jobs through the project's adapter.- - **MCP token storage**: `src/server/mcp/tokens.ts` — project-scoped tokens- in SQLite, surfaced via `mcp/state.ts` (`getMcpStatus`, `setMcpBearer`,- `disconnectMcp`).- - **Agent provisioning**: `src/server/agents/{provisioning,clone,- cascade-delete,files,skills}.ts` — workspace ownership and- create / clone / delete entirely in fs + SQLite.--**Routes + UI rewired**--- `/api/chat` dispatches through the project's harness adapter and persists- every event to `transcript_events`.-- `/api/agents/.../threads/.../live` polls `transcript_events` at 500 ms and- streams new rows as SSE — no shadow JSONL anymore.-- `/api/agents/.../threads/.../transcript` reads the same table by `seq`- cursor for paged tail.-- `/api/mcp-oauth/callback` writes tokens straight into `mcp_tokens`.-- Onboarding flow shows a recommended-harnesses picker (Claude Code default,- Codex available) with paperclip-style "Recommended" badges. Choice persists- on the project row.-- `agent-templates.ts` provisions every agent through the chosen adapter and- registers the notfair-orchestration MCP per-agent at provision time.-- Orchestration wake-ups (`run-task.ts`, `approval-wakeup.ts`,- `question-wakeup.ts`) all dispatch via adapter + persist to- `transcript_events`.--**bin/cli.mjs**--- `NotFair doctor` checks Claude Code and Codex separately, requires at- least one of them on PATH, and drops every former `openclaw --version` /- gateway / LLM-config probe.--**Deleted**--- `src/server/openclaw/` — entire directory (24 files) including- `cli.ts`, `gateway-client.ts`, `gateway-rpc.ts`, `crons.ts`,- `cron-schedule.ts`, `sessions.ts`, `transcript-tail.ts`,- `shadow-transcript.ts`, `thread-origins.ts`, `clone-agent.ts`,- `project-delete.ts`, `agent-turn.ts`.-- `src/server/mcp-state.ts` (replaced by `src/server/mcp/state.ts`).-- `src/components/paired-openclaw-pill.tsx` and the sidebar footer that hosted it.-- Legacy tests that mocked the removed modules (8 test files removed; will- be re-added with adapter-aware coverage as the new surfaces stabilise).--**Tests**--- 852 tests passing across 69 files.-- New adapter parsers (`claude-code-local/parse`, `codex-local/parse`)- have dedicated coverage.-- Full test suite + dev server boot verified after every migration step.--## 0.1.0--Initial OpenClaw-coupled release.diff --git a/notfair/CLAUDE.md b/notfair/CLAUDE.mddeleted file mode 100644index cbc2a1bb..00000000--- a/notfair/CLAUDE.md+++ /dev/null@@ -1,99 +0,0 @@-# CLAUDE.md--Project conventions and notes for AI assistants working on NotFair.--## What NotFair is--A local, single-user, goal-driven agent runner. The user states a goal; NotFair-provisions an anonymous agent for it (agent = goal, 1:1), the agent defines a-platform-verifiable metric + target in chat, the user confirms the plan (which-starts the loop on the spot), and a-heartbeat loop ("checks") measures the metric and lets the agent act — with-observation windows, a spend envelope, and per-goal memory as the controls.-No approvals, no tasks, no orchestration layer: goals are the only unit.--## Verification--This repo carries no migrations or legacy/compat code. Verification is:--1. `pnpm typecheck` — must be clean.-2. `pnpm test` — vitest; must be clean. Tests live next to the code they- cover (`src/lib/foo.ts` → `src/lib/foo.test.ts`). Default environment is- node; component tests opt into a DOM with a leading- `// @vitest-environment jsdom` pragma and use `@testing-library/react`.- Mock at the server-action / db-module boundary (`vi.mock`), not deeper.- Test pure logic and user-visible component behavior. Prefer testing below- the page boundary, but use a focused page regression test when the bug is- in server-page wiring that lower-level tests cannot observe. Route handlers- normally stay covered by the live smoke.- SQLite tests use the real better-sqlite3 against a tmpdir — and the- `NOTFAIR_DATA_DIR` override MUST be set inside `vi.hoisted(...)`:- static imports evaluate before module-level statements, so a plain- assignment points the suite at the developer's live `~/.notfair`.-3. `pnpm build` — must be clean.-4. Live smoke: `pnpm dev` (port 3326), then walk the affected flow in the- browser (goal index → goal page → chat / confirm / checks).--Prompt-affecting changes (`src/server/goals/identity.ts`, tick briefs in-`src/server/goals/tick.ts`, tool descriptions in-`src/server/mcp-server/tools.ts`) must be validated by running a real goal-loop end-to-end and reading the agent's actual behavior in the transcript.--## Project structure conventions--- **Database**: SQLite via `better-sqlite3` at `~/.notfair/db.sqlite`- (overridable via `NOTFAIR_DATA_DIR`). The entire schema lives in- `src/server/db/schema.ts` and is applied idempotently on boot — there is- no migration system. Schema changes edit that file; dev databases are- recreated, not migrated.-- **Agent state**: agent workspaces live at `~/.notfair/agents/<agent-id>/`.- NotFair owns the workspace; the chosen harness adapter writes whatever- files it expects (CLAUDE.md for Claude Code, AGENTS.md for Codex, plus the- shared IDENTITY.md / SKILL.md / PROJECT.md NotFair writes).-- **Sessions / transcripts**: stored in SQLite (`sessions`,- `transcript_events`). The chat route persists every adapter event; the UI- replays them on attach. Tick sessions are labeled `tick-<n>`; the intake- chat is `main`.-- **Goals**: agent = goal. `goals` + `goal_actions` + `goal_metric_snapshots`- + `goal_learnings` + `goal_ticks` tables; db module `src/server/db/goals.ts`;- loop runtime under `src/server/goals/` (intake, tick, metric, provision,- identity). The 30s scheduler in `src/server/scheduler/tick.ts` sweeps- `goals.next_tick_at`.-- **MCP**: NotFair exposes two internal MCP servers as Next routes —- `notfair-goals` (`/api/mcp/goals`, the goal tools) and `notfair-browser`- (`/api/mcp/browser`). External catalog tokens are project-scoped in- `mcp_tokens`; every agent in a project gets every connected server.-- **Memory**: shared workspace context is `~/.notfair/projects/<slug>/PROJECT.md`- (synced into every agent identity; written via the `set_shared_context`- tool). Per-agent memory is the `goal_learnings` ledger + the agent's own- workspace files.--## Architectural tenets--- **Harness-agnostic.** NotFair runs on top of any local AI coding agent that- conforms to the `HarnessAdapter` contract under `src/server/adapters/`.- Today: Claude Code (`claude-code-local`) and Codex (`codex-local`).-- **NotFair owns the runtime services.** Goal scheduling, MCP token storage,- agent provisioning, session/transcript persistence — all in SQLite + Node.- Adapters only handle: (1) spawning the harness to stream a turn, (2) writing- harness-specific workspace config, (3) registering MCP servers for the- harness to find.-- **Single-user local CLI.** A local Next.js process launched via the- `notfair` bin. No multi-tenant code paths, no auth, no multi-process state- coordination.-- **No legacy code.** No migration shims, no backward-compat branches, no- dead flags. When a concept is removed, every trace of it goes — code,- schema, comments, and on-disk state.-- **Don't rebuild the wheels.** Before proposing any new abstraction,- identify whether an existing tool already solves the sub-problem. Prefer- thin glue layers over custom infrastructure.--## Commit style--Conventional commits with type-scope-description: `feat(goals): backfill-metric history at intake`, `fix(tick): clamp smart sleep to deadline`.--Co-author trailer when AI-assisted:-```-Co-Authored-By: Claude Fable 5 <[email protected]>-```diff --git a/notfair/CONTRIBUTING.md b/notfair/CONTRIBUTING.mddeleted file mode 100644index 92427d3e..00000000--- a/notfair/CONTRIBUTING.md+++ /dev/null@@ -1,121 +0,0 @@-# Contributing--Thanks for poking around! NotFair is small, opinionated, and willing to grow.--## Dev setup--The app lives in the `notfair/` directory of the [nowork-studio/notfair-plugin](https://github.com/nowork-studio/notfair-plugin) repo:--```bash-git clone https://github.com/nowork-studio/notfair-plugin.git-cd notfair-plugin/notfair-pnpm install-```--Native deps (`better-sqlite3`, `keytar`) need build approvals on pnpm — already-configured in `package.json` under `pnpm.onlyBuiltDependencies`, so they build-on install with no extra prompts.--Make sure you have:-- Node 20+ (24 preferred — that's what the prebuilt `better-sqlite3` / `keytar` binaries target)-- At least one harness installed and authenticated: [Claude Code](https://docs.claude.com/en/docs/agents-and-tools/claude-code/overview) (`claude`) or [Codex CLI](https://github.com/openai/codex) (`codex`)--Quickest way to verify the host machine is set up is the doctor, which the-shipped CLI exposes and which you can run against the dev source too:--```bash-pnpm cli doctor # same checks the published `notfair doctor` runs-```--## Dev loop--```bash-pnpm dev # next dev --turbopack on port 3326 (the published CLI serves on 3327)-pnpm typecheck # tsc --noEmit-pnpm test # vitest run-pnpm build # next build + scripts/copy-standalone-assets.mjs (npm-tarball-ready)-pnpm cli # the CLI (start, doctor) from your checkout — start needs a pnpm build first-```--`pnpm dev` is the day-to-day. The dev server points at the same-`~/.notfair/db.sqlite` as a globally installed `notfair` does, so if-you also run the published CLI on this machine, point one of them at a-different data dir to avoid stomping each other's state:--```bash-NOTFAIR_DATA_DIR=$PWD/.notfair-dev pnpm dev-```--`.notfair-dev/` is already gitignored.--To reset local state for a clean run, stop any running server and:--```bash-rm ~/.notfair/db.sqlite # blow away product state-rm -rf ~/.notfair/agents/ # blow away agent workspaces-```--There is no migration system: the entire schema lives in-`src/server/db/schema.ts` and is applied idempotently on boot. Schema changes-edit that file; dev databases are recreated, not migrated.--## Project shape--See `ARCHITECTURE.md`. Short version:-- Frontend: Next.js 16 App Router + React 19 + Tailwind 4 + shadcn/ui primitives, styled per `DESIGN.md`-- Backend: Next.js server actions + SQLite (`better-sqlite3` at `~/.notfair/db.sqlite`) + the goal-loop runtime under `src/server/goals/`-- Harness-agnostic: goal agents run on any local AI coding agent that implements the `HarnessAdapter` contract in `src/server/adapters/` — Claude Code (`claude-code-local`) and Codex (`codex-local`) today-- NotFair hosts two internal MCP servers as Next routes — `notfair-goals` (`/api/mcp/goals`, the goal tools) and `notfair-browser` (`/api/mcp/browser`) — and connects external catalog MCPs (Google Ads, Search Console, PostHog, …) per project via the Connections page--## Adding a feature--1. Open an issue describing the user-facing change (the *what* and *why*).-2. Branch off `main`.-3. Build it. Keep modules small. shadcn primitives over custom CSS; follow `DESIGN.md`.-4. Run `pnpm typecheck && pnpm test && pnpm build`. All three must pass.-5. Live smoke: `pnpm dev`, then walk the affected flow in the browser (goal index → goal page → chat / confirm / checks). Prompt-affecting changes (`src/server/goals/identity.ts`, tick briefs in `src/server/goals/tick.ts`, tool descriptions in `src/server/mcp-server/tools.ts`) must be validated by running a real goal loop end-to-end and reading the agent's actual behavior in the transcript. `scripts/e2e-provision.ts` is a starting point for spinning up a fresh project + agents from a script.-6. Update README / ARCHITECTURE if behavior changed.-7. Open a PR. Describe what you changed and how to verify.--## Module conventions--- **Server-only modules** live in `src/server/`. Anything in there can use `node:*` modules + native deps.-- **Client components**: start the file with `"use client";`.-- **Server actions**: `"use server";`. Throw on validation failure (form actions) or return discriminated `{ ok: true, ... } | { ok: false, error }` (programmatic).-- **Database access**: only via helpers in `src/server/db/`. Don't reach for `getDb()` from a component or route.-- **Harness access**: only via the adapter registry (`src/server/adapters/`). Don't spawn `claude` or `codex` directly from a route — adapters own process lifecycle, workspace config, and MCP registration.-- **Slugs**: only via `src/lib/slug.ts`. Reserved words checked.-- **Types**: shared types go in `src/types/`. Server-only types stay near their server module.--## Style--- TypeScript strict mode. No `any` unless interfacing with untyped externals.-- Prefer named exports. Default exports only for Next.js pages/layouts/route handlers.-- Visual language lives in `DESIGN.md` — surfaces are separated by elevation (shadow/surface tokens), not borders; use the existing `ns-*` utility classes before inventing new ones.-- No comments unless the *why* is non-obvious. Identifiers do the explaining; PR descriptions carry the context.--## Testing--`pnpm test` runs the Vitest suite. Conventions:--- Tests live next to the code they cover (`src/lib/foo.ts` → `src/lib/foo.test.ts`).-- Default environment is node; component tests opt into a DOM with a leading `// @vitest-environment jsdom` pragma and use `@testing-library/react`.-- Mock at the server-action / db-module boundary (`vi.mock`), not deeper.-- SQLite tests run the real `better-sqlite3` against a tmpdir. The `NOTFAIR_DATA_DIR` override MUST be set inside `vi.hoisted(...)` — static imports evaluate before module-level statements, so a plain assignment would point the suite at your live `~/.notfair`.-- Test pure logic and user-visible component behavior. Prefer testing below the page boundary, but use a focused page regression test when the bug is in server-page wiring that lower-level tests cannot observe. Route handlers normally stay covered by the live smoke.--## Commits + PRs--- One logical change per commit. Conventional commits with type-scope-description: `feat(goals): backfill metric history at intake`, `fix(tick): clamp smart sleep to deadline`. Look at `git log` — recent history is the template.-- When AI-assisted, credit the model with a co-author trailer, e.g.:-- ```- Co-Authored-By: Claude Fable 5 <[email protected]>- ```--- Never bypass hooks (`--no-verify`), never skip signing, never force-push without an explicit ask.-- Don't commit secrets. If a `.env`, OAuth token, or API key shows up in a diff, stop and fix the diff before pushing.--## License--By contributing, you agree your contributions are licensed under MIT.diff --git a/notfair/DESIGN.md b/notfair/DESIGN.mddeleted file mode 100644index f1a76035..00000000--- a/notfair/DESIGN.md+++ /dev/null@@ -1,188 +0,0 @@-# NotFair Design System--**Direction.** Codex-flavored product UI: monochrome chrome, dark-first with a full light mode, depth from **elevation** (surface steps + soft shadows) instead of border lines, monospace for machine-flavored metadata. Color is reserved for **semantics** — green means live/connected, amber means attention, red means error. Primary actions are inverted monochrome (white-on-dark / black-on-light), the OpenAI/Codex signature.--If a design choice would feel at home in the OpenAI Codex app or ChatGPT's product chrome — it belongs. If it would feel at home in a magazine, a brutalist landing page, or macOS System Settings — it doesn't.-------## Brand--The mark lives at `notfair/public/notfair-mark.svg` (green "!" + ink "F") with a dark-mode variant at `public/notfair-mark-dark.svg` (the F flips to light ink). Swap them with `dark:hidden` / `hidden dark:block` — never render the light mark on a dark surface.--The green `#4CAF6E` lifted from the mark is `--notfair-accent`. It is **status-only**: connected dots, live indicators, "ok" run outcomes, completed wizard pips, the recommended chip. It is never a CTA fill, never a link color, never chrome.-------## Color--All tokens live in `src/app/globals.css` as HSL triples on `:root` (light) and `.dark`. Never hardcode hex/Tailwind palette colors in components — reach for `--notfair-*` or the mapped shadcn tokens.--### Dark (native mode)--| Token | Approx | Use |-|---|---|---|-| `--background` | `#161618` | Content background |-| `--notfair-sidebar` | `#0F0F10` | Sidebar rail (darker than content — the step *is* the separator) |-| `--card` | `#202024` | Raised surfaces — one step lighter than content so elevation reads without borders |-| `--notfair-surface-2` | `#26262A` | Inset fills: secondary buttons, chips, glyph wells, active pills |-| `--notfair-ink` | `#ECECEE` | Headings, primary text |-| `--notfair-ink-2/3/4` | `#D6D6DA` / `#A6A6AD` / `#77777E` | Strong body / body / labels+metadata |-| `--notfair-cta` / `--notfair-cta-text` | `#ECECEC` / `#101012` | Inverted primary button |--### Light--| Token | Approx | Use |-|---|---|---|-| `--background` | `#F7F7F8` | Content background |-| `--notfair-sidebar` | `#EFEFF0` | Sidebar rail |-| `--card` | `#FFFFFF` | Raised surfaces |-| `--notfair-surface-2` | `#F0F0F1` | Inset fills |-| `--notfair-ink` …`-4` | `#131316` → `#85858C` | Ink scale |-| `--notfair-cta` / `--notfair-cta-text` | `#131316` / `#FFFFFF` | Inverted primary button |--### Semantic--| Token | Use |-|---|---|-| `--notfair-accent` | Green — live/connected/ok only |-| `--notfair-accent-soft` | Green-tinted well (light wash in light mode, dark green well in dark) |-| `--notfair-warn` / `--notfair-warn-soft` | Amber text / amber wash (token expired, approval pending) |-| `--destructive` | Errors, danger zone |--Per-agent hues (`src/lib/agent-colors.ts`) survive only as small **dots and labels** — chip fills are neutral inset for every agent.--### What we don't have--No border-line chrome (see Elevation). No colored CTA fills. No purple/blue "tech" accents. No colored block chips — hue lives in dots.-------## Theme switching--`next-themes` with `attribute="class"`, default **dark**, system honored. The `.dark` class on `<html>` flips every token; the toggle lives in the sidebar footer (`src/components/theme-toggle.tsx`). Components must work in both modes by construction — if you write a color that isn't a token (or a Tailwind token-mapped class), you've broken one of the modes.-------## Typography--**Stack.** System sans (`-apple-system, …, Inter`) for UI. **Monospace** (`ui-monospace, SF Mono, JetBrains Mono, Menlo`) is a first-class citizen: hosts, counts, IDs, slugs, usage meters, tool-call verbs, timestamps, version strings. The mono metadata is what makes the chrome read "Codex". Use `.ns-mono` or `font-mono`.--**Tracking.** Near-neutral: body `-0.006em` (not Apple-tight). Titles land around `-0.02em`.--| Role | Size | Weight |-|---|---|---|-| Hero (wizard h1) | 30px | 600 |-| Page title | 28px | 600 |-| Section heading (`.ns-h2`) | 13px | 600 |-| Body / row title | 13.5–14.5px | 400–500 |-| Row description | 12–12.5px | 400 |-| Metadata (mono) | 10.5–11px | 400–500 |--Use color for hierarchy before weight. Sidebar group labels are small uppercase mono-ish (`10.5px / 500 / +0.07em`).-------## Elevation (replaces borders)--**No border lines in chrome.** Cards separate from the page by being a lighter surface (dark) or by shadow (light); lists separate rows with **gaps between elevated cards**, not dividers; the sidebar separates from content by surface step alone.--```css---notfair-shadow-sm /* resting chips, kanban cards, tool-call cards */---notfair-shadow /* primary cards, list rows, day-well "today" */---notfair-shadow-lg /* floating panels: dropdowns, dialogs */-```--Dark-mode shadows are stronger (soft black) and the lighter card surface does half the work. Borders are still fine *inside content*: markdown tables, blockquote rules, focus rings.-------## Spacing & radii--8px grid. Grouped lists use `9px` gaps between row-cards. Card padding `14–18px`.--| Radius | Use |-|---|---|-| `8px` | Buttons |-| `7px` | Tab pills, small chips, cron event chips |-| `9px` | Glyph wells (38px) |-| `10–12px` | Cards, list rows, kanban cards |-| `14px` | Large containers (kanban columns, KPI cards) |-| `999px` | Status pills, role badges only |-------## Components--### Buttons (`.ns-btn`)--- **Primary** — inverted fill: `--notfair-cta` bg, `--notfair-cta-text` text. Hover dims opacity.-- **Secondary / "outline"** — borderless inset fill (`--notfair-surface-2`). There is no true outlined button; `.ns-btn-outline` is an alias kept for call sites.-- **Ghost** — transparent, ink text, inset hover.-- Radius 8px, `13.5px / 500`.--### Grouped list (`.ns-list` / `.ns-group`)--Separated elevated cards with 9px gaps — each direct child (usually `<li>`) gets `bg-card + radius 12px + --notfair-shadow`. No dividers. Rows keep the 38px glyph + title/desc + right status/action shape.--### Tabs (`.ns-tabs`)--Pill pattern: no underline, no bottom border. Active tab = inset filled pill (`--notfair-surface-2`) with ink text.--### Status--- **Connected** — 6–7px green dot + lowercase word in `--notfair-accent`.-- **Attention** — `ns-tag-amber` (warn tokens). **Error** — `ns-tag-red`.-- Neutral machine states ("scheduled", "past") — `ns-tag-mono` inset chips.--### Chat surface--User messages: inset bubbles (`bg-muted`, `rounded-2xl` with a tucked corner). Tool calls: elevated cards with mono verb + target + step counts and a green status dot. Composer: elevated borderless field with inverted send button. Agent tab bar: pill tabs over a translucent background wash.--### Cron calendar--Seven borderless day wells (`--notfair-ink` at 3.5% alpha); **today** is an elevated card. Events are neutral inset mono chips with a small agent-colored dot before the time.--### Kanban (tasks)--Columns are tinted wells (no ring, no header divider); task cards are elevated (`shadow-sm`), mono task IDs and dates, neutral assignee pill. Status dots on column headers: amber working / red blocked / green done.--### Forms--Inputs and textareas are borderless inset fields (`--notfair-surface-2` fill, transparent border, focus ring only). Form cards are elevated. Disabled buttons drop to 45% opacity.--### Progress pips--Inset dots; **done** = green-soft well with accent glyph, **active** = inverted CTA fill, pending = inset neutral. Connectors are 1px inset-colored (not border-strong).-------## Motion--`0.15s ease` for color/background/opacity. `0.18s cubic-bezier(.2,.7,.3,1)` for elevation/position. No bounce, no springs. The WorkingIndicator's aurora/heartbeat animations are the one deliberately alive surface.-------## DO / DON'T--**DO**-- Separate with **surface steps and shadows**, never hairlines.-- Put machine-flavored text (hosts, IDs, counts, times) in **mono**.-- Keep green sacred: if it isn't live/connected/ok, it isn't green.-- Check every change in **both** modes — dark is native, light is first-class.--**DON'T**-- Don't add border lines to chrome (cards, lists, sidebars, headers, buttons).-- Don't fill chips/badges with hue — agent identity lives in dots.-- Don't use colored CTA fills — primary is inverted monochrome.-- Don't hardcode Tailwind palette colors (`emerald-500`, `amber-600`, `zinc-*`) — use tokens; palette classes break one of the two modes.-- Don't reach for emoji as glyphs — use letterform glyph wells or SVG icons.-------## Open questions (parked)--- **Density mode.** A compact table density for large accounts — revisit when a customer hits it.-- **Charts.** When data viz arrives, derive a mono-axis, semantic-color chart spec; don't extrapolate from chips.--Treat this `DESIGN.md` as the source of truth for the Codex-theme system; the approved mockups from the 2026-07-07 session are disposable.diff --git a/notfair/LICENSE b/notfair/LICENSEdeleted file mode 100644index 26abff99..00000000--- a/notfair/LICENSE+++ /dev/null@@ -1,21 +0,0 @@-MIT License--Copyright (c) 2026 NotFair contributors--Permission is hereby granted, free of charge, to any person obtaining a copy-of this software and associated documentation files (the "Software"), to deal-in the Software without restriction, including without limitation the rights-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell-copies of the Software, and to permit persons to whom the Software is-furnished to do so, subject to the following conditions:--The above copyright notice and this permission notice shall be included in all-copies or substantial portions of the Software.--THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE-SOFTWARE.diff --git a/notfair/PLAN.md b/notfair/PLAN.mddeleted file mode 100644index ef7a4be9..00000000--- a/notfair/PLAN.md+++ /dev/null@@ -1,817 +0,0 @@-----status: ACTIVE------# CEO Plan: NotFair (né notfair CMO) — AI Marketing OS--Generated by /plan-ceo-review on 2026-05-17-Mode: SCOPE EXPANSION | Approach: B (CMO-first Marketing OS)-Repo: notfair-workspace/notfair (greenfield)-------## Guiding tenet--**Don't rebuild the wheels.** Before any new abstraction, registry, broker, or service in this architecture, identify what OpenClaw, Vercel platform services, AI SDK, the AI Gateway, or existing skill ecosystems already provide. Default to: existing system as source of truth + thin attribution/glue layer + frontend view layer. The product is differentiated at the product surface (CMO UX, project memory, cross-channel signals, autonomy), not by reimplementing commodity infrastructure.-------## PIVOT (Revision 5, 2026-05-17): open-source local CLI tool--**Major scope adjustment.** notfair CMO is now an **open-source local app** distributed as an npm package. User runs `npx notfair` in their terminal; it launches a local Next.js server on `localhost:3000` and opens their browser. Single-user, single-machine, no SaaS hosting, no auth, no multi-tenancy. **OpenClaw is assumed installed + running locally on the user's machine** (we verified its capabilities via live spike — see [[openclaw-capabilities]]).--This pivot eliminates significant infrastructure (multi-tenant auth, RLS, envelope encryption per tenant, hosted Postgres, Vercel deployment, AI Gateway tenancy tagging) AND leverages OpenClaw native capabilities we were about to rebuild (memory, cron, agent isolation, MCP tool exposure, WebSocket gateway). Net effect: V1 effort drops from ~3-4 weeks CC to ~1-2 weeks CC.--**Sections superseded by this pivot:**-- Original "Approach" → see "Approach: B-local" below-- Original "Architecture decisions (locked in eng-review)" → see "Architecture decisions (revised for local OSS)" below-- Original "Wheel-rebuilding audit" → see updated audit reflecting OpenClaw native primitives-- Original "Protocol definitions" → see simplified MCP-based versions-- Original "Code conventions" → simpler (no multi-tenant middleware)--**Sections that stay valid:**-- Vision (the "hire a CMO" framing still works for OSS, just with developer-marketer hybrid audience)-- Design specifications (UI doesn't change with runtime; sidebar, screens, states all stay)-- Test strategy structure (concrete tests change but discipline stays)-------## Vision--### Product positioning-**"The AI marketing team you hire on day one."** Not "manage 6 agents" — *hire a CMO that runs your marketing function.* The user sets direction, the CMO orchestrates execution, specialist agents do channel work, results flow back. Specialists are an implementation detail; the CMO is the product.--### 10x check-The user sets direction at 9am, reviews outcomes at 5pm. Overnight, agents ran experiments, killed losers, escalated winners, drafted tomorrow's plan. The user wakes up to a 3-paragraph briefing with one decision to make today. By day 90, project memory has compounded so the CMO's recommendations are noticeably sharper than day 1's. By day 180, agencies run 10-brand portfolios on this and switching is painful because nothing else has the per-brand memory.--### Platonic ideal — solo founder onboarding-1. Paste site URL (20 seconds)-2. CMO scrapes site → derives brand voice fingerprint + ICP hypothesis (2 minutes)-3. CMO proposes 30-day experiment program across 2 channels (1 minute review)-4. Founder approves budget + caps-5. Day 7: first weekly review with what shipped and what's working-6. Day 30: noticeably sharper recommendations from accumulated project memory-------## Approach: B-local — CMO-first Marketing OS (open-source local)--Substrate:-- **Distribution:** npm package; user runs `npx notfair` → spawns local Next.js server + opens browser-- **Frontend:** Next.js App Router (standalone build, runs locally — no Vercel)-- **Local DB:** SQLite (better-sqlite3) at `~/.notfair/db.sqlite` for our own state (tasks, approvals, cost events, oauth tokens, project metadata)-- **AI orchestration:** AI SDK v6 with user's own LLM API key (OpenAI/Anthropic/Google — they supply); no AI Gateway tenancy needed-- **Agent runtime:** **OpenClaw** (assumed installed + running on user's machine). We invoke via subprocess (`openclaw ... --json`) and connect to its WebSocket Gateway on loopback.-- **Agent memory:** **OpenClaw memory subsystem** (built-in: index, search, REM reflection, promotion to MEMORY.md). We don't run pgvector.-- **Agent cron:** **OpenClaw cron** (built-in: `openclaw cron add/list/edit/disable/runs`). We don't run our own scheduler.-- **Tool bridge:** Our Next.js exposes an MCP server with tools (`approve_action`, `record_cost`, `log_action`, `query_project_state`, etc.). Registered with OpenClaw via `openclaw mcp set`. OpenClaw agents call our tools via MCP.-- **Skills:** preloaded per agent via OpenClaw's existing skill/MCP system. Reuse `notfair-googleads` MCP (user already has it configured). Add SEO MCP for V1.-- **No auth:** loopback-only Next.js server, single user, single machine. Gateway runs in `--auth none` mode bound to loopback.-- **OAuth (Google Ads, GSC):** `localhost:<port>/oauth/callback` redirect; tokens stored encrypted in SQLite using OS keychain (keytar) for the master key. No tenancy — just one set per user per channel.--We own:-- Local Next.js UI (sidebar shell, CMO chat, approval inbox, cron tab, cost meter, project home, onboarding)-- MCP server exposing tools to OpenClaw agents-- Subprocess wrapper around `openclaw` CLI for agent/cron/memory management-- Project concept (group OpenClaw agents + crons under a project namespace via name prefix)-- OAuth flows for Google Ads + GSC-- Local SQLite schema (tasks, approvals, cost events, oauth tokens, projects)-- npm package + CLI launcher--We do NOT own:-- Agent reasoning logic (OpenClaw)-- Agent memory (OpenClaw memory)-- Cron scheduler (OpenClaw cron)-- Individual channel skills (reuse `notfair-googleads`; create curated SEO MCP)-- LLM cost (user's own API key + their provider's billing)-- Hosting (it's local)-------## Scope Decisions--| # | Proposal | Decision | Reasoning |-|---|----------|----------|-----------|-| D1 | Project memory + brand voice fingerprint | **V1 (via OpenClaw memory)** | Use OpenClaw's built-in memory subsystem (per-agent + REM promotion). Brand voice fingerprint is a memory entry tagged for cross-agent retrieval. We don't run pgvector. |-| D2 | CMO autonomous within user-set guardrails | **V1** | The "review outcomes at 5pm" promise requires this. Guardrails enforced by our MCP-side `approve_action` tool — autonomous below threshold, else routes to approval inbox. |-| D3 | Cross-agent signal sharing | **V1 (via OpenClaw memory + MCP)** | Agents write signals as memory entries with a `signal:` tag; CMO + specialists query via `memory search` MCP tool. No custom pub/sub. |-| D4 | Agency multi-brand mode as first-class | **DROPPED entirely** | Single-user local app. Users who want multi-brand just create multiple projects in their local install. If agency demand emerges post-OSS-launch, consider a hosted SaaS edition as a separate product. |--**V1 effort revised post-pivot:** ~1-2 weeks of CC-time. No OAuth verification calendar wait — `localhost` callback is exempt from Google's app verification for non-production-restricted scopes.-------## Accepted scope (V1) — post-pivot--### CLI + launcher-1. **`notfair` CLI** — npm package; `npx notfair` or `pnpm dlx notfair` starts local Next.js server, opens browser at `http://localhost:<port>`. Subcommands: `start` (default), `stop`, `doctor` (checks OpenClaw is running), `version`.-2. **Local data dir** at `~/.notfair/` (SQLite + logs + cached scrape data). Override via `--data-dir`.-3. **Doctor command** — verifies OpenClaw is installed + running (`openclaw health`), LLM API key set, port available; surfaces clear fix-instructions for any failure.--### Core product (UI)-4. **Project management** — create/archive/switch projects; project = a name + slug + the OpenClaw agents/crons whose names start with that slug-5. **Agent setup — 2 V1 agent templates** (Google Ads, SEO). Creating a project provisions OpenClaw agents per template via `openclaw agents add <project-slug>-<template>`. Each gets preloaded skills via MCP (existing `notfair-googleads` for Google Ads; new curated SEO MCP for SEO).-6. **CMO agent** per project — `openclaw agents add <project-slug>-cmo` with system prompt + access to our tool MCP. Orchestrates specialists.-7. **CMO chat UI** — AI SDK `useChat` connecting to our Next.js route that bridges to OpenClaw via `openclaw agent --json` per turn (or WebSocket Gateway if streaming required).-8. **Task board** — UI view of tasks stored in our SQLite. Tasks are user-facing units the CMO creates via the `assign_task` MCP tool. State lifecycle in protocol section.--### Memory + intelligence (D1, D3 — via OpenClaw)-9. **Project memory via OpenClaw memory** — each agent has its own memory file (`agent.md` per OpenClaw convention). For project-shared memory (brand voice, ICP, competitor intel), all project agents share a common workspace dir so the memory pool is shared. CMO can `memory search` across project memory before any decision.-10. **Brand voice fingerprint** — derived during onboarding from URL scrape + uploaded samples, written as a structured memory entry tagged `voice:`. Every agent's system prompt pulls this via memory search.-11. **Cross-agent signals via tagged memory + MCP** — agents emit observations as memory entries tagged `signal:<type>` with payload + suggested_actions. The CMO and specialists query `memory search "signal:" --agent <project-slug>-*` to discover unconsumed signals. No custom pub/sub.--### Autonomy + safety (D2)-12. **Guardrail config** — stored in SQLite + surfaced in Settings UI. Same threshold schema as before.-13. **Autonomy enforcement via the `approve_action` MCP tool** — every potentially-spending agent action MUST call `approve_action(action_summary, cost_estimate, type)` first. Our tool checks against the guardrail config; either returns `{approved: true}` (within threshold) or stores in approvals queue + returns `{approved: false, approval_id}`. Agent retries after user approves.-14. **Approval inbox UI** — reads approvals queue from SQLite, one-click approve/edit/reject, fires a webhook (loopback) back to a waiting agent to resume.-15. **"Why?" inline in chat** — every agent action message has expandable reasoning fetched from `agent_actions` log table.--### Always-on ops-16. **Cost meter** — sums `cost_events` table; LLM costs reported by agents via `record_cost` MCP tool after each LLM call (using AI SDK usage data they receive). Ad spend reported by Google Ads MCP after every spend change. Always-visible in sidebar.-17. **OAuth flows for Google Ads + GSC** — localhost redirect `http://localhost:<port>/oauth/<provider>/callback`. Tokens encrypted with OS keychain master key (via `keytar`), stored in SQLite `oauth_tokens` table.-18. **Cron tab** — wraps `openclaw cron list --json`; groups by project (parsing project slug prefix from cron name) and by `--agent` (already a column in OpenClaw output). Create/pause/resume/delete forward to OpenClaw via CLI subprocess.-19. **Daily briefing** — in-app card on Project Home; generated nightly via an OpenClaw cron that calls our `generate_briefing` MCP tool, result stored in SQLite. No email/external delivery in V1.--### Distribution-20. **GitHub repo** — public, MIT license (recommended; user can choose), README with quickstart, ARCHITECTURE.md, CONTRIBUTING.md-21. **npm publish workflow** — GitHub Actions: on tag, build standalone Next.js + bundle + publish to npm registry-22. **Telemetry: opt-in only** — no phone-home by default; opt-in posts anonymous usage events to a (TBD) endpoint. OSS users will be hostile to default telemetry.--## Deferred to v1.1+--- **More agent templates** — GEO, Cold Email, Reddit, X (gated until their channel skills/MCPs are curated)-- **Channel delivery via OpenClaw native (Telegram, Slack, iMessage)** — OpenClaw already supports it; we don't surface it in V1 UI but advanced users can wire it manually-- **Standalone binary distribution** (Tauri/pkg) for users without Node installed-- **Docker distribution** for users who want isolation-- **Settings export/import** — for backup/migration between machines-- **Multi-machine sync** — Tailscale-based or via OpenClaw's existing remote-gateway feature-- **Hosted SaaS edition** — if agency demand emerges, separate product with auth + multi-tenancy + managed Postgres-- **Competitive observation loop, pause-and-handoff to human, automatic post-mortems** — all post-V1-------## Deferred to backlog (v1.1+)--- **Competitive observation loop** — weekly competitor scan, response suggestions-- **Pause-and-handoff to human freelancer** — Loom-style brief export-- **Automatic post-mortems** when campaigns underperform (stretch; project memory makes this easy to add later)-- **Cross-project intelligence** — learnings from one brand inform another (carefully — competitive overlap risk for agencies)-- **Slack integration** — daily briefing in Slack channel-- **Mobile companion app**-------## Out of scope (explicitly)--- **Hosted SaaS** — local-only V1; if hosted demand emerges, separate product-- **Authentication** — local loopback, single user-- **Multi-tenancy** — no organizations, no roles, no RLS-- **Custom agent runtime** — OpenClaw owns-- **Custom memory layer** — OpenClaw memory owns-- **Custom cron scheduler** — OpenClaw cron owns-- **Custom pub/sub for signals** — OpenClaw memory (tagged entries) owns-- **Channel skills from scratch** — reuse existing MCPs (`notfair-googleads` already exists; curate SEO MCP)-- **Marketing site / brand identity** — OSS project; README + GitHub repo is the marketing site V1-- **Closed-source distribution** — open source by design-- **White-label / reseller** — OSS, users fork if they want--## Design specifications (V1)--### Design direction--**Locked: shadcn/ui defaults.** Zinc neutral palette, Inter font, default radii. No custom brand in V1. Defer brand work to post-GA via /design-consultation. AI slop avoidance even with defaults: no purple gradients, no icon-in-colored-circle decoration, no generic hero copy ("Welcome to notfair CMO!"), no centered-everything layouts, no decorative blobs.--### App shell--**Locked: Pattern A — persistent left sidebar + main area.**--```-┌──────────────────────────────────────────────────────────────────────┐-│ SIDEBAR (256px, collapsible to 56px <1024px) │ MAIN │-│ ┌──────────────────────────────────┐ │ │-│ │ [Logo] Project switcher ▾ │ │ Page content │-│ ├──────────────────────────────────┤ │ │-│ │ 🏠 Home (project dashboard) │ │ │-│ │ 💬 Chat with CMO │ │ │-│ │ ✅ Approvals ⓐ │ (badge on │ │-│ │ 📋 Tasks │ unread) │ │-│ │ ⏱ Crons │ │ │-│ │ 🔌 Connections │ │ │-│ │ ⚙ Settings │ │ │-│ ├──────────────────────────────────┤ │ │-│ │ COST METER (always visible) │ │ │-│ │ ▓▓▓▓▓░░░░ $124 / $300 today │ │ │-│ ├──────────────────────────────────┤ │ │-│ │ [User avatar] Account ▾ │ │ │-│ └──────────────────────────────────┘ │ │-└──────────────────────────────────────────────────────────────────────┘-```--Use shadcn `<Sidebar>` (already designed). Sidebar collapses to 56px icon rail below 1024px. Mobile (<768px) hides sidebar behind a hamburger; sheet/drawer overlay.--**Why not chat-first:** considered (Pattern B), rejected. Sidebar pattern is more legible to agency operators managing many things; chat-first risks burying tasks/approvals/crons behind a drawer where users miss them.--### Hard-cap state (app-wide)--When daily spend cap hits: red banner across top of every screen, dismissible only after raising cap or waiting until rollover. Pauses ALL autonomous agent actions. Approval inbox still works for manual override. Cost meter turns red. Surfaces in CMO chat as the next agent turn.--### Screen 1: Project Home (default landing after project select)--**Information architecture:**-```-┌─ TOP STRIP ─────────────────────────────────────────────────┐-│ Project name • period selector (7d / 30d / 90d) │-├─ PRIMARY: 3 KPI cards ──────────────────────────────────────┤-│ [Active campaigns] [Spend MTD] [Conversions MTD] │-├─ SECONDARY: Two columns ────────────────────────────────────┤-│ Recent CMO recommendations │ Pending approvals (top 3) │-│ (last 5 items) │ with [Review] link │-├─ TERTIARY: Agent status grid ───────────────────────────────┤-│ [Google Ads: 🟢 active, 4 crons] [SEO: 🟢 active, 2 crons]│-│ [GEO: 🔒 beta] [Cold Email: 🔒 beta] ... │-└─────────────────────────────────────────────────────────────┘-```--Hierarchy reasoning: a marketer landing here wants to know "is it working" first (KPIs), "what needs me" second (recommendations + approvals), "what's running" third (agent grid).--**Interaction states:**-| State | What user sees |-|---|---|-| Loading | shadcn `<Skeleton>` rectangles for each card; no spinners |-| Empty (new project) | KPI cards show "—"; CMO recommendations area shows full-width CTA "Start onboarding to see your first plan" |-| Error | Toast (shadcn `<Toaster>`) + per-card retry; KPIs that failed show "—" with retry icon |-| Success | Live numbers, recommendations clickable into chat with that thread, approvals clickable into inbox |-| Partial | Mix — some KPIs may load before others; render as they arrive, no blocking |--**Responsive:** KPI cards stack 1-column <768px. Recommendations/approvals stack <1024px.-**A11y:** `<main>` landmark, skip-to-content link, KPI cards announce value + label, focus order: project switcher → period selector → KPI 1-3 → recommendations → approvals → agent grid.--### Screen 2: CMO Chat--**Information architecture:**-```-┌─ CONTEXT STRIP (sticky top) ────────────────────────────────┐-│ Project X • SEO + Google Ads active • 3 tasks running │-├─ MESSAGE THREAD (scrollable) ──┬─ CONTEXT DRAWER (toggle)──┤-│ │ │-│ USER: Run a 30-day │ ACTIVE TASKS │-│ experiment to triple │ • Bid optimization │-│ our trial signups │ • SEO audit │-│ │ │-│ CMO: [streaming response] │ RECENT SIGNALS │-│ 📋 Created task "Audit │ • 12 users on Reddit │-│ current CPA" │ complaining about │-│ 📋 Created task "SEO │ competitor pricing │-│ opportunity scan" │ │-│ [Want me to proceed?] │ MEMORY INJECTED │-│ │ • ICP: B2B sales teams │-│ [Approve all] [Review each] │ • Voice: direct, no buzz │-│ │ │-├─ COMPOSER ─────────────────────┴───────────────────────────┤-│ [Message CMO...] [Send →] │-└─────────────────────────────────────────────────────────────┘-```--Use AI SDK `useChat` + chat-sdk reference components. Tool calls render inline as collapsible badges with status (running/done/failed). Context drawer is collapsed by default, toggle in top-right.--**Interaction states:**-| State | What user sees |-|---|---|-| Loading (first load) | Skeleton message; thread fetches in background |-| Empty (new project chat) | CMO greets first: "I've looked at your site. Here's what I recommend for your first 30 days. Want me to walk through it?" |-| Error (LLM failure mid-stream) | Inline error bubble with retry; partial message preserved |-| Streaming | Token-by-token render; tool calls appear as inline badges (yellow=running, green=done, red=failed) |-| Partial (tool call mid-flight) | Tool call badge spinning; message continues streaming around it |--**Responsive:** Context drawer hidden by default <1024px; toggle to reveal as sheet overlay. Composer stays sticky.-**A11y:** Live region (`aria-live="polite"`) for streamed messages, tool call status announcements, keyboard send (Enter), shift-Enter for newline.--### Screen 3: Onboarding Magic Moment--**Information architecture:**-```-┌─────────────────────────────────────────────────────────────┐-│ │-│ "Let's set up your CMO." │-│ │-│ [https://yourcompany.com ] [Go →] │-│ │-│ Or use one of our example sites: Acme, Plaid, Linear │-│ │-├─ PROGRESS (after URL submit) ───────────────────────────────┤-│ ● Scraping your site... (5s) │-│ ○ Deriving brand voice fingerprint (10s) │-│ ○ Drafting ICP hypothesis (15s) │-│ ○ Building your 30-day plan (20s) │-│ │-│ [Each step expands inline as it completes, showing preview]│-│ │-├─ FINAL: 30-day plan preview ────────────────────────────────┤-│ Week 1: Google Ads bid optimization on 12 keywords │-│ Week 1: SEO audit + 3 page content proposals │-│ Week 2: ... │-│ │-│ [Approve & launch] [Edit plan] [Save & decide later] │-└─────────────────────────────────────────────────────────────┘-```--Single column, max-width 720px, centered. Use shadcn `<Card>` for the progress steps. Live updates via SSE.--**Interaction states:**-| State | What user sees |-|---|---|-| Loading (initial) | Just the URL input; placeholder examples |-| Empty | Default state — input + example chips |-| Error (URL unreachable) | Inline error under input: "Couldn't reach that URL. Try https:// prefix or a different page." |-| Per-step running | Spinner + step name + elapsed time |-| Per-step error | Red icon + retry button + "Use placeholder" option (don't block whole flow) |-| Success (all steps done) | 30-day plan preview expanded; CTAs prominent |-| Partial (skipped step) | Step shows "Used placeholder for [thing]; CMO will refine over time" |--**Responsive:** Works at 375px; max-width breaks intelligently. Plan preview cards stack 1-col on mobile.-**A11y:** Progress announced as each step changes state; focus moves to "Approve & launch" when plan ready; error states announced.--### Screen 4: Approval Inbox--**Information architecture:**-```-┌─ TOP STRIP ─────────────────────────────────────────────────┐-│ Approvals (12) [All ▾] [Spend] [Content] [Settings] │-├─ CARDS (stacked) ───────────────────────────────────────────┤-│ ┌──────────────────────────────────────────────────────┐ │-│ │ [Google Ads] Increase bid for "marketing automation"│ │-│ │ Current: $4.20 → Proposed: $5.80 (+38%) │ │-│ │ Why ▾ Cost: ~$45/day Expected: 3-5 more conv/day │ │-│ │ │ │-│ │ [Approve] [Edit] [Reject] Created 5m ago by CMO │ │-│ └──────────────────────────────────────────────────────┘ │-│ ┌──────────────────────────────────────────────────────┐ │-│ │ [Cold Email] Send sequence to 47 new leads │ │-│ │ ... │ │-│ └──────────────────────────────────────────────────────┘ │-└─────────────────────────────────────────────────────────────┘-```--Use shadcn `<Card>` per item, `<Tabs>` for filter. "Why ▾" expands inline to show CMO's reasoning chain.--**Interaction states:**-| State | What user sees |-|---|---|-| Loading | Skeleton cards |-| **Empty (the most important state)** | Large, calm centered text: "All caught up. CMO will surface decisions here." Subtle subtext: "Items above your thresholds appear here for approval. Adjust thresholds in Settings." No CTAs — empty is the *goal*. |-| Error (action failed) | Per-card error banner + retry; card stays in inbox |-| Success (approved) | Card slides out with green toast: "Approved — running now" |-| Partial (some cards still loading details) | Card shows summary, expandable details show spinner |--**Responsive:** Cards stack natively. Buttons stay 44px+ tappable. Edit opens shadcn `<Dialog>` modal.-**A11y:** Each card is a `<region aria-label="...">`, buttons keyboard-accessible, edit dialog traps focus, escape closes.--### Screen 5: Cron Tab--**Information architecture:**-```-┌─ TOP STRIP ─────────────────────────────────────────────────┐-│ Scheduled work • [Project ▾] [Agent ▾] [+ New cron] │-├─ GROUPED LIST ──────────────────────────────────────────────┤-│ ▾ Google Ads agent (4 active) │-│ ┌────────────────────────────────────────────────────┐ │-│ │ Name Schedule Last Next Status │ │-│ ├────────────────────────────────────────────────────┤ │-│ │ Daily bid opt 09:14 daily 9h ago 15h 🟢 ok │ │-│ │ Hourly metrics hourly 45m ago 15m 🟢 ok │ │-│ │ Negative kw... Mon 06:00 2d ago 5d ⚠ warn │ │-│ │ Budget pacing :30 hourly 20m ago 10m 🟢 ok │ │-│ └────────────────────────────────────────────────────┘ │-│ ▾ SEO agent (2 active) │-│ ┌────────────────────────────────────────────────────┐ │-│ │ Weekly rank check Mon 06:14 3d ago 4d 🟢 ok │ │-│ │ Daily content idea 09:23 daily 9h 15h 🟢 ok │ │-│ └────────────────────────────────────────────────────┘ │-└─────────────────────────────────────────────────────────────┘-```--Each row click expands to show last 7 runs + pause/resume/delete actions. Schedule shown in human-readable form, not raw cron syntax (use cronstrue). Times in user's local timezone.--**Interaction states:**-| State | What user sees |-|---|---|-| Loading | Skeleton table rows |-| Empty per agent | "No scheduled work for [agent]. Ask CMO to schedule something." |-| Empty whole tab | "No crons yet. CMO and specialists schedule work here when they need recurring jobs." |-| Error per row | Row shows ⚠ icon + tooltip; click for detail + reschedule action |-| Status: missed run | Row shows ⚠ + "Missed last run, see history"; click expands history |-| Success | Live status updates from OpenClaw via SSE |-| Hard halt (project archived mid-flight) | All rows show "halting..." then disappear; toast confirms |--**Responsive:** Collapse table to stacked card list <768px; each cron becomes a card with project+agent labels inline.-**A11y:** Table is a proper `<table>` with `<th scope="col">` headers; sortable; keyboard nav between rows; expandable rows announce state.--### Cross-cutting: Cost meter (sidebar persistent component)--**States:**-| State | Visual |-|---|---|-| Under 50% budget | Zinc bar, white text, no flag |-| 50-75% | Same, slight emphasis on number |-| 75-90% | Amber bar |-| 90-100% | Red bar + "Approaching cap" tooltip on hover |-| At/over cap | Solid red + "HALTED" label + clickable → opens cap settings |--Click anywhere on the meter → opens detailed cost panel: breakdown by source (LLM by agent, ad spend by channel), historical 7-day chart, edit cap.--### Cross-cutting: Activity log--Every autonomous action by every agent gets an entry in a per-project `agent_actions` log. Accessible from settings or via "Why?" command in chat. Each entry: timestamp, agent, action, cost, outcome, reasoning summary, [undo if applicable]. Builds the trust foundation that the autonomy promise depends on.--### User journey emotional arc--| Step | User does | User feels | Plan supports it via |-|---|---|---|---|-| 1 | Lands on signup | Curious, skeptical | Clean, no marketing fluff; "Sign in with Google" prominent |-| 2 | Creates first project | Hopeful | Onboarding magic moment loads fast, paste-URL is one field |-| 3 | Watches CMO build first plan | "Is this actually smart?" | Live step progress, real previews per step (not just spinners) |-| 4 | Approves first plan | "I'm committing money to this" | Plan shows projected cost + cap visible + "you can pause anytime" |-| 5 | Returns next day | "Did anything happen?" | Project home shows yesterday's results, CMO chat top-of-mind |-| 6 | Sees first approval | "Wait, what is it doing?" | Approval inbox card has "Why?" prominently; reasoning is concrete |-| 7 | Sees first results | Relief, validation | KPI card shows delta vs last period; "your CMO did this" attribution |-| 8 | Day 30 | Sticky | Project memory shows compounding learning; switching costs feel real |--The most emotionally-charged moments are (3) and (6) — the trust-building moments. Both have explicit UX investment: live previews during build, concrete reasoning per approval.--### Responsive breakpoints--- `<640px` (mobile): single column, sidebar as bottom sheet via hamburger, tables → cards, max 1 KPI per row-- `640-1023px` (tablet): sidebar collapses to icon rail, KPIs 2-up, tables OK-- `≥1024px` (desktop): full sidebar, KPIs 3-up, chat context drawer visible--### Accessibility baseline--- All interactive elements ≥44px touch target-- Color contrast ≥4.5:1 for body text (shadcn defaults pass)-- Keyboard navigable: all screens fully usable without mouse-- Focus visible: shadcn `focus-visible` rings respected-- Live regions: chat messages, approval status changes, cost meter state changes-- Skip-to-content link in every layout-- ARIA landmarks: `<header>`, `<nav>`, `<main>`, `<aside>` for sidebar context drawer-- Forms: labels visible, never placeholder-as-label-- Hard-cap banner: `role="alert"` so screen readers announce immediately--## Design decisions deferred (intentionally)--- **Brand identity** — typography, color palette, illustration style, motion language → /design-consultation post-GA-- **Marketing site / landing page** — V1 ships product-first; marketing site is separate work-- **Specialist agent chat detail design** — inherits CMO chat layout; revisit per-agent unique tools-- **Settings page detail** — inherits standard shadcn form patterns; revisit when autonomy config gets more dimensions-- **Connection manager detail** — inherits OAuth-button + connected-account-card pattern; revisit per channel--## Wheel-rebuilding audit (post-pivot, post-OpenClaw-spike)--Per the guiding tenet, every custom thing must be justified. Updated after live OpenClaw capability spike:--| Component | Verdict | Reasoning |-|---|---|---|-| Agent runtime | ✅ NOT REBUILDING | `openclaw agents add` per project + template |-| Agent memory | ✅ NOT REBUILDING (was building!) | `openclaw memory` (search, REM, promote, index) — full subsystem, fully replaces our planned pgvector |-| Cron scheduler | ✅ NOT REBUILDING | `openclaw cron` (add/list/edit/runs/show/status) — has agent attribution + name + description metadata |-| Signal pub/sub | ✅ NOT REBUILDING (was building!) | Tagged memory entries (`signal:opportunity`, `signal:risk`) discoverable via `memory search` — eliminates need for Postgres LISTEN/NOTIFY |-| Auth | ✅ NOT REBUILDING (was building!) | Local loopback, no auth needed; OpenClaw gateway runs `--auth none --bind loopback` |-| Multi-tenant DB isolation | ✅ NOT REBUILDING (was building!) | Single user, single SQLite file, no RLS, no envelope encryption per tenant |-| Webhook signing/reconciliation | ✅ NOT REBUILDING (was building!) | Loopback only, trusted; agent state is OpenClaw's source of truth, we read on demand |-| Chat UI | ✅ NOT REBUILDING | AI SDK `useChat` + chat-sdk patterns |-| Channel skills | ✅ NOT REBUILDING | Existing `notfair-googleads` MCP + new curated SEO MCP |-| Hosting/deploy infra | ✅ NOT REBUILDING (was building!) | Local Next.js standalone build, no Vercel |-| AI Gateway tenancy | ✅ NOT REBUILDING (was building!) | User's own LLM API key directly to provider; AI SDK reports usage |-| **Local SQLite for our state** | ✅ JUSTIFIED CUSTOM | Tasks/approvals/cost events/oauth tokens/project metadata are notfair-CMO-specific; OpenClaw doesn't model them |-| **MCP server exposing our tools** | ✅ JUSTIFIED CUSTOM | `approve_action`, `record_cost`, `log_action`, `query_project_state` etc. are notfair-CMO-specific; how OpenClaw agents reach our state |-| **OAuth flows + token storage** | ✅ JUSTIFIED CUSTOM | Localhost callback flow + OS-keychain-encrypted SQLite storage. OpenClaw doesn't manage external API OAuth tokens for our purpose |-| **Project concept (name-prefix grouping)** | ✅ JUSTIFIED CUSTOM | OpenClaw is flat-namespaced; project = our UX concept layered on top via consistent agent/cron name prefixes |-| **CLI launcher (`npx notfair`)** | ✅ JUSTIFIED CUSTOM | Distribution; no off-the-shelf option fits |-------## Protocol definitions (post-pivot — MCP-based, OpenClaw-native)--### Our MCP server: tools exposed to OpenClaw agents--Our Next.js runs an MCP server (stdio when the agent invokes via OpenClaw runtime, or HTTP-over-loopback for the gateway-mode setup). Registered with OpenClaw via `openclaw mcp set NotFair '{ ... }'`. Every project's CMO + specialist agents are configured to load this MCP.--Tools:-- `assign_task(project_slug, specialist_agent_id, brief, success_criteria, deadline_iso)` → `{task_id}`. Creates row in our SQLite `tasks` table. Returns task_id. Specialist picks up the brief by querying task status at next turn or via cron trigger.-- `query_task_status(task_id)` → `{status, latest_result, agent_id}`. Reads our SQLite.-- `update_task_status(task_id, status, result?, error?)` → `{ok: true}`. Specialist agents call when finishing.-- `cancel_task(task_id, reason)` → `{cancelled: bool}`.-- `approve_action(action_summary, cost_estimate_usd, type, agent_id)` → `{approved: true}` if within guardrails, else `{approved: false, approval_id}` and the agent waits/exits and retries later when approval comes in.-- `record_cost(amount_usd, source, project_slug, agent_id, ref?)` → `{ok: true}`. Source = `llm|google_ads|gsc|...`. Used by cost meter.-- `log_action(agent_id, action_type, summary, reasoning, payload?)` → `{ok: true}`. Append-only audit log; powers "Why?" in chat.-- `query_project_state(project_slug)` → `{guardrails, recent_signals, active_tasks, cost_today}`. Cheap aggregate query agents call at turn start.-- `emit_signal(project_slug, source_agent_id, signal_type, summary, evidence, confidence)` → writes structured memory entry tagged `signal:<type>` via `openclaw memory` write (or shell out). Specialists discover via memory search at next turn.-- `get_oauth_credentials(provider, project_slug)` → decrypts + returns the access token + handles refresh-if-near-expiry. Agents never see refresh tokens directly.--### CMO ↔ specialist orchestration (no custom protocol; uses MCP)--CMO is an OpenClaw agent. When user chats:-1. Our Next.js receives message, calls `openclaw agent --agent <project-slug>-cmo --message "..." --json` (or via WebSocket Gateway for streaming).-2. CMO agent runs its turn, can call our MCP tools (`assign_task`, `approve_action`, etc.) and OpenClaw's native tools (`memory search`).-3. When CMO calls `assign_task(specialist, brief)`, our tool creates SQLite row, returns task_id, AND triggers the specialist agent via either:- - `openclaw agent --agent <project-slug>-<specialist> --message "TASK <task_id>: <brief>"` (synchronous, if user is waiting)- - `openclaw cron add ... --at +1m` (deferred, if user can wait)-4. Specialist agent reads brief from its message, optionally fetches latest task state via `query_task_status`, executes, calls `update_task_status` when done.-5. CMO sees result on next user turn via `query_task_status` (we inject "tasks updated since last turn: ..." into context).--No webhooks needed for V1: loopback subprocess calls are synchronous; the UI updates via polling our SQLite or via SSE that reads our `tasks` table on change.--### Signal sharing: tagged memory entries--When specialist agents observe something useful, they call `emit_signal(...)`. Our tool writes a structured memory entry via OpenClaw memory:-```-agent: <project-slug>-<specialist>-tags: signal, signal:<type>, project:<project-slug>-body: |- summary: <one-liner>- evidence: <json>- suggested_actions: [{target_agent: seo, brief: "..."}]- confidence: 0.8- ttl_until: 2026-05-24T00:00:00Z-```--Other agents in the project discover via `openclaw memory search "signal:" --agent <project-slug>-*` at task start or as a "morning brief" routine for the CMO.--### Autonomy / approval threshold model (unchanged from pre-pivot, simpler enforcement)--Same threshold schema. Enforcement: every spending agent action MUST first call `approve_action(...)`. Our tool checks SQLite `guardrails` table; if within thresholds → returns `{approved: true}` immediately. If above → writes to `approvals` queue, returns `{approved: false, approval_id}`, agent exits gracefully. When user approves in UI, we fire a webhook (loopback) to OpenClaw gateway: `openclaw agent --agent <project>-<specialist> --message "RESUME approval_id=<id>"`. Agent re-runs the action.--```yaml-# Stored as JSON in SQLite guardrails table-autonomy:- max_daily_spend_usd: 200- max_concurrent_experiments: 3- require_approval_above:- spend_per_action_usd: 50- new_channel_first_action: true- content_publishing: true- bid_changes_percent: 25- audience_change: true- fully_autonomous:- keyword_pause: true- budget_reallocation: true- ab_test_winner_selection: true- negative_keyword_add: true-```--### Cron management (OpenClaw native + project-prefix naming)--Tenet: OpenClaw cron is the source of truth. Our value-add is project attribution + UI grouping.--**Naming convention** (simplified — no account level since single user):-```-<project-slug> / <agent-slug> / <cron-slug>--Example: acme-q4 / google-ads / daily-bid-opt-```--Constraints:-- Lowercase, alphanumeric + hyphens; spaces and `/` allowed as visual separators-- Slugs immutable once created (decoupled from project display name)-- Total length: OpenClaw shows full name in cron list — keep readable, no hash truncation needed at this length--**Operations (wrappers over `openclaw cron` CLI):**-- Create: `openclaw cron add --name "<proj> / <agent> / <name>" --description "..." --agent <project-slug>-<agent-slug> --cron "..." --message "RUN <task_id>: <brief>" --json`-- List: `openclaw cron list --json`, filter client-side by name prefix-- Halt: `openclaw cron disable <id>`-- Delete: `openclaw cron rm <id>`-- Run history: `openclaw cron runs <id> --json`-- Update: `openclaw cron edit <id> --cron "..." --message "..."`--**Frontend cron tab:**-- Calls `openclaw cron list --json` via our backend-- Groups by project (parsed from name prefix); within project, groups by `--agent` column (which OpenClaw already provides)-- Per-row actions forward to the CLI commands above-- Per-row click: shows last 7 runs from `openclaw cron runs <id>`--**Autonomy + crons:** cron creation goes through `approve_action` if cron count > cap or if cron is content-publishing.--### Task lifecycle (unchanged, stored in our SQLite)--States: `proposed` → `approved` → `running` → (`succeeded` | `failed` | `cancelled`)--Tasks live in our SQLite `tasks` table. OpenClaw agents reference them by task_id in messages and in cron `--message` payloads. State transitions via the MCP tools.-------## Architecture decisions (revised for local OSS, post-OpenClaw-spike)--1. **CMO loop: OpenClaw agent per project.** `openclaw agents add <project-slug>-cmo` with our MCP server attached. CMO calls our tools via MCP (zero HTTP roundtrips — stdio). Specialist agents same pattern: `<project-slug>-google-ads`, `<project-slug>-seo`.-2. **No auth.** Local loopback only. OpenClaw gateway started with `--auth none --bind loopback`. Our Next.js binds to 127.0.0.1 only. No Clerk. Settings page is single-user; no roles, no permissions.-3. **Storage: SQLite via better-sqlite3.** Single file at `~/.notfair/db.sqlite`. Tables: `projects`, `tasks`, `approvals`, `cost_events`, `oauth_tokens`, `guardrails`, `agent_actions`. No pgvector — memory is OpenClaw's job.-4. **Long-running work: OpenClaw cron + cursor in our SQLite.** Cold email sequences = a cron that runs the agent every N minutes; agent reads `cursor` from our `sequence_runs` table, processes next chunk, updates cursor, exits. Same pattern as before but now OpenClaw is running, not Vercel — no 300s timeout pressure (OpenClaw can run longer turns), but pattern is unchanged for resilience.-5. **Inter-process integration: subprocess + MCP.** Three integration surfaces with OpenClaw:- - **CLI subprocess** for management ops (`agents add`, `cron add/list/edit/rm`, `memory search/index`): spawn `openclaw <cmd> --json`, parse stdout. Wrapped in `apps/web/lib/openclaw/cli.ts`.- - **WebSocket Gateway** for agent invocation with streaming (`openclaw gateway` running; we connect via `ws://localhost:<port>`). Wrapped in `apps/web/lib/openclaw/gateway.ts`.- - **MCP server** (we run) exposing our tools to OpenClaw agents. Registered once at install via `openclaw mcp set NotFair '{...}'`. Implementation in `apps/web/lib/mcp-server/`.-6. **OAuth: localhost callback + OS-keychain master key.** Localhost redirect (Google Ads + GSC accept this for desktop apps). Master key generated on first launch + stored in OS keychain via `keytar`. OAuth tokens AES-256-GCM encrypted with this key, stored in SQLite. Refresh handled by a single function called before any agent action; no cron needed.-7. **Real-time UI: SSE from our Next.js to browser, gateway WebSocket from Next.js to OpenClaw.** Chat uses AI SDK streaming through our Next.js (which proxies to gateway WS). Task board / approvals / cron tab updates via SSE that listens to a local pub/sub (Node `EventEmitter` is sufficient — single-process).-8. **Distribution: npm package + standalone Next.js build.** `notfair` package exports a CLI bin. CLI uses `next start` against a pre-built `.next/standalone` directory. Targets Node 20+. No native deps beyond `better-sqlite3` and `keytar` (both have prebuilds for major platforms).-9. **No monorepo.** Single-package npm project. TypeScript types live in `src/types/` and are imported via relative paths. (Monorepo was needed when CMO ran in OpenClaw with separate tool definitions; now everything is in our Next.js codebase or in OpenClaw config.)-10. **Project = name-prefix grouping.** Project slug is the prefix on OpenClaw agent names and cron names. Project metadata (display name, slug, created_at, archived_at) lives in our SQLite. Archive = mark archived + disable all matching crons + optionally remove agents.--## Code conventions (adopt from line 1)--1. **`withProjectScope(handler)` middleware** at `src/server/with-project-scope.ts`. Wraps every API route that takes a project param. Validates project exists + not archived, attaches project metadata, returns standard error envelope on failure. NO auth check (no auth).-2. **`defineMcpTool({name, schema, handler})` factory** at `src/server/mcp-server/define-tool.ts`. Single source of truth for our MCP tools: Zod schema validation, structured logging, audit log entry to `agent_actions`, standard error envelope. Every tool registered through it.-3. **Single slugification utility** at `src/lib/slug.ts`. `slugify(input, maxLen)` → kebab-case, ASCII, length-capped, validated against reserved words. Used by project/agent/cron name.-4. **Standard error envelope** in `src/types/errors.ts`: `{ok: false, error_code, message, retryable, user_message}`. All MCP tools return this shape on error so agents have predictable handling.-5. **`openclaw()` wrapper** at `src/server/openclaw/cli.ts`. Single function: `openclaw(args: string[]) → Promise<JsonValue>`. Spawns subprocess with `--json` flag, parses stdout, throws structured error on stderr. Every interaction with OpenClaw CLI goes through this.-6. **`OpenClawGateway` class** at `src/server/openclaw/gateway.ts`. Singleton; lazy-connects to `ws://localhost:<port>`; reconnects on drop. Streaming chat goes through here.-7. **ASCII state diagram inline in `tasks` schema file.** 5-state lifecycle (proposed → approved → running → succeeded/failed/cancelled) deserves a diagram in code comments next to the SQLite schema.-8. **Single-file SQLite migrations** in `src/server/db/migrations/`. Sequential numbered (`001_init.sql`, `002_add_oauth.sql`). Auto-applied on startup; no separate migration command. No down-migrations (forward-only).--## Test strategy (V1 ship gate)--### Coverage diagram--```-CODE PATHS USER FLOWS / E2E-[+] CMO orchestration loop [+] Onboarding (URL → first plan)- ├── tool: assign_task ├── [→E2E] paste URL → scrape → voice →- │ [→EVAL] right specialist + brief shape │ ICP → 30-day plan rendered- │ [GAP] invalid agent_type rejection └── [→E2E] approve plan → first task runs- │ [GAP] deadline-in-past rejection [+] Project isolation (security-critical)- ├── tool: query_task_status ├── [→E2E] User A cannot read User B's- │ [GAP] 200 OK valid task │ project data via any endpoint- │ [GAP] 404 cross-project └── [→E2E] User A cannot list/halt- ├── tool: schedule_recurring_work │ User B's crons- │ [GAP] cap enforcement + approval inbox [+] OAuth flows- │ [GAP] content-publishing always needs apr ├── [→E2E] Google Ads connect → token- ├── tool: query_signals + query_memory │ stored encrypted → agent uses- │ [GAP] project-scoped, no cross-project │ token → token refresh- │ [GAP] ttl + consumed_by filtering └── [→E2E] GSC connect (same)- └── [→EVAL] CMO weekly briefing quality [+] Cron lifecycle- ├── [→E2E] create → fires → archive-[+] Signal bus │ project → cron halted- ├── [GAP] publish + LISTEN dispatch └── [→E2E] orphan detection- ├── [GAP] ttl expiry filters from query [+] Autonomy guardrails- └── [GAP] confidence scoring honored ├── [→E2E] daily spend cap actually halts- └── [→E2E] action above threshold → approval-[+] OAuth vault (security-critical) inbox, not executed- ├── [GAP] encrypt at rest, decrypt for use [+] Cost meter- ├── [GAP] per-project key derivation └── [→E2E] spend visible + hard cap halts- ├── [GAP] refresh before expiry- └── [GAP] cross-project key isolation EVALS (critical, V1 gate)- ├── [→EVAL] CMO orchestration: 20 scenarios;-[+] Approval inbox + autonomy thresholds │ gate on right specialist + brief- ├── [GAP] every require_approval_above rule ├── [→EVAL] Brand voice fingerprint: derive- │ catches the action │ then generate; human review- └── [GAP] approved item executes; rejected halts matches source voice- └── [→EVAL] CMO weekly briefing quality--V1 ship gate: all E2E + EVAL paths green-```--### Eval harness (light, V1)--- `packages/evals` workspace with 20 curated scenarios at V1-- Scenario shape: project context + user message → assert right specialist + brief shape + no obvious errors-- Runs in CI on every PR touching CMO prompts or orchestration logic-- Gates CI on regression vs baseline (no merge if scenarios that passed yesterday fail today)-- Uses AI SDK + AI Gateway; budget ~$0.50 per full eval run-- Expand to 100+ scenarios + LLM-as-judge quality scoring post-GA--### Project-isolation harness--- Test helper `withTwoProjects(testFn)` spins up Project A (user A) + Project B (user B)-- Every API route test must include cross-project access test-- Static lint rule: any route handler test file without a `cross-project` test fails CI--### OAuth E2E uses real provider sandboxes--- Google Ads sandbox + GSC sandbox accounts maintained for V1-- Don't mock the OAuth dance — Google's verification cycle means we validate the real flow early-- E2E runs nightly + on PR touching OAuth code--## Performance notes (V1)--1. **pgvector: HNSW index, single index with `project_id` filter column.** Better recall than IVFFlat at low volumes; memory tradeoff fine at V1. Re-evaluate at 100k+ projects.-2. **AI Gateway caching aggressive on deterministic prompts.** Brand voice fingerprint, ICP analysis, post-mortems have stable inputs → 7-day cache TTL. Saves real money + speeds onboarding.-3. **Cron jitter at creation time.** Add random 0-59 min offset per cron to spread "9am daily" across the hour. One-line fix at create; saves an incident later.-4. **CMO chat SLOs:** first-token <2s, full-turn <10s for ≤5 tool calls. Measure post-spike. If OpenClaw → Next.js roundtrip >300ms, add `batch_tool_calls([...])` so CMO issues parallel queries in one roundtrip.--## Failure modes (V1, post-pivot)--| Codepath | Failure | Test | Handling | User sees |-|---|---|---|---|---|-| CLI launch | OpenClaw not installed/running | doctor cmd | `NotFair doctor` runs at startup; surfaces clear install instructions if missing | Terminal output: "OpenClaw not running. Start it with `openclaw gateway` then retry." |-| CLI launch | Port already in use | Unit | Try N+1 up to 5 times; surface chosen port | "NotFair running on http://localhost:3247 (3000 was busy)" |-| CMO turn | OpenClaw subprocess fails | Integration | Catch, retry once with backoff; surface error to UI | "Couldn't reach agent. Try `openclaw doctor` in another terminal." |-| MCP tool call | Tool throws unexpectedly | Unit | `defineMcpTool` wraps in try/catch, returns standard error envelope | Agent sees structured error, retries or surfaces to user |-| `approve_action` | Race: two agents check cap simultaneously | Unit | SQLite transaction with `BEGIN IMMEDIATE` around check+record | Second action sees updated state, halts correctly |-| Cron tick | OpenClaw cron fires while our app not running | Manual + integration | OpenClaw runs autonomously; cron triggers agent which calls our MCP. If our MCP server unreachable, agent fails gracefully and OpenClaw records as failed run. Next user open shows failed cron. | Cron tab shows ⚠ on failed runs; click for retry |-| OAuth refresh | Refresh token revoked | Unit + manual | Mark credential as `needs_reauth`; agent calls to `get_oauth_credentials` return error envelope; UI banner | "Reconnect your Google Ads account" banner in Connections page |-| Cost meter | Cost event missed (agent crashed before reporting) | Manual | Underreport possible but bounded; doctor cmd cross-checks against OpenClaw logs | Slight cost lag possible; doctor surfaces drift |-| SQLite | DB file corrupted | Manual | better-sqlite3 detects on open; backup auto-restored from `db.sqlite.bak` if recent | "Restored from automatic backup (data from <time>)" |-| Project archive | In-flight cron mid-tick | Integration | Archive halts crons via `openclaw cron disable` loop; in-flight ticks complete; new ticks blocked | Archive progress: "halting 12 crons..." then done |-| OS keychain | Locked / unavailable | Unit | Surface error at startup; offer fallback (password prompt for master key) | "Unlock your keychain to use stored OAuth credentials" |--**Critical gaps:** None at V1 plan stage. Failure modes mostly simpler than pre-pivot since loopback + single-process eliminates classes of distributed-system failures.--## Implementation lanes (parallel-friendly)--Plan implementation in 3 lanes, all parallel:--| Lane | Workstream | Files | Depends on |-|---|---|---|---|-| **A (parallel)** | CLI + UI shell: package.json + bin/cli.ts + sidebar shell + project CRUD + SQLite schema | `package.json`, `bin/`, `src/app/(shell)/`, `src/server/db/` | — |-| **B (parallel)** | OpenClaw integration: CLI subprocess wrapper + gateway WS client + MCP server scaffold | `src/server/openclaw/`, `src/server/mcp-server/` | — |-| **C (parallel)** | CMO chat UI + AI SDK integration + first agent template (Google Ads via existing MCP) | `src/app/api/chat/`, `src/components/chat/`, `src/server/agent-templates/` | — |--After all 3 land: lane D integrates them — onboarding flow + approval inbox UI + cron tab UI + cost meter + OAuth flow for Google Ads + SEO MCP curation.--No conflict flags — different file trees per lane.--## Still deferred (handle in implementation or post-V1)--- **Concrete SQLite schema DDL** — draft during lane A; refine as features land. Migrations are forward-only single SQL files.-- **Telemetry endpoint + opt-in UX** — design + ship in V1.1 once we have an OSS user base to measure-- **Standalone binary distribution** (Tauri/pkg) — V1 ships npm only; revisit if user feedback says install friction is real-- **Multi-machine sync of projects** — use Tailscale + OpenClaw's remote-gateway mode; post-V1-- **SEO MCP curation** — V1 needs a curated SEO MCP. Either build inline during lane C/D, or vendor from an existing OSS source. Decide during scaffolding.-------## OpenClaw capabilities spike — COMPLETED 2026-05-17--Live spike against the running OpenClaw v2026.5.7 install on user's machine. All results passed; full findings in [[openclaw-capabilities]] memory file. Summary:--| Capability | Status | Notes |-|---|---|---|-| Isolated agents per workspace | ✅ | `openclaw agents add <name> --workspace <dir> --model <id>` — existing install has agents `main` + `supa` |-| Cron with metadata + run history | ✅ | `openclaw cron add` accepts `--name`, `--description`, `--agent`, `--cron`/`--every`, `--message`, `--session-key`, `--tools`, `--tz`. List shows ID/Name/Schedule/Next/Last/Status/Target/Delivery/Agent ID/Model. `cron runs <id>` shows history. |-| Memory subsystem | ✅ | `openclaw memory search/index/promote/REM`. Per-agent by default. Has REM (reflective episodic memory) with deep promotion to MEMORY.md. |-| MCP server registration | ✅ | `openclaw mcp set/list/show`. Existing install already has `notfair-googleads` MCP registered. |-| WebSocket Gateway | ✅ | `openclaw gateway` configurable auth (none/token/password/trusted-proxy), bind (loopback/lan/tailnet). |-| Tool-calling via MCP | ✅ | Agents call MCP-registered tools natively. |-| Long-running work | ✅ via cron chunks | Crons with `--every` reawaken agents; combined with our SQLite cursor pattern. |-| Channels (Telegram/Slack/iMessage/etc) | ✅ (bonus) | Existing install has iMessage + Slack + Telegram configured. Crons can deliver to channels via `--announce`. Out of V1 scope but available for power users. |--**No hard blockers found.** Spike validated the architecture. No further validation needed before scaffolding.-------## Success criteria (V1 ship readiness)--- `npx notfair` works on fresh macOS + Linux + WSL machine where OpenClaw is installed-- Solo founder can complete onboarding (URL → first plan) in <5 minutes-- CMO can launch and monitor a Google Ads campaign within guardrails (using user's connected Google Ads account)-- CMO can launch SEO work (audit, content recommendations) and surface signals consumed by Google Ads agent on next turn-- CMO + specialist agents can schedule recurring work via `openclaw cron`; cron tab shows them grouped by project + agent-- Cost meter always visible; hard cap actually halts spending-- Approval inbox catches all `require_approval_above` events; no false negatives in test-- Archive a project → all of its OpenClaw crons disabled, agents optionally removed-- GitHub repo: README + ARCHITECTURE + CONTRIBUTING + LICENSE-- npm package published; install instructions verified--**Stretch (validate but don't gate):** project memory measurably improves agent output between week 1 and week 4 (requires eval harness + 4 weeks wall-clock; design harness now)-------## Risk register (post-pivot)--| Risk | Likelihood | Impact | Mitigation |-|------|-----------|--------|-----------|-| Users don't have OpenClaw installed | High | High | `doctor` command surfaces install instructions; README leads with OpenClaw prereq; consider bundling OpenClaw install script as part of `NotFair install` |-| OpenClaw version drift breaks our subprocess wrapper | Med | High | Test against multiple OpenClaw versions in CI; record min-supported version; fail fast with clear error |-| Google Ads OAuth complexity (localhost callback edge cases) | Med | Med | Use Google's standard desktop-app OAuth flow; document well; provide troubleshooting in doctor |-| User runs out of disk for SQLite/memory growth | Low | Med | Default cap on memory entries per agent; quarterly cleanup cron; doctor shows db size |-| CMO autonomy generates user fear ("it spent my money!") | High | High | Hard caps + always-visible cost meter + approval inbox for big actions + activity log + dry-run mode |-| LLM costs surprise user | Med | Med | Cost meter visible; daily cap with hard halt; AI SDK reports per-call usage |-| MCP tools become a security hole (e.g., shell-injection via cron payload) | Med | High | Strict Zod validation on every MCP tool input; no shell-out from MCP tool bodies; security audit before V1 |-| OSS user base hostile (license complaints, telemetry pushback) | Med | Low | MIT/Apache license, telemetry opt-in only, README addresses both upfront |-| `keytar` not available on user's OS | Low | High | Fallback to encrypted file with prompt-based password on every launch; doctor surfaces fallback mode |-| Single-process EventEmitter pub/sub doesn't scale | Low | Low | Single user, single project active at a time — won't hit limits in V1 |-------## Recommended next steps (post-pivot)--1. **Scaffold the project** — `pnpm create next-app NotFair`, set up directory structure (`src/server/`, `src/app/`, `src/types/`, `bin/`), install deps (`ai`, `@ai-sdk/openai`, `@ai-sdk/anthropic`, `better-sqlite3`, `keytar`, `zod`, `commander`, shadcn-cli), set up `package.json` with `bin` entry.-2. **Doctor command** — `bin/cli.ts doctor` that verifies OpenClaw is installed + running + accessible. Build first; surfaces what's missing for users.-3. **OpenClaw CLI wrapper** — `src/server/openclaw/cli.ts` with `openclaw(args)` function. Cover the operations we need (agents add/list, cron add/list/disable, memory search, mcp set).-4. **SQLite schema + migrations** — `src/server/db/migrations/001_init.sql` with `projects`, `tasks`, `approvals`, `cost_events`, `oauth_tokens`, `guardrails`, `agent_actions`, `sequence_runs`.-5. **MCP server skeleton** — `src/server/mcp-server/` with `defineMcpTool` factory + stub implementations of the 9 tools.-6. **Sidebar shell + project CRUD UI** — Lane A.-7. **CMO chat UI + first agent template** — Lane C (after lanes A + B partially landed).-8. **Onboarding magic moment + approval inbox + cron tab + cost meter** — Lane D.-9. **README + ARCHITECTURE + CONTRIBUTING + LICENSE** — before any GitHub push.-10. **npm publish workflow + initial release as v0.1.0**.-------## Spec-review log--- Initial plan written 2026-05-17-- Independent adversarial review: 6/10, surfaced scope/protocol/feasibility gaps-- Revision 1: cut V1 from 6 channels to 2, deferred D4 agency mode to v1.1, added protocol definitions (CMO↔specialist tool-calling, signal envelope schema, autonomy threshold model, task lifecycle), restructured OpenClaw spike with fallback plan, marked memory-improvement criterion as stretch-- Revision 2: added "don't rebuild the wheels" as guiding tenet, added cron management as V1 item (OpenClaw-backed via naming convention `notfair-<account-slug>-<project-slug>-<agent-slug>-<cron-slug>` with immutable slugs decoupled from display names), added wheel-rebuilding audit table, extended CMO orchestration tools with `schedule_recurring_work` + `query_scheduled_work`, extended OpenClaw spike with cron capability checks-- Revision 3 (eng-review): locked 8 architecture decisions (CMO in OpenClaw, Clerk, cron-driven chunks for long-running work, HMAC webhooks + idempotency + reconciliation, AES-256-GCM OAuth vault, AI SDK streaming + SSE, pnpm monorepo + `@notfair/types`), added 5 code conventions, added test strategy (coverage diagram + light eval harness + project-isolation harness + real OAuth sandboxes), added performance notes, added failure modes table, added worktree parallelization lanes-- Revision 4 (design-review): locked shadcn defaults + no brand in V1, locked Pattern A app shell (sidebar + main), added complete design specs for 5 screens (Project Home, CMO Chat, Onboarding, Approval Inbox, Cron Tab) + cost meter + activity log, defined interaction states per screen, defined responsive breakpoints, defined a11y baseline, defined user journey emotional arc-- **Revision 5 (PIVOT, 2026-05-17): open-source local CLI tool.** Major scope adjustment after user pivot. Eliminated: auth (Clerk), multi-tenancy, hosted Postgres + pgvector, Vercel deployment, AI Gateway tenancy, webhook signing infrastructure, per-tenant envelope encryption, D4 agency mode entirely, OAuth verification calendar wait. Leveraged after live OpenClaw spike: OpenClaw memory (replaces pgvector), OpenClaw cron (already had it but now no naming convention needed beyond project prefix — OpenClaw tracks agent + name + description natively), OpenClaw agents (workspace per agent), MCP server pattern (how we expose tools to OpenClaw agents). New scope: npm CLI launcher, local SQLite, OS-keychain master key for OAuth, doctor command, GitHub OSS repo. V1 effort revised: ~1-2 weeks CC. All architecture, code conventions, protocol definitions, failure modes, risk register, recommended next steps revised. Design specs unchanged (UI doesn't depend on runtime).-- **Revision 6 (2026-05-17): defer MCP-from-agents to v1.1.** User decision: skip wiring the MCP server into OpenClaw agents for V1. The 12 MCP tools remain built and registered (the server runs) but agents do not call them mid-turn. V1 becomes an "agent runner + chat portal" rather than the orchestrated-CMO product. Drops from critical path: CMO orchestration loop verification, `get_oauth_credentials` runtime path, `emit_signal` → OpenClaw memory integration, `approve_action`-driven autonomy enforcement, MCP server auto-registration. Re-promoted to V1: backend-driven cron creation UI (user clicks "Schedule recurring work" on an agent → our API calls `openclaw cron add` directly), manual approval queue (placeholder for v1.1), zero-cost meter default (real cost tracking comes with MCP). Re-framed V1 promise: "talk to an OpenClaw agent scoped to a marketing project, schedule recurring work, manage cron jobs cleanly." Full CMO orchestration promise moves to v1.1.diff --git a/notfair/README.md b/notfair/README.mddeleted file mode 100644index dcf6f76e..00000000--- a/notfair/README.md+++ /dev/null@@ -1,125 +0,0 @@-# NotFair--> Goal-driven, loop-powered marketing agents that crush your business goals 24/7 — on your own machine, on top of Claude Code or Codex. State an ambition — "cut CAC to $30", "keep wasted spend at $0" — and a dedicated agent turns it into a measured metric and runs a disciplined loop against it while you sleep. Goals are the only thing you name, see, and manage; the agents behind them are invisible plumbing.--Open source. Runs entirely on your machine. Bring your own LLM credentials (via the harness CLI you already authenticate to) and your own ad-platform OAuth.--## What it gives you--- **Goals are the identity.** Type the ambition, and you land in a chat where the goal's agent is already working: it sharpens the ask, labels the goal ("Wasted X spend → $0"), authors + tests a metric query against your connected platforms, and the platform *re-runs the query server-side* — only a reproducible number with a measured baseline goes on the books. You agree the target in chat — the moment you confirm, the loop starts and the first tick runs immediately. Two modes: **achieve** (reach the number, done) and **maintain** (hold it there forever — a watchdog).-- **Platform-focused onboarding.** Connect the data sources a goal needs, choose the relevant account or property, and tag the goal with its platform focus. The focus guides the intake conversation and metric design; every project connection is still wired to every goal agent.-- **The tick loop.** On the cadence you agree, the platform measures the metric mechanically (the agent never self-reports the number it's judged on) and wakes the agent: it scores past moves against their predicted effects, then the protocol allows at most **one** new move and requires a log entry with a falsifiable expected effect and observation window. Future goal turns use those records to avoid gated resources until review. The agent's page is the diary: sparkline vs. target, tick-by-tick log, open actions, accumulated memory.-- **Fully autonomous, visibly so.** No approval inbox — agents are instructed to act inside the spend envelope you set, with observation-window discipline, a pause button for scheduled work, and their recorded moves visible in the app. These are workflow controls for a trusted harness, not a sandbox against arbitrary local commands.-- **Code changes through pull requests.** Attach a GitHub-backed codebase and an agent can work in its own branch, commit and push the change, then register the pull request with NotFair. The app tracks the PR, while its goal protocol instructs the agent to leave merge decisions to you and keep one code mutation in flight at a time. Those rules are prompt-level guardrails, not mechanically enforced permissions.-- **Shared context + private memory.** `PROJECT.md` is the workspace brief every agent carries (any agent can update it via `set_shared_context`); each agent also keeps its own learnings ledger and workspace files. All connected MCPs are shared by every agent.-- **One screen per goal.** The conversation and the loop's state live together: chat on the left (where the goal is defined and steered), a status rail on the right — the progress chart, the plan, every check with its own follow-up chat, open actions with review dates, and the agent's memory. Opening a check also exposes the fully rendered Markdown prompt that triggered it, so the original instruction and follow-up conversation stay together. No tabs, no thread management, nothing else to learn.-- **Progress you can see.** A time-true chart with the target line, every agent action as a marker on the moment it happened (hover: what it did, what it predicted, what actually happened), observation windows shaded, and history backfilled at setup from the platform's own date-segmented stats — context from day one. Maintain goals get a streak ("held at target for 12 days") with a per-check strip; the workspace index shows a mini sparkline + 7-day delta per goal.-- **Project-scoped MCP connections** — one-click PKCE OAuth brings third-party tools (Google Ads via NotFair's hosted MCP) into the agents' toolbox. Connection records are stored in local SQLite and wired into the chosen harness automatically; Codex receives bearer tokens through per-server environment variables at process launch.--## Pick your harness--At onboarding you pick which local AI coding agent runs the work:--| Harness | Status | Notes |-|---|---|---|-| **Codex** | Recommended | Uses your existing `codex` login. Per-server env-var bearers. The sidebar reports the authenticated account's plan and usage; model selectors use Codex's configured/provider metadata, show the default once, and expose each model's supported reasoning efforts per goal. The adapter launches Codex with `--dangerously-bypass-approvals-and-sandbox`; that process inherits the parent environment and can access files available to your local user. Treat goal agents as trusted local automation. |-| **Claude Code** | Supported | Uses your existing `claude` login. Per-agent `.mcp.json` for isolation. |--Different projects can run on different harnesses; the choice persists on the project row.--## Prerequisites--- **Apple Silicon Mac.** The published npm package currently declares `darwin`/`arm64` support only.-- **Node 20+** (Node 24 recommended for native-module prebuilds).-- **At least one harness installed and authenticated**:- - [Claude Code](https://docs.claude.com/en/docs/agents-and-tools/claude-code/overview), or- - [Codex CLI](https://github.com/openai/codex)--Run `notfair doctor` to check Node, both harness binaries, the data directory, and the port. The current command exits non-zero when either Claude Code or Codex is missing, even though the app itself only needs the harness selected for the project.--## Install + run--```bash-# One-shot, no install:-npx notfair@latest doctor # verify env-npx notfair@latest # start in the background + open http://127.0.0.1:3327--# Or install globally:-npm install -g notfair-notfair-```--The server runs as a background process (state in `~/.notfair/server.json`, log in `~/.notfair/logs/server.log`) and the UI opens in your browser — your terminal stays free, and closing it doesn't kill the loop. Sidebar is project-scoped; create one to start.--To survive reboots, enable autostart (macOS):--```bash-notfair autostart enable # launchd: starts at login, restarts on crash-```--## CLI--```-notfair Start in the background + open UI (default)-notfair start Same as above (--foreground to stay attached)-notfair status Running? pid, port, uptime, autostart state-notfair stop Stop the background server-notfair logs [-n N] [-f] Show / follow the server log-notfair update Update to the latest npm version + restart the server-notfair autostart enable Start automatically at login (macOS launchd)-notfair autostart disable Remove the LaunchAgent + stop the server-notfair autostart status Is the LaunchAgent installed and loaded?-notfair doctor Run preflight checks (see below)-notfair --version-notfair --help-```--Options on `start`: `--port <n>` (default 3327), `--no-open`, `--foreground`, `--data-dir <path>`.-Options on `doctor`: `--port <n>`, `--data-dir <path>`.--**Updating.** `notfair update` checks npm, installs the newer version globally, and restarts whatever is running — through launchd when autostart is enabled (rewriting the LaunchAgent to the fresh install), or by stopping and relaunching the background daemon. The app has the same flow built in: when npm reports a newer release, the sidebar downloads it automatically and then shows **Update to vX.Y.Z**. Clicking that button restarts a launchd- or daemon-managed server, applies the release, and reloads the page immediately; there is no second restart step. Foreground/dev runs are never killed from the app; they get a "restart in your terminal" note instead.--When autostart is enabled, launchd owns the server: `notfair start` delegates to it (never spawns a competing copy), `notfair stop` stops it until your next login, and `notfair autostart disable` removes it entirely. The LaunchAgent captures your shell's PATH so the `claude` / `codex` binaries stay reachable at login, and `notfair start` self-heals the entry if an upgrade moved the package on disk. Global install is recommended for autostart — the npx cache can be cleared at any time.--`doctor` checks Node ≥ 20 (24 recommended), Claude Code on PATH, Codex on PATH, at least one harness ready, a writable data directory, and a free preferred port. It exits 0 if every check is passing and 1 otherwise, with a `Fix:` line under each failure naming the exact command to run.--## What happens when you create a goal--1. You type a goal statement and can select its platform focus. NotFair creates the goal row (status `intake`), provisions an anonymous goal agent, and creates its workspace at `~/.notfair/agents/<agent-id>/`. The goal protocol is mirrored into the harness's native config (`CLAUDE.md` / `AGENTS.md`, `.mcp.json` for Claude Code, sections in `~/.codex/config.toml` for Codex), with the project's connected MCPs wired in.-2. You chat while the agent records the ambition (`define_goal`), authors and tests a metric query, submits it (`propose_goal_metric` — the platform re-runs it server-side and stores the measured baseline), then proposes the measured target. When you confirm in chat, the agent records the agreement (`propose_target`) — the goal goes active and the first tick runs immediately.-3. The heartbeat rides a `setInterval` in the Next.js process polling every 30 seconds. Due goals get a tick: the metric is measured, a brief is composed from the database, one adapter turn runs, and the diary row is written. A completed check shows a static terminal status but keeps its composer active, so follow-up turns continue in that check's original session.--## Code changes through pull requests--Attach a local Git repository to the project in **Settings → Codebase**. When a goal requires source changes, the agent works in a dedicated worktree and branch, commits and pushes its changes, opens a GitHub pull request, and registers it with NotFair. Pull-request state is synchronized back into the goal. The goal protocol tells the agent not to merge its own PR or begin a second code mutation before the first is resolved, but the unsandboxed harness can technically run those commands; review the branch and PR as you would any other trusted local automation.--## Connecting MCP servers (for live ad-platform data)--The Connections page lists the MCP servers in our catalog (NotFair Google Ads, Meta Ads, Google Search Console, Google Analytics, X Ads — plus browseable extras like Stripe and Supabase, or any custom MCP URL). Click **Connect** to start a one-click PKCE OAuth flow — no environment variables to set, no Google Cloud project of your own to register.--Connections that expose multiple accounts or properties let you choose and later switch the active selection from the Connections page. Goals use that project-scoped selection when querying the platform.--OAuth credentials are persisted in the project-scoped `mcp_tokens` table and the catalog MCP is automatically registered with every agent in the project via the chosen harness's config. New agents provisioned later get the same wiring. The credentials are not yet encrypted at the application layer, so protect access to `~/.notfair/db.sqlite` and your local user account.--## Live transcript--Chat events (deltas, tool calls, lifecycle) are persisted to `transcript_events` and **also** pushed through an in-process `EventEmitter` keyed by session id. Open tabs subscribe via SSE; new events land in milliseconds. Re-attach to a streaming thread (open the URL in a second tab while the agent is mid-turn) is race-free: the server backfills from cursor=0 before attaching the live subscription, with dedup-by-seq.--## Data location--- App state: `~/.notfair/db.sqlite` (override with `--data-dir` or `NOTFAIR_DATA_DIR`)-- Agent workspaces: `~/.notfair/agents/<agent-id>/`-- Harness configs: `~/.claude/` for Claude Code; `~/.codex/config.toml` for Codex (managed by the respective CLI)-- Orchestration MCP secret: `~/.notfair/mcp-server-secret` (0600 perms)--## What V1 is and isn't--**Is:** the goal loop — conversational goal intake with server-verified metrics, heartbeat ticks with measurement discipline, per-agent memory, shared workspace context — plus goal chat, PR-governed code changes, and an MCP connection hub. Runs on Claude Code or Codex, no proprietary agent runtime.--**Isn't (yet):** cross-goal coordination (resource leases between agents touching the same campaigns), per-LLM-call cost tracking, or a hosted mode. Those land as the loop earns trust in the field.--See `ARCHITECTURE.md` for the design and `CONTRIBUTING.md` for development setup.--## License--MIT — see LICENSE.diff --git a/notfair/bin/cli.mjs b/notfair/bin/cli.mjsdeleted file mode 100755index b2d00d01..00000000--- a/notfair/bin/cli.mjs+++ /dev/null@@ -1,1022 +0,0 @@-#!/usr/bin/env node-// NotFair CLI entry point.-// Compiled-free: stays as plain ESM JS so it works straight from npm without a build step-// for the CLI surface. The Next.js app itself is built and shipped under .next/standalone.-//-// Process model: `notfair start` runs the server as a detached background-// process (state in <data-dir>/server.json, log in <data-dir>/logs/server.log);-// `--foreground` stays attached and is what launchd runs. When autostart is-// enabled, launchd is the single owner — start/stop delegate to launchctl so-// KeepAlive never fights the CLI over the same port.--import { spawn } from "node:child_process";-import {- closeSync,- cpSync,- existsSync,- mkdirSync,- openSync,- readFileSync,- unlinkSync,- writeFileSync,-} from "node:fs";-import { homedir } from "node:os";-import { dirname, join, resolve, sep } from "node:path";-import { fileURLToPath } from "node:url";-import { createServer } from "node:net";-import { Command } from "commander";-import open from "open";--import {- resolveCompatibleNodeRuntime,- syncStandaloneNativeBindings,-} from "./native-bindings.mjs";--const CLI_PATH = fileURLToPath(import.meta.url);-const __dirname = dirname(CLI_PATH);-const PKG_ROOT = dirname(__dirname);-// Resolved to absolute: the value is forwarded as NOTFAIR_DATA_DIR to the-// standalone server, whose cwd is the package dir — a relative path would-// silently land the database inside the npm/npx cache.-const DATA_DIR = resolve(process.env.NOTFAIR_DATA_DIR ?? join(homedir(), ".notfair"));-const LAUNCHD_LABEL = "co.notfair.server";--const program = new Command();-program- .name("notfair")- .description("Goal-driven, loop-powered marketing agents that crush your business goals 24/7 — on top of Claude Code or Codex.")- .version(readPackageVersion());--program- .command("start", { isDefault: true })- .description("Start NotFair in the background and open the UI in your browser.")- .option("-p, --port <port>", "Port to bind", "3327")- .option("--no-open", "Do not auto-open the browser")- .option("--foreground", "Stay attached to this terminal instead of running in the background")- .option("--data-dir <dir>", "Override data directory", (dir) => resolve(dir), DATA_DIR)- .action(async (opts) => {- ensureDataDir(opts.dataDir);-- const standalonePath = join(PKG_ROOT, ".next", "standalone", "server.js");- if (!existsSync(standalonePath)) {- console.error("Build artifacts not found. This usually means you're running");- console.error("from source without a build. Run: pnpm build");- console.error(`Expected: ${standalonePath}`);- process.exit(2);- }-- // When autostart owns the server, starting it by hand would race launchd- // onto the same port — delegate to launchctl instead.- if (!opts.foreground && process.platform === "darwin" && existsSync(plistPath())) {- await startViaLaunchd(opts);- return;- }-- if (!opts.foreground) {- const running = getState(opts.dataDir);- if (running && (await isHealthy(running.url))) {- console.log(`NotFair is already running on ${running.url} (pid ${running.pid}).`);- if (opts.open !== false) await open(running.url).catch(() => {});- return;- }- if (running) {- console.log(- `A NotFair process (pid ${running.pid}) exists but isn't answering on ${running.url} yet.`,- );- console.log("Check `notfair status` / `notfair logs`, or `notfair stop` and retry.");- process.exit(1);- }- }-- const desired = Number.parseInt(opts.port, 10);- const port = await findFreePort(desired);- if (port !== desired) {- console.log(`Port ${desired} was busy, using ${port} instead.`);- }-- // Next.js standalone output omits .next/static and public by default; copy- // them in if they're missing so the server can serve CSS/JS chunks.- ensureStandaloneAssets();- const serverNode = resolveCompatibleNodeRuntime(PKG_ROOT);- syncStandaloneNativeBindings(PKG_ROOT);-- const url = `http://127.0.0.1:${port}`;- const env = {- ...process.env,- PORT: String(port),- HOSTNAME: "127.0.0.1",- NOTFAIR_DATA_DIR: opts.dataDir,- // Tells the server who supervises it, so /api/restart knows whether- // an in-app "Restart now" is safe (launchd flows through untouched).- NOTFAIR_MANAGED: opts.foreground- ? process.env.NOTFAIR_MANAGED ?? "foreground"- : "daemon",- };-- if (opts.foreground) {- const child = spawn(serverNode, [standalonePath], { stdio: "inherit", env });- writeState(opts.dataDir, {- pid: child.pid,- port,- url,- data_dir: opts.dataDir,- version: readPackageVersion(),- started_at: new Date().toISOString(),- managed: process.env.NOTFAIR_MANAGED ?? "foreground",- });-- console.log(`NotFair running on ${url}`);-- if (opts.open !== false) {- setTimeout(() => {- open(url).catch(() => {- console.log(`Open ${url} in your browser.`);- });- }, 800);- }-- const shutdown = () => {- child.kill("SIGTERM");- };- process.on("SIGINT", shutdown);- process.on("SIGTERM", shutdown);- child.on("close", (code) => {- clearState(opts.dataDir);- process.exit(code ?? 0);- });- return;- }-- // Background mode: detach, log to a file, and only report success once- // the server actually answers HTTP.- mkdirSync(dirname(logFile(opts.dataDir)), { recursive: true });- const fd = openSync(logFile(opts.dataDir), "a");- const child = spawn(serverNode, [standalonePath], {- detached: true,- stdio: ["ignore", fd, fd],- env,- });- child.unref();- closeSync(fd);- writeState(opts.dataDir, {- pid: child.pid,- port,- url,- data_dir: opts.dataDir,- version: readPackageVersion(),- started_at: new Date().toISOString(),- managed: "daemon",- });-- const healthy = await waitFor(() => isHealthy(url), 30_000, 500);- if (!healthy) {- console.error(`NotFair did not answer on ${url} within 30s. Last log lines:`);- printLogTail(opts.dataDir, 20);- console.error(`Full log: ${logFile(opts.dataDir)}`);- try {- process.kill(child.pid, "SIGTERM");- } catch {}- clearState(opts.dataDir);- process.exit(1);- }-- console.log(`NotFair running in the background on ${url} (pid ${child.pid}).`);- console.log(" notfair status check health");- console.log(" notfair logs -f follow the server log");- console.log(" notfair stop stop the background server");- if (process.platform === "darwin" && !existsSync(plistPath())) {- console.log(" notfair autostart enable start automatically at login");- }- if (opts.open !== false) {- await open(url).catch(() => {- console.log(`Open ${url} in your browser.`);- });- }- });--program- .command("stop")- .description("Stop the background NotFair server.")- .option("--data-dir <dir>", "Override data directory", (dir) => resolve(dir), DATA_DIR)- .action(async (opts) => {- // launchd-managed: stop through launchctl, or KeepAlive resurrects the- // process the moment we kill it.- if (process.platform === "darwin" && (await launchAgentLoaded())) {- await runCheck("launchctl", ["bootout", launchdServiceTarget()]);- const state = getState(opts.dataDir);- if (state) {- await waitFor(() => !isPidAlive(state.pid), 10_000);- clearState(opts.dataDir);- }- console.log("Stopped NotFair (launchd-managed).");- if (existsSync(plistPath())) {- console.log(- "Autostart stays enabled — it starts again at your next login. `notfair autostart disable` turns that off.",- );- }- return;- }-- const state = getState(opts.dataDir);- if (!state || !isPidAlive(state.pid)) {- clearState(opts.dataDir);- console.log("NotFair is not running.");- return;- }- try {- process.kill(state.pid, "SIGTERM");- } catch {}- let dead = await waitFor(() => !isPidAlive(state.pid), 10_000);- if (!dead) {- try {- process.kill(state.pid, "SIGKILL");- } catch {}- dead = await waitFor(() => !isPidAlive(state.pid), 3_000);- }- clearState(opts.dataDir);- if (!dead) {- console.error(`Could not stop pid ${state.pid} — kill it manually.`);- process.exit(1);- }- console.log(`Stopped NotFair (pid ${state.pid}).`);- });--program- .command("status")- .description("Show whether NotFair is running, where, and its autostart state.")- .option("--data-dir <dir>", "Override data directory", (dir) => resolve(dir), DATA_DIR)- .action(async (opts) => {- const state = getState(opts.dataDir);- const alive = state ? isPidAlive(state.pid) : false;- const healthy = alive ? await isHealthy(state.url) : false;-- if (!alive) {- if (state) clearState(opts.dataDir);- console.log("NotFair is not running.");- } else {- console.log(- healthy- ? "NotFair is running."- : "NotFair process is alive but not answering HTTP (starting up, or wedged — see logs).",- );- console.log(` url ${state.url}`);- console.log(` pid ${state.pid}`);- console.log(` version ${state.version ?? "unknown"}`);- console.log(` mode ${state.managed ?? "unknown"}`);- console.log(` started ${state.started_at ?? "unknown"}${formatUptime(state.started_at)}`);- console.log(` log ${logFile(opts.dataDir)}`);- }-- if (process.platform === "darwin") {- const enabled = existsSync(plistPath());- const loaded = enabled && (await launchAgentLoaded());- console.log(- ` autostart ${enabled ? (loaded ? "enabled (loaded)" : "enabled (loads at next login)") : "disabled"}`,- );- }-- process.exit(alive && healthy ? 0 : 1);- });--program- .command("logs")- .description("Show the background server's log.")- .option("-n, --lines <n>", "Number of trailing lines to print", "100")- .option("-f, --follow", "Keep following the log (like tail -f)")- .option("--data-dir <dir>", "Override data directory", (dir) => resolve(dir), DATA_DIR)- .action((opts) => {- const file = logFile(opts.dataDir);- if (!existsSync(file)) {- console.log(`No log yet at ${file} — has the server been started in the background?`);- return;- }- const lines = Number.parseInt(opts.lines, 10) || 100;- if (opts.follow) {- const tail = spawn("tail", ["-n", String(lines), "-F", file], { stdio: "inherit" });- tail.on("close", (code) => process.exit(code ?? 0));- return;- }- printLogTail(opts.dataDir, lines);- });--program- .command("doctor")- .description("Verify this machine is ready to run NotFair.")- .option("--data-dir <dir>", "Override data directory", (dir) => resolve(dir), DATA_DIR)- .option("-p, --port <port>", "Preferred port for the server", "3327")- .action(async (opts) => {- const results = [];-- const node = checkNodeVersion();- results.push(node);-- // Probe each supported harness adapter. NotFair can run on any of- // them, so doctor lists status for all; at least one needs to be ok.- const claude = node.ok- ? await checkHarnessInstalled("Claude Code", "claude")- : skipped("Claude Code installed", "node version too old");- results.push(claude);-- const codex = node.ok- ? await checkHarnessInstalled("Codex", "codex")- : skipped("Codex installed", "node version too old");- results.push(codex);-- if (!claude.ok && !codex.ok) {- results.push(- fail(- "Harness available",- "neither Claude Code nor Codex is on PATH",- "Install at least one: https://docs.claude.com/en/docs/agents-and-tools/claude-code/overview or https://github.com/openai/codex",- ),- );- } else {- const ready = [claude.ok ? "Claude Code" : null, codex.ok ? "Codex" : null].filter(Boolean);- results.push(pass("Harness available", ready.join(", ")));- }-- const dataDir = checkDataDir(opts.dataDir);- results.push(dataDir);-- const port = await checkPortAvailable(Number.parseInt(opts.port, 10));- results.push(port);-- printResults(results);-- const failed = results.filter((r) => r.status === "fail").length;- process.exit(failed === 0 ? 0 : 1);- });--program- .command("update")- .description("Update NotFair to the latest npm version and restart the running server.")- .option("--data-dir <dir>", "Override data directory", (dir) => resolve(dir), DATA_DIR)- .action(async (opts) => {- const current = readPackageVersion();- const latest = await fetchLatestVersion();- if (!latest) {- console.error("Could not reach the npm registry — are you online?");- process.exit(1);- }- if (!isVersionNewer(latest, current)) {- console.log(`Already on the latest version (v${current}).`);- return;- }- console.log(`Update available: v${current} → v${latest}`);-- // A source checkout can't be updated by npm — don't pave over it.- if (existsSync(join(PKG_ROOT, "src")) && existsSync(join(PKG_ROOT, "next.config.ts"))) {- console.log("You're running from source. Update with: git pull && pnpm install && pnpm build");- process.exit(1);- }-- console.log(`Installing notfair@${latest} globally…`);- const installed = await runInherit("npm", ["install", "-g", `notfair@${latest}`]);- if (!installed) {- console.error("npm install failed. Try it directly: npm install -g notfair@latest");- process.exit(1);- }- const newCli = await globalCliPath();- if (PKG_ROOT.includes(`${sep}_npx${sep}`) && newCli) {- console.log("Installed globally — run future commands as plain `notfair`.");- }-- // Restart whatever is running so the new version actually loads.- if (process.platform === "darwin" && existsSync(plistPath())) {- const cfg = readPlistConfig();- const port = cfg?.port ?? 3327;- if (newCli) {- writeFileSync(plistPath(), renderPlist(port, cfg?.dataDir ?? DATA_DIR, newCli));- }- await reloadLaunchAgent();- const url = `http://127.0.0.1:${port}`;- const healthy = await waitFor(() => isHealthy(url), 30_000, 500);- console.log(- healthy- ? `Updated to v${latest} — NotFair restarted on ${url}.`- : `Updated to v${latest}, but the restart hasn't answered yet — check \`notfair status\`.`,- );- return;- }-- const state = getState(opts.dataDir);- if (state && isPidAlive(state.pid)) {- if (!newCli) {- console.log(`Updated to v${latest}. Restart to apply: notfair stop && notfair start`);- return;- }- console.log("Restarting the background server…");- try {- process.kill(state.pid, "SIGTERM");- } catch {}- await waitFor(() => !isPidAlive(state.pid), 10_000);- clearState(opts.dataDir);- const args = [newCli, "start", "--no-open", "--port", String(state.port), "--data-dir", state.data_dir ?? opts.dataDir];- const ok = await runInherit(process.execPath, args);- process.exit(ok ? 0 : 1);- }-- console.log(`Updated to v${latest}. Start it with: notfair start`);- });--const autostart = program- .command("autostart")- .description("Start NotFair automatically at login (macOS launchd).");--autostart- .command("enable")- .description("Install a launchd LaunchAgent: starts at login, restarts on crash.")- .option("-p, --port <port>", "Port the login server binds", "3327")- .option("--data-dir <dir>", "Override data directory", (dir) => resolve(dir), DATA_DIR)- .action(async (opts) => {- requireDarwin();- if (PKG_ROOT.includes(`${sep}_npx${sep}`)) {- console.log("Warning: you're running from the npx cache, which npm may clear at any time.");- console.log("For a reliable autostart, install globally first: npm install -g notfair");- }- ensureDataDir(opts.dataDir);- mkdirSync(dirname(logFile(opts.dataDir)), { recursive: true });-- // Hand the port over: a CLI-started daemon would collide with the- // launchd copy the moment it boots.- const state = getState(opts.dataDir);- if (state && isPidAlive(state.pid)) {- console.log(`Stopping the current NotFair (pid ${state.pid}) so launchd can own it…`);- try {- process.kill(state.pid, "SIGTERM");- } catch {}- await waitFor(() => !isPidAlive(state.pid), 10_000);- clearState(opts.dataDir);- }-- writeFileSync(plistPath(), renderPlist(Number.parseInt(opts.port, 10), opts.dataDir));- await reloadLaunchAgent();-- const url = `http://127.0.0.1:${opts.port}`;- const healthy = await waitFor(() => isHealthy(url), 30_000, 500);- if (healthy) {- console.log(`Autostart enabled — NotFair is running on ${url} and starts at every login.`);- } else {- console.log("Autostart enabled, but the server hasn't answered yet.");- console.log("Check `notfair status` and `notfair logs`.");- process.exit(1);- }- });--autostart- .command("disable")- .description("Remove the LaunchAgent and stop the launchd-managed server.")- .action(async () => {- requireDarwin();- await runCheck("launchctl", ["bootout", launchdServiceTarget()]);- try {- unlinkSync(plistPath());- } catch {}- console.log("Autostart disabled; the launchd-managed server (if any) was stopped.");- });--autostart- .command("status")- .description("Show whether the LaunchAgent is installed and loaded.")- .action(async () => {- requireDarwin();- const enabled = existsSync(plistPath());- if (!enabled) {- console.log("Autostart is disabled. Enable with: notfair autostart enable");- process.exit(1);- }- const loaded = await launchAgentLoaded();- console.log(`Autostart is enabled (${plistPath()}).`);- console.log(loaded ? "LaunchAgent is loaded." : "LaunchAgent loads at next login.");- });--program.parseAsync(process.argv).catch((err) => {- console.error(err);- process.exit(1);-});--// --- daemon state helpers -----function stateFile(dataDir) {- return join(dataDir, "server.json");-}--function logFile(dataDir) {- return join(dataDir, "logs", "server.log");-}--function getState(dataDir) {- try {- const state = JSON.parse(readFileSync(stateFile(dataDir), "utf8"));- if (!isPidAlive(state.pid)) {- clearState(dataDir);- return null;- }- return state;- } catch {- return null;- }-}--function writeState(dataDir, state) {- writeFileSync(stateFile(dataDir), `${JSON.stringify(state, null, 2)}\n`);-}--function clearState(dataDir) {- try {- unlinkSync(stateFile(dataDir));- } catch {}-}--function isPidAlive(pid) {- if (!Number.isInteger(pid) || pid <= 0) return false;- try {- process.kill(pid, 0);- return true;- } catch (err) {- return err.code === "EPERM";- }-}--async function isHealthy(url) {- try {- const res = await fetch(url, {- signal: AbortSignal.timeout(2_500),- redirect: "manual",- });- return res.status < 500;- } catch {- return false;- }-}--function sleep(ms) {- return new Promise((r) => setTimeout(r, ms));-}--async function waitFor(fn, timeoutMs, stepMs = 300) {- const deadline = Date.now() + timeoutMs;- for (;;) {- if (await fn()) return true;- if (Date.now() >= deadline) return false;- await sleep(stepMs);- }-}--function printLogTail(dataDir, n) {- try {- const lines = readFileSync(logFile(dataDir), "utf8").trimEnd().split("\n");- for (const line of lines.slice(-n)) console.log(line);- } catch {}-}--function formatUptime(startedAt) {- if (!startedAt) return "";- const ms = Date.now() - new Date(startedAt).getTime();- if (!Number.isFinite(ms) || ms < 0) return "";- const min = Math.floor(ms / 60_000);- if (min < 1) return " (just now)";- if (min < 60) return ` (up ${min}m)`;- const h = Math.floor(min / 60);- if (h < 48) return ` (up ${h}h ${min % 60}m)`;- return ` (up ${Math.floor(h / 24)}d)`;-}--// --- update helpers -----async function fetchLatestVersion() {- try {- const res = await fetch("https://registry.npmjs.org/notfair/latest", {- signal: AbortSignal.timeout(5_000),- headers: { accept: "application/json" },- });- if (!res.ok) return null;- const data = await res.json();- return typeof data.version === "string" ? data.version : null;- } catch {- return null;- }-}--/** True when `a` is strictly newer than `b` by major.minor.patch. */-function isVersionNewer(a, b) {- const parse = (v) => v.split(/[-+]/)[0].split(".").map((n) => Number(n) || 0);- const [amaj, amin, apat] = parse(a);- const [bmaj, bmin, bpat] = parse(b);- if (amaj !== bmaj) return amaj > bmaj;- if (amin !== bmin) return amin > bmin;- return apat > bpat;-}--/** The freshly-installed global CLI — stable across upgrades, unlike npx cache paths. */-async function globalCliPath() {- const r = await runCheck("npm", ["root", "-g"], 15_000);- if (!r.ok) return null;- const cli = join(r.stdout.trim(), "notfair", "bin", "cli.mjs");- return existsSync(cli) ? cli : null;-}--/** Run a command with inherited stdio; true on exit 0. */-function runInherit(cmd, args) {- return new Promise((resolvePromise) => {- let child;- try {- child = spawn(cmd, args, { stdio: "inherit" });- } catch {- resolvePromise(false);- return;- }- child.on("error", () => resolvePromise(false));- child.on("close", (code) => resolvePromise(code === 0));- });-}--// --- launchd helpers (macOS autostart) -----function requireDarwin() {- if (process.platform === "darwin") return;- console.error("Autostart is only supported on macOS today (launchd).");- console.error(- "On Linux, create a systemd user unit that runs: notfair start --foreground --no-open",- );- process.exit(1);-}--function plistPath() {- return join(homedir(), "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);-}--function launchdServiceTarget() {- return `gui/${process.getuid()}/${LAUNCHD_LABEL}`;-}--async function launchAgentLoaded() {- if (process.platform !== "darwin") return false;- const r = await runCheck("launchctl", ["print", launchdServiceTarget()]);- return r.ok;-}--async function reloadLaunchAgent() {- await runCheck("launchctl", ["bootout", launchdServiceTarget()]);- const boot = await runCheck("launchctl", ["bootstrap", `gui/${process.getuid()}`, plistPath()]);- if (!boot.ok) {- // Older macOS without bootstrap/bootout semantics.- await runCheck("launchctl", ["load", "-w", plistPath()]);- }-}--function xmlEscape(s) {- return String(s)- .replaceAll("&", "&")- .replaceAll("<", "<")- .replaceAll(">", ">");-}--/**- * The LaunchAgent runs the CLI itself in --foreground so launchd supervises- * a real process tree (RunAtLoad = start at login, KeepAlive = restart on- * crash). PATH is captured from the enabling shell — launchd's default PATH- * would hide the claude/codex binaries the agents need.- */-function renderPlist(port, dataDir, cliPath = CLI_PATH) {- const args = [- process.execPath,- cliPath,- "start",- "--foreground",- "--no-open",- "--port",- String(port),- "--data-dir",- dataDir,- ];- const argStrings = args.map((a) => ` <string>${xmlEscape(a)}</string>`).join("\n");- return `<?xml version="1.0" encoding="UTF-8"?>-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">-<plist version="1.0">-<dict>- <key>Label</key><string>${LAUNCHD_LABEL}</string>- <key>ProgramArguments</key>- <array>-${argStrings}- </array>- <key>RunAtLoad</key><true/>- <key>KeepAlive</key><true/>- <key>WorkingDirectory</key><string>${xmlEscape(PKG_ROOT)}</string>- <key>StandardOutPath</key><string>${xmlEscape(logFile(dataDir))}</string>- <key>StandardErrorPath</key><string>${xmlEscape(logFile(dataDir))}</string>- <key>EnvironmentVariables</key>- <dict>- <key>PATH</key><string>${xmlEscape(process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin")}</string>- <key>HOME</key><string>${xmlEscape(homedir())}</string>- <key>NOTFAIR_MANAGED</key><string>launchd</string>- </dict>-</dict>-</plist>-`;-}--/** Pull port/data-dir back out of the installed plist (regex, not a parser —- * we wrote the file, so the shape is known). */-function readPlistConfig() {- try {- const xml = readFileSync(plistPath(), "utf8");- const strings = [...xml.matchAll(/<string>([^<]*)<\/string>/g)].map((m) => m[1]);- const port = Number.parseInt(strings[strings.indexOf("--port") + 1] ?? "", 10);- const dataDir = strings[strings.indexOf("--data-dir") + 1] ?? DATA_DIR;- // Anchor on the "start" argument: ProgramArguments is [node, cli, "start",- // ...], but document order puts the Label's <string> first.- const startIdx = strings.indexOf("start");- return {- port: Number.isFinite(port) ? port : 3327,- dataDir,- execPath: startIdx >= 2 ? strings[startIdx - 2] : null,- cliPath: startIdx >= 1 ? strings[startIdx - 1] : null,- };- } catch {- return null;- }-}--/**- * `notfair start` while autostart is enabled: launchd owns the server.- * Heal a plist that points at a previous install (npx cache paths and- * global-install realpaths move on upgrade), make sure the agent is- * loaded, and wait for health — never spawn a competing daemon.- */-async function startViaLaunchd(opts) {- const cfg = readPlistConfig();- const port = cfg?.port ?? 3327;- const url = `http://127.0.0.1:${port}`;- const desired = Number.parseInt(opts.port, 10);- if (Number.isFinite(desired) && desired !== port && opts.port !== "3327") {- console.log(- `Autostart is enabled on port ${port}; ignoring --port ${desired}. Re-run \`notfair autostart enable --port ${desired}\` to move it.`,- );- }-- const stale =- (cfg?.cliPath && cfg.cliPath !== CLI_PATH) ||- (cfg?.execPath && cfg.execPath !== process.execPath);- if (stale) {- writeFileSync(plistPath(), renderPlist(port, cfg.dataDir));- console.log("Refreshed the login autostart entry to this NotFair install.");- await reloadLaunchAgent();- } else if (await isHealthy(url)) {- console.log(`NotFair is already running on ${url} (launchd-managed).`);- if (opts.open !== false) await open(url).catch(() => {});- return;- } else if (await launchAgentLoaded()) {- await runCheck("launchctl", ["kickstart", launchdServiceTarget()]);- } else {- await reloadLaunchAgent();- }-- const healthy = await waitFor(() => isHealthy(url), 30_000, 500);- if (!healthy) {- console.error(`launchd did not bring NotFair up on ${url} within 30s.`);- console.error(`Check \`notfair logs\` (${logFile(cfg?.dataDir ?? DATA_DIR)}).`);- process.exit(1);- }- console.log(`NotFair running on ${url} (launchd-managed).`);- if (opts.open !== false) {- await open(url).catch(() => {- console.log(`Open ${url} in your browser.`);- });- }-}--// --- helpers -----function ensureStandaloneAssets() {- const standaloneStatic = join(PKG_ROOT, ".next", "standalone", ".next", "static");- const sourceStatic = join(PKG_ROOT, ".next", "static");- if (!existsSync(standaloneStatic) && existsSync(sourceStatic)) {- cpSync(sourceStatic, standaloneStatic, { recursive: true });- }- const standalonePublic = join(PKG_ROOT, ".next", "standalone", "public");- const sourcePublic = join(PKG_ROOT, "public");- if (!existsSync(standalonePublic) && existsSync(sourcePublic)) {- cpSync(sourcePublic, standalonePublic, { recursive: true });- }-}--function readPackageVersion() {- try {- const pkg = JSON.parse(readFileSync(join(PKG_ROOT, "package.json"), "utf8"));- return pkg.version ?? "0.0.0";- } catch {- return "0.0.0";- }-}--function ensureDataDir(dir) {- if (!existsSync(dir)) {- mkdirSync(dir, { recursive: true, mode: 0o700 });- }-}--function findFreePort(start, maxTries = 5) {- return new Promise((resolve, reject) => {- let attempt = 0;- const tryPort = (port) => {- const server = createServer();- server.once("error", (err) => {- server.close();- if (err.code === "EADDRINUSE" && attempt < maxTries) {- attempt += 1;- tryPort(port + 1);- } else {- reject(err);- }- });- server.listen(port, "127.0.0.1", () => {- server.close(() => resolve(port));- });- };- tryPort(start);- });-}--function runCheck(cmd, args, timeoutMs = 5000) {- return new Promise((resolve) => {- let stdout = "";- let stderr = "";- let settled = false;- const finish = (value) => {- if (settled) return;- settled = true;- resolve(value);- };- let child;- try {- child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });- } catch (err) {- finish({ ok: false, stdout: "", stderr: err instanceof Error ? err.message : String(err) });- return;- }- child.stdout.on("data", (c) => {- stdout += c.toString();- });- child.stderr.on("data", (c) => {- stderr += c.toString();- });- child.on("error", () => finish({ ok: false, stdout: "", stderr: "" }));- child.on("close", (code) => {- finish({ ok: code === 0, stdout, stderr });- });- setTimeout(() => {- if (!settled) {- child.kill("SIGTERM");- finish({ ok: false, stdout, stderr: "timed out" });- }- }, timeoutMs).unref?.();- });-}--// --- doctor helpers -----const COLORS = {- reset: "\x1b[0m",- green: "\x1b[32m",- red: "\x1b[31m",- yellow: "\x1b[33m",- dim: "\x1b[2m",- bold: "\x1b[1m",-};--function useColor() {- if (process.env.NO_COLOR) return false;- return process.stdout.isTTY === true;-}--function color(name, text) {- if (!useColor()) return text;- return `${COLORS[name]}${text}${COLORS.reset}`;-}--function pass(name, detail) {- return { name, status: "pass", ok: true, detail };-}-function fail(name, detail, fix) {- return { name, status: "fail", ok: false, detail, fix };-}-function skipped(name, detail) {- return { name, status: "skip", ok: false, detail };-}--function checkNodeVersion() {- const raw = process.versions.node;- const major = Number.parseInt(raw.split(".")[0], 10);- if (Number.isNaN(major)) {- return fail("Node version", `unrecognized: ${raw}`, "Install Node 20+ (24 recommended) — https://nodejs.org");- }- if (major < 20) {- return fail(- "Node version",- `v${raw} (need ≥20)`,- "Install Node 20+ (24 recommended) — https://nodejs.org, or use nvm: nvm install 24",- );- }- const note = major >= 24 ? "" : " — 24 recommended";- return pass("Node version", `v${raw}${note}`);-}--async function checkHarnessInstalled(label, binary) {- const r = await runCheck(binary, ["--version"]);- if (!r.ok) {- return fail(- `${label} installed`,- "not on PATH",- label === "Claude Code"- ? "Install: https://docs.claude.com/en/docs/agents-and-tools/claude-code/overview"- : "Install: https://github.com/openai/codex",- );- }- return pass(`${label} installed`, r.stdout.trim().split("\n")[0] || "ok");-}--function checkDataDir(dir) {- const overrideEnv = process.env.NOTFAIR_DATA_DIR;- const source = overrideEnv ? "NOTFAIR_DATA_DIR" : dir === DATA_DIR ? "default" : "--data-dir";- try {- ensureDataDir(dir);- const probe = join(dir, ".doctor-write-probe");- writeFileSync(probe, String(Date.now()));- unlinkSync(probe);- return pass("Data dir writable", `${dir} (${source})`);- } catch (err) {- const message = err instanceof Error ? err.message : String(err);- return fail(- "Data dir writable",- `${dir}: ${message}`,- "Pass --data-dir <path> or set NOTFAIR_DATA_DIR to a writable directory",- );- }-}--async function checkPortAvailable(preferred) {- if (!Number.isFinite(preferred) || preferred <= 0) {- return fail(- "Port available",- `invalid preferred port: ${preferred}`,- "Pass --port <n> with a valid TCP port (1-65535)",- );- }- try {- const port = await findFreePort(preferred, 5);- const detail =- port === preferred ? `${preferred}` : `${port} (preferred ${preferred} was busy)`;- return pass("Port available", detail);- } catch {- return fail(- "Port available",- `none free in ${preferred}–${preferred + 5}`,- `Pass --port <n> with a free port (ports ${preferred}–${preferred + 5} are all in use)`,- );- }-}--function printResults(results) {- const nameWidth = Math.max(...results.map((r) => r.name.length));- for (const r of results) {- const pad = " ".repeat(nameWidth - r.name.length);- const icon =- r.status === "pass"- ? color("green", "✓")- : r.status === "fail"- ? color("red", "✗")- : color("yellow", "-");- const label =- r.status === "pass"- ? color("green", r.name)- : r.status === "fail"- ? color("red", r.name)- : color("yellow", r.name);- const detail = r.detail ? ` ${color("dim", r.detail)}` : "";- console.log(`${icon} ${label}${pad}${detail}`);- if (r.status === "fail" && r.fix) {- console.log(` ${color("bold", "Fix:")} ${r.fix}`);- }- if (r.status === "skip" && r.detail) {- // detail already printed above; no extra line- }- }- console.log("");- const failed = results.filter((r) => r.status === "fail").length;- const skipped = results.filter((r) => r.status === "skip").length;- if (failed === 0 && skipped === 0) {- console.log(color("green", "All checks passed. You're ready to run NotFair."));- } else if (failed === 0) {- console.log(- color("yellow", `Passed, with ${skipped} check${skipped === 1 ? "" : "s"} skipped.`),- );- } else {- console.log(- color(- "red",- `${failed} check${failed === 1 ? "" : "s"} failed${skipped ? `, ${skipped} skipped` : ""}.`,- ),- );- }-}diff --git a/notfair/bin/native-bindings.mjs b/notfair/bin/native-bindings.mjsdeleted file mode 100644index 3cc5d8c7..00000000--- a/notfair/bin/native-bindings.mjs+++ /dev/null@@ -1,84 +0,0 @@-import { spawnSync } from "node:child_process";-import { copyFileSync, existsSync, readdirSync } from "node:fs";-import { dirname, join } from "node:path";--function runtimeBindingPath(packageRoot) {- return join(- packageRoot,- "node_modules",- "better-sqlite3",- "build",- "Release",- "better_sqlite3.node",- );-}--function packagePrefixNode(packageRoot, platform = process.platform) {- const prefix = dirname(dirname(dirname(packageRoot)));- return platform === "win32" ? join(prefix, "node.exe") : join(prefix, "bin", "node");-}--function probeNativeBinding(nodePath, bindingPath) {- const result = spawnSync(- nodePath,- ["-e", "require(process.argv[1])", bindingPath],- { stdio: "ignore", timeout: 5_000 },- );- return result.status === 0 && !result.error;-}--/**- * A globally installed CLI can be launched through a different Node manager- * than the one npm used for installation. Native addons belong to the- * installing Node ABI, so run the standalone server with a Node executable- * that can actually load the installed binding.- */-export function resolveCompatibleNodeRuntime(- packageRoot,- {- execPath = process.execPath,- platform = process.platform,- probe = probeNativeBinding,- } = {},-) {- const binding = runtimeBindingPath(packageRoot);- if (!existsSync(binding)) return execPath;-- const candidates = [- ...new Set([execPath, packagePrefixNode(packageRoot, platform)]),- ];- for (const candidate of candidates) {- if (existsSync(candidate) && probe(candidate, binding)) return candidate;- }-- throw new Error(- `The installed better-sqlite3 binding is incompatible with the available Node.js runtimes. ` +- `Reinstall NotFair with the active Node.js version: npm install -g notfair@latest`,- );-}--/**- * npm builds the top-level better-sqlite3 dependency for the Node.js version- * that installed NotFair. Next.js also ships traced copies compiled on the- * release builder, so refresh those copies before every server start.- */-export function syncStandaloneNativeBindings(packageRoot) {- const runtimeBinding = runtimeBindingPath(packageRoot);- if (!existsSync(runtimeBinding)) return 0;-- const targets = [];- const visit = (directory) => {- for (const entry of readdirSync(directory, { withFileTypes: true })) {- const path = join(directory, entry.name);- if (entry.isDirectory()) {- visit(path);- } else if (entry.isFile() && entry.name === "better_sqlite3.node") {- targets.push(path);- }- }- };- visit(join(packageRoot, ".next", "standalone"));-- for (const target of targets) copyFileSync(runtimeBinding, target);- return targets.length;-}diff --git a/notfair/components.json b/notfair/components.jsondeleted file mode 100644index 3e7c73d1..00000000--- a/notfair/components.json+++ /dev/null@@ -1,21 +0,0 @@-{- "$schema": "https://ui.shadcn.com/schema.json",- "style": "new-york",- "rsc": true,- "tsx": true,- "tailwind": {- "config": "",- "css": "src/app/globals.css",- "baseColor": "zinc",- "cssVariables": true,- "prefix": ""- },- "aliases": {- "components": "@/components",- "utils": "@/lib/utils",- "ui": "@/components/ui",- "lib": "@/lib",- "hooks": "@/hooks"- },- "iconLibrary": "lucide"-}diff --git a/notfair/next-env.d.ts b/notfair/next-env.d.tsdeleted file mode 100644index 9edff1c7..00000000--- a/notfair/next-env.d.ts+++ /dev/null@@ -1,6 +0,0 @@-/// <reference types="next" />-/// <reference types="next/image-types/global" />-import "./.next/types/routes.d.ts";--// NOTE: This file should not be edited-// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.diff --git a/notfair/next.config.ts b/notfair/next.config.tsdeleted file mode 100644index a37f4ad7..00000000--- a/notfair/next.config.ts+++ /dev/null@@ -1,30 +0,0 @@-import type { NextConfig } from "next";--const config: NextConfig = {- output: "standalone",- serverExternalPackages: ["better-sqlite3", "keytar"],- // The CLI opens the portal on 127.0.0.1, but the Next dev server's origin is- // localhost. Without this, dev resources are blocked cross-origin and the- // client never hydrates (blank shell). Allow the loopback IP explicitly.- allowedDevOrigins: ["127.0.0.1"],- // pnpm + standalone output drops transitive deps that Next.js's own- // compiled chunks require at runtime (e.g. @swc/helpers, @next/env).- // Force-include them so the published tarball boots. (better-sqlite3's- // native loader `bindings` is present but unresolvable in the standalone- // tree; scripts/copy-standalone-assets.mjs hoists it to a resolvable path.)- outputFileTracingIncludes: {- "*": [- "./node_modules/@swc/helpers/**/*",- "./node_modules/@next/env/**/*",- // playwright-core reads browsers.json at runtime via require(); file- // tracing only follows code, so the workspace browser fails to launch- // from the published tarball without it.- "./node_modules/playwright-core/browsers.json",- ],- },- // typedRoutes intentionally disabled in V1 — our nav table builds Link hrefs- // dynamically. Re-enable once the route map settles and Link wrappers can- // be properly typed.-};--export default config;diff --git a/notfair/package.json b/notfair/package.jsondeleted file mode 100644index 514df309..00000000--- a/notfair/package.json+++ /dev/null@@ -1,91 +0,0 @@-{- "name": "notfair",- "version": "0.9.19",- "description": "Goal-driven, loop-powered marketing agents that crush your business goals 24/7 — on your own machine. Say 'cut CAC to $30' and a dedicated agent turns it into a server-verified metric, then moves the number check after check while you sleep. Rides your existing Claude Code or Codex login.",- "license": "MIT",- "bin": {- "notfair": "bin/cli.mjs"- },- "files": [- "bin/",- ".next/standalone/",- ".next/static/",- "public/"- ],- "scripts": {- "dev": "next dev --turbopack -p 3326",- "build": "next build && node scripts/copy-standalone-assets.mjs",- "start": "next start",- "cli": "node bin/cli.mjs",- "typecheck": "tsc --noEmit",- "test": "vitest run",- "test:watch": "vitest",- "test:coverage": "vitest run --coverage"- },- "dependencies": {- "@next/env": "16.2.6",- "@radix-ui/react-dialog": "^1.1.0",- "@radix-ui/react-dropdown-menu": "^2.1.0",- "@radix-ui/react-slot": "^1.1.0",- "@swc/helpers": "^0.5.21",- "better-sqlite3": "^12.10.0",- "class-variance-authority": "^0.7.0",- "clsx": "^2.1.0",- "commander": "^12.1.0",- "cron-parser": "^5.5.0",- "keytar": "^7.9.0",- "lucide-react": "^0.460.0",- "next": "^16.2.6",- "next-themes": "^0.4.6",- "open": "^10.1.0",- "playwright-core": "^1.60.0",- "radix-ui": "^1.4.3",- "react": "^19.0.0",- "react-dom": "^19.0.0",- "react-markdown": "^10.1.0",- "remark-gfm": "^4.0.1",- "sonner": "^2.0.7",- "tailwind-merge": "^2.5.0",- "ws": "^8.20.1",- "zod": "^3.23.0"- },- "devDependencies": {- "@tailwindcss/postcss": "^4.0.0",- "@testing-library/jest-dom": "^6.9.1",- "@testing-library/react": "^16.3.2",- "@types/better-sqlite3": "^7.6.0",- "@types/node": "^22.0.0",- "@types/react": "^19.0.0",- "@types/react-dom": "^19.0.0",- "@types/ws": "^8.18.1",- "@vitejs/plugin-react": "^6.0.2",- "@vitest/coverage-v8": "4.1.10",- "eslint": "^9.0.0",- "eslint-config-next": "^16.2.6",- "jsdom": "^29.1.1",- "postcss": "^8.4.0",- "tailwindcss": "^4.0.0",- "tsx": "^4.19.0",- "typescript": "^5.6.0",- "vitest": "^4.1.10"- },- "engines": {- "node": ">=20"- },- "pnpm": {- "onlyBuiltDependencies": [- "better-sqlite3",- "keytar",- "esbuild",- "sharp",- "unrs-resolver",- "node-pty"- ]- },- "os": [- "darwin"- ],- "cpu": [- "arm64"- ]-}diff --git a/notfair/pnpm-lock.yaml b/notfair/pnpm-lock.yamldeleted file mode 100644index 9f92d78d..00000000--- a/notfair/pnpm-lock.yaml+++ /dev/null@@ -1,8535 +0,0 @@-lockfileVersion: '9.0'--settings:- autoInstallPeers: true- excludeLinksFromLockfile: false--importers:-- .:- dependencies:- '@next/env':- specifier: 16.2.6- version: 16.2.6- '@radix-ui/react-dialog':- specifier: ^1.1.0- version: 1.1.15(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-dropdown-menu':- specifier: ^2.1.0- version: 2.1.16(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-slot':- specifier: ^1.1.0- version: 1.2.4(@types/[email protected])([email protected])- '@swc/helpers':- specifier: ^0.5.21- version: 0.5.21- better-sqlite3:- specifier: ^12.10.0- version: 12.10.0- class-variance-authority:- specifier: ^0.7.0- version: 0.7.1- clsx:- specifier: ^2.1.0- version: 2.1.1- commander:- specifier: ^12.1.0- version: 12.1.0- cron-parser:- specifier: ^5.5.0- version: 5.5.0- keytar:- specifier: ^7.9.0- version: 7.9.0- lucide-react:- specifier: ^0.460.0- version: 0.460.0([email protected])- next:- specifier: ^16.2.6- version: 16.2.6(@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])- next-themes:- specifier: ^0.4.6- open:- specifier: ^10.1.0- version: 10.2.0- playwright-core:- specifier: ^1.60.0- version: 1.60.0- radix-ui:- specifier: ^1.4.3- version: 1.4.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- react:- specifier: ^19.0.0- version: 19.2.6- react-dom:- specifier: ^19.0.0- version: 19.2.6([email protected])- react-markdown:- specifier: ^10.1.0- version: 10.1.0(@types/[email protected])([email protected])- remark-gfm:- specifier: ^4.0.1- version: 4.0.1- sonner:- specifier: ^2.0.7- tailwind-merge:- specifier: ^2.5.0- version: 2.6.1- ws:- specifier: ^8.20.1- version: 8.20.1- zod:- specifier: ^3.23.0- version: 3.25.76- devDependencies:- '@tailwindcss/postcss':- specifier: ^4.0.0- version: 4.3.0- '@testing-library/jest-dom':- specifier: ^6.9.1- version: 6.9.1- '@testing-library/react':- specifier: ^16.3.2- version: 16.3.2(@testing-library/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@types/better-sqlite3':- specifier: ^7.6.0- version: 7.6.13- '@types/node':- specifier: ^22.0.0- version: 22.19.19- '@types/react':- specifier: ^19.0.0- version: 19.2.14- '@types/react-dom':- specifier: ^19.0.0- version: 19.2.3(@types/[email protected])- '@types/ws':- specifier: ^8.18.1- version: 8.18.1- '@vitejs/plugin-react':- specifier: ^6.0.2- version: 6.0.2([email protected](@types/[email protected])([email protected])([email protected])([email protected]))- '@vitest/coverage-v8':- specifier: 4.1.10- version: 4.1.10([email protected])- eslint:- specifier: ^9.0.0- version: 9.39.4([email protected])- eslint-config-next:- specifier: ^16.2.6- version: 16.2.6(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])- jsdom:- specifier: ^29.1.1- version: 29.1.1- postcss:- specifier: ^8.4.0- version: 8.5.14- tailwindcss:- specifier: ^4.0.0- version: 4.3.0- tsx:- specifier: ^4.19.0- version: 4.22.1- typescript:- specifier: ^5.6.0- version: 5.9.3- vitest:- specifier: ^4.1.10- version: 4.1.10(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected]))--packages:-- '@adobe/[email protected]':- resolution: {integrity: sha512-6OzddxPio9UiWTCemp4N8cYLV2ZN1ncRnV1cVGtve7dhPOtRkleRyx32GQCYSwDYgaHU3USMm84tNsvKzRCa1Q==}-- '@alloc/[email protected]':- resolution: {integrity: sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==}- engines: {node: '>=10'}-- '@asamuzakjp/[email protected]':- resolution: {integrity: sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg==}- engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}-- '@asamuzakjp/[email protected]':- resolution: {integrity: sha512-67RZDnYRc8H/8MLDgQCDE//zoqVFwajkepHZgmXrbwybzXOEwOWGPYGmALYl9J2DOLfFPPs6kKCqmbzV895hTQ==}- engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}-- '@asamuzakjp/[email protected]':- resolution: {integrity: sha512-wajfB8KqzMCN2KGNFdLkReeHncd0AslUSrvHVvvYWuU8ghncRJoA50kT3zP9MVL0+9g4/67H+cdvBskj9THPzg==}- engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}-- '@asamuzakjp/[email protected]':- resolution: {integrity: sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==}-- '@babel/[email protected]':- resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==}- engines: {node: '>=6.9.0'}-- '@babel/[email protected]':- resolution: {integrity: sha512-LIVqM46zQWZhj17qA8wb4nW/ixr2y1Nw+r1etiAWgRM6U1IqP+LNhL1yg440jYZR72jCWcWbLWzIosH+uP1fqg==}- engines: {node: '>=6.9.0'}-- '@babel/[email protected]':- resolution: {integrity: sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==}- engines: {node: '>=6.9.0'}-- '@babel/[email protected]':- resolution: {integrity: sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==}- engines: {node: '>=6.9.0'}-- '@babel/[email protected]':- resolution: {integrity: sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==}- engines: {node: '>=6.9.0'}-- '@babel/[email protected]':- resolution: {integrity: sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==}- engines: {node: '>=6.9.0'}-- '@babel/[email protected]':- resolution: {integrity: sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==}- engines: {node: '>=6.9.0'}-- '@babel/[email protected]':- resolution: {integrity: sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==}- engines: {node: '>=6.9.0'}- peerDependencies:- '@babel/core': ^7.0.0-- '@babel/[email protected]':- resolution: {integrity: sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==}- engines: {node: '>=6.9.0'}-- '@babel/[email protected]':- resolution: {integrity: sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==}- engines: {node: '>=6.9.0'}-- '@babel/[email protected]':- resolution: {integrity: sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==}- engines: {node: '>=6.9.0'}-- '@babel/[email protected]':- resolution: {integrity: sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==}- engines: {node: '>=6.9.0'}-- '@babel/[email protected]':- resolution: {integrity: sha512-b3ctpQwp+PROvU/cttc4OYl4MzfJUWy6FZg+PMXfzmt/+39iHVF0sDfqay8TQM3JA2EUOyKcFZt75jWriQijsA==}- engines: {node: '>=6.0.0'}- hasBin: true-- '@babel/[email protected]':- resolution: {integrity: sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==}- engines: {node: '>=6.9.0'}-- '@babel/[email protected]':- resolution: {integrity: sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==}- engines: {node: '>=6.9.0'}-- '@babel/[email protected]':- resolution: {integrity: sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==}- engines: {node: '>=6.9.0'}-- '@babel/[email protected]':- resolution: {integrity: sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==}- engines: {node: '>=6.9.0'}-- '@bcoe/[email protected]':- resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==}- engines: {node: '>=18'}-- '@bramus/[email protected]':- resolution: {integrity: sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==}- hasBin: true-- '@csstools/[email protected]':- resolution: {integrity: sha512-064IFJdjTfUqnjpCVpMOdbr8FLQBhinbZj6yRv2An2E41O/pLEXqfFRWqGq/SxlE5PEUYTlvWsG2r8MswAVvkg==}- engines: {node: '>=20.19.0'}-- '@csstools/[email protected]':- resolution: {integrity: sha512-DtdHlgXh5ZkA43cwBcAm+huzgJiwx3ZTWVjBs94kwz2xKqSimDA3lBgCjphYgwgVUMWatSM0pDd8TILB1yrVVg==}- engines: {node: '>=20.19.0'}- peerDependencies:- '@csstools/css-parser-algorithms': ^4.0.0- '@csstools/css-tokenizer': ^4.0.0-- '@csstools/[email protected]':- resolution: {integrity: sha512-paQcIaOO53Rk5+YrBaBjm/SgrV4INImjo2BT1DtQRYr+XeTRbeAYlS+jxXp9drqvKmtFnWRJKIalDLhZZDu42A==}- engines: {node: '>=20.19.0'}- peerDependencies:- '@csstools/css-parser-algorithms': ^4.0.0- '@csstools/css-tokenizer': ^4.0.0-- '@csstools/[email protected]':- resolution: {integrity: sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==}- engines: {node: '>=20.19.0'}- peerDependencies:- '@csstools/css-tokenizer': ^4.0.0-- '@csstools/[email protected]':- resolution: {integrity: sha512-TcJCWFbXLPpJYq6z7bfOyjWYJDiDg2/I4gyUC9pqPNqHFRIey0EB0q0L5cSnQDfWJg8Jd6VadakxdIez/3zkqQ==}- peerDependencies:- css-tree: ^3.2.1- peerDependenciesMeta:- css-tree:- optional: true-- '@csstools/[email protected]':- resolution: {integrity: sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==}- engines: {node: '>=20.19.0'}-- '@emnapi/[email protected]':- resolution: {integrity: sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==}-- '@emnapi/[email protected]':- resolution: {integrity: sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==}-- '@emnapi/[email protected]':- resolution: {integrity: sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==}-- '@esbuild/[email protected]':- resolution: {integrity: sha512-lhRUCeuOyJQURhTxl4WkpFTjIsbDayJHih5kZC1giwE+MhIzAb7mEsQMqMf18rHLsrb5qI1tafG20mLxEWcWlA==}- engines: {node: '>=18'}- cpu: [ppc64]- os: [aix]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-+WzIXQOSaGs33tLEgYPYe/yQHf0WTU0X42Jca3y8NWMbUVhp7rUnw+vAsRC/QiDrdD31IszMrZy+qwPOPjd+rw==}- engines: {node: '>=18'}- cpu: [arm64]- os: [android]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-wqh0ByljabXLKHeWXYLqoJ5jKC4XBaw6Hk08OfMrCRd2nP2ZQ5eleDZC41XHyCNgktBGYMbqnrJKq/K/lzPMSQ==}- engines: {node: '>=18'}- cpu: [arm]- os: [android]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-+VJggoaKhk2VNNqVL7f6S189UzShHC/mR9EE8rDdSkdpN0KflSwWY/gWjDrNxxisg8Fp1ZCD9jLMo4m0OUfeUA==}- engines: {node: '>=18'}- cpu: [x64]- os: [android]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-0T+A9WZm+bZ84nZBtk1ckYsOvyA3x7e2Acj1KdVfV4/2tdG4fzUp91YHx+GArWLtwqp77pBXVCPn2We7Letr0Q==}- engines: {node: '>=18'}- cpu: [arm64]- os: [darwin]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-fyzLm/DLDl/84OCfp2f/XQ4flmORsjU7VKt8HLjvIXChJoFFOIL6pLJPH4Yhd1n1gGFF9mPwtlN5Wf82DZs+LQ==}- engines: {node: '>=18'}- cpu: [x64]- os: [darwin]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-l9GeW5UZBT9k9brBYI+0WDffcRxgHQD8ShN2Ur4xWq/NFzUKm3k5lsH4PdaRgb2w7mI9u61nr2gI2mLI27Nh3Q==}- engines: {node: '>=18'}- cpu: [arm64]- os: [freebsd]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-BXoQai/A0wPO6Es3yFJ7APCiKGc1tdAEOgeTNy3SsB491S3aHn4S4r3e976eUnPdU+NbdtmBuLncYir2tMU9Nw==}- engines: {node: '>=18'}- cpu: [x64]- os: [freebsd]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-RVyzfb3FWsGA55n6WY0MEIEPURL1FcbhFE6BffZEMEekfCzCIMtB5yyDcFnVbTnwk+CLAgTujmV/Lgvih56W+A==}- engines: {node: '>=18'}- cpu: [arm64]- os: [linux]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-CjaaREJagqJp7iTaNQjjidaNbCKYcd4IDkzbwwxtSvjI7NZm79qiHc8HqciMddQ6CKvJT6aBd8lO9kN/ZudLlw==}- engines: {node: '>=18'}- cpu: [arm]- os: [linux]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-KBnSTt1kxl9x70q+ydterVdl+Cn0H18ngRMRCEQfrbqdUuntQQ0LoMZv47uB97NljZFzY6HcfqEZ2SAyIUTQBQ==}- engines: {node: '>=18'}- cpu: [ia32]- os: [linux]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-zpSlUce1mnxzgBADvxKXX5sl8aYQHo2ezvMNI8I0lbblJtp8V4odlm3Yzlj7gPyt3T8ReksE6bK+pT3WD+aJRg==}- engines: {node: '>=18'}- cpu: [loong64]- os: [linux]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-2jIfP6mmjkdmeTlsX/9vmdmhBmKADrWqN7zcdtHIeNSCH1SqIoNI63cYsjQR8J+wGa4Y5izRcSHSm8K3QWmk3w==}- engines: {node: '>=18'}- cpu: [mips64el]- os: [linux]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-bc0FE9wWeC0WBm49IQMPSPILRocGTQt3j5KPCA8os6VprfuJ7KD+5PzESSrJ6GmPIPJK965ZJHTUlSA6GNYEhg==}- engines: {node: '>=18'}- cpu: [ppc64]- os: [linux]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-SQPZOwoTTT/HXFXQJG/vBX8sOFagGqvZyXcgLA3NhIqcBv1BJU1d46c0rGcrij2B56Z2rNiSLaZOYW5cUk7yLQ==}- engines: {node: '>=18'}- cpu: [riscv64]- os: [linux]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-SCfR0HN8CEEjnYnySJTd2cw0k9OHB/YFzt5zgJEwa+wL/T/raGWYMBqwDNAC6dqFKmJYZoQBRfHjgwLHGSrn3Q==}- engines: {node: '>=18'}- cpu: [s390x]- os: [linux]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-us0dSb9iFxIi8srnpl931Nvs65it/Jd2a2K3qs7fz2WfGPHqzfzZTfec7oxZJRNPXPnNYZtanmRc4AL/JwVzHQ==}- engines: {node: '>=18'}- cpu: [x64]- os: [linux]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-CR/RYotgtCKwtftMwJlUU7xCVNg3lMYZ0RzTmAHSfLCXw3NtZtNpswLEj/Kkf6kEL3Gw+BpOekRX0BYCtklhUw==}- engines: {node: '>=18'}- cpu: [arm64]- os: [netbsd]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-nU1yhmYutL+fQ71Kxnhg8uEOdC0pwEW9entHykTgEbna2pw2dkbFSMeqjjyHZoCmt8SBkOSvV+yNmm94aUrrqw==}- engines: {node: '>=18'}- cpu: [x64]- os: [netbsd]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-cXb5vApOsRsxsEl4mcZ1XY3D4DzcoMxR/nnc4IyqYs0rTI8ZKmW6kyyg+11Z8yvgMfAEldKzP7AdP64HnSC/6g==}- engines: {node: '>=18'}- cpu: [arm64]- os: [openbsd]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-8wZM2qqtv9UP3mzy7HiGYNH/zjTA355mpeuA+859TyR+e+Tc08IHYpLJuMsfpDJwoLo1ikIJI8jC3GFjnRClzA==}- engines: {node: '>=18'}- cpu: [x64]- os: [openbsd]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-FLGfyizszcef5C3YtoyQDACyg95+dndv79i2EekILBofh5wpCa1KuBqOWKrEHZg3zrL3t5ouE5jgr94vA+Wb2w==}- engines: {node: '>=18'}- cpu: [arm64]- os: [openharmony]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-1ZgjUoEdHZZl/YlV76TSCz9Hqj9h9YmMGAgAPYd+q4SicWNX3G5GCyx9uhQWSLcbvPW8Ni7lj4gDa1T40akdlw==}- engines: {node: '>=18'}- cpu: [x64]- os: [sunos]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-Q9StnDmQ/enxnpxCCLSg0oo4+34B9TdXpuyPeTedN/6+iXBJ4J+zwfQI28u/Jl40nOYAxGoNi7mFP40RUtkmUA==}- engines: {node: '>=18'}- cpu: [arm64]- os: [win32]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-zF3ag/gfiCe6U2iczcRzSYJKH1DCI+ByzSENHlM2FcDbEeo5Zd2C86Aq0tKUYAJJ1obRP84ymxIAksZUcdztHA==}- engines: {node: '>=18'}- cpu: [ia32]- os: [win32]-- '@esbuild/[email protected]':- resolution: {integrity: sha512-pEl1bO9mfAmIC+tW5btTmrKaujg3zGtUmWNdCw/xs70FBjwAL3o9OEKNHvNmnyylD6ubxUERiEhdsL0xBQ9efw==}- engines: {node: '>=18'}- cpu: [x64]- os: [win32]-- '@eslint-community/[email protected]':- resolution: {integrity: sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==}- engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}- peerDependencies:- eslint: ^6.0.0 || ^7.0.0 || >=8.0.0-- '@eslint-community/[email protected]':- resolution: {integrity: sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==}- engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0}-- '@eslint/[email protected]':- resolution: {integrity: sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw==}- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}-- '@eslint/[email protected]':- resolution: {integrity: sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==}- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}-- '@eslint/[email protected]':- resolution: {integrity: sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==}- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}-- '@eslint/[email protected]':- resolution: {integrity: sha512-4IlJx0X0qftVsN5E+/vGujTRIFtwuLbNsVUe7TO6zYPDR1O6nFwvwhIKEKSrl6dZchmYBITazxKoUYOjdtjlRg==}- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}-- '@eslint/[email protected]':- resolution: {integrity: sha512-nE7DEIchvtiFTwBw4Lfbu59PG+kCofhjsKaCWzxTpt4lfRjRMqG6uMBzKXuEcyXhOHoUp9riAm7/aWYGhXZ9cw==}- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}-- '@eslint/[email protected]':- resolution: {integrity: sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==}- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}-- '@eslint/[email protected]':- resolution: {integrity: sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==}- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}-- '@exodus/[email protected]':- resolution: {integrity: sha512-S6mL0yNB/Abt9Ei4tq8gDhcczc4S3+vQ4ra7vxnAf+YHC02srtqxKKZghx2Dq6p0e66THKwR6r8N6P95wEty7Q==}- engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}- peerDependencies:- '@noble/hashes': ^1.8.0 || ^2.0.0- peerDependenciesMeta:- '@noble/hashes':- optional: true-- '@floating-ui/[email protected]':- resolution: {integrity: sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==}-- '@floating-ui/[email protected]':- resolution: {integrity: sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ==}-- '@floating-ui/[email protected]':- resolution: {integrity: sha512-cC52bHwM/n/CxS87FH0yWdngEZrjdtLW/qVruo68qg+prK7ZQ4YGdut2GyDVpoGeAYe/h899rVeOVm6Oi40k2A==}- peerDependencies:- react: '>=16.8.0'- react-dom: '>=16.8.0'-- '@floating-ui/[email protected]':- resolution: {integrity: sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==}-- '@humanfs/[email protected]':- resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==}- engines: {node: '>=18.18.0'}-- '@humanfs/[email protected]':- resolution: {integrity: sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==}- engines: {node: '>=18.18.0'}-- '@humanfs/[email protected]':- resolution: {integrity: sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==}- engines: {node: '>=18.18.0'}-- '@humanwhocodes/[email protected]':- resolution: {integrity: sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==}- engines: {node: '>=12.22'}-- '@humanwhocodes/[email protected]':- resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==}- engines: {node: '>=18.18'}-- '@img/[email protected]':- resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==}- engines: {node: '>=18'}-- '@img/[email protected]':- resolution: {integrity: sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==}- engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}- cpu: [arm64]- os: [darwin]-- '@img/[email protected]':- resolution: {integrity: sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==}- engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}- cpu: [x64]- os: [darwin]-- '@img/[email protected]':- resolution: {integrity: sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==}- cpu: [arm64]- os: [darwin]-- '@img/[email protected]':- resolution: {integrity: sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==}- cpu: [x64]- os: [darwin]-- '@img/[email protected]':- resolution: {integrity: sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==}- cpu: [arm64]- os: [linux]- libc: [glibc]-- '@img/[email protected]':- resolution: {integrity: sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==}- cpu: [arm]- os: [linux]- libc: [glibc]-- '@img/[email protected]':- resolution: {integrity: sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==}- cpu: [ppc64]- os: [linux]- libc: [glibc]-- '@img/[email protected]':- resolution: {integrity: sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==}- cpu: [riscv64]- os: [linux]- libc: [glibc]-- '@img/[email protected]':- resolution: {integrity: sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==}- cpu: [s390x]- os: [linux]- libc: [glibc]-- '@img/[email protected]':- resolution: {integrity: sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==}- cpu: [x64]- os: [linux]- libc: [glibc]-- '@img/[email protected]':- resolution: {integrity: sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==}- cpu: [arm64]- os: [linux]- libc: [musl]-- '@img/[email protected]':- resolution: {integrity: sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==}- cpu: [x64]- os: [linux]- libc: [musl]-- '@img/[email protected]':- resolution: {integrity: sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==}- engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}- cpu: [arm64]- os: [linux]- libc: [glibc]-- '@img/[email protected]':- resolution: {integrity: sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==}- engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}- cpu: [arm]- os: [linux]- libc: [glibc]-- '@img/[email protected]':- resolution: {integrity: sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==}- engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}- cpu: [ppc64]- os: [linux]- libc: [glibc]-- '@img/[email protected]':- resolution: {integrity: sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==}- engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}- cpu: [riscv64]- os: [linux]- libc: [glibc]-- '@img/[email protected]':- resolution: {integrity: sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==}- engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}- cpu: [s390x]- os: [linux]- libc: [glibc]-- '@img/[email protected]':- resolution: {integrity: sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==}- engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}- cpu: [x64]- os: [linux]- libc: [glibc]-- '@img/[email protected]':- resolution: {integrity: sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==}- engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}- cpu: [arm64]- os: [linux]- libc: [musl]-- '@img/[email protected]':- resolution: {integrity: sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==}- engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}- cpu: [x64]- os: [linux]- libc: [musl]-- '@img/[email protected]':- resolution: {integrity: sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==}- engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}- cpu: [wasm32]-- '@img/[email protected]':- resolution: {integrity: sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==}- engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}- cpu: [arm64]- os: [win32]-- '@img/[email protected]':- resolution: {integrity: sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==}- engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}- cpu: [ia32]- os: [win32]-- '@img/[email protected]':- resolution: {integrity: sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==}- engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}- cpu: [x64]- os: [win32]-- '@jridgewell/[email protected]':- resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}-- '@jridgewell/[email protected]':- resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==}-- '@jridgewell/[email protected]':- resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==}- engines: {node: '>=6.0.0'}-- '@jridgewell/[email protected]':- resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==}-- '@jridgewell/[email protected]':- resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}-- '@napi-rs/[email protected]':- resolution: {integrity: sha512-ZVWUcfwY4E/yPitQJl481FjFo3K22D6qF0DuFH6Y/nbnE11GY5uguDxZMGXPQ8WQ0128MXQD7TnfHyK4oWoIJQ==}-- '@napi-rs/[email protected]':- resolution: {integrity: sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow==}- peerDependencies:- '@emnapi/core': ^1.7.1- '@emnapi/runtime': ^1.7.1-- '@next/[email protected]':- resolution: {integrity: sha512-gd8HoHN4ufj73WmR3JmVolrpJR47ILK6LouP5xElPglaVxir6e1a7VzvTvDWkOoPXT9rkkTzyCxBu4yeZfZwcw==}-- '@next/[email protected]':- resolution: {integrity: sha512-Z8l6o4JWKUl755x4R+wogD86KPeU+Ckw4K+SYG4kHeOJtRenDeK+OSbGcqZpDtbwn9DsJVdir2UxmwXuinUbUw==}-- '@next/[email protected]':- resolution: {integrity: sha512-ZJGkkcNfYgrrMkqOdZ7zoLa1TOy0qpcMfk/z4Mh/FKUz40gVO+HNQWqmLxf67Z5WB64DRp0dhEbyHfel+6sJUg==}- engines: {node: '>= 10'}- cpu: [arm64]- os: [darwin]-- '@next/[email protected]':- resolution: {integrity: sha512-v/YLBHIY132Ced3puBJ7YJKw1lqsCrgcNo2aRJlCEyQrrCeRJlvGlnmxhPxNQI3KE3N1DN5r9TPNPvka3nq5RQ==}- engines: {node: '>= 10'}- cpu: [x64]- os: [darwin]-- '@next/[email protected]':- resolution: {integrity: sha512-RPOvqlYBbcQjkz9VQQDZ2T2bARIjXZV1KFlt+V2Mr6SW/e4I9fcKsaA0hdyf2FHoTlsV2xnBd5Y912rP/1Ce6w==}- engines: {node: '>= 10'}- cpu: [arm64]- os: [linux]- libc: [glibc]-- '@next/[email protected]':- resolution: {integrity: sha512-URUTu1+dMkxJsPFgm+OeEvq9wf5sujw0EvgYy80TDGHTSLTnIHeqb0Eu8A3sC95IRgjejQL+kC4mw+4yPxiAXA==}- engines: {node: '>= 10'}- cpu: [arm64]- os: [linux]- libc: [musl]-- '@next/[email protected]':- resolution: {integrity: sha512-DOj182mPV8G3UkrayLoREM5YEYI+Dk5wv7Ox9xl1fFibAELEsFD0lDPfHIeILlutMMfdyhlzYPELG3peuKaurw==}- engines: {node: '>= 10'}- cpu: [x64]- os: [linux]- libc: [glibc]-- '@next/[email protected]':- resolution: {integrity: sha512-HKQ5SP/V/ub73UvF7n/zeJlxk2kLmtL7Wzrg4WfmkjmNos5onJ2tKu7yZOPdL18A6Svfn3max29ym+ry7NkK4g==}- engines: {node: '>= 10'}- cpu: [x64]- os: [linux]- libc: [musl]-- '@next/[email protected]':- resolution: {integrity: sha512-LZXpTlPyS5v7HhSmnvsLGP3iIYgYOBnc8r8ArlT55sGHV89bR2HlDdBjWQ+PY6SJMmk8TuVGFuxalnP3k/0Dwg==}- engines: {node: '>= 10'}- cpu: [arm64]- os: [win32]-- '@next/[email protected]':- resolution: {integrity: sha512-F0+4i0h9J6C4eE3EAPWsoCk7UW/dbzOjyzxY0qnDUOYFu6FFmdZ6l97/XdV3/Nz3VYyO7UWjyEJUXkGqcoXfMA==}- engines: {node: '>= 10'}- cpu: [x64]- os: [win32]-- '@nodelib/[email protected]':- resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}- engines: {node: '>= 8'}-- '@nodelib/[email protected]':- resolution: {integrity: sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==}- engines: {node: '>= 8'}-- '@nodelib/[email protected]':- resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==}- engines: {node: '>= 8'}-- '@nolyfill/[email protected]':- resolution: {integrity: sha512-nn5ozdjYQpUCZlWGuxcJY/KpxkWQs4DcbMCmKojjyrYDEAGy4Ce19NN4v5MduafTwJlbKc99UA8YhSVqq9yPZA==}- engines: {node: '>=12.4.0'}-- '@opentelemetry/[email protected]':- resolution: {integrity: sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==}- engines: {node: '>=8.0.0'}-- '@oxc-project/[email protected]':- resolution: {integrity: sha512-ibD2usx9JRu7f5pu2tMKMI4cpA4NgXJQoYRP4pQ7Pxmn1l6k/53qWtQWZayhYy3X4QZkt90Ot+mJEaeXouio6Q==}-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g==}-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg==}-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-XM+E4WXl0OqUJFovy6GjmxxFyx9opfCAIUku4dlKRd5YEPqt4kALOkQOp0Of6reHuUkJuiPBEc5k0o4z4lTC8A==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-T4nygeh9YE9dLRPhAHSeOZi7HBXo+0kYIPJXayZfvWOWA0+n3dESrZbjfDPUABkUNym6Hd+f2IR113To8D2GPA==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-oTVLkEw5GpdRe29BqJ0LSDFWI3qu0vR1M0mUkOQWDIUnY/QIkLpgDMWuKxP94c2NAC2LGcgVhG1ImF3jkZ5wXw==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-F+M1tLhO+mlQaOWspE8Wstg+z6PwxwRd8oQ8IXceWz92kfAmalTRf0EjrouQeo7QssEPfCn05B4Ihs1K9WQ/7w==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-Yq6lvO9HQyPwev1onK1daHCHqXVLzPhSVjmsNjCa2Zcxy2f7uJD2itDtxknv6FzAKCwD1qQkeVDmX/cev13n/g==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-V8piFfWapM5OmNCXTzVQY+E1rDa53zY+MQ4Y7356v4fFz6vqCyUtIz2rUD44ZEdwg78/jKmMJHj07+C/Z/rcog==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-wBbpv+NQftHDdG86Qc0pIyXk5IR3tM8Vd0nWLKDcX8nNn4nXFOFwsKuqw2okA/1D/mpaAkmuyndrPJTYDNZtFw==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-Uu+mSh4agx2ib1uIGPP4/CKNULyajb3p92LsVXmH2EHVMTfZWpll88XJ0j4W0z3f8NK1eYl1+Mf/szHPmcHzyA==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg==}- peerDependencies:- '@types/react': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-O8morBEW+HsVG28gYDZPTrT9UUovQUlJue5YO836tiTJhuIWBm/zQHc7j388sHWtdH/xUZurK9olD2+pcqx5ww==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA==}- peerDependencies:- '@types/react': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-TCglVRtzlffRNxRMEyR36DGBLJpeusFcgMVD9PZEzAKnUs1lKCgX5u9BmC2Yg+LL9MgZDugFFs1Vl+Jp4t/PGw==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-1UEWRX6jnOA2y4H5WczZ44gOOjTEmlqv1uNW4GAJEO5+bauCBhv8snY65Iw5/VOS/ghKN9gr2KjnLKxrsvoMVw==}- peerDependencies:- '@types/react': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-Nqcp+t5cTB8BinFkZgXiMJniQH0PsUt2k51FUhbdfeKvc4ACcG2uQniY/8+h1Yv6Kza4Q7lD7PQV0z0oicE0Mg==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-1PLGQEynI/3OX/ftV54COn+3Sud/Mn8vALg2rWnBLnRaGtJDduNW/22XjlGgPdpcIbiQxjKtb7BkcjP00nqfJw==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-0rFg/Rj2Q62NCm62jZw0QX7a3sz6QCQU0LpZdNrJX8byRGaGVTqbrW9jAoIAHyMQqsNpeZ81YgSizOt5WXq0Pw==}- peerDependencies:- '@types/react': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-t2ODlkXBQyn7jkl6TNaw/MtVEVvIGelJDCG41Okq/KwUsJBwQ4XVZsHAVUkK4mBv3ewiAS3PGuUWuY2BoK4ZUw==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-QM70k4Zwjttifr5a4sZFts9fn8FzHYvQ5PiB19O2HsYibaHSVt9fH9rzB0XZo/YcM+b7t/p7lYCT/F5eOeF5yQ==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-qgTkjNT1CfKMoP0rcasmlH2r1DAiYicWsDsufxl940sT2wHNEWWv6FMWIQXWhVdmC1d/HYfbhQx60KYyAtKxjg==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg==}- peerDependencies:- '@types/react': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-YT1GqPSL8kJn20djelMX7/cTRp/Y9w5IZHvfxQTVHrOqa2yMl7i/UfMqKRU5V7mEyKTrUVgJXhNQPVCG8PBLoQ==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-72F2T+PLlphrqLcAotYPp0uJMr5SjP5SL01wfEspJbru5Zs5vQaSHb4VB3ZMJPimgHHCHG7gMOeOB9H3Hdmtxg==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-EB1FktTz5xRRi2Er974AUQZWg2yVBb1yjip38/lgwtCVRd3a+maUoGHN/xs9Yv8SY8QwbSEb+YrxGadVWbEutA==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-YB9mTFQvCOAQMHU+C/jVl96WmuWeltyUEpRJJky51huhds5W2FQr1J8D/16sQlf0ozxkPK8uF3niQMdUwZPv5w==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-ycS4rbwURavDPVjCb5iS3aG4lURFDILi6sKI/WITUMZ13gMmn/xGjpLoqBAalhJaDk8I3UbCM5GzKHrnzwHbvg==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-/UuCrDBWravcaMix4TdT+qlNdVwOM1Nck9kWx/vafXsdfj1ChfhOdfi3cy9SGBpWgTXwYCuboT/oYpJy3clqfw==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-kr0X2+6Yy/vJzLYJUPCZEc8SfQcf+1COFoAqauJm74umQhta9M7lNJHP7QQS3vkvcGLQUbWpMzwrXYwrYztHKA==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-0NJQ4LFFUuWkE7Oxf0htBKS6zLkkjBH+hM1uk7Ng705ReR8m/uelduy1DBo0PyBXPKVnBA6YBlU94MBGXrSBCw==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-bpIxvq03if6UNwXZ+HTK71JLh4APvnXntDc6XOX8UVq4XQOVl7lwok0AvIl+b8zgCw3fSaVTZMpAPPagXbKmHQ==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-/jfEwNDdQVBCNvjkGit4h6pMOzq8bHkopq458dPt2lMjx+eBQUohZNG9A7DtO/O5ukSbxuaNGXMjHicgwy6rQQ==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-vPdg/tF6YC/ynuBIJlk1mm7Le0VgW6ub6J2UWnTQ7/D23KXcPI1qy+0vBkgKgd38RCMJavBXpB83HPNFMTb0Fg==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-VBKYIYImA5zsxACdisNQ3BjCBfmbGH3kQlnFVqlWU4tXwjy7cGX8ta80BcrO+WJXIn5iBylEH3K6ZTlee//lgQ==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-7A6S9jSgm/S+7MdtNDSb+IU859vQqJ/QAtcYQcfFC6W8RS4IxIZDldLR0xqCFZ6DCyrQLjLPsxtTNch5jVA4lA==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-tAXIa1g3sM5CGpVT0uIbUx/U3Gs5N8T52IICuCtObaos1S8fzsrPXG5WObkQN3S6NVl6wKgPhAIiBGbWnvc97A==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-I30RydO+bnn2PQztvo25tswPH+wFBjehVGtmagkU78yMdwTwVf12wnAOF+AeP8S2N8xD+5UPbGhkUfPyvT+mwQ==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-0HEb8R9E8A+jZjvmFCy/J4xhbXy3TV+9XSnGJ3KvTtjlIUy/YQ/p6UYZvi7YbeoeXdyU9+Y3scizK6hkY37baA==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-JPYb1GuM1bxfjMRlNLE+BcmBC8onfCi60Blk7OBqi2MLTFdS+8401U4uFjnwkOr49BLmXxLC6JHkvAsx5OJvHw==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A==}- peerDependencies:- '@types/react': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-Jl+bCv8HxKnlTLVrcDE8zTMJ09R9/ukw4qBs/oZClOfoQk/cOTbDn+NceXfV7j09YPVQUryJPHurafcSg6EVKA==}- peerDependencies:- '@types/react': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-bByzr1+ep1zk4VubeEVViV592vu2lHE2BZY5OnzehZqOOgogN80+mNtCqPkhn2gklJqOpxWgPoYTSnhBCqpOXQ==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-7xdcatg7/U+7+Udyoj2zodtI9H/IIopqo+YOIcZOq1nJwXWBZ9p8xiu5llXlekDbZkca79a/fozEYQXIA4sW6A==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-3OSz3TacUWy4WtOXV38DggwxoqJK4+eDkNMl5Z/MJZaoUPaP4/9lf81xXMe1I2ReTAptverZUpbPY4wWwWyL5g==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-5umnS0T8JQzQT6HbPyO7Hh9dgd82NmS36DQr+X/YJ9ctFNCiiQd6IJAYYZ33LUwm8M+taCz5t2ui29fHZc4Y6Q==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-lS1odchhFTeZv3xwHH31YPObmJn8gOg7Lq12inrr0+BH/l3Tsq32VfjqH1oh80ARM3mlkfMic15n0kg4sD1poQ==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-4ol06/1bLoFu1nwUqzdD4Y5RZ9oDdKeiHIsntug54Hcr1pgaHiPqHFEaXI1IFP/EsOfROQZ8Mig9VTIRza6Tjg==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-tY7sVt1yL9ozIxvmbtN5qtmH2krXcBCfjEiCgKGLqunJHvgvZG2Pcl2oQ3kbcZARb1BGEHdkLzcYGO8ynVlieg==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg==}- peerDependencies:- '@types/react': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg==}- peerDependencies:- '@types/react': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA==}- peerDependencies:- '@types/react': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-Il0+boE7w/XebUHyBjroE+DbByORGR9KKmITzbR7MyQ4akpORYP/ZmbhAr0DG7RmmBqoOnZdy2QlvajJ2QA59g==}- peerDependencies:- '@types/react': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-U+UORVEq+cTnRIaostJv9AGdV3G6Y+zbVd+12e18jQ5A3c0xL03IhnHuiU4UV69wolOQp5GfR58NW/EgdQhwOA==}- peerDependencies:- '@types/react': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ==}- peerDependencies:- '@types/react': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-2dHfToCj/pzca2Ck724OZ5L0EVrr3eHRNsG/b3xQJLA2hZpVCS99bLAX+hm1IHXDEnzU6by5z/5MIY794/a8NQ==}- peerDependencies:- '@types/react': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-QTYuDesS0VtuHNNvMh+CjlKJ4LJickCMUAqjlE3+j8w+RlRpwyX3apEQKGFzbZGdo7XNG1tXa+bQqIE7HIXT2w==}- peerDependencies:- '@types/react': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-ewrXRDTAqAXlkl6t/fkXWNAhFX9I+CkKlw6zjEwk86RSPKwZr3xpBRso655aqYafwtnbpHLj6toFzmd6xdVptQ==}- peerDependencies:- '@types/react': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-pzJq12tEaaIhqjbzpCuv/OypJY/BPavOofm+dbab+MHLajy277+1lLm6JFcGgF5eskJ6mquGirhXY2GD/8u8Ug==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@radix-ui/[email protected]':- resolution: {integrity: sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw==}-- '@rolldown/[email protected]':- resolution: {integrity: sha512-fJI3I0r3C3Oj/zdBCpaCmBRZYf07xpaq4yCfDDoSFm+beWNzbIl26puW8RraUdugoJw/95zerNOn6jasAhzSmg==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [arm64]- os: [android]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-cKnAhWEsV7TPcA/5EAteDp6KcJZBQ2G+BqE7zayMMi7kMvwRsbv7WT9aOnn0WNl4SKEIf43vjS31iUPu80nzXg==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [arm64]- os: [darwin]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-YKrVwQjIRBPo+5G/u03wGjbdy4q7pyzCe93DK9VJ7zkVmeg8LJ7GbgsiHWdR4xSoe4CAXRD7Bcjgbtr64bkXNg==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [x64]- os: [darwin]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-z/oBsREo46SsFqBwYtFe0kpJeBijAT48O/WXLI4suiCLBkr03RTtTJMCzSdDd2znlh8VJizL09XVkQgk8IZonw==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [x64]- os: [freebsd]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-ik8q7GM11zxvYxFc2PeDcT6TBvhCQMaUxfph/M5l9sKuTs/Sjg3L+Byw0F7w0ZVLBZmx30P+gG0ECzzN+MFcmQ==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [arm]- os: [linux]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-QoSx2EkyrrdZ6kcyE8stqZ62t0Yra8Fs5ia9lOxJrh6TMQJK7gQKmscdTHf7pOXKREKrVwOtJcQG3qVSfc866A==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [arm64]- os: [linux]- libc: [glibc]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-uwNwFpwKeNiZawfAWBgg0VIztPTV3ihhh1vV334h9ivnNLorxnQMU6Fz8wG1Zb4Qh9LC1/MkcyT3YlDXG3Rsgg==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [arm64]- os: [linux]- libc: [musl]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-zY1bul7OWr7DFBiJ++wofXvnr8B45ce3QsQUhKrIhXsygAh7bTkwyeM1bi1a2g5C/yC/N8TZyGDEoMfm/l9mpg==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [ppc64]- os: [linux]- libc: [glibc]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-0frlsT/f4Ft6I7SMESTKnF3cZsdicQn1dCMkF/jT9wDLE+gGoiQfv1nmT9e+s7s/fekvvy6tZM2jHvI2tkbJDQ==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [s390x]- os: [linux]- libc: [glibc]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-XABVmGp9Tg0WspTVvwduTc4fpqy6JnAUrSQe6OuyqD/03nI7r0O9OWUkMIwFrjKAIqolvqoA4ZrJppgwE0Gxmw==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [x64]- os: [linux]- libc: [glibc]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-bV4fzswuzVcKD90o/VM6QqKxnxlDq0g2BISDLNVmxrnhpv1DDbyPhCIjYfvzYLV+MvkKKnQt2Q6AO86SEBULUQ==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [x64]- os: [linux]- libc: [musl]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-/Mh0Zhq3OP7fVs0kcQHZP6lZEthMGTaSf8UBQYSFEZDWGXXlEC+nJ6EqenaK2t4LBXMe3A+K/G2BVXXdtOr4PQ==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [arm64]- os: [openharmony]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-+1xc9X45l8ufsBAm6Gjvx2qDRIY9lTVt0cgWNcJ+1gdhXvkbxePA60yRTwSTuXL09CMhyJmjpV7E3NoyxbqFQQ==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [wasm32]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-1D+UqZdfnuR+Jy1GgMJwi85bD40H21uNmOPRWQhw4oRSuolZ/B5rixZ45DK2KXOTCvmVCecauWgEhbw8bI7tOw==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [arm64]- os: [win32]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-INAycaWuhlOK3wk4mRHGsdgwYWmd9cChdPdE9bwWmy6rn9VqVNYNFGhOdXrofXUxwHIncSiPNb8tNm8knDVIeQ==}- engines: {node: ^20.19.0 || >=22.12.0}- cpu: [x64]- os: [win32]-- '@rolldown/[email protected]':- resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==}-- '@rtsao/[email protected]':- resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==}-- '@standard-schema/[email protected]':- resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}-- '@swc/[email protected]':- resolution: {integrity: sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==}-- '@swc/[email protected]':- resolution: {integrity: sha512-jI/VAmtdjB/RnI8GTnokyX7Ug8c+g+ffD6QRLa6XQewtnGyukKkKSk3wLTM3b5cjt1jNh9x0jfVlagdN2gDKQg==}-- '@tailwindcss/[email protected]':- resolution: {integrity: sha512-aFb4gUhFOgdh9AXo4IzBEOzBkkAxm9VigwDJnMIYv3lcfXCJVesNfbEaBl4BNgVRyid92AmdviqwBUBRKSeY3g==}-- '@tailwindcss/[email protected]':- resolution: {integrity: sha512-TJPiq67tKlLuObP6RkwvVGDoxCMBVtDgKkLfa/uyj7/FyxvQwHS+UOnVrXXgbEsfUaMgiVvC4KbJnRr26ho4Ng==}- engines: {node: '>= 20'}- cpu: [arm64]- os: [android]-- '@tailwindcss/[email protected]':- resolution: {integrity: sha512-oMN/WZRb+SO37BmUElEgeEWuU8E/HXRkiODxJxLe1UTHVXLrdVSgfaJV7pSlhRGMSOiXLuxTIjfsF3wYvz8cgQ==}- engines: {node: '>= 20'}- cpu: [arm64]- os: [darwin]-- '@tailwindcss/[email protected]':- resolution: {integrity: sha512-N6CUmu4a6bKVADfw77p+iw6Yd9Q3OBhe0veaDX+QazfuVYlQsHfDgxBrsjQ/IW+zywL8mTrNd0SdJT/zgtvMdA==}- engines: {node: '>= 20'}- cpu: [x64]- os: [darwin]-- '@tailwindcss/[email protected]':- resolution: {integrity: sha512-zDL5hBkQdH5C6MpqbK3gQAgP80tsMwSI26vjOzjJtNCMUo0lFgOItzHKBIupOZNQxt3ouPH7RPhvNhiTfCe5CQ==}- engines: {node: '>= 20'}- cpu: [x64]- os: [freebsd]-- '@tailwindcss/[email protected]':- resolution: {integrity: sha512-R06HdNi7A7OEoMsf6d4tjZ71RCWnZQPHj2mnotSFURjNLdBC+cIgXQ7l81CqeoiQftjf6OOblxXMInMgN2VzMA==}- engines: {node: '>= 20'}- cpu: [arm]- os: [linux]-- '@tailwindcss/[email protected]':- resolution: {integrity: sha512-qTJHELX8jetjhRQHCLilkVLmybpzNQAtaI/gaoVoidn/ufbNDbAo8KlK2J+yPoc8wQxvDxCmh/5lr8nC1+lTbg==}- engines: {node: '>= 20'}- cpu: [arm64]- os: [linux]- libc: [glibc]-- '@tailwindcss/[email protected]':- resolution: {integrity: sha512-Z6sukiQsngnWO+l39X4pPbiWT81IC+PLKF+PHxIlyZbGNb9MODfYlXEVlFvej5BOZInWX01kVyzeLvHsXhfczQ==}- engines: {node: '>= 20'}- cpu: [arm64]- os: [linux]- libc: [musl]-- '@tailwindcss/[email protected]':- resolution: {integrity: sha512-DRNdQRpSGzRGfARVuVkxvM8Q12nh19l4BF/G7zGA1oe+9wcC6saFBHTISrpIcKzhiXtSrlSrluCfvMuledoCTQ==}- engines: {node: '>= 20'}- cpu: [x64]- os: [linux]- libc: [glibc]-- '@tailwindcss/[email protected]':- resolution: {integrity: sha512-Z0IADbDo8bh6I7h2IQMx601AdXBLfFpEdUotft86evd/8ZPflZe9COPO8Q1vw+pfLWIUo9zN/JGZvwuAJqduqg==}- engines: {node: '>= 20'}- cpu: [x64]- os: [linux]- libc: [musl]-- '@tailwindcss/[email protected]':- resolution: {integrity: sha512-HNZGOUxEmElksYR7S6sC5jTeNGpobAsy9u7Gu0AskJ8/20FR9GqebUyB+HBcU/ax6BHuiuJi+Oda4B+YX6H1yA==}- engines: {node: '>=14.0.0'}- cpu: [wasm32]- bundledDependencies:- - '@napi-rs/wasm-runtime'- - '@emnapi/core'- - '@emnapi/runtime'- - '@tybys/wasm-util'- - '@emnapi/wasi-threads'- - tslib-- '@tailwindcss/[email protected]':- resolution: {integrity: sha512-Pe+RPVTi1T+qymuuRpcdvwSVZjnll/f7n8gBxMMh3xLTctMDKqpdfGimbMyioqtLhUYZxdJ9wGNhV7MKHvgZsQ==}- engines: {node: '>= 20'}- cpu: [arm64]- os: [win32]-- '@tailwindcss/[email protected]':- resolution: {integrity: sha512-Mvrf2kXW/yeW/OTezZlCGOirXRcUuLIBx/5Y12BaPM7wJoryG6dfS/NJL8aBPqtTEx/Vm4T4vKzFUcKDT+TKUA==}- engines: {node: '>= 20'}- cpu: [x64]- os: [win32]-- '@tailwindcss/[email protected]':- resolution: {integrity: sha512-F7HZGBeN9I0/AuuJS5PwcD8xayx5ri5GhjYUDBEVYUkexyA/giwbDNjRVrxSezE3T250OU2K/wp/ltWx3UOefg==}- engines: {node: '>= 20'}-- '@tailwindcss/[email protected]':- resolution: {integrity: sha512-Jm05Tjx+9yCLGv5qw1c+84Psds8MnyrEQYCB+FFk2lgGiUjlRqdxke4mVTuYrj2xnVZqKim2Apr5ySuQRYAw/w==}-- '@testing-library/[email protected]':- resolution: {integrity: sha512-o4PXJQidqJl82ckFaXUeoAW+XysPLauYI43Abki5hABd853iMhitooc6znOnczgbTYmEP6U6/y1ZyKAIsvMKGg==}- engines: {node: '>=18'}-- '@testing-library/[email protected]':- resolution: {integrity: sha512-zIcONa+hVtVSSep9UT3jZ5rizo2BsxgyDYU7WFD5eICBE7no3881HGeb/QkGfsJs6JTkY1aQhT7rIPC7e+0nnA==}- engines: {node: '>=14', npm: '>=6', yarn: '>=1'}-- '@testing-library/[email protected]':- resolution: {integrity: sha512-XU5/SytQM+ykqMnAnvB2umaJNIOsLF3PVv//1Ew4CTcpz0/BRyy/af40qqrt7SjKpDdT1saBMc42CUok5gaw+g==}- engines: {node: '>=18'}- peerDependencies:- '@testing-library/dom': ^10.0.0- '@types/react': ^18.0.0 || ^19.0.0- '@types/react-dom': ^18.0.0 || ^19.0.0- react: ^18.0.0 || ^19.0.0- react-dom: ^18.0.0 || ^19.0.0- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- '@tybys/[email protected]':- resolution: {integrity: sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==}-- '@types/[email protected]':- resolution: {integrity: sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==}-- '@types/[email protected]':- resolution: {integrity: sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==}-- '@types/[email protected]':- resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}-- '@types/[email protected]':- resolution: {integrity: sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==}-- '@types/[email protected]':- resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}-- '@types/[email protected]':- resolution: {integrity: sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==}-- '@types/[email protected]':- resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==}-- '@types/[email protected]':- resolution: {integrity: sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==}-- '@types/[email protected]':- resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==}-- '@types/[email protected]':- resolution: {integrity: sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==}-- '@types/[email protected]':- resolution: {integrity: sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==}-- '@types/[email protected]':- resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==}-- '@types/[email protected]':- resolution: {integrity: sha512-dyh/xO2Fh5bYrfWaaqGrRQQGkNdmYw6AmaAUvYeUMNTWQtvb796ikLdmTchRmOlOiIJ1TDXfWgVx1QkUlQ6Hew==}-- '@types/[email protected]':- resolution: {integrity: sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==}- peerDependencies:- '@types/react': ^19.2.0-- '@types/[email protected]':- resolution: {integrity: sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==}-- '@types/[email protected]':- resolution: {integrity: sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==}-- '@types/[email protected]':- resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==}-- '@types/[email protected]':- resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}-- '@typescript-eslint/[email protected]':- resolution: {integrity: sha512-PwFvSKsXGShKGW6n5bZOhGHEcCZXM8HofLK9fNsEwZXzFRjoY+XT1Vsf1zgyXdwTr0ZYz1/2tkZ0DBTT9jZjhw==}- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}- peerDependencies:- '@typescript-eslint/parser': ^8.59.3- eslint: ^8.57.0 || ^9.0.0 || ^10.0.0- typescript: '>=4.8.4 <6.1.0'-- '@typescript-eslint/[email protected]':- resolution: {integrity: sha512-HPwA+hVkfcriajbNvTmZv4VRauibay+cWArYUYq7u7W7PmGShMxbPxLvrwDme55a6d5alG3nrYfhyJ/G28XlLg==}- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}- peerDependencies:- eslint: ^8.57.0 || ^9.0.0 || ^10.0.0- typescript: '>=4.8.4 <6.1.0'-- '@typescript-eslint/[email protected]':- resolution: {integrity: sha512-ECiUWa/KYRGDFUqTNehaRgzDshnJfkTABJxVemHk4ko22gcr0ukloKjWvyQ64g8YCV/UI47kN1dbmjf/GaQYng==}- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}- peerDependencies:- typescript: '>=4.8.4 <6.1.0'-- '@typescript-eslint/[email protected]':- resolution: {integrity: sha512-t2LvZnoEfzKtnPjgeEu41xw5gxq9mQVfYy4OoZ4Vlt0sk3JwxmhCca/AR7DwOiHrjWgjAj6as4AhRLKSDfvZIA==}- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}-- '@typescript-eslint/[email protected]':- resolution: {integrity: sha512-PcIJHjmaREXLgIAIzLnSY9VucEzz8FKXsRgFa1DmdGCK/5tJpW03TKJF01Q6VZd1lLdz2sIKPWaDUZN9dp//dw==}- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}- peerDependencies:- typescript: '>=4.8.4 <6.1.0'-- '@typescript-eslint/[email protected]':- resolution: {integrity: sha512-g71d8QD8UaiHGvrJwyIS1hCX5r63w6Jll+4VEYhEAHXTDIqX1JgxhTAbEHtKntL9kuc4jRo7/GWw5xfCepSccQ==}- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}- peerDependencies:- eslint: ^8.57.0 || ^9.0.0 || ^10.0.0- typescript: '>=4.8.4 <6.1.0'-- '@typescript-eslint/[email protected]':- resolution: {integrity: sha512-ePFoH0g4ludssdRFqqDxQePCxU4WQyRa9+XVwjm7yLn0FKhMeoetC+qBEEI1Eyb1pGSDveTIT09Bvw2WhlGayg==}- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}-- '@typescript-eslint/[email protected]':- resolution: {integrity: sha512-CbRjVRAf7Lr9Kr8RopKcbY45p2VfmmHrm0ygOCYFi7oU8q19m0Fs/6iHS7kNOmwpp+ob07ZVcAqlxUod9lYdmg==}- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}- peerDependencies:- typescript: '>=4.8.4 <6.1.0'-- '@typescript-eslint/[email protected]':- resolution: {integrity: sha512-JAvT14goBzRzzzZyqq3P9BLArIxTtQURUtFgQ/V7FO+eU+Gg6ES+5ymOPP1wRxXcxAYeivCk4uS3jCKWI1K8Zg==}- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}- peerDependencies:- eslint: ^8.57.0 || ^9.0.0 || ^10.0.0- typescript: '>=4.8.4 <6.1.0'-- '@typescript-eslint/[email protected]':- resolution: {integrity: sha512-f1UQF7ggd42YiwI5wGrRaPsa+P0CINBlrkLPmGfpq/u/I/oVtecoEIfFR9ag/oa1sLOsRNZ6xehf6qMZhQGBDg==}- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}-- '@ungap/[email protected]':- resolution: {integrity: sha512-mUFwbeTqrVgDQxFveS+df2yfap6iuP20NAKAsBt5jDEoOTDew+zwLAOilHCeQJOVSvmgCX4ogqIrA0mnyr08yQ==}-- '@unrs/[email protected]':- resolution: {integrity: sha512-ppLRUgHVaGRWUx0R0Ut06Mjo9gBaBkg3v/8AxusGLhsIotbBLuRk51rAzqLC8gq6NyyAojEXglNjzf6R948DNw==}- cpu: [arm]- os: [android]-- '@unrs/[email protected]':- resolution: {integrity: sha512-lCxkVtb4wp1v+EoN+HjIG9cIIzPkX5OtM03pQYkG+U5O/wL53LC4QbIeazgiKqluGeVEeBlZahHalCaBvU1a2g==}- cpu: [arm64]- os: [android]-- '@unrs/[email protected]':- resolution: {integrity: sha512-gPVA1UjRu1Y/IsB/dQEsp2V1pm44Of6+LWvbLc9SDk1c2KhhDRDBUkQCYVWe6f26uJb3fOK8saWMgtX8IrMk3g==}- cpu: [arm64]- os: [darwin]-- '@unrs/[email protected]':- resolution: {integrity: sha512-cFzP7rWKd3lZaCsDze07QX1SC24lO8mPty9vdP+YVa3MGdVgPmFc59317b2ioXtgCMKGiCLxJ4HQs62oz6GfRQ==}- cpu: [x64]- os: [darwin]-- '@unrs/[email protected]':- resolution: {integrity: sha512-fqtGgak3zX4DCB6PFpsH5+Kmt/8CIi4Bry4rb1ho6Av2QHTREM+47y282Uqiu3ZRF5IQioJQ5qWRV6jduA+iGw==}- cpu: [x64]- os: [freebsd]-- '@unrs/[email protected]':- resolution: {integrity: sha512-u92mvlcYtp9MRKmP+ZvMmtPN34+/3lMHlyMj7wXJDeXxuM0Vgzz0+PPJNsro1m3IZPYChIkn944wW8TYgGKFHw==}- cpu: [arm]- os: [linux]-- '@unrs/[email protected]':- resolution: {integrity: sha512-cINaoY2z7LVCrfHkIcmvj7osTOtm6VVT16b5oQdS4beibX2SYBwgYLmqhBjA1t51CarSaBuX5YNsWLjsqfW5Cw==}- cpu: [arm]- os: [linux]-- '@unrs/[email protected]':- resolution: {integrity: sha512-34gw7PjDGB9JgePJEmhEqBhWvCiiWCuXsL9hYphDF7crW7UgI05gyBAi6MF58uGcMOiOqSJ2ybEeCvHcq0BCmQ==}- cpu: [arm64]- os: [linux]- libc: [glibc]-- '@unrs/[email protected]':- resolution: {integrity: sha512-RyMIx6Uf53hhOtJDIamSbTskA99sPHS96wxVE/bJtePJJtpdKGXO1wY90oRdXuYOGOTuqjT8ACccMc4K6QmT3w==}- cpu: [arm64]- os: [linux]- libc: [musl]-- '@unrs/[email protected]':- resolution: {integrity: sha512-D8Vae74A4/a+mZH0FbOkFJL9DSK2R6TFPC9M+jCWYia/q2einCubX10pecpDiTmkJVUH+y8K3BZClycD8nCShA==}- cpu: [ppc64]- os: [linux]- libc: [glibc]-- '@unrs/[email protected]':- resolution: {integrity: sha512-frxL4OrzOWVVsOc96+V3aqTIQl1O2TjgExV4EKgRY09AJ9leZpEg8Ak9phadbuX0BA4k8U5qtvMSQQGGmaJqcQ==}- cpu: [riscv64]- os: [linux]- libc: [glibc]-- '@unrs/[email protected]':- resolution: {integrity: sha512-mJ5vuDaIZ+l/acv01sHoXfpnyrNKOk/3aDoEdLO/Xtn9HuZlDD6jKxHlkN8ZhWyLJsRBxfv9GYM2utQ1SChKew==}- cpu: [riscv64]- os: [linux]- libc: [musl]-- '@unrs/[email protected]':- resolution: {integrity: sha512-kELo8ebBVtb9sA7rMe1Cph4QHreByhaZ2QEADd9NzIQsYNQpt9UkM9iqr2lhGr5afh885d/cB5QeTXSbZHTYPg==}- cpu: [s390x]- os: [linux]- libc: [glibc]-- '@unrs/[email protected]':- resolution: {integrity: sha512-C3ZAHugKgovV5YvAMsxhq0gtXuwESUKc5MhEtjBpLoHPLYM+iuwSj3lflFwK3DPm68660rZ7G8BMcwSro7hD5w==}- cpu: [x64]- os: [linux]- libc: [glibc]-- '@unrs/[email protected]':- resolution: {integrity: sha512-rV0YSoyhK2nZ4vEswT/QwqzqQXw5I6CjoaYMOX0TqBlWhojUf8P94mvI7nuJTeaCkkds3QE4+zS8Ko+GdXuZtA==}- cpu: [x64]- os: [linux]- libc: [musl]-- '@unrs/[email protected]':- resolution: {integrity: sha512-5u4RkfxJm+Ng7IWgkzi3qrFOvLvQYnPBmjmZQ8+szTK/b31fQCnleNl1GgEt7nIsZRIf5PLhPwT0WM+q45x/UQ==}- engines: {node: '>=14.0.0'}- cpu: [wasm32]-- '@unrs/[email protected]':- resolution: {integrity: sha512-nRcz5Il4ln0kMhfL8S3hLkxI85BXs3o8EYoattsJNdsX4YUU89iOkVn7g0VHSRxFuVMdM4Q1jEpIId1Ihim/Uw==}- cpu: [arm64]- os: [win32]-- '@unrs/[email protected]':- resolution: {integrity: sha512-DCEI6t5i1NmAZp6pFonpD5m7i6aFrpofcp4LA2i8IIq60Jyo28hamKBxNrZcyOwVOZkgsRp9O2sXWBWP8MnvIQ==}- cpu: [ia32]- os: [win32]-- '@unrs/[email protected]':- resolution: {integrity: sha512-lrW200hZdbfRtztbygyaq/6jP6AKE8qQN2KvPcJ+x7wiD038YtnYtZ82IMNJ69GJibV7bwL3y9FgK+5w/pYt6g==}- cpu: [x64]- os: [win32]-- '@vitejs/[email protected]':- resolution: {integrity: sha512-DlSMqo4WhThw4vB8Mpn0Woe9J+Jfq1geJ61AKW0QEgLzGMNwtIMdxbDUzLxcun8W7NbJO0e2Jg/Nxm3cCSVzzg==}- engines: {node: ^20.19.0 || >=22.12.0}- peerDependencies:- '@rolldown/plugin-babel': ^0.1.7 || ^0.2.0- babel-plugin-react-compiler: ^1.0.0- vite: ^8.0.0- peerDependenciesMeta:- '@rolldown/plugin-babel':- optional: true- babel-plugin-react-compiler:- optional: true-- '@vitest/[email protected]':- resolution: {integrity: sha512-IM49HmthevbgAO4anp1hwtoT9wYe59w0LR00gr+eagHE+ZJ5lK4sLPeO0ubgoJcwLk6dehU3R24N+FbEEKDc8g==}- peerDependencies:- '@vitest/browser': 4.1.10- vitest: 4.1.10- peerDependenciesMeta:- '@vitest/browser':- optional: true-- '@vitest/[email protected]':- resolution: {integrity: sha512-YsCn+qAk1GWjQOWFEsEcL2gNQ0zmVmQu3T03qP6UyjhtmdtwtbuI+DASn/7iQB3HGTXkdBwGddzxPlmiql5vlA==}-- '@vitest/[email protected]':- resolution: {integrity: sha512-v0xaezt+DKEmKfaxg133ldzADrwLGd7Ze1MfQQTYfvs8OqZIwbxyxaYURivwV7sWy5fqn3rH5uOrSp07bp44Ow==}- peerDependencies:- msw: ^2.4.9- vite: ^6.0.0 || ^7.0.0 || ^8.0.0- peerDependenciesMeta:- msw:- optional: true- vite:- optional: true-- '@vitest/[email protected]':- resolution: {integrity: sha512-W1HsjSH4MXQ9YfmmhLAoIYf1HRfekQCGngeIgcei6MP5QQGWUe0gkopdZQaVCFO+JDJMrAJGwa5pRpNpvy4P8Q==}-- '@vitest/[email protected]':- resolution: {integrity: sha512-IKI6kpIH+LmpROplyLwBBaCfMgOZOMsygVa6BARD6ahA04VRuJSa6OaVG7kRvSEMD870Vd91rSSw0eegtWyLGg==}-- '@vitest/[email protected]':- resolution: {integrity: sha512-xRkfOT1qpTAi/Ti4Y1LtfRc3kEuqxGw59eN2jN9pRWMtS/XDevekhcFSqvQqjUNGksfjMJu3Y+oJ+4Ypn2OaJw==}-- '@vitest/[email protected]':- resolution: {integrity: sha512-PLf/Ugvoq5wO/b4rwYCR1h2PSIdXz7wnkQFMiUpLdtM7l6pqVFcQIBEHyT1+l+cj7mNwAfZHzqXqDyjvOuwbDw==}-- '@vitest/[email protected]':- resolution: {integrity: sha512-fy9am/HWxbaGt/Sawrp90vt6Y6jQwf1RX77cz3uwoJwJVMli/e1IEwRPnMNJ7vKfPTwo0diXifkpPvwH9v7nGA==}-- resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==}- peerDependencies:- acorn: ^6.0.0 || ^7.0.0 || ^8.0.0-- resolution: {integrity: sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==}- engines: {node: '>=0.4.0'}- hasBin: true-- resolution: {integrity: sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==}-- resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==}- engines: {node: '>=8'}-- resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==}- engines: {node: '>=8'}-- resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==}- engines: {node: '>=10'}-- resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==}-- resolution: {integrity: sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==}- engines: {node: '>=10'}-- resolution: {integrity: sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==}-- resolution: {integrity: sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-FmeCCAenzH0KH381SPT5FZmiA/TmpndpcaShhfgEN9eCVjnFBqq3l1xrI42y8+PPLI6hypzou4GXw00WHmPBLQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-CVvd6FHg1Z3POpBLxO6E6zr+rSKEQ9L6rZHAaY7lLfhKsWYUBBOuMs0e9o24oopj6H+geRCX0YJ+TJLBK2eHyQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-F/TKATkzseUExPlfvmwQKGITM3DGTK+vkAsCZoDc5daVygbJBnjEUCbgkAvVFsgfXfX4YIqZ/27G3k3tdXrTxQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-rwG/ja1neyLqCuGZ5YYrznA62D4mZXg0i1cIskIUKSiqF3Cje9/wXAls9B9s1Wa2fomMsIv8czB8jZcPmxCXFg==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-Y7Wt51eKJSyi80hFrJCePGGNo5ktJCslFuboqJsbf57CCPcm5zztluPlc4/aD8sWsKvlwatezpV4U1efk8kpjg==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-p6Fx8B7b7ZhL/gmUsAy0D15WhvDccw3mnGNbZpi3pmeJdxtWsj2jEaI4Y6oo3XiHfzuSgPwKc04MYt6KgvC/wA==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}- engines: {node: '>=12'}-- resolution: {integrity: sha512-OH/2E5Fg20h2aPrbe+QL8JZQFko0YZaF+j4mnQ7BGhfavO7OpSLa8a0y9sBwomHdSbkhTS8TQNayBfnW5DwbvQ==}-- resolution: {integrity: sha512-UPAgKJFSEGMWSDr3LX4tqnAb4f7KGT8O40Tyx8wbYmmZ/yn58lNCm8h3svs3eXgiGd5AXxz8NDOvXWvicq+rJA==}-- resolution: {integrity: sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-KunSNx+TVpkAw/6ULfhnx+HWRecjqZGTOyquAoWHYLRSdK1tB5Ihce1ZW+UY3fj33bYAFWPu7W/GRSmmrCGuxA==}- engines: {node: '>=4'}-- resolution: {integrity: sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==}-- resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}-- resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==}- engines: {node: 18 || 20 || >=22}-- resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}-- resolution: {integrity: sha512-xjOFN16Ha1+Rz4nFYKqHU/LSB+gx/Vi3yQLX7r7sAW+Wa+8hhF2h4pvqTrTMc8+WcDBEunnUurr46Jvv0jk3Vg==}- engines: {node: '>=6.0.0'}- hasBin: true-- resolution: {integrity: sha512-CyzaZRQKyHkB2ZInfTTl2nvT33EbDpjkLEbE8/Zck3Ll6O0qqvuGdrJ45HgtH+HykRg88ITY3AdreBGN70aBSQ==}- engines: {node: 20.x || 22.x || 23.x || 24.x || 25.x || 26.x}-- resolution: {integrity: sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==}-- resolution: {integrity: sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==}-- resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==}-- resolution: {integrity: sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g==}-- resolution: {integrity: sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==}- engines: {node: 18 || 20 || >=22}-- resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==}- engines: {node: '>=8'}-- resolution: {integrity: sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==}- engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}- hasBin: true-- resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==}-- resolution: {integrity: sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q==}- engines: {node: '>=18'}-- resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==}- engines: {node: '>=6'}-- resolution: {integrity: sha512-iwSsYWaCOoh26cV8NwNRViHlrfUvYsHDfRVcbtmw0Kg6PJIZZXwMkj1442FYLBGkeUf1juAsU3DTfxW579mrPA==}-- resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==}-- resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==}- engines: {node: '>=18'}-- resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==}- engines: {node: '>=10'}-- resolution: {integrity: sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==}-- resolution: {integrity: sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==}-- resolution: {integrity: sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==}-- resolution: {integrity: sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==}-- resolution: {integrity: sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==}-- resolution: {integrity: sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==}-- resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==}-- resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==}- engines: {node: '>=6'}-- resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==}- engines: {node: '>=7.0.0'}-- resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==}-- resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==}-- resolution: {integrity: sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==}- engines: {node: '>=18'}-- resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==}-- resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}-- resolution: {integrity: sha512-oML4lKUXxizYswqmxuOCpgFS8BNUJpIu6k/2HVHyaL8Ynnf3wdf9tkns0yRdJLSIjkJ+b0DXHMZEHGpMwjnPww==}- engines: {node: '>=18'}-- resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}- engines: {node: '>= 8'}-- resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==}- engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0}-- resolution: {integrity: sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==}-- resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}-- resolution: {integrity: sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==}-- resolution: {integrity: sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==}- engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}-- resolution: {integrity: sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==}- peerDependencies:- supports-color: '*'- peerDependenciesMeta:- supports-color:- optional: true-- resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}- engines: {node: '>=6.0'}- peerDependencies:- supports-color: '*'- peerDependenciesMeta:- supports-color:- optional: true-- resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==}-- resolution: {integrity: sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==}-- resolution: {integrity: sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==}- engines: {node: '>=10'}-- resolution: {integrity: sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==}- engines: {node: '>=4.0.0'}-- resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==}-- resolution: {integrity: sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q==}- engines: {node: '>=18'}-- resolution: {integrity: sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw==}- engines: {node: '>=18'}-- resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg==}- engines: {node: '>=12'}-- resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==}- engines: {node: '>=6'}-- resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}- engines: {node: '>=8'}-- resolution: {integrity: sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ==}-- resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==}-- resolution: {integrity: sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==}- engines: {node: '>=0.10.0'}-- resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==}-- resolution: {integrity: sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==}-- resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-NHlTIQDK8fmVwHwuIzmXYEJ1Ewq3D9wDNc0cWXxDGysP6Pb21giwGNkxiTifyKy/4SoPuN5l6GLP1W9Sv7zB2g==}-- resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==}-- resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==}-- resolution: {integrity: sha512-QyL119InA+XXEkNLNTPCXPugSvOfhwv0JOlGNzvxs0hZaiHLNvXSpudUWsOlsXGWJh8G6ckCScEkVHfX3kw/2Q==}- engines: {node: '>=10.13.0'}-- resolution: {integrity: sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==}- engines: {node: '>=20.19.0'}-- resolution: {integrity: sha512-2FpH9Q5i2RRwyEP1AylXe6nYLR5OhaJTZwmlcP0dL/+JCbgg7yyEo/sEK6HeGZRf3dFpWwThaRHVApXSkW3xeg==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-HVLACW1TppGYjJ8H6/jqH/pqOtKRw6wMlrB23xfExmFWxFquAIWCmwoLsOyN96K4a5KbmOf5At9ZUO3GZbetAw==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-shc1dbU90Yl/xq1QrC7QRtfcwURZuVRfPhZbDoldJ1cn1gzDvBaBWlv0eFolj5+0znnPJz5TXLxsN77X/12KTA==}-- resolution: {integrity: sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-d9T8ucsEhh8Bi1woXCf+TIKDIROLG5WCkxg8geBCbvk22kzwC5G2OnXVMO6FUsvQlgUUXQ2itephWDLqDzbeCw==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-w+5mJ3GuFL+NjVtJlvydShqE1eN3h3PbI7/5LAsYJP/2qtuMXjfL2LpHSRqo4b4eSF5K/DH1JXKUAHSB2UW50g==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-sNR9MHpXSUV/XB4zmsFKN+QgVG82Cc7+/aaxJ8Adi8hyOac+EXptIp45QBPaVyX3N70664wRbTcLTOemCAnyqw==}- engines: {node: '>=18'}- hasBin: true-- resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==}- engines: {node: '>=6'}-- resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==}- engines: {node: '>=10'}-- resolution: {integrity: sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==}- engines: {node: '>=12'}-- resolution: {integrity: sha512-z2ELYSkyrrJ6cuunTU8vhsT/RpouPkjaSah06nVW6Rg2Hpg0Vs8s497/e5s8G8qtdp4ccsiovz5P1rv+5VSW2Q==}- peerDependencies:- eslint: '>=9.0.0'- typescript: '>=3.3.1'- peerDependenciesMeta:- typescript:- optional: true-- resolution: {integrity: sha512-tRrKqFyCaKict5hOd244sL6EQFNycnMQnBe+j8uqGNXYzsImGbGUU4ibtoaBmv5FLwJwcFJNeg1GeVjQfbMrDQ==}-- resolution: {integrity: sha512-A1rHYb06zjMGAxdLSkN2fXPBwuSaQ0iO5M/hdyS0Ajj1VBaRp0sPD3dn1FhME3c/JluGFbwSxyCfqdSbtQLAHQ==}- engines: {node: ^14.18.0 || >=16.0.0}- peerDependencies:- eslint: '*'- eslint-plugin-import: '*'- eslint-plugin-import-x: '*'- peerDependenciesMeta:- eslint-plugin-import:- optional: true- eslint-plugin-import-x:- optional: true-- resolution: {integrity: sha512-L8jSWTze7K2mTg0vos/RuLRS5soomksDPoJLXIslC7c8Wmut3bx7CPpJijDcBZtxQ5lrbUdM+s0OlNbz0DCDNw==}- engines: {node: '>=4'}- peerDependencies:- '@typescript-eslint/parser': '*'- eslint: '*'- eslint-import-resolver-node: '*'- eslint-import-resolver-typescript: '*'- eslint-import-resolver-webpack: '*'- peerDependenciesMeta:- '@typescript-eslint/parser':- optional: true- eslint:- optional: true- eslint-import-resolver-node:- optional: true- eslint-import-resolver-typescript:- optional: true- eslint-import-resolver-webpack:- optional: true-- resolution: {integrity: sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==}- engines: {node: '>=4'}- peerDependencies:- '@typescript-eslint/parser': '*'- eslint: ^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8 || ^9- peerDependenciesMeta:- '@typescript-eslint/parser':- optional: true-- resolution: {integrity: sha512-scB3nz4WmG75pV8+3eRUQOHZlNSUhFNq37xnpgRkCCELU3XMvXAxLk1eqWWyE22Ki4Q01Fnsw9BA3cJHDPgn2Q==}- engines: {node: '>=4.0'}- peerDependencies:- eslint: ^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9-- resolution: {integrity: sha512-f2I7Gw6JbvCexzIInuSbZpfdQ44D7iqdWX01FKLvrPgqxoE7oMj8clOfto8U6vYiz4yd5oKu39rRSVOe1zRu0g==}- engines: {node: '>=18'}- peerDependencies:- eslint: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0-- resolution: {integrity: sha512-Qteup0SqU15kdocexFNAJMvCJEfa2xUKNV4CC1xsVMrIIqEy3SQ/rqyxCWNzfrd3/ldy6HMlD2e0JDVpDg2qIA==}- engines: {node: '>=4'}- peerDependencies:- eslint: ^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7-- resolution: {integrity: sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==}- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}-- resolution: {integrity: sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==}- engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}-- resolution: {integrity: sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==}- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}-- resolution: {integrity: sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==}- engines: {node: ^20.19.0 || ^22.13.0 || >=24}-- resolution: {integrity: sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ==}- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}- hasBin: true- peerDependencies:- jiti: '*'- peerDependenciesMeta:- jiti:- optional: true-- resolution: {integrity: sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==}- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}-- resolution: {integrity: sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==}- engines: {node: '>=0.10'}-- resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==}- engines: {node: '>=4.0'}-- resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==}- engines: {node: '>=4.0'}-- resolution: {integrity: sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==}-- resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}-- resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==}- engines: {node: '>=0.10.0'}-- resolution: {integrity: sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==}- engines: {node: '>=6'}-- resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==}- engines: {node: '>=12.0.0'}-- resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==}-- resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}-- resolution: {integrity: sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg==}- engines: {node: '>=8.6.0'}-- resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==}-- resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==}-- resolution: {integrity: sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==}-- resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}- engines: {node: '>=12.0.0'}- peerDependencies:- picomatch: ^3 || ^4- peerDependenciesMeta:- picomatch:- optional: true-- resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==}- engines: {node: '>=16.0.0'}-- resolution: {integrity: sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==}-- resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==}- engines: {node: '>=8'}-- resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==}- engines: {node: '>=10'}-- resolution: {integrity: sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==}- engines: {node: '>=16'}-- resolution: {integrity: sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==}-- resolution: {integrity: sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==}-- resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}- engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}- os: [darwin]-- resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==}-- resolution: {integrity: sha512-e5iwyodOHhbMr/yNrc7fDYG4qlbIvI5gajyzPnb5TCwyhjApznQh1BMFou9b30SevY43gCJKXycoCBjMbsuW0Q==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==}-- resolution: {integrity: sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==}- engines: {node: '>=6.9.0'}-- resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q==}- engines: {node: '>=6'}-- resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA==}-- resolution: {integrity: sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==}-- resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==}- engines: {node: '>= 6'}-- resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==}- engines: {node: '>=10.13.0'}-- resolution: {integrity: sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==}- engines: {node: '>=18'}-- resolution: {integrity: sha512-ob/2LcVVaVGCYN+r14cnwnoDPUufjiYgSqRhiFD0Q1iI4Odora5RE8Iv1D24hAz5oMophRGkGz+yuvQmmUMnMw==}- engines: {node: '>=18'}-- resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}-- resolution: {integrity: sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==}- engines: {node: '>=8'}-- resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==}-- resolution: {integrity: sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg==}-- resolution: {integrity: sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==}-- resolution: {integrity: sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==}-- resolution: {integrity: sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==}-- resolution: {integrity: sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==}- engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}-- resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==}-- resolution: {integrity: sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ==}-- resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==}-- resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==}- engines: {node: '>= 4'}-- resolution: {integrity: sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==}- engines: {node: '>= 4'}-- resolution: {integrity: sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==}- engines: {node: '>=6'}-- resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==}- engines: {node: '>=0.8.19'}-- resolution: {integrity: sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==}- engines: {node: '>=8'}-- resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}-- resolution: {integrity: sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==}-- resolution: {integrity: sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==}-- resolution: {integrity: sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==}-- resolution: {integrity: sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==}-- resolution: {integrity: sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-gNCGbnnnnFAUGKeZ9PdbyeGYJqewpmc2aKHUEMO5nQPWU9lOmv7jcmQIv+qHD8fXW6W7qfuCwX4rY9LNRjXrkQ==}-- resolution: {integrity: sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==}-- resolution: {integrity: sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==}- engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}- hasBin: true-- resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==}- engines: {node: '>=0.10.0'}-- resolution: {integrity: sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-upqt1SkGkODW9tsGNG5mtXTXtECizwtS2kA161M+gJPc1xdb/Ax629af6YrTwcOeQHbewrPNlE5Dx7kzvXTizA==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==}- engines: {node: '>=0.10.0'}-- resolution: {integrity: sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==}-- resolution: {integrity: sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==}- engines: {node: '>=14.16'}- hasBin: true-- resolution: {integrity: sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==}- engines: {node: '>=0.12.0'}-- resolution: {integrity: sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==}- engines: {node: '>=12'}-- resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==}-- resolution: {integrity: sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw==}- engines: {node: '>=16'}-- resolution: {integrity: sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==}-- resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}-- resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==}- engines: {node: '>=8'}-- resolution: {integrity: sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==}- engines: {node: '>=10'}-- resolution: {integrity: sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==}- engines: {node: '>=8'}-- resolution: {integrity: sha512-H0dkQoCa3b2VEeKQBOxFph+JAbcrQdE7KC0UkqwpLmv2EC4P41QXP+rqo9wYodACiG5/WM5s9oDApTU8utwj9g==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}- hasBin: true-- resolution: {integrity: sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==}-- resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}-- resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==}- hasBin: true-- resolution: {integrity: sha512-ECi4Fi2f7BdJtUKTflYRTiaMxIB0O6zfR1fX0GXpUrf6flp8QIYn1UT20YQqdSOfk2dfkCwS8LAFoJDEppNK5Q==}- engines: {node: ^20.19.0 || ^22.13.0 || >=24.0.0}- peerDependencies:- canvas: ^3.0.0- peerDependenciesMeta:- canvas:- optional: true-- resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==}- engines: {node: '>=6'}- hasBin: true-- resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==}-- resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==}-- resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==}-- resolution: {integrity: sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==}- hasBin: true-- resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==}- engines: {node: '>=6'}- hasBin: true-- resolution: {integrity: sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ==}- engines: {node: '>=4.0'}-- resolution: {integrity: sha512-VPD8mtVtm5JNtA2AErl6Chp06JBfy7diFQ7TQQhdpWOl6MrCRB+eRbvAZUsbGQS9kiMq0coJsy0W0vHpDCkWsQ==}-- resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==}-- resolution: {integrity: sha512-0K65Lea881pHotoGEa5gDlMxt3pctLi2RplBb7Ezh4rRdLEOtgi7n4EwK9lamnUCkKBqaeKRVebTq6BAxSkpXQ==}-- resolution: {integrity: sha512-MbjN408fEndfiQXbFQ1vnd+1NoLDsnQW41410oQBXiyXDMYH5z505juWa4KUE1LqxRC7DgOgZDbKLxHIwm27hA==}- engines: {node: '>=0.10'}-- resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==}- engines: {node: '>= 0.8.0'}-- resolution: {integrity: sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==}- engines: {node: '>= 12.0.0'}- cpu: [arm64]- os: [android]-- resolution: {integrity: sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==}- engines: {node: '>= 12.0.0'}- cpu: [arm64]- os: [darwin]-- resolution: {integrity: sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==}- engines: {node: '>= 12.0.0'}- cpu: [x64]- os: [darwin]-- resolution: {integrity: sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==}- engines: {node: '>= 12.0.0'}- cpu: [x64]- os: [freebsd]-- resolution: {integrity: sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==}- engines: {node: '>= 12.0.0'}- cpu: [arm]- os: [linux]-- resolution: {integrity: sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==}- engines: {node: '>= 12.0.0'}- cpu: [arm64]- os: [linux]- libc: [glibc]-- resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==}- engines: {node: '>= 12.0.0'}- cpu: [arm64]- os: [linux]- libc: [musl]-- resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==}- engines: {node: '>= 12.0.0'}- cpu: [x64]- os: [linux]- libc: [glibc]-- resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==}- engines: {node: '>= 12.0.0'}- cpu: [x64]- os: [linux]- libc: [musl]-- resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==}- engines: {node: '>= 12.0.0'}- cpu: [arm64]- os: [win32]-- resolution: {integrity: sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==}- engines: {node: '>= 12.0.0'}- cpu: [x64]- os: [win32]-- resolution: {integrity: sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==}- engines: {node: '>= 12.0.0'}-- resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==}- engines: {node: '>=10'}-- resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==}-- resolution: {integrity: sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==}-- resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}- hasBin: true-- resolution: {integrity: sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==}- engines: {node: 20 || >=22}-- resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}-- resolution: {integrity: sha512-BVtq/DykVeIvRTJvRAgCsOwaGL8Un3Bxh8MbDxMhEWlZay3T4IpEKDEpwt5KZ0KJMHzgm6jrltxlT5eXOWXDHg==}- peerDependencies:- react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0-rc-- resolution: {integrity: sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==}- engines: {node: '>=12'}-- resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==}- hasBin: true-- resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}-- resolution: {integrity: sha512-pVKE4UdSQ7DvHzivsCIFx2BJn1mHG6KsyrFcaxFx6tONdneEuThrDx0Cj3AMg58KyN4pzYT+LHOotxDQDjNvkw==}-- resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==}- engines: {node: '>=10'}-- resolution: {integrity: sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==}-- resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg==}-- resolution: {integrity: sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q==}-- resolution: {integrity: sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ==}-- resolution: {integrity: sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ==}-- resolution: {integrity: sha512-mKKb915TF+OC5ptj5bJ7WFRPdYtuHv0yTRxK2tJvi+BDqbkiG7h7u/9SI89nRAYcmap2xHQL9D+QG/6wSrTtXg==}-- resolution: {integrity: sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg==}-- resolution: {integrity: sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ==}-- resolution: {integrity: sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==}-- resolution: {integrity: sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ==}-- resolution: {integrity: sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==}-- resolution: {integrity: sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==}-- resolution: {integrity: sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w==}-- resolution: {integrity: sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==}-- resolution: {integrity: sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==}-- resolution: {integrity: sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==}-- resolution: {integrity: sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==}-- resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==}- engines: {node: '>= 8'}-- resolution: {integrity: sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==}-- resolution: {integrity: sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==}-- resolution: {integrity: sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==}-- resolution: {integrity: sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==}-- resolution: {integrity: sha512-t2OU/dXXioARrC6yWfJ4hqB7rct14e8f7m0cbI5hUmDyyIlwv5vEtooptH8INkbLzOatzKuVbQmAYcbWoyz6Dg==}-- resolution: {integrity: sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==}-- resolution: {integrity: sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==}-- resolution: {integrity: sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==}-- resolution: {integrity: sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==}-- resolution: {integrity: sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==}-- resolution: {integrity: sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==}-- resolution: {integrity: sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==}-- resolution: {integrity: sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==}-- resolution: {integrity: sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==}-- resolution: {integrity: sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==}-- resolution: {integrity: sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==}-- resolution: {integrity: sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==}-- resolution: {integrity: sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==}-- resolution: {integrity: sha512-nDV/77Fj6eH1ynwscYTOsbK7rR//Uj0bZXBwJZRfaLEJ1iGBR6kIfNmlNqaqJf649EP0F3NWNdeJi03elllNUQ==}-- resolution: {integrity: sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==}-- resolution: {integrity: sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==}-- resolution: {integrity: sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==}-- resolution: {integrity: sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==}-- resolution: {integrity: sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==}-- resolution: {integrity: sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==}-- resolution: {integrity: sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==}-- resolution: {integrity: sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==}-- resolution: {integrity: sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==}-- resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==}- engines: {node: '>=8.6'}-- resolution: {integrity: sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==}- engines: {node: '>=10'}-- resolution: {integrity: sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==}- engines: {node: '>=4'}-- resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==}- engines: {node: 18 || 20 || >=22}-- resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==}-- resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==}-- resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==}-- resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}-- resolution: {integrity: sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==}- engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}- hasBin: true-- resolution: {integrity: sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==}-- resolution: {integrity: sha512-PHI5f1O0EP5xJ9gQmFGMS6IZcrVvTjpXjz7Na41gTE7eE2hK11lg04CECCYEEjdc17EV4DO+fkGEtt7TpTaTiQ==}- engines: {node: ^12.20.0 || ^14.18.0 || >=16.0.0}- hasBin: true-- resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==}-- resolution: {integrity: sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA==}- peerDependencies:- react: ^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc- react-dom: ^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc-- resolution: {integrity: sha512-qOVgKJg1+At15NpeUP+eJgCHvTCgXsogweq87Ri/Ix7PkqQHg4sdaXmSFqKlgaIXE4kW0g25LE68W87UANlHtw==}- engines: {node: '>=20.9.0'}- hasBin: true- peerDependencies:- '@opentelemetry/api': ^1.1.0- '@playwright/test': ^1.51.1- babel-plugin-react-compiler: '*'- react: ^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0- react-dom: ^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0- sass: ^1.3.0- peerDependenciesMeta:- '@opentelemetry/api':- optional: true- '@playwright/test':- optional: true- babel-plugin-react-compiler:- optional: true- sass:- optional: true-- resolution: {integrity: sha512-KdHvFWZjEKDf0cakgFjebl371GPsISX2oZHcuyKqM7DtogIsHrqKeLTo8wBHxaXRAQlY2PsPlZmfo+9ZCxEREQ==}- engines: {node: '>=10'}-- resolution: {integrity: sha512-73sE9+3UaLYYFmDsFZnqCInzPyh3MqIwZO9cw58yIqAZhONrrabrYyYe3TuIqtIiOuTXVhsGau8hcrhhwSsDIQ==}-- resolution: {integrity: sha512-pyFS63ptit/P5WqUkt+UUfe+4oevH+bFeIiPPdfb0pFeYEu/1ELnJu5l+5EcTKYL5M7zaAa7S8ddywgXypqKCw==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-5WUyunoPMsvvEhS8AxHtRzP+oA8UCkJ7YRxatWKjngndhDGLiqEVAQKWjFAiAiuL8zMRGzGSJxFnLetoa43qGQ==}-- resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}- engines: {node: '>=0.10.0'}-- resolution: {integrity: sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-8u/hfXFRBD1O0hPUjioLhoWFHRmt6tKA4/vZPyckBr18l1KE9uHrFaFaUi8MDRTpi4uak2goyPTSNJLXX2k2Hw==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-+Lhy3TQTuzXI5hevh8sBGqbmurHbbIjAi0Z4S63nthVLmLxfbj4T54a4CfZrXIrt9iP4mVAPYMo/v99taj3wjQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-9miFgM2OFba7hB+pRgvtV84pYTBaoTHohvmIgiRt6dRIzbwEOIaNaP+dIlGs2fNFoB0SeISs0Jz5WFVRid6Xyg==}- engines: {node: '>=12.20.0'}-- resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}-- resolution: {integrity: sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA==}- engines: {node: '>=18'}-- resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==}- engines: {node: '>= 0.8.0'}-- resolution: {integrity: sha512-qFOyK5PjiWZd+QQIh+1jhdb9LpxTF0qs7Pm8o5QHYZ0M3vKqSqzsZaEB6oWlxZ+q2sJBMI/Ktgd2N5ZwQoRHfg==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==}- engines: {node: '>=10'}-- resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==}- engines: {node: '>=10'}-- resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==}- engines: {node: '>=6'}-- resolution: {integrity: sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==}-- resolution: {integrity: sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==}-- resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==}- engines: {node: '>=8'}-- resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==}- engines: {node: '>=8'}-- resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==}-- resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}-- resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}-- resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==}- engines: {node: '>=8.6'}-- resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==}- engines: {node: '>=12'}-- resolution: {integrity: sha512-9bW6zvX/m0lEbgTKJ6YppOKx8H3VOPBMOCFh2irXFOT4BbHgrx5hPjwJYLT40Lu+4qtD36qKc/Hn56StUW57IA==}- engines: {node: '>=18'}- hasBin: true-- resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==}- engines: {node: ^10 || ^12 || >=14}-- resolution: {integrity: sha512-SoSL4+OSEtR99LHFZQiJLkT59C5B1amGO1NzTwj7TT1qCUgUO6hxOvzkOYxD+vMrXBM3XJIKzokoERdqQq/Zmg==}- engines: {node: ^10 || ^12 || >=14}-- resolution: {integrity: sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==}- engines: {node: '>=10'}- deprecated: No longer maintained. Please contact the author of the relevant native addon; alternatives are available.- hasBin: true-- resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==}- engines: {node: '>= 0.8.0'}-- resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==}- engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0}-- resolution: {integrity: sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==}-- resolution: {integrity: sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==}-- resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==}-- resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}- engines: {node: '>=6'}-- resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}-- resolution: {integrity: sha512-aWizCQiyeAenIdUbqEpXgRA1ya65P13NKn/W8rWkcN0OPkRDxdBVLWnIEDsS2RpwCK2nobI7oMUSmexzTDyAmA==}- peerDependencies:- '@types/react': '*'- '@types/react-dom': '*'- react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true- '@types/react-dom':- optional: true-- resolution: {integrity: sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==}- hasBin: true-- resolution: {integrity: sha512-0prMI+hvBbPjsWnxDLxlCGyM8PN6UuWjEUCYmZhO67xIV9Xasa/r/vDnq+Xyq4Lo27g8QSbO5YzARu0D1Sps3g==}- peerDependencies:- react: ^19.2.6-- resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}-- resolution: {integrity: sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==}-- resolution: {integrity: sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==}- peerDependencies:- '@types/react': '>=18'- react: '>=18'-- resolution: {integrity: sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q==}- engines: {node: '>=10'}- peerDependencies:- '@types/react': '*'- react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0- peerDependenciesMeta:- '@types/react':- optional: true-- resolution: {integrity: sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q==}- engines: {node: '>=10'}- peerDependencies:- '@types/react': '*'- react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true-- resolution: {integrity: sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==}- engines: {node: '>=10'}- peerDependencies:- '@types/react': '*'- react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true-- resolution: {integrity: sha512-sfWGGfavi0xr8Pg0sVsyHMAOziVYKgPLNrS7ig+ivMNb3wbCBw3KxtflsGBAwD3gYQlE/AEZsTLgToRrSCjb0Q==}- engines: {node: '>=0.10.0'}-- resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==}- engines: {node: '>= 6'}-- resolution: {integrity: sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==}- engines: {node: '>=8'}-- resolution: {integrity: sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==}-- resolution: {integrity: sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==}-- resolution: {integrity: sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==}-- resolution: {integrity: sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==}-- resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}- engines: {node: '>=0.10.0'}-- resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==}- engines: {node: '>=4'}-- resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==}-- resolution: {integrity: sha512-tqt+NBWwyaMgw3zDsnygx4CByWjQEJHOPMdslYhppaQSJUtL/D4JO9CcBBlhPoI8lz9oJIDXkwXfhF4aWqP8xQ==}- engines: {node: '>= 0.4'}- hasBin: true-- resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==}- engines: {iojs: '>=1.0.0', node: '>=0.10.0'}-- resolution: {integrity: sha512-X0KQHljNnEkWNqqiz9zJrGunh1B0HgOxLXvnFpCOcadzcy5qohZ3tqMEUg00vncoRovXuK3ZqCT9KnnKzoInFQ==}- engines: {node: ^20.19.0 || >=22.12.0}- hasBin: true-- resolution: {integrity: sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q==}- engines: {node: '>=18'}-- resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==}-- resolution: {integrity: sha512-wtZlHyOje6OZTGqAoaDKxFkgRtkF9CnHAVnCHKfuj200wAgL+bSJhdsCD2l0Qx/2ekEXjPWcyKkfGb5CPboslg==}- engines: {node: '>=0.4'}-- resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==}-- resolution: {integrity: sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==}- engines: {node: '>=v12.22.7'}-- resolution: {integrity: sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==}-- resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==}- hasBin: true-- resolution: {integrity: sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==}- engines: {node: '>=10'}- hasBin: true-- resolution: {integrity: sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==}- engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}-- resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==}- engines: {node: '>=8'}-- resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==}- engines: {node: '>=8'}-- resolution: {integrity: sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}-- resolution: {integrity: sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==}-- resolution: {integrity: sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==}-- resolution: {integrity: sha512-W6ZN4p58k8aDKA4XPcx2hpIQXBRAgyiWVkYhT7CvK6D3iAu7xjvVyhQHg2/iaKJZ1XVJ4r7XuwGL+WGEK37i9w==}- peerDependencies:- react: ^18.0.0 || ^19.0.0 || ^19.0.0-rc- react-dom: ^18.0.0 || ^19.0.0 || ^19.0.0-rc-- resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}- engines: {node: '>=0.10.0'}-- resolution: {integrity: sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==}-- resolution: {integrity: sha512-+L3ccpzibovGXFK+Ap/f8LOS0ahMrHTf3xu7mMLSpEGU0EO9ucaysSylKo9eRDFNhWve/y275iPmIZ4z39a9iA==}-- resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}-- resolution: {integrity: sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==}-- resolution: {integrity: sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-o7+c9bW6zpAdJHTtujeePODAhkuicdAryFsfVKwA+wGw89wJ4GTY484WTucM9hLtDEOpOvI+aHnzqnC5lHp4Rg==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-6CC9uyBL+/48dYizRf7H7VAYCMCNTBeM78x/VTUe9bFEaxBepPJDa1Ow99LqI/1yF7kuy7Q3cQsYMrcjGUcskA==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-0u/TldDbKD8bFCQ/4f5+mNRrXwZ8hg2w7ZR8wa16e8z9XpePWl3eGEcUD0OXpEH/VJH/2G3gjUtR3ZOiBe2S/w==}-- resolution: {integrity: sha512-Rs66F0P/1kedk5lyYyH9uBzuiI/kNRmwJAR9quK6VOtIpZ2G+hMZd+HQbbv25MgCA6gEffoMZYxlTod4WcdrKA==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-G7Ok5C6E/j4SGfyLCloXTrngQIQU3PWtXGst3yM7Bea9FRURf1S42ZHlZZtsNque2FN2PoUhfZXYLNWwEr4dLQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==}-- resolution: {integrity: sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==}-- resolution: {integrity: sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==}- engines: {node: '>=4'}-- resolution: {integrity: sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==}- engines: {node: '>=8'}-- resolution: {integrity: sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==}- engines: {node: '>=0.10.0'}-- resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==}- engines: {node: '>=8'}-- resolution: {integrity: sha512-RjQetxJrrUJLQPHbLku6U/ocGtzyjbJMP9lCNK7Ag0CNh690nSH8woqWH9u16nMjYBAok+i7JO1NP2pOy8IsPQ==}-- resolution: {integrity: sha512-LIN7rULI0jBscWQYaSswptyderlarFkjQ+t79nzty8tcIAceVomEVlLzH5VP4Cmsv6MtKhs7qaAiwlcp+Mgaxw==}-- resolution: {integrity: sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==}- engines: {node: '>= 12.0.0'}- peerDependencies:- '@babel/core': '*'- babel-plugin-macros: '*'- react: '>= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0'- peerDependenciesMeta:- '@babel/core':- optional: true- babel-plugin-macros:- optional: true-- resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==}- engines: {node: '>=8'}-- resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==}-- resolution: {integrity: sha512-Oo6tHdpZsGpkKG88HJ8RR1rg/RdnEkQEfMoEk2x1XRI3F1AxeU+ijRXpiVUF4UbLfcxxRGw6TbUINKYdWVsQTQ==}-- resolution: {integrity: sha512-y6nxMGB1nMW9R6k96e5gdIFzcfL/gTJRNaqGes1YvkLnPVXzWgbqFF2yLC0T8G774n24cx3Pe8XrKoniCOAH+Q==}-- resolution: {integrity: sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==}- engines: {node: '>=6'}-- resolution: {integrity: sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==}-- resolution: {integrity: sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==}- engines: {node: '>=6'}-- resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}-- resolution: {integrity: sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg==}- engines: {node: '>=18'}-- resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==}- engines: {node: '>=12.0.0'}-- resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==}- engines: {node: '>=14.0.0'}-- resolution: {integrity: sha512-c1P7u0EhACHj7lPy4MJm8iTFEU8+nB0LCtddH0fhP7noaVoXAqafMtOOeX+ulpuPBqnrRgRhw494RICT3mbhnw==}-- resolution: {integrity: sha512-htwgN/8KRB3z3vnC0BOETVh2m499g5GmyTK9Wq5JBLX3FNz6tSBveAd+fQhzy9hkjif8vy2jwDMR1sGhLtZl2A==}- hasBin: true-- resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==}- engines: {node: '>=8.0'}-- resolution: {integrity: sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==}- engines: {node: '>=16'}-- resolution: {integrity: sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==}- engines: {node: '>=20'}-- resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==}-- resolution: {integrity: sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==}-- resolution: {integrity: sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==}- engines: {node: '>=18.12'}- peerDependencies:- typescript: '>=4.8.4'-- resolution: {integrity: sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg==}-- resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}-- resolution: {integrity: sha512-TvncJykhxAzFCk0VQZKBTClall4Pm7qXDSodb6uxi8QFa8X8mT6ABjxxsQ2opDRYxG7AzcRWXaFtruz5HJKuWg==}- engines: {node: '>=18.0.0'}- hasBin: true-- resolution: {integrity: sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==}-- resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==}- engines: {node: '>= 0.8.0'}-- resolution: {integrity: sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-bTlAFB/FBYMcuX81gbL4OcpH5PmlFHqlCCpAl8AlEzMz5k53oNDvN8p1PNOWLEmI2x4orp3raOFB51tv9X+MFQ==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-3KS2b+kL7fsuk/eJZ7EQdnEmQoaho/r6KUef7hxvltNA5DR8NAUM+8wJMbJyZ4G9/7i3v5zPBIMN5aybAh2/Jg==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-KgusgyDgG4LI8Ih/sWaCtZ06tckLAS5CvT5A4D1Q7bYVoAAyzwiZvE4BmwDHkhRVkvhRBepKeASoFzQetha7Fg==}- engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0}- peerDependencies:- eslint: ^8.57.0 || ^9.0.0 || ^10.0.0- typescript: '>=4.8.4 <6.1.0'-- resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}- engines: {node: '>=14.17'}- hasBin: true-- resolution: {integrity: sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}-- resolution: {integrity: sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==}- engines: {node: '>=20.18.1'}-- resolution: {integrity: sha512-xKvGhPWw3k84Qjh8bI3ZeJjqnyadK+GEFtazSfZv/rKeTkTjOJho6mFqh2SM96iIcZokxiOpg78GazTSg8+KHA==}-- resolution: {integrity: sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==}-- resolution: {integrity: sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==}-- resolution: {integrity: sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==}-- resolution: {integrity: sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==}-- resolution: {integrity: sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==}-- resolution: {integrity: sha512-bSjt9pjaEBnNiGgc9rUiHGKv5l4/TGzDmYw3RhnkJGtLhbnnA/5qJj7x3dNDCRx/PJxu774LlH8lCOlB4hEfKg==}-- resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==}- hasBin: true- peerDependencies:- browserslist: '>= 4.21.0'-- resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==}-- resolution: {integrity: sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg==}- engines: {node: '>=10'}- peerDependencies:- '@types/react': '*'- react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true-- resolution: {integrity: sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ==}- engines: {node: '>=10'}- peerDependencies:- '@types/react': '*'- react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc- peerDependenciesMeta:- '@types/react':- optional: true-- resolution: {integrity: sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==}- peerDependencies:- react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0-- resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}-- resolution: {integrity: sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==}-- resolution: {integrity: sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==}-- resolution: {integrity: sha512-MFtjBYgzmSxmgA4RAfjIyXWpGe1oALnjgUTzzV7QLx/TKxCzjtMH6Fd9/eVK+5Fg1qNoz5VAwsmMs/NofrmJvw==}- engines: {node: ^20.19.0 || >=22.12.0}- hasBin: true- peerDependencies:- '@types/node': ^20.19.0 || >=22.12.0- '@vitejs/devtools': ^0.1.18- esbuild: ^0.27.0 || ^0.28.0- jiti: '>=1.21.0'- less: ^4.0.0- sass: ^1.70.0- sass-embedded: ^1.70.0- stylus: '>=0.54.8'- sugarss: ^5.0.0- terser: ^5.16.0- tsx: ^4.8.1- yaml: ^2.4.2- peerDependenciesMeta:- '@types/node':- optional: true- '@vitejs/devtools':- optional: true- esbuild:- optional: true- jiti:- optional: true- less:- optional: true- sass:- optional: true- sass-embedded:- optional: true- stylus:- optional: true- sugarss:- optional: true- terser:- optional: true- tsx:- optional: true- yaml:- optional: true-- resolution: {integrity: sha512-R9jUTe5S4Qb0HCd4TNqpC7oGcrMssMRGXLW80ubjWsW9VH5GF8y1Y0SFLY9AbqSk6nt0PnOx4H4WNJYZ13GUPw==}- engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0}- hasBin: true- peerDependencies:- '@edge-runtime/vm': '*'- '@opentelemetry/api': ^1.9.0- '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0- '@vitest/browser-playwright': 4.1.10- '@vitest/browser-preview': 4.1.10- '@vitest/browser-webdriverio': 4.1.10- '@vitest/coverage-istanbul': 4.1.10- '@vitest/coverage-v8': 4.1.10- '@vitest/ui': 4.1.10- happy-dom: '*'- jsdom: '*'- vite: ^6.0.0 || ^7.0.0 || ^8.0.0- peerDependenciesMeta:- '@edge-runtime/vm':- optional: true- '@opentelemetry/api':- optional: true- '@types/node':- optional: true- '@vitest/browser-playwright':- optional: true- '@vitest/browser-preview':- optional: true- '@vitest/browser-webdriverio':- optional: true- '@vitest/coverage-istanbul':- optional: true- '@vitest/coverage-v8':- optional: true- '@vitest/ui':- optional: true- happy-dom:- optional: true- jsdom:- optional: true-- resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==}- engines: {node: '>=18'}-- resolution: {integrity: sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==}- engines: {node: '>=20'}-- resolution: {integrity: sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==}- engines: {node: '>=20'}-- resolution: {integrity: sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==}- engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}-- resolution: {integrity: sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-LYfpUkmqwl0h9A2HL09Mms427Q1RZWuOHsukfVcKRq9q95iQxdw0ix1JQrqbcDR9PH1QDwf5Qo8OZb5lksZ8Xg==}- engines: {node: '>= 0.4'}-- resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==}- engines: {node: '>= 8'}- hasBin: true-- resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}- engines: {node: '>=8'}- hasBin: true-- resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}- engines: {node: '>=0.10.0'}-- resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}-- resolution: {integrity: sha512-It4dO0K5v//JtTXuPkfEOaI3uUN87iYPnqo/ZzqCoG3g8uhA66QUMs/SrM0YK7/NAu+r4LMh/9dq2A7k+rHs+w==}- engines: {node: '>=10.0.0'}- peerDependencies:- bufferutil: ^4.0.1- utf-8-validate: '>=5.0.2'- peerDependenciesMeta:- bufferutil:- optional: true- utf-8-validate:- optional: true-- resolution: {integrity: sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw==}- engines: {node: '>=18'}-- resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==}- engines: {node: '>=18'}-- resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==}-- resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}-- resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}- engines: {node: '>=10'}-- resolution: {integrity: sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==}- engines: {node: '>=18.0.0'}- peerDependencies:- zod: ^3.25.0 || ^4.0.0-- resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==}-- resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}--snapshots:-- '@adobe/[email protected]': {}-- '@alloc/[email protected]': {}-- '@asamuzakjp/[email protected]':- dependencies:- '@asamuzakjp/generational-cache': 1.0.1- '@csstools/css-calc': 3.2.1(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])- '@csstools/css-color-parser': 4.1.9(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])- '@csstools/css-parser-algorithms': 4.0.0(@csstools/[email protected])- '@csstools/css-tokenizer': 4.0.0-- '@asamuzakjp/[email protected]':- dependencies:- '@asamuzakjp/generational-cache': 1.0.1- '@asamuzakjp/nwsapi': 2.3.9- bidi-js: 1.0.3- css-tree: 3.2.1- is-potential-custom-element-name: 1.0.1-- '@asamuzakjp/[email protected]': {}-- '@asamuzakjp/[email protected]': {}-- '@babel/[email protected]':- dependencies:- '@babel/helper-validator-identifier': 7.28.5- js-tokens: 4.0.0- picocolors: 1.1.1-- '@babel/[email protected]': {}-- '@babel/[email protected]':- dependencies:- '@babel/code-frame': 7.29.0- '@babel/generator': 7.29.1- '@babel/helper-compilation-targets': 7.28.6- '@babel/helper-module-transforms': 7.28.6(@babel/[email protected])- '@babel/helpers': 7.29.2- '@babel/parser': 7.29.3- '@babel/template': 7.28.6- '@babel/traverse': 7.29.0- '@babel/types': 7.29.0- '@jridgewell/remapping': 2.3.5- convert-source-map: 2.0.0- debug: 4.4.3- gensync: 1.0.0-beta.2- json5: 2.2.3- semver: 6.3.1- transitivePeerDependencies:- - supports-color-- '@babel/[email protected]':- dependencies:- '@babel/parser': 7.29.3- '@babel/types': 7.29.0- '@jridgewell/gen-mapping': 0.3.13- '@jridgewell/trace-mapping': 0.3.31- jsesc: 3.1.0-- '@babel/[email protected]':- dependencies:- '@babel/compat-data': 7.29.3- '@babel/helper-validator-option': 7.27.1- browserslist: 4.28.2- lru-cache: 5.1.1- semver: 6.3.1-- '@babel/[email protected]': {}-- '@babel/[email protected]':- dependencies:- '@babel/traverse': 7.29.0- '@babel/types': 7.29.0- transitivePeerDependencies:- - supports-color-- '@babel/[email protected](@babel/[email protected])':- dependencies:- '@babel/core': 7.29.0- '@babel/helper-module-imports': 7.28.6- '@babel/helper-validator-identifier': 7.28.5- '@babel/traverse': 7.29.0- transitivePeerDependencies:- - supports-color-- '@babel/[email protected]': {}-- '@babel/[email protected]': {}-- '@babel/[email protected]': {}-- '@babel/[email protected]':- dependencies:- '@babel/template': 7.28.6- '@babel/types': 7.29.0-- '@babel/[email protected]':- dependencies:- '@babel/types': 7.29.0-- '@babel/[email protected]': {}-- '@babel/[email protected]':- dependencies:- '@babel/code-frame': 7.29.0- '@babel/parser': 7.29.3- '@babel/types': 7.29.0-- '@babel/[email protected]':- dependencies:- '@babel/code-frame': 7.29.0- '@babel/generator': 7.29.1- '@babel/helper-globals': 7.28.0- '@babel/parser': 7.29.3- '@babel/template': 7.28.6- '@babel/types': 7.29.0- debug: 4.4.3- transitivePeerDependencies:- - supports-color-- '@babel/[email protected]':- dependencies:- '@babel/helper-string-parser': 7.27.1- '@babel/helper-validator-identifier': 7.28.5-- '@bcoe/[email protected]': {}-- '@bramus/[email protected]':- dependencies:- css-tree: 3.2.1-- '@csstools/[email protected]': {}-- '@csstools/[email protected](@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])':- dependencies:- '@csstools/css-parser-algorithms': 4.0.0(@csstools/[email protected])- '@csstools/css-tokenizer': 4.0.0-- '@csstools/[email protected](@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])':- dependencies:- '@csstools/color-helpers': 6.1.0- '@csstools/css-calc': 3.2.1(@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])- '@csstools/css-parser-algorithms': 4.0.0(@csstools/[email protected])- '@csstools/css-tokenizer': 4.0.0-- '@csstools/[email protected](@csstools/[email protected])':- dependencies:- '@csstools/css-tokenizer': 4.0.0-- '@csstools/[email protected]([email protected])':- optionalDependencies:- css-tree: 3.2.1-- '@csstools/[email protected]': {}-- '@emnapi/[email protected]':- dependencies:- '@emnapi/wasi-threads': 1.2.1- tslib: 2.8.1- optional: true-- '@emnapi/[email protected]':- dependencies:- tslib: 2.8.1- optional: true-- '@emnapi/[email protected]':- dependencies:- tslib: 2.8.1- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- '@esbuild/[email protected]':- optional: true-- dependencies:- eslint: 9.39.4([email protected])- eslint-visitor-keys: 3.4.3-- '@eslint-community/[email protected]': {}-- '@eslint/[email protected]':- dependencies:- '@eslint/object-schema': 2.1.7- debug: 4.4.3- minimatch: 3.1.5- transitivePeerDependencies:- - supports-color-- '@eslint/[email protected]':- dependencies:- '@eslint/core': 0.17.0-- '@eslint/[email protected]':- dependencies:- '@types/json-schema': 7.0.15-- '@eslint/[email protected]':- dependencies:- ajv: 6.15.0- debug: 4.4.3- espree: 10.4.0- globals: 14.0.0- ignore: 5.3.2- import-fresh: 3.3.1- js-yaml: 4.1.1- minimatch: 3.1.5- strip-json-comments: 3.1.1- transitivePeerDependencies:- - supports-color-- '@eslint/[email protected]': {}-- '@eslint/[email protected]': {}-- '@eslint/[email protected]':- dependencies:- '@eslint/core': 0.17.0- levn: 0.4.1-- '@exodus/[email protected]': {}-- '@floating-ui/[email protected]':- dependencies:- '@floating-ui/utils': 0.2.11-- '@floating-ui/[email protected]':- dependencies:- '@floating-ui/core': 1.7.5- '@floating-ui/utils': 0.2.11-- dependencies:- '@floating-ui/dom': 1.7.6- react: 19.2.6- react-dom: 19.2.6([email protected])-- '@floating-ui/[email protected]': {}-- '@humanfs/[email protected]':- dependencies:- '@humanfs/types': 0.15.0-- '@humanfs/[email protected]':- dependencies:- '@humanfs/core': 0.19.2- '@humanfs/types': 0.15.0- '@humanwhocodes/retry': 0.4.3-- '@humanfs/[email protected]': {}-- '@humanwhocodes/[email protected]': {}-- '@humanwhocodes/[email protected]': {}-- '@img/[email protected]':- optional: true-- '@img/[email protected]':- optionalDependencies:- '@img/sharp-libvips-darwin-arm64': 1.2.4- optional: true-- '@img/[email protected]':- optionalDependencies:- '@img/sharp-libvips-darwin-x64': 1.2.4- optional: true-- '@img/[email protected]':- optional: true-- '@img/[email protected]':- optional: true-- '@img/[email protected]':- optional: true-- '@img/[email protected]':- optional: true-- '@img/[email protected]':- optional: true-- '@img/[email protected]':- optional: true-- '@img/[email protected]':- optional: true-- '@img/[email protected]':- optional: true-- '@img/[email protected]':- optional: true-- '@img/[email protected]':- optional: true-- '@img/[email protected]':- optionalDependencies:- '@img/sharp-libvips-linux-arm64': 1.2.4- optional: true-- '@img/[email protected]':- optionalDependencies:- '@img/sharp-libvips-linux-arm': 1.2.4- optional: true-- '@img/[email protected]':- optionalDependencies:- '@img/sharp-libvips-linux-ppc64': 1.2.4- optional: true-- '@img/[email protected]':- optionalDependencies:- '@img/sharp-libvips-linux-riscv64': 1.2.4- optional: true-- '@img/[email protected]':- optionalDependencies:- '@img/sharp-libvips-linux-s390x': 1.2.4- optional: true-- '@img/[email protected]':- optionalDependencies:- '@img/sharp-libvips-linux-x64': 1.2.4- optional: true-- '@img/[email protected]':- optionalDependencies:- '@img/sharp-libvips-linuxmusl-arm64': 1.2.4- optional: true-- '@img/[email protected]':- optionalDependencies:- '@img/sharp-libvips-linuxmusl-x64': 1.2.4- optional: true-- '@img/[email protected]':- dependencies:- '@emnapi/runtime': 1.10.0- optional: true-- '@img/[email protected]':- optional: true-- '@img/[email protected]':- optional: true-- '@img/[email protected]':- optional: true-- '@jridgewell/[email protected]':- dependencies:- '@jridgewell/sourcemap-codec': 1.5.5- '@jridgewell/trace-mapping': 0.3.31-- '@jridgewell/[email protected]':- dependencies:- '@jridgewell/gen-mapping': 0.3.13- '@jridgewell/trace-mapping': 0.3.31-- '@jridgewell/[email protected]': {}-- '@jridgewell/[email protected]': {}-- '@jridgewell/[email protected]':- dependencies:- '@jridgewell/resolve-uri': 3.1.2- '@jridgewell/sourcemap-codec': 1.5.5-- '@napi-rs/[email protected]':- dependencies:- '@emnapi/core': 1.10.0- '@emnapi/runtime': 1.10.0- '@tybys/wasm-util': 0.10.2- optional: true-- dependencies:- '@emnapi/core': 1.10.0- '@emnapi/runtime': 1.10.0- '@tybys/wasm-util': 0.10.2- optional: true-- '@next/[email protected]': {}-- '@next/[email protected]':- dependencies:- fast-glob: 3.3.1-- '@next/[email protected]':- optional: true-- '@next/[email protected]':- optional: true-- '@next/[email protected]':- optional: true-- '@next/[email protected]':- optional: true-- '@next/[email protected]':- optional: true-- '@next/[email protected]':- optional: true-- '@next/[email protected]':- optional: true-- '@next/[email protected]':- optional: true-- '@nodelib/[email protected]':- dependencies:- '@nodelib/fs.stat': 2.0.5- run-parallel: 1.2.0-- '@nodelib/[email protected]': {}-- '@nodelib/[email protected]':- dependencies:- '@nodelib/fs.scandir': 2.1.5- fastq: 1.20.1-- '@nolyfill/[email protected]': {}-- '@opentelemetry/[email protected]':- optional: true-- '@oxc-project/[email protected]': {}-- '@radix-ui/[email protected]': {}-- '@radix-ui/[email protected]': {}-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/react-visually-hidden': 1.2.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-collapsible': 1.1.12(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-collection': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-dialog': 1.1.15(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-use-is-hydrated': 0.1.0(@types/[email protected])([email protected])- '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-presence': 1.1.5(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- '@radix-ui/react-use-previous': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-use-size': 1.1.1(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-presence': 1.1.5(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- dependencies:- react: 19.2.6- optionalDependencies:- '@types/react': 19.2.14-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-menu': 2.1.16(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- dependencies:- react: 19.2.6- optionalDependencies:- '@types/react': 19.2.14-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-dismissable-layer': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-focus-guards': 1.1.3(@types/[email protected])([email protected])- '@radix-ui/react-focus-scope': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-portal': 1.1.9(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-presence': 1.1.5(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- aria-hidden: 1.2.6- react: 19.2.6- react-dom: 19.2.6([email protected])- react-remove-scroll: 2.7.2(@types/[email protected])([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- dependencies:- react: 19.2.6- optionalDependencies:- '@types/react': 19.2.14-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-use-escape-keydown': 1.1.1(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-menu': 2.1.16(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- dependencies:- react: 19.2.6- optionalDependencies:- '@types/react': 19.2.14-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-label': 2.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-dismissable-layer': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-popper': 1.2.8(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-portal': 1.1.9(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-presence': 1.1.5(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- dependencies:- '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])- react: 19.2.6- optionalDependencies:- '@types/react': 19.2.14-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-collection': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-dismissable-layer': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-focus-guards': 1.1.3(@types/[email protected])([email protected])- '@radix-ui/react-focus-scope': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-popper': 1.2.8(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-portal': 1.1.9(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-presence': 1.1.5(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-roving-focus': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])- '@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])- aria-hidden: 1.2.6- react: 19.2.6- react-dom: 19.2.6([email protected])- react-remove-scroll: 2.7.2(@types/[email protected])([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-collection': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-menu': 2.1.16(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-roving-focus': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-collection': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-dismissable-layer': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-presence': 1.1.5(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-use-previous': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-visually-hidden': 1.2.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/number': 1.1.1- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-collection': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-roving-focus': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- '@radix-ui/react-use-effect-event': 0.0.2(@types/[email protected])([email protected])- '@radix-ui/react-use-is-hydrated': 0.1.0(@types/[email protected])([email protected])- '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- '@radix-ui/react-use-effect-event': 0.0.2(@types/[email protected])([email protected])- '@radix-ui/react-use-is-hydrated': 0.1.0(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-dismissable-layer': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-focus-guards': 1.1.3(@types/[email protected])([email protected])- '@radix-ui/react-focus-scope': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-popper': 1.2.8(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-portal': 1.1.9(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-presence': 1.1.5(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- aria-hidden: 1.2.6- react: 19.2.6- react-dom: 19.2.6([email protected])- react-remove-scroll: 2.7.2(@types/[email protected])([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/react-arrow': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-use-rect': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-use-size': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/rect': 1.1.1- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-presence': 1.1.5(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-roving-focus': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- '@radix-ui/react-use-previous': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-use-size': 1.1.1(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-collection': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/number': 1.1.1- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-presence': 1.1.5(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/number': 1.1.1- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-collection': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-dismissable-layer': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-focus-guards': 1.1.3(@types/[email protected])([email protected])- '@radix-ui/react-focus-scope': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-popper': 1.2.8(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-portal': 1.1.9(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])- '@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-use-previous': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-visually-hidden': 1.2.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- aria-hidden: 1.2.6- react: 19.2.6- react-dom: 19.2.6([email protected])- react-remove-scroll: 2.7.2(@types/[email protected])([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/number': 1.1.1- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-collection': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-use-previous': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-use-size': 1.1.1(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- dependencies:- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- react: 19.2.6- optionalDependencies:- '@types/react': 19.2.14-- dependencies:- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- react: 19.2.6- optionalDependencies:- '@types/react': 19.2.14-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- '@radix-ui/react-use-previous': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-use-size': 1.1.1(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-presence': 1.1.5(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-roving-focus': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-collection': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-dismissable-layer': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-portal': 1.1.9(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-presence': 1.1.5(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-visually-hidden': 1.2.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-roving-focus': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-toggle': 1.1.10(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-roving-focus': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-separator': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-toggle-group': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-dismissable-layer': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-id': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-popper': 1.2.8(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-portal': 1.1.9(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-presence': 1.1.5(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- '@radix-ui/react-visually-hidden': 1.2.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- dependencies:- react: 19.2.6- optionalDependencies:- '@types/react': 19.2.14-- dependencies:- '@radix-ui/react-use-effect-event': 0.0.2(@types/[email protected])([email protected])- '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])- react: 19.2.6- optionalDependencies:- '@types/react': 19.2.14-- dependencies:- '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])- react: 19.2.6- optionalDependencies:- '@types/react': 19.2.14-- dependencies:- '@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])- react: 19.2.6- optionalDependencies:- '@types/react': 19.2.14-- dependencies:- react: 19.2.6- use-sync-external-store: 1.6.0([email protected])- optionalDependencies:- '@types/react': 19.2.14-- dependencies:- react: 19.2.6- optionalDependencies:- '@types/react': 19.2.14-- dependencies:- react: 19.2.6- optionalDependencies:- '@types/react': 19.2.14-- dependencies:- '@radix-ui/rect': 1.1.1- react: 19.2.6- optionalDependencies:- '@types/react': 19.2.14-- dependencies:- '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])- react: 19.2.6- optionalDependencies:- '@types/react': 19.2.14-- '@radix-ui/[email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@radix-ui/[email protected]': {}-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- dependencies:- '@emnapi/core': 1.10.0- '@emnapi/runtime': 1.10.0- '@napi-rs/wasm-runtime': 1.1.4(@emnapi/[email protected])(@emnapi/[email protected])- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]':- optional: true-- '@rolldown/[email protected]': {}-- '@rtsao/[email protected]': {}-- '@standard-schema/[email protected]': {}-- '@swc/[email protected]':- dependencies:- tslib: 2.8.1-- '@swc/[email protected]':- dependencies:- tslib: 2.8.1-- '@tailwindcss/[email protected]':- dependencies:- '@jridgewell/remapping': 2.3.5- enhanced-resolve: 5.21.3- jiti: 2.7.0- lightningcss: 1.32.0- magic-string: 0.30.21- source-map-js: 1.2.1- tailwindcss: 4.3.0-- '@tailwindcss/[email protected]':- optional: true-- '@tailwindcss/[email protected]':- optional: true-- '@tailwindcss/[email protected]':- optional: true-- '@tailwindcss/[email protected]':- optional: true-- '@tailwindcss/[email protected]':- optional: true-- '@tailwindcss/[email protected]':- optional: true-- '@tailwindcss/[email protected]':- optional: true-- '@tailwindcss/[email protected]':- optional: true-- '@tailwindcss/[email protected]':- optional: true-- '@tailwindcss/[email protected]':- optional: true-- '@tailwindcss/[email protected]':- optional: true-- '@tailwindcss/[email protected]':- optional: true-- '@tailwindcss/[email protected]':- optionalDependencies:- '@tailwindcss/oxide-android-arm64': 4.3.0- '@tailwindcss/oxide-darwin-arm64': 4.3.0- '@tailwindcss/oxide-darwin-x64': 4.3.0- '@tailwindcss/oxide-freebsd-x64': 4.3.0- '@tailwindcss/oxide-linux-arm-gnueabihf': 4.3.0- '@tailwindcss/oxide-linux-arm64-gnu': 4.3.0- '@tailwindcss/oxide-linux-arm64-musl': 4.3.0- '@tailwindcss/oxide-linux-x64-gnu': 4.3.0- '@tailwindcss/oxide-linux-x64-musl': 4.3.0- '@tailwindcss/oxide-wasm32-wasi': 4.3.0- '@tailwindcss/oxide-win32-arm64-msvc': 4.3.0- '@tailwindcss/oxide-win32-x64-msvc': 4.3.0-- '@tailwindcss/[email protected]':- dependencies:- '@alloc/quick-lru': 5.2.0- '@tailwindcss/node': 4.3.0- '@tailwindcss/oxide': 4.3.0- postcss: 8.5.14- tailwindcss: 4.3.0-- '@testing-library/[email protected]':- dependencies:- '@babel/code-frame': 7.29.0- '@babel/runtime': 7.29.7- '@types/aria-query': 5.0.4- aria-query: 5.3.0- dom-accessibility-api: 0.5.16- lz-string: 1.5.0- picocolors: 1.1.1- pretty-format: 27.5.1-- '@testing-library/[email protected]':- dependencies:- '@adobe/css-tools': 4.5.0- aria-query: 5.3.2- css.escape: 1.5.1- dom-accessibility-api: 0.6.3- picocolors: 1.1.1- redent: 3.0.0-- '@testing-library/[email protected](@testing-library/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@babel/runtime': 7.29.7- '@testing-library/dom': 10.4.1- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- '@tybys/[email protected]':- dependencies:- tslib: 2.8.1- optional: true-- '@types/[email protected]': {}-- '@types/[email protected]':- dependencies:- '@types/node': 22.19.19-- '@types/[email protected]':- dependencies:- '@types/deep-eql': 4.0.2- assertion-error: 2.0.1-- '@types/[email protected]':- dependencies:- '@types/ms': 2.1.0-- '@types/[email protected]': {}-- '@types/[email protected]':- dependencies:- '@types/estree': 1.0.9-- '@types/[email protected]': {}-- '@types/[email protected]':- dependencies:- '@types/unist': 3.0.3-- '@types/[email protected]': {}-- '@types/[email protected]': {}-- '@types/[email protected]':- dependencies:- '@types/unist': 3.0.3-- '@types/[email protected]': {}-- '@types/[email protected]':- dependencies:- undici-types: 6.21.0-- '@types/[email protected](@types/[email protected])':- dependencies:- '@types/react': 19.2.14-- '@types/[email protected]':- dependencies:- csstype: 3.2.3-- '@types/[email protected]': {}-- '@types/[email protected]': {}-- '@types/[email protected]':- dependencies:- '@types/node': 22.19.19-- '@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])':- dependencies:- '@eslint-community/regexpp': 4.12.2- '@typescript-eslint/scope-manager': 8.59.3- '@typescript-eslint/visitor-keys': 8.59.3- eslint: 9.39.4([email protected])- ignore: 7.0.5- natural-compare: 1.4.0- ts-api-utils: 2.5.0([email protected])- typescript: 5.9.3- transitivePeerDependencies:- - supports-color-- dependencies:- '@typescript-eslint/scope-manager': 8.59.3- '@typescript-eslint/types': 8.59.3- '@typescript-eslint/typescript-estree': 8.59.3([email protected])- '@typescript-eslint/visitor-keys': 8.59.3- debug: 4.4.3- eslint: 9.39.4([email protected])- typescript: 5.9.3- transitivePeerDependencies:- - supports-color-- '@typescript-eslint/[email protected]([email protected])':- dependencies:- '@typescript-eslint/tsconfig-utils': 8.59.3([email protected])- '@typescript-eslint/types': 8.59.3- debug: 4.4.3- typescript: 5.9.3- transitivePeerDependencies:- - supports-color-- '@typescript-eslint/[email protected]':- dependencies:- '@typescript-eslint/types': 8.59.3- '@typescript-eslint/visitor-keys': 8.59.3-- '@typescript-eslint/[email protected]([email protected])':- dependencies:- typescript: 5.9.3-- dependencies:- '@typescript-eslint/types': 8.59.3- '@typescript-eslint/typescript-estree': 8.59.3([email protected])- debug: 4.4.3- eslint: 9.39.4([email protected])- ts-api-utils: 2.5.0([email protected])- typescript: 5.9.3- transitivePeerDependencies:- - supports-color-- '@typescript-eslint/[email protected]': {}-- '@typescript-eslint/[email protected]([email protected])':- dependencies:- '@typescript-eslint/project-service': 8.59.3([email protected])- '@typescript-eslint/tsconfig-utils': 8.59.3([email protected])- '@typescript-eslint/types': 8.59.3- '@typescript-eslint/visitor-keys': 8.59.3- debug: 4.4.3- minimatch: 10.2.5- semver: 7.8.0- tinyglobby: 0.2.16- ts-api-utils: 2.5.0([email protected])- typescript: 5.9.3- transitivePeerDependencies:- - supports-color-- dependencies:- '@eslint-community/eslint-utils': 4.9.1([email protected]([email protected]))- '@typescript-eslint/scope-manager': 8.59.3- '@typescript-eslint/types': 8.59.3- '@typescript-eslint/typescript-estree': 8.59.3([email protected])- eslint: 9.39.4([email protected])- typescript: 5.9.3- transitivePeerDependencies:- - supports-color-- '@typescript-eslint/[email protected]':- dependencies:- '@typescript-eslint/types': 8.59.3- eslint-visitor-keys: 5.0.1-- '@ungap/[email protected]': {}-- '@unrs/[email protected]':- optional: true-- '@unrs/[email protected]':- optional: true-- '@unrs/[email protected]':- optional: true-- '@unrs/[email protected]':- optional: true-- '@unrs/[email protected]':- optional: true-- '@unrs/[email protected]':- optional: true-- '@unrs/[email protected]':- optional: true-- '@unrs/[email protected]':- optional: true-- '@unrs/[email protected]':- optional: true-- '@unrs/[email protected]':- optional: true-- '@unrs/[email protected]':- optional: true-- '@unrs/[email protected]':- optional: true-- '@unrs/[email protected]':- optional: true-- '@unrs/[email protected]':- optional: true-- '@unrs/[email protected]':- optional: true-- '@unrs/[email protected]':- dependencies:- '@napi-rs/wasm-runtime': 0.2.12- optional: true-- '@unrs/[email protected]':- optional: true-- '@unrs/[email protected]':- optional: true-- '@unrs/[email protected]':- optional: true-- '@vitejs/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected]))':- dependencies:- '@rolldown/pluginutils': 1.0.1-- '@vitest/[email protected]([email protected])':- dependencies:- '@bcoe/v8-coverage': 1.0.2- '@vitest/utils': 4.1.10- ast-v8-to-istanbul: 1.0.5- istanbul-lib-coverage: 3.2.2- istanbul-lib-report: 3.0.1- istanbul-reports: 3.2.0- magicast: 0.5.3- obug: 2.1.3- std-env: 4.2.0- tinyrainbow: 3.1.0- vitest: 4.1.10(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected]))-- '@vitest/[email protected]':- dependencies:- '@standard-schema/spec': 1.1.0- '@types/chai': 5.2.3- '@vitest/spy': 4.1.10- '@vitest/utils': 4.1.10- chai: 6.2.2- tinyrainbow: 3.1.0-- '@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected]))':- dependencies:- '@vitest/spy': 4.1.10- estree-walker: 3.0.3- magic-string: 0.30.21- optionalDependencies:-- '@vitest/[email protected]':- dependencies:- tinyrainbow: 3.1.0-- '@vitest/[email protected]':- dependencies:- '@vitest/utils': 4.1.10- pathe: 2.0.3-- '@vitest/[email protected]':- dependencies:- '@vitest/pretty-format': 4.1.10- '@vitest/utils': 4.1.10- magic-string: 0.30.21- pathe: 2.0.3-- '@vitest/[email protected]': {}-- '@vitest/[email protected]':- dependencies:- '@vitest/pretty-format': 4.1.10- convert-source-map: 2.0.0- tinyrainbow: 3.1.0-- dependencies:- acorn: 8.16.0-- [email protected]: {}-- dependencies:- fast-deep-equal: 3.1.3- fast-json-stable-stringify: 2.1.0- json-schema-traverse: 0.4.1- uri-js: 4.4.1-- [email protected]: {}-- dependencies:- color-convert: 2.0.1-- [email protected]: {}-- [email protected]: {}-- dependencies:- tslib: 2.8.1-- dependencies:- dequal: 2.0.3-- [email protected]: {}-- dependencies:- call-bound: 1.0.4- is-array-buffer: 3.0.5-- dependencies:- call-bind: 1.0.9- call-bound: 1.0.4- define-properties: 1.2.1- es-abstract: 1.24.2- es-object-atoms: 1.1.1- get-intrinsic: 1.3.0- is-string: 1.1.1- math-intrinsics: 1.1.0-- dependencies:- call-bind: 1.0.9- define-properties: 1.2.1- es-abstract: 1.24.2- es-errors: 1.3.0- es-object-atoms: 1.1.1- es-shim-unscopables: 1.1.0-- dependencies:- call-bind: 1.0.9- call-bound: 1.0.4- define-properties: 1.2.1- es-abstract: 1.24.2- es-errors: 1.3.0- es-object-atoms: 1.1.1- es-shim-unscopables: 1.1.0-- dependencies:- call-bind: 1.0.9- define-properties: 1.2.1- es-abstract: 1.24.2- es-shim-unscopables: 1.1.0-- dependencies:- call-bind: 1.0.9- define-properties: 1.2.1- es-abstract: 1.24.2- es-shim-unscopables: 1.1.0-- dependencies:- call-bind: 1.0.9- define-properties: 1.2.1- es-abstract: 1.24.2- es-errors: 1.3.0- es-shim-unscopables: 1.1.0-- dependencies:- array-buffer-byte-length: 1.0.2- call-bind: 1.0.9- define-properties: 1.2.1- es-abstract: 1.24.2- es-errors: 1.3.0- get-intrinsic: 1.3.0- is-array-buffer: 3.0.5-- [email protected]: {}-- [email protected]: {}-- dependencies:- '@jridgewell/trace-mapping': 0.3.31- estree-walker: 3.0.3- js-tokens: 10.0.0-- [email protected]: {}-- dependencies:- possible-typed-array-names: 1.1.0-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- bindings: 1.5.0- prebuild-install: 7.1.3-- dependencies:- require-from-string: 2.0.2-- dependencies:- file-uri-to-path: 1.0.0-- dependencies:- buffer: 5.7.1- inherits: 2.0.4- readable-stream: 3.6.2-- dependencies:- balanced-match: 1.0.2- concat-map: 0.0.1-- dependencies:- balanced-match: 4.0.4-- dependencies:- fill-range: 7.1.1-- dependencies:- baseline-browser-mapping: 2.10.30- caniuse-lite: 1.0.30001793- electron-to-chromium: 1.5.357- node-releases: 2.0.44- update-browserslist-db: 1.2.3([email protected])-- dependencies:- base64-js: 1.5.1- ieee754: 1.2.1-- dependencies:- run-applescript: 7.1.0-- dependencies:- es-errors: 1.3.0- function-bind: 1.1.2-- dependencies:- call-bind-apply-helpers: 1.0.2- es-define-property: 1.0.1- get-intrinsic: 1.3.0- set-function-length: 1.2.2-- dependencies:- call-bind-apply-helpers: 1.0.2- get-intrinsic: 1.3.0-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- ansi-styles: 4.3.0- supports-color: 7.2.0-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- clsx: 2.1.1-- [email protected]: {}-- [email protected]: {}-- dependencies:- color-name: 1.1.4-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- luxon: 3.7.2-- dependencies:- path-key: 3.1.1- shebang-command: 2.0.0- which: 2.0.2-- dependencies:- mdn-data: 2.27.1- source-map-js: 1.2.1-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- whatwg-mimetype: 5.0.0- whatwg-url: 16.0.1- transitivePeerDependencies:- - '@noble/hashes'-- dependencies:- call-bound: 1.0.4- es-errors: 1.3.0- is-data-view: 1.0.2-- dependencies:- call-bound: 1.0.4- es-errors: 1.3.0- is-data-view: 1.0.2-- dependencies:- call-bound: 1.0.4- es-errors: 1.3.0- is-data-view: 1.0.2-- dependencies:- ms: 2.1.3-- dependencies:- ms: 2.1.3-- [email protected]: {}-- dependencies:- character-entities: 2.0.2-- dependencies:- mimic-response: 3.1.0-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- bundle-name: 4.1.0- default-browser-id: 5.0.1-- dependencies:- es-define-property: 1.0.1- es-errors: 1.3.0- gopd: 1.2.0-- [email protected]: {}-- dependencies:- define-data-property: 1.1.4- has-property-descriptors: 1.0.2- object-keys: 1.1.1-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- dequal: 2.0.3-- dependencies:- esutils: 2.0.3-- [email protected]: {}-- [email protected]: {}-- dependencies:- call-bind-apply-helpers: 1.0.2- es-errors: 1.3.0- gopd: 1.2.0-- [email protected]: {}-- [email protected]: {}-- dependencies:- once: 1.4.0-- dependencies:- graceful-fs: 4.2.11- tapable: 2.3.3-- [email protected]: {}-- dependencies:- array-buffer-byte-length: 1.0.2- arraybuffer.prototype.slice: 1.0.4- available-typed-arrays: 1.0.7- call-bind: 1.0.9- call-bound: 1.0.4- data-view-buffer: 1.0.2- data-view-byte-length: 1.0.2- data-view-byte-offset: 1.0.1- es-define-property: 1.0.1- es-errors: 1.3.0- es-object-atoms: 1.1.1- es-set-tostringtag: 2.1.0- es-to-primitive: 1.3.0- function.prototype.name: 1.1.8- get-intrinsic: 1.3.0- get-proto: 1.0.1- get-symbol-description: 1.1.0- globalthis: 1.0.4- gopd: 1.2.0- has-property-descriptors: 1.0.2- has-proto: 1.2.0- has-symbols: 1.1.0- hasown: 2.0.3- internal-slot: 1.1.0- is-array-buffer: 3.0.5- is-callable: 1.2.7- is-data-view: 1.0.2- is-negative-zero: 2.0.3- is-regex: 1.2.1- is-set: 2.0.3- is-shared-array-buffer: 1.0.4- is-string: 1.1.1- is-typed-array: 1.1.15- is-weakref: 1.1.1- math-intrinsics: 1.1.0- object-inspect: 1.13.4- object-keys: 1.1.1- object.assign: 4.1.7- own-keys: 1.0.1- regexp.prototype.flags: 1.5.4- safe-array-concat: 1.1.4- safe-push-apply: 1.0.0- safe-regex-test: 1.1.0- set-proto: 1.0.0- stop-iteration-iterator: 1.1.0- string.prototype.trim: 1.2.10- string.prototype.trimend: 1.0.9- string.prototype.trimstart: 1.0.8- typed-array-buffer: 1.0.3- typed-array-byte-length: 1.0.3- typed-array-byte-offset: 1.0.4- typed-array-length: 1.0.7- unbox-primitive: 1.1.0- which-typed-array: 1.1.20-- [email protected]: {}-- [email protected]: {}-- dependencies:- call-bind: 1.0.9- call-bound: 1.0.4- define-properties: 1.2.1- es-abstract: 1.24.2- es-errors: 1.3.0- es-set-tostringtag: 2.1.0- function-bind: 1.1.2- get-intrinsic: 1.3.0- globalthis: 1.0.4- gopd: 1.2.0- has-property-descriptors: 1.0.2- has-proto: 1.2.0- has-symbols: 1.1.0- internal-slot: 1.1.0- iterator.prototype: 1.1.5- math-intrinsics: 1.1.0-- [email protected]: {}-- dependencies:- es-errors: 1.3.0-- dependencies:- es-errors: 1.3.0- get-intrinsic: 1.3.0- has-tostringtag: 1.0.2- hasown: 2.0.3-- dependencies:- hasown: 2.0.3-- dependencies:- is-callable: 1.2.7- is-date-object: 1.1.0- is-symbol: 1.1.1-- optionalDependencies:- '@esbuild/aix-ppc64': 0.28.0- '@esbuild/android-arm': 0.28.0- '@esbuild/android-arm64': 0.28.0- '@esbuild/android-x64': 0.28.0- '@esbuild/darwin-arm64': 0.28.0- '@esbuild/darwin-x64': 0.28.0- '@esbuild/freebsd-arm64': 0.28.0- '@esbuild/freebsd-x64': 0.28.0- '@esbuild/linux-arm': 0.28.0- '@esbuild/linux-arm64': 0.28.0- '@esbuild/linux-ia32': 0.28.0- '@esbuild/linux-loong64': 0.28.0- '@esbuild/linux-mips64el': 0.28.0- '@esbuild/linux-ppc64': 0.28.0- '@esbuild/linux-riscv64': 0.28.0- '@esbuild/linux-s390x': 0.28.0- '@esbuild/linux-x64': 0.28.0- '@esbuild/netbsd-arm64': 0.28.0- '@esbuild/netbsd-x64': 0.28.0- '@esbuild/openbsd-arm64': 0.28.0- '@esbuild/openbsd-x64': 0.28.0- '@esbuild/openharmony-arm64': 0.28.0- '@esbuild/sunos-x64': 0.28.0- '@esbuild/win32-arm64': 0.28.0- '@esbuild/win32-ia32': 0.28.0- '@esbuild/win32-x64': 0.28.0-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected]):- dependencies:- '@next/eslint-plugin-next': 16.2.6- eslint: 9.39.4([email protected])- eslint-import-resolver-node: 0.3.10- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))- eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))- eslint-plugin-jsx-a11y: 6.10.2([email protected]([email protected]))- eslint-plugin-react: 7.37.5([email protected]([email protected]))- eslint-plugin-react-hooks: 7.1.1([email protected]([email protected]))- globals: 16.4.0- optionalDependencies:- typescript: 5.9.3- transitivePeerDependencies:- - '@typescript-eslint/parser'- - eslint-import-resolver-webpack- - eslint-plugin-import-x- - supports-color-- dependencies:- debug: 3.2.7- is-core-module: 2.16.2- resolve: 2.0.0-next.7- transitivePeerDependencies:- - supports-color-- dependencies:- '@nolyfill/is-core-module': 1.0.39- debug: 4.4.3- eslint: 9.39.4([email protected])- get-tsconfig: 4.14.0- is-bun-module: 2.0.0- stable-hash: 0.0.5- tinyglobby: 0.2.16- unrs-resolver: 1.11.1- optionalDependencies:- eslint-plugin-import: 2.32.0(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected]))- transitivePeerDependencies:- - supports-color-- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected])):- dependencies:- debug: 3.2.7- optionalDependencies:- eslint: 9.39.4([email protected])- eslint-import-resolver-node: 0.3.10- eslint-import-resolver-typescript: 3.10.1([email protected])([email protected]([email protected]))- transitivePeerDependencies:- - supports-color-- [email protected](@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected]([email protected])):- dependencies:- '@rtsao/scc': 1.1.0- array-includes: 3.1.9- array.prototype.findlastindex: 1.2.6- array.prototype.flat: 1.3.3- array.prototype.flatmap: 1.3.3- debug: 3.2.7- doctrine: 2.1.0- eslint: 9.39.4([email protected])- eslint-import-resolver-node: 0.3.10- eslint-module-utils: 2.12.1(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected]([email protected]))- hasown: 2.0.3- is-core-module: 2.16.2- is-glob: 4.0.3- minimatch: 3.1.5- object.fromentries: 2.0.8- object.groupby: 1.0.3- object.values: 1.2.1- semver: 6.3.1- string.prototype.trimend: 1.0.9- tsconfig-paths: 3.15.0- optionalDependencies:- transitivePeerDependencies:- - eslint-import-resolver-typescript- - eslint-import-resolver-webpack- - supports-color-- dependencies:- aria-query: 5.3.2- array-includes: 3.1.9- array.prototype.flatmap: 1.3.3- ast-types-flow: 0.0.8- axe-core: 4.11.4- axobject-query: 4.1.0- damerau-levenshtein: 1.0.8- emoji-regex: 9.2.2- eslint: 9.39.4([email protected])- hasown: 2.0.3- jsx-ast-utils: 3.3.5- language-tags: 1.0.9- minimatch: 3.1.5- object.fromentries: 2.0.8- safe-regex-test: 1.1.0- string.prototype.includes: 2.0.1-- dependencies:- '@babel/core': 7.29.0- '@babel/parser': 7.29.3- eslint: 9.39.4([email protected])- hermes-parser: 0.25.1- zod: 3.25.76- zod-validation-error: 4.0.2([email protected])- transitivePeerDependencies:- - supports-color-- dependencies:- array-includes: 3.1.9- array.prototype.findlast: 1.2.5- array.prototype.flatmap: 1.3.3- array.prototype.tosorted: 1.1.4- doctrine: 2.1.0- es-iterator-helpers: 1.3.2- eslint: 9.39.4([email protected])- estraverse: 5.3.0- hasown: 2.0.3- jsx-ast-utils: 3.3.5- minimatch: 3.1.5- object.entries: 1.1.9- object.fromentries: 2.0.8- object.values: 1.2.1- prop-types: 15.8.1- resolve: 2.0.0-next.7- semver: 6.3.1- string.prototype.matchall: 4.0.12- string.prototype.repeat: 1.0.0-- dependencies:- esrecurse: 4.3.0- estraverse: 5.3.0-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- '@eslint-community/eslint-utils': 4.9.1([email protected]([email protected]))- '@eslint-community/regexpp': 4.12.2- '@eslint/config-array': 0.21.2- '@eslint/config-helpers': 0.4.2- '@eslint/core': 0.17.0- '@eslint/eslintrc': 3.3.5- '@eslint/js': 9.39.4- '@eslint/plugin-kit': 0.4.1- '@humanfs/node': 0.16.8- '@humanwhocodes/module-importer': 1.0.1- '@humanwhocodes/retry': 0.4.3- '@types/estree': 1.0.9- ajv: 6.15.0- chalk: 4.1.2- cross-spawn: 7.0.6- debug: 4.4.3- escape-string-regexp: 4.0.0- eslint-scope: 8.4.0- eslint-visitor-keys: 4.2.1- espree: 10.4.0- esquery: 1.7.0- esutils: 2.0.3- fast-deep-equal: 3.1.3- file-entry-cache: 8.0.0- find-up: 5.0.0- glob-parent: 6.0.2- ignore: 5.3.2- imurmurhash: 0.1.4- is-glob: 4.0.3- json-stable-stringify-without-jsonify: 1.0.1- lodash.merge: 4.6.2- minimatch: 3.1.5- natural-compare: 1.4.0- optionator: 0.9.4- optionalDependencies:- jiti: 2.7.0- transitivePeerDependencies:- - supports-color-- dependencies:- acorn: 8.16.0- acorn-jsx: 5.3.2([email protected])- eslint-visitor-keys: 4.2.1-- dependencies:- estraverse: 5.3.0-- dependencies:- estraverse: 5.3.0-- [email protected]: {}-- [email protected]: {}-- dependencies:- '@types/estree': 1.0.9-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- '@nodelib/fs.stat': 2.0.5- '@nodelib/fs.walk': 1.2.8- glob-parent: 5.1.2- merge2: 1.4.1- micromatch: 4.0.8-- [email protected]: {}-- [email protected]: {}-- dependencies:- reusify: 1.1.0-- optionalDependencies:- picomatch: 4.0.4-- dependencies:- flat-cache: 4.0.1-- [email protected]: {}-- dependencies:- to-regex-range: 5.0.1-- dependencies:- locate-path: 6.0.0- path-exists: 4.0.0-- dependencies:- flatted: 3.4.2- keyv: 4.5.4-- [email protected]: {}-- dependencies:- is-callable: 1.2.7-- [email protected]: {}-- optional: true-- [email protected]: {}-- dependencies:- call-bind: 1.0.9- call-bound: 1.0.4- define-properties: 1.2.1- functions-have-names: 1.2.3- hasown: 2.0.3- is-callable: 1.2.7-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- call-bind-apply-helpers: 1.0.2- es-define-property: 1.0.1- es-errors: 1.3.0- es-object-atoms: 1.1.1- function-bind: 1.1.2- get-proto: 1.0.1- gopd: 1.2.0- has-symbols: 1.1.0- hasown: 2.0.3- math-intrinsics: 1.1.0-- [email protected]: {}-- dependencies:- dunder-proto: 1.0.1- es-object-atoms: 1.1.1-- dependencies:- call-bound: 1.0.4- es-errors: 1.3.0- get-intrinsic: 1.3.0-- dependencies:- resolve-pkg-maps: 1.0.0-- [email protected]: {}-- dependencies:- is-glob: 4.0.3-- dependencies:- is-glob: 4.0.3-- [email protected]: {}-- [email protected]: {}-- dependencies:- define-properties: 1.2.1- gopd: 1.2.0-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- es-define-property: 1.0.1-- dependencies:- dunder-proto: 1.0.1-- [email protected]: {}-- dependencies:- has-symbols: 1.1.0-- dependencies:- function-bind: 1.1.2-- dependencies:- '@types/estree': 1.0.9- '@types/hast': 3.0.4- '@types/unist': 3.0.3- comma-separated-tokens: 2.0.3- devlop: 1.1.0- estree-util-is-identifier-name: 3.0.0- hast-util-whitespace: 3.0.0- mdast-util-mdx-expression: 2.0.1- mdast-util-mdx-jsx: 3.2.0- mdast-util-mdxjs-esm: 2.0.1- property-information: 7.1.0- space-separated-tokens: 2.0.2- style-to-js: 1.1.21- unist-util-position: 5.0.0- vfile-message: 4.0.3- transitivePeerDependencies:- - supports-color-- dependencies:- '@types/hast': 3.0.4-- [email protected]: {}-- dependencies:- hermes-estree: 0.25.1-- dependencies:- '@exodus/bytes': 1.15.1- transitivePeerDependencies:- - '@noble/hashes'-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- parent-module: 1.0.1- resolve-from: 4.0.0-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- es-errors: 1.3.0- hasown: 2.0.3- side-channel: 1.1.0-- [email protected]: {}-- dependencies:- is-alphabetical: 2.0.1- is-decimal: 2.0.1-- dependencies:- call-bind: 1.0.9- call-bound: 1.0.4- get-intrinsic: 1.3.0-- dependencies:- async-function: 1.0.0- call-bound: 1.0.4- get-proto: 1.0.1- has-tostringtag: 1.0.2- safe-regex-test: 1.1.0-- dependencies:- has-bigints: 1.1.0-- dependencies:- call-bound: 1.0.4- has-tostringtag: 1.0.2-- dependencies:- semver: 7.8.0-- [email protected]: {}-- dependencies:- hasown: 2.0.3-- dependencies:- call-bound: 1.0.4- get-intrinsic: 1.3.0- is-typed-array: 1.1.15-- dependencies:- call-bound: 1.0.4- has-tostringtag: 1.0.2-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- call-bound: 1.0.4-- dependencies:- call-bound: 1.0.4- generator-function: 2.0.1- get-proto: 1.0.1- has-tostringtag: 1.0.2- safe-regex-test: 1.1.0-- dependencies:- is-extglob: 2.1.1-- [email protected]: {}-- dependencies:- is-docker: 3.0.0-- [email protected]: {}-- [email protected]: {}-- dependencies:- call-bound: 1.0.4- has-tostringtag: 1.0.2-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- call-bound: 1.0.4- gopd: 1.2.0- has-tostringtag: 1.0.2- hasown: 2.0.3-- [email protected]: {}-- dependencies:- call-bound: 1.0.4-- dependencies:- call-bound: 1.0.4- has-tostringtag: 1.0.2-- dependencies:- call-bound: 1.0.4- has-symbols: 1.1.0- safe-regex-test: 1.1.0-- dependencies:- which-typed-array: 1.1.20-- [email protected]: {}-- dependencies:- call-bound: 1.0.4-- dependencies:- call-bound: 1.0.4- get-intrinsic: 1.3.0-- dependencies:- is-inside-container: 1.0.0-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- istanbul-lib-coverage: 3.2.2- make-dir: 4.0.0- supports-color: 7.2.0-- dependencies:- html-escaper: 2.0.2- istanbul-lib-report: 3.0.1-- dependencies:- define-data-property: 1.1.4- es-object-atoms: 1.1.1- get-intrinsic: 1.3.0- get-proto: 1.0.1- has-symbols: 1.1.0- set-function-name: 2.0.2-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- argparse: 2.0.1-- dependencies:- '@asamuzakjp/css-color': 5.1.11- '@asamuzakjp/dom-selector': 7.1.1- '@bramus/specificity': 2.4.2- '@csstools/css-syntax-patches-for-csstree': 1.1.6([email protected])- '@exodus/bytes': 1.15.1- css-tree: 3.2.1- data-urls: 7.0.0- decimal.js: 10.6.0- html-encoding-sniffer: 6.0.0- is-potential-custom-element-name: 1.0.1- lru-cache: 11.5.2- parse5: 8.0.1- saxes: 6.0.0- symbol-tree: 3.2.4- tough-cookie: 6.0.2- undici: 7.28.0- w3c-xmlserializer: 5.0.0- webidl-conversions: 8.0.1- whatwg-mimetype: 5.0.0- whatwg-url: 16.0.1- xml-name-validator: 5.0.0- transitivePeerDependencies:- - '@noble/hashes'-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- minimist: 1.2.8-- [email protected]: {}-- dependencies:- array-includes: 3.1.9- array.prototype.flat: 1.3.3- object.assign: 4.1.7- object.values: 1.2.1-- dependencies:- node-addon-api: 4.3.0- prebuild-install: 7.1.3-- dependencies:- json-buffer: 3.0.1-- [email protected]: {}-- dependencies:- language-subtag-registry: 0.3.23-- dependencies:- prelude-ls: 1.2.1- type-check: 0.4.0-- optional: true-- optional: true-- optional: true-- optional: true-- optional: true-- optional: true-- optional: true-- optional: true-- optional: true-- optional: true-- optional: true-- dependencies:- detect-libc: 2.1.2- optionalDependencies:- lightningcss-android-arm64: 1.32.0- lightningcss-darwin-arm64: 1.32.0- lightningcss-darwin-x64: 1.32.0- lightningcss-freebsd-x64: 1.32.0- lightningcss-linux-arm-gnueabihf: 1.32.0- lightningcss-linux-arm64-gnu: 1.32.0- lightningcss-linux-arm64-musl: 1.32.0- lightningcss-linux-x64-gnu: 1.32.0- lightningcss-linux-x64-musl: 1.32.0- lightningcss-win32-arm64-msvc: 1.32.0- lightningcss-win32-x64-msvc: 1.32.0-- dependencies:- p-locate: 5.0.0-- [email protected]: {}-- [email protected]: {}-- dependencies:- js-tokens: 4.0.0-- [email protected]: {}-- dependencies:- yallist: 3.1.1-- dependencies:- react: 19.2.6-- [email protected]: {}-- [email protected]: {}-- dependencies:- '@jridgewell/sourcemap-codec': 1.5.5-- dependencies:- '@babel/parser': 7.29.3- '@babel/types': 7.29.0- source-map-js: 1.2.1-- dependencies:- semver: 7.8.0-- [email protected]: {}-- [email protected]: {}-- dependencies:- '@types/mdast': 4.0.4- escape-string-regexp: 5.0.0- unist-util-is: 6.0.1- unist-util-visit-parents: 6.0.2-- dependencies:- '@types/mdast': 4.0.4- '@types/unist': 3.0.3- decode-named-character-reference: 1.3.0- devlop: 1.1.0- mdast-util-to-string: 4.0.0- micromark: 4.0.2- micromark-util-decode-numeric-character-reference: 2.0.2- micromark-util-decode-string: 2.0.1- micromark-util-normalize-identifier: 2.0.1- micromark-util-symbol: 2.0.1- micromark-util-types: 2.0.2- unist-util-stringify-position: 4.0.0- transitivePeerDependencies:- - supports-color-- dependencies:- '@types/mdast': 4.0.4- ccount: 2.0.1- devlop: 1.1.0- mdast-util-find-and-replace: 3.0.2- micromark-util-character: 2.1.1-- dependencies:- '@types/mdast': 4.0.4- devlop: 1.1.0- mdast-util-from-markdown: 2.0.3- mdast-util-to-markdown: 2.1.2- micromark-util-normalize-identifier: 2.0.1- transitivePeerDependencies:- - supports-color-- dependencies:- '@types/mdast': 4.0.4- mdast-util-from-markdown: 2.0.3- mdast-util-to-markdown: 2.1.2- transitivePeerDependencies:- - supports-color-- dependencies:- '@types/mdast': 4.0.4- devlop: 1.1.0- markdown-table: 3.0.4- mdast-util-from-markdown: 2.0.3- mdast-util-to-markdown: 2.1.2- transitivePeerDependencies:- - supports-color-- dependencies:- '@types/mdast': 4.0.4- devlop: 1.1.0- mdast-util-from-markdown: 2.0.3- mdast-util-to-markdown: 2.1.2- transitivePeerDependencies:- - supports-color-- dependencies:- mdast-util-from-markdown: 2.0.3- mdast-util-gfm-autolink-literal: 2.0.1- mdast-util-gfm-footnote: 2.1.0- mdast-util-gfm-strikethrough: 2.0.0- mdast-util-gfm-table: 2.0.0- mdast-util-gfm-task-list-item: 2.0.0- mdast-util-to-markdown: 2.1.2- transitivePeerDependencies:- - supports-color-- dependencies:- '@types/estree-jsx': 1.0.5- '@types/hast': 3.0.4- '@types/mdast': 4.0.4- devlop: 1.1.0- mdast-util-from-markdown: 2.0.3- mdast-util-to-markdown: 2.1.2- transitivePeerDependencies:- - supports-color-- dependencies:- '@types/estree-jsx': 1.0.5- '@types/hast': 3.0.4- '@types/mdast': 4.0.4- '@types/unist': 3.0.3- ccount: 2.0.1- devlop: 1.1.0- mdast-util-from-markdown: 2.0.3- mdast-util-to-markdown: 2.1.2- parse-entities: 4.0.2- stringify-entities: 4.0.4- unist-util-stringify-position: 4.0.0- vfile-message: 4.0.3- transitivePeerDependencies:- - supports-color-- dependencies:- '@types/estree-jsx': 1.0.5- '@types/hast': 3.0.4- '@types/mdast': 4.0.4- devlop: 1.1.0- mdast-util-from-markdown: 2.0.3- mdast-util-to-markdown: 2.1.2- transitivePeerDependencies:- - supports-color-- dependencies:- '@types/mdast': 4.0.4- unist-util-is: 6.0.1-- dependencies:- '@types/hast': 3.0.4- '@types/mdast': 4.0.4- '@ungap/structured-clone': 1.3.1- devlop: 1.1.0- micromark-util-sanitize-uri: 2.0.1- trim-lines: 3.0.1- unist-util-position: 5.0.0- unist-util-visit: 5.1.0- vfile: 6.0.3-- dependencies:- '@types/mdast': 4.0.4- '@types/unist': 3.0.3- longest-streak: 3.1.0- mdast-util-phrasing: 4.1.0- mdast-util-to-string: 4.0.0- micromark-util-classify-character: 2.0.1- micromark-util-decode-string: 2.0.1- unist-util-visit: 5.1.0- zwitch: 2.0.4-- dependencies:- '@types/mdast': 4.0.4-- [email protected]: {}-- [email protected]: {}-- dependencies:- decode-named-character-reference: 1.3.0- devlop: 1.1.0- micromark-factory-destination: 2.0.1- micromark-factory-label: 2.0.1- micromark-factory-space: 2.0.1- micromark-factory-title: 2.0.1- micromark-factory-whitespace: 2.0.1- micromark-util-character: 2.1.1- micromark-util-chunked: 2.0.1- micromark-util-classify-character: 2.0.1- micromark-util-html-tag-name: 2.0.1- micromark-util-normalize-identifier: 2.0.1- micromark-util-resolve-all: 2.0.1- micromark-util-subtokenize: 2.1.0- micromark-util-symbol: 2.0.1- micromark-util-types: 2.0.2-- dependencies:- micromark-util-character: 2.1.1- micromark-util-sanitize-uri: 2.0.1- micromark-util-symbol: 2.0.1- micromark-util-types: 2.0.2-- dependencies:- devlop: 1.1.0- micromark-core-commonmark: 2.0.3- micromark-factory-space: 2.0.1- micromark-util-character: 2.1.1- micromark-util-normalize-identifier: 2.0.1- micromark-util-sanitize-uri: 2.0.1- micromark-util-symbol: 2.0.1- micromark-util-types: 2.0.2-- dependencies:- devlop: 1.1.0- micromark-util-chunked: 2.0.1- micromark-util-classify-character: 2.0.1- micromark-util-resolve-all: 2.0.1- micromark-util-symbol: 2.0.1- micromark-util-types: 2.0.2-- dependencies:- devlop: 1.1.0- micromark-factory-space: 2.0.1- micromark-util-character: 2.1.1- micromark-util-symbol: 2.0.1- micromark-util-types: 2.0.2-- dependencies:- micromark-util-types: 2.0.2-- dependencies:- devlop: 1.1.0- micromark-factory-space: 2.0.1- micromark-util-character: 2.1.1- micromark-util-symbol: 2.0.1- micromark-util-types: 2.0.2-- dependencies:- micromark-extension-gfm-autolink-literal: 2.1.0- micromark-extension-gfm-footnote: 2.1.0- micromark-extension-gfm-strikethrough: 2.1.0- micromark-extension-gfm-table: 2.1.1- micromark-extension-gfm-tagfilter: 2.0.0- micromark-extension-gfm-task-list-item: 2.1.0- micromark-util-combine-extensions: 2.0.1- micromark-util-types: 2.0.2-- dependencies:- micromark-util-character: 2.1.1- micromark-util-symbol: 2.0.1- micromark-util-types: 2.0.2-- dependencies:- devlop: 1.1.0- micromark-util-character: 2.1.1- micromark-util-symbol: 2.0.1- micromark-util-types: 2.0.2-- dependencies:- micromark-util-character: 2.1.1- micromark-util-types: 2.0.2-- dependencies:- micromark-factory-space: 2.0.1- micromark-util-character: 2.1.1- micromark-util-symbol: 2.0.1- micromark-util-types: 2.0.2-- dependencies:- micromark-factory-space: 2.0.1- micromark-util-character: 2.1.1- micromark-util-symbol: 2.0.1- micromark-util-types: 2.0.2-- dependencies:- micromark-util-symbol: 2.0.1- micromark-util-types: 2.0.2-- dependencies:- micromark-util-symbol: 2.0.1-- dependencies:- micromark-util-character: 2.1.1- micromark-util-symbol: 2.0.1- micromark-util-types: 2.0.2-- dependencies:- micromark-util-chunked: 2.0.1- micromark-util-types: 2.0.2-- dependencies:- micromark-util-symbol: 2.0.1-- dependencies:- decode-named-character-reference: 1.3.0- micromark-util-character: 2.1.1- micromark-util-decode-numeric-character-reference: 2.0.2- micromark-util-symbol: 2.0.1-- [email protected]: {}-- [email protected]: {}-- dependencies:- micromark-util-symbol: 2.0.1-- dependencies:- micromark-util-types: 2.0.2-- dependencies:- micromark-util-character: 2.1.1- micromark-util-encode: 2.0.1- micromark-util-symbol: 2.0.1-- dependencies:- devlop: 1.1.0- micromark-util-chunked: 2.0.1- micromark-util-symbol: 2.0.1- micromark-util-types: 2.0.2-- [email protected]: {}-- [email protected]: {}-- dependencies:- '@types/debug': 4.1.13- debug: 4.4.3- decode-named-character-reference: 1.3.0- devlop: 1.1.0- micromark-core-commonmark: 2.0.3- micromark-factory-space: 2.0.1- micromark-util-character: 2.1.1- micromark-util-chunked: 2.0.1- micromark-util-combine-extensions: 2.0.1- micromark-util-decode-numeric-character-reference: 2.0.2- micromark-util-encode: 2.0.1- micromark-util-normalize-identifier: 2.0.1- micromark-util-resolve-all: 2.0.1- micromark-util-sanitize-uri: 2.0.1- micromark-util-subtokenize: 2.1.0- micromark-util-symbol: 2.0.1- micromark-util-types: 2.0.2- transitivePeerDependencies:- - supports-color-- dependencies:- braces: 3.0.3- picomatch: 2.3.2-- [email protected]: {}-- [email protected]: {}-- dependencies:- brace-expansion: 5.0.6-- dependencies:- brace-expansion: 1.1.14-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- react: 19.2.6- react-dom: 19.2.6([email protected])-- [email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected]([email protected]))([email protected]):- dependencies:- '@next/env': 16.2.6- '@swc/helpers': 0.5.15- baseline-browser-mapping: 2.10.30- caniuse-lite: 1.0.30001793- postcss: 8.4.31- react: 19.2.6- react-dom: 19.2.6([email protected])- styled-jsx: 5.1.6(@babel/[email protected])([email protected])- optionalDependencies:- '@next/swc-darwin-arm64': 16.2.6- '@next/swc-darwin-x64': 16.2.6- '@next/swc-linux-arm64-gnu': 16.2.6- '@next/swc-linux-arm64-musl': 16.2.6- '@next/swc-linux-x64-gnu': 16.2.6- '@next/swc-linux-x64-musl': 16.2.6- '@next/swc-win32-arm64-msvc': 16.2.6- '@next/swc-win32-x64-msvc': 16.2.6- '@opentelemetry/api': 1.9.0- sharp: 0.34.5- transitivePeerDependencies:- - '@babel/core'- - babel-plugin-macros-- dependencies:- semver: 7.8.0-- [email protected]: {}-- dependencies:- array.prototype.flatmap: 1.3.3- es-errors: 1.3.0- object.entries: 1.1.9- semver: 6.3.1-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- call-bind: 1.0.9- call-bound: 1.0.4- define-properties: 1.2.1- es-object-atoms: 1.1.1- has-symbols: 1.1.0- object-keys: 1.1.1-- dependencies:- call-bind: 1.0.9- call-bound: 1.0.4- define-properties: 1.2.1- es-object-atoms: 1.1.1-- dependencies:- call-bind: 1.0.9- define-properties: 1.2.1- es-abstract: 1.24.2- es-object-atoms: 1.1.1-- dependencies:- call-bind: 1.0.9- define-properties: 1.2.1- es-abstract: 1.24.2-- dependencies:- call-bind: 1.0.9- call-bound: 1.0.4- define-properties: 1.2.1- es-object-atoms: 1.1.1-- [email protected]: {}-- dependencies:- wrappy: 1.0.2-- dependencies:- default-browser: 5.5.0- define-lazy-prop: 3.0.0- is-inside-container: 1.0.0- wsl-utils: 0.1.0-- dependencies:- deep-is: 0.1.4- fast-levenshtein: 2.0.6- levn: 0.4.1- prelude-ls: 1.2.1- type-check: 0.4.0- word-wrap: 1.2.5-- dependencies:- get-intrinsic: 1.3.0- object-keys: 1.1.1- safe-push-apply: 1.0.0-- dependencies:- yocto-queue: 0.1.0-- dependencies:- p-limit: 3.1.0-- dependencies:- callsites: 3.1.0-- dependencies:- '@types/unist': 2.0.11- character-entities-legacy: 3.0.0- character-reference-invalid: 2.0.1- decode-named-character-reference: 1.3.0- is-alphanumerical: 2.0.1- is-decimal: 2.0.1- is-hexadecimal: 2.0.1-- dependencies:- entities: 8.0.0-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- nanoid: 3.3.12- picocolors: 1.1.1- source-map-js: 1.2.1-- dependencies:- nanoid: 3.3.12- picocolors: 1.1.1- source-map-js: 1.2.1-- dependencies:- detect-libc: 2.1.2- expand-template: 2.0.3- github-from-package: 0.0.0- minimist: 1.2.8- mkdirp-classic: 0.5.3- napi-build-utils: 2.0.0- node-abi: 3.92.0- pump: 3.0.4- rc: 1.2.8- simple-get: 4.0.1- tar-fs: 2.1.4- tunnel-agent: 0.6.0-- [email protected]: {}-- dependencies:- ansi-regex: 5.0.1- ansi-styles: 5.2.0- react-is: 17.0.2-- dependencies:- loose-envify: 1.4.0- object-assign: 4.1.1- react-is: 16.13.1-- [email protected]: {}-- dependencies:- end-of-stream: 1.4.5- once: 1.4.0-- [email protected]: {}-- [email protected]: {}-- [email protected](@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected]):- dependencies:- '@radix-ui/primitive': 1.1.3- '@radix-ui/react-accessible-icon': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-accordion': 1.2.12(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-alert-dialog': 1.1.15(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-arrow': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-aspect-ratio': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-avatar': 1.1.10(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-checkbox': 1.3.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-collapsible': 1.1.12(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-collection': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-compose-refs': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context': 1.1.2(@types/[email protected])([email protected])- '@radix-ui/react-context-menu': 2.2.16(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-dialog': 1.1.15(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-direction': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-dismissable-layer': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-dropdown-menu': 2.1.16(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-focus-guards': 1.1.3(@types/[email protected])([email protected])- '@radix-ui/react-focus-scope': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-form': 0.1.8(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-hover-card': 1.1.15(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-label': 2.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-menu': 2.1.16(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-menubar': 1.1.16(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-navigation-menu': 1.2.14(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-one-time-password-field': 0.1.8(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-password-toggle-field': 0.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-popover': 1.1.15(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-popper': 1.2.8(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-portal': 1.1.9(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-presence': 1.1.5(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-primitive': 2.1.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-progress': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-radio-group': 1.3.8(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-roving-focus': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-scroll-area': 1.2.10(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-select': 2.2.6(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-separator': 1.1.7(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-slider': 1.3.6(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-slot': 1.2.3(@types/[email protected])([email protected])- '@radix-ui/react-switch': 1.2.6(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-tabs': 1.1.13(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-toast': 1.2.15(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-toggle': 1.1.10(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-toggle-group': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-toolbar': 1.1.11(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-tooltip': 1.2.8(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- '@radix-ui/react-use-callback-ref': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-use-controllable-state': 1.2.2(@types/[email protected])([email protected])- '@radix-ui/react-use-effect-event': 0.0.2(@types/[email protected])([email protected])- '@radix-ui/react-use-escape-keydown': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-use-is-hydrated': 0.1.0(@types/[email protected])([email protected])- '@radix-ui/react-use-layout-effect': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-use-size': 1.1.1(@types/[email protected])([email protected])- '@radix-ui/react-visually-hidden': 1.2.3(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])- react: 19.2.6- react-dom: 19.2.6([email protected])- optionalDependencies:- '@types/react': 19.2.14- '@types/react-dom': 19.2.3(@types/[email protected])-- dependencies:- deep-extend: 0.6.0- ini: 1.3.8- minimist: 1.2.8- strip-json-comments: 2.0.1-- dependencies:- react: 19.2.6- scheduler: 0.27.0-- [email protected]: {}-- [email protected]: {}-- dependencies:- '@types/hast': 3.0.4- '@types/mdast': 4.0.4- '@types/react': 19.2.14- devlop: 1.1.0- hast-util-to-jsx-runtime: 2.3.6- html-url-attributes: 3.0.1- mdast-util-to-hast: 13.2.1- react: 19.2.6- remark-parse: 11.0.0- remark-rehype: 11.1.2- unified: 11.0.5- unist-util-visit: 5.1.0- vfile: 6.0.3- transitivePeerDependencies:- - supports-color-- dependencies:- react: 19.2.6- react-style-singleton: 2.2.3(@types/[email protected])([email protected])- tslib: 2.8.1- optionalDependencies:- '@types/react': 19.2.14-- dependencies:- react: 19.2.6- react-remove-scroll-bar: 2.3.8(@types/[email protected])([email protected])- react-style-singleton: 2.2.3(@types/[email protected])([email protected])- tslib: 2.8.1- use-callback-ref: 1.3.3(@types/[email protected])([email protected])- use-sidecar: 1.1.3(@types/[email protected])([email protected])- optionalDependencies:- '@types/react': 19.2.14-- dependencies:- get-nonce: 1.0.1- react: 19.2.6- tslib: 2.8.1- optionalDependencies:- '@types/react': 19.2.14-- [email protected]: {}-- dependencies:- inherits: 2.0.4- string_decoder: 1.3.0- util-deprecate: 1.0.2-- dependencies:- indent-string: 4.0.0- strip-indent: 3.0.0-- dependencies:- call-bind: 1.0.9- define-properties: 1.2.1- es-abstract: 1.24.2- es-errors: 1.3.0- es-object-atoms: 1.1.1- get-intrinsic: 1.3.0- get-proto: 1.0.1- which-builtin-type: 1.2.1-- dependencies:- call-bind: 1.0.9- define-properties: 1.2.1- es-errors: 1.3.0- get-proto: 1.0.1- gopd: 1.2.0- set-function-name: 2.0.2-- dependencies:- '@types/mdast': 4.0.4- mdast-util-gfm: 3.1.0- micromark-extension-gfm: 3.0.0- remark-parse: 11.0.0- remark-stringify: 11.0.0- unified: 11.0.5- transitivePeerDependencies:- - supports-color-- dependencies:- '@types/mdast': 4.0.4- mdast-util-from-markdown: 2.0.3- micromark-util-types: 2.0.2- unified: 11.0.5- transitivePeerDependencies:- - supports-color-- dependencies:- '@types/hast': 3.0.4- '@types/mdast': 4.0.4- mdast-util-to-hast: 13.2.1- unified: 11.0.5- vfile: 6.0.3-- dependencies:- '@types/mdast': 4.0.4- mdast-util-to-markdown: 2.1.2- unified: 11.0.5-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- es-errors: 1.3.0- is-core-module: 2.16.2- node-exports-info: 1.6.0- object-keys: 1.1.1- path-parse: 1.0.7- supports-preserve-symlinks-flag: 1.0.0-- [email protected]: {}-- dependencies:- '@oxc-project/types': 0.130.0- '@rolldown/pluginutils': 1.0.1- optionalDependencies:- '@rolldown/binding-android-arm64': 1.0.1- '@rolldown/binding-darwin-arm64': 1.0.1- '@rolldown/binding-darwin-x64': 1.0.1- '@rolldown/binding-freebsd-x64': 1.0.1- '@rolldown/binding-linux-arm-gnueabihf': 1.0.1- '@rolldown/binding-linux-arm64-gnu': 1.0.1- '@rolldown/binding-linux-arm64-musl': 1.0.1- '@rolldown/binding-linux-ppc64-gnu': 1.0.1- '@rolldown/binding-linux-s390x-gnu': 1.0.1- '@rolldown/binding-linux-x64-gnu': 1.0.1- '@rolldown/binding-linux-x64-musl': 1.0.1- '@rolldown/binding-openharmony-arm64': 1.0.1- '@rolldown/binding-wasm32-wasi': 1.0.1- '@rolldown/binding-win32-arm64-msvc': 1.0.1- '@rolldown/binding-win32-x64-msvc': 1.0.1-- [email protected]: {}-- dependencies:- queue-microtask: 1.2.3-- dependencies:- call-bind: 1.0.9- call-bound: 1.0.4- get-intrinsic: 1.3.0- has-symbols: 1.1.0- isarray: 2.0.5-- [email protected]: {}-- dependencies:- es-errors: 1.3.0- isarray: 2.0.5-- dependencies:- call-bound: 1.0.4- es-errors: 1.3.0- is-regex: 1.2.1-- dependencies:- xmlchars: 2.2.0-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- define-data-property: 1.1.4- es-errors: 1.3.0- function-bind: 1.1.2- get-intrinsic: 1.3.0- gopd: 1.2.0- has-property-descriptors: 1.0.2-- dependencies:- define-data-property: 1.1.4- es-errors: 1.3.0- functions-have-names: 1.2.3- has-property-descriptors: 1.0.2-- dependencies:- dunder-proto: 1.0.1- es-errors: 1.3.0- es-object-atoms: 1.1.1-- dependencies:- '@img/colour': 1.1.0- detect-libc: 2.1.2- semver: 7.8.0- optionalDependencies:- '@img/sharp-darwin-arm64': 0.34.5- '@img/sharp-darwin-x64': 0.34.5- '@img/sharp-libvips-darwin-arm64': 1.2.4- '@img/sharp-libvips-darwin-x64': 1.2.4- '@img/sharp-libvips-linux-arm': 1.2.4- '@img/sharp-libvips-linux-arm64': 1.2.4- '@img/sharp-libvips-linux-ppc64': 1.2.4- '@img/sharp-libvips-linux-riscv64': 1.2.4- '@img/sharp-libvips-linux-s390x': 1.2.4- '@img/sharp-libvips-linux-x64': 1.2.4- '@img/sharp-libvips-linuxmusl-arm64': 1.2.4- '@img/sharp-libvips-linuxmusl-x64': 1.2.4- '@img/sharp-linux-arm': 0.34.5- '@img/sharp-linux-arm64': 0.34.5- '@img/sharp-linux-ppc64': 0.34.5- '@img/sharp-linux-riscv64': 0.34.5- '@img/sharp-linux-s390x': 0.34.5- '@img/sharp-linux-x64': 0.34.5- '@img/sharp-linuxmusl-arm64': 0.34.5- '@img/sharp-linuxmusl-x64': 0.34.5- '@img/sharp-wasm32': 0.34.5- '@img/sharp-win32-arm64': 0.34.5- '@img/sharp-win32-ia32': 0.34.5- '@img/sharp-win32-x64': 0.34.5- optional: true-- dependencies:- shebang-regex: 3.0.0-- [email protected]: {}-- dependencies:- es-errors: 1.3.0- object-inspect: 1.13.4-- dependencies:- call-bound: 1.0.4- es-errors: 1.3.0- get-intrinsic: 1.3.0- object-inspect: 1.13.4-- dependencies:- call-bound: 1.0.4- es-errors: 1.3.0- get-intrinsic: 1.3.0- object-inspect: 1.13.4- side-channel-map: 1.0.1-- dependencies:- es-errors: 1.3.0- object-inspect: 1.13.4- side-channel-list: 1.0.1- side-channel-map: 1.0.1- side-channel-weakmap: 1.0.2-- [email protected]: {}-- [email protected]: {}-- dependencies:- decompress-response: 6.0.0- once: 1.4.0- simple-concat: 1.0.1-- dependencies:- react: 19.2.6- react-dom: 19.2.6([email protected])-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- es-errors: 1.3.0- internal-slot: 1.1.0-- dependencies:- call-bind: 1.0.9- define-properties: 1.2.1- es-abstract: 1.24.2-- dependencies:- call-bind: 1.0.9- call-bound: 1.0.4- define-properties: 1.2.1- es-abstract: 1.24.2- es-errors: 1.3.0- es-object-atoms: 1.1.1- get-intrinsic: 1.3.0- gopd: 1.2.0- has-symbols: 1.1.0- internal-slot: 1.1.0- regexp.prototype.flags: 1.5.4- set-function-name: 2.0.2- side-channel: 1.1.0-- dependencies:- define-properties: 1.2.1- es-abstract: 1.24.2-- dependencies:- call-bind: 1.0.9- call-bound: 1.0.4- define-data-property: 1.1.4- define-properties: 1.2.1- es-abstract: 1.24.2- es-object-atoms: 1.1.1- has-property-descriptors: 1.0.2-- dependencies:- call-bind: 1.0.9- call-bound: 1.0.4- define-properties: 1.2.1- es-object-atoms: 1.1.1-- dependencies:- call-bind: 1.0.9- define-properties: 1.2.1- es-object-atoms: 1.1.1-- dependencies:- safe-buffer: 5.2.1-- dependencies:- character-entities-html4: 2.1.0- character-entities-legacy: 3.0.0-- [email protected]: {}-- dependencies:- min-indent: 1.0.1-- [email protected]: {}-- [email protected]: {}-- dependencies:- style-to-object: 1.0.14-- dependencies:- inline-style-parser: 0.2.7-- dependencies:- client-only: 0.0.1- react: 19.2.6- optionalDependencies:- '@babel/core': 7.29.0-- dependencies:- has-flag: 4.0.0-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- chownr: 1.1.4- mkdirp-classic: 0.5.3- pump: 3.0.4- tar-stream: 2.2.0-- dependencies:- bl: 4.1.0- end-of-stream: 1.4.5- fs-constants: 1.0.0- inherits: 2.0.4- readable-stream: 3.6.2-- [email protected]: {}-- [email protected]: {}-- dependencies:- fdir: 6.5.0([email protected])- picomatch: 4.0.4-- [email protected]: {}-- [email protected]: {}-- dependencies:- tldts-core: 7.4.8-- dependencies:- is-number: 7.0.0-- dependencies:- tldts: 7.4.8-- dependencies:- punycode: 2.3.1-- [email protected]: {}-- [email protected]: {}-- dependencies:- typescript: 5.9.3-- dependencies:- '@types/json5': 0.0.29- json5: 1.0.2- minimist: 1.2.8- strip-bom: 3.0.0-- [email protected]: {}-- dependencies:- esbuild: 0.28.0- optionalDependencies:- fsevents: 2.3.3-- dependencies:- safe-buffer: 5.2.1-- dependencies:- prelude-ls: 1.2.1-- dependencies:- call-bound: 1.0.4- es-errors: 1.3.0- is-typed-array: 1.1.15-- dependencies:- call-bind: 1.0.9- for-each: 0.3.5- gopd: 1.2.0- has-proto: 1.2.0- is-typed-array: 1.1.15-- dependencies:- available-typed-arrays: 1.0.7- call-bind: 1.0.9- for-each: 0.3.5- gopd: 1.2.0- has-proto: 1.2.0- is-typed-array: 1.1.15- reflect.getprototypeof: 1.0.10-- dependencies:- call-bind: 1.0.9- for-each: 0.3.5- gopd: 1.2.0- is-typed-array: 1.1.15- possible-typed-array-names: 1.1.0- reflect.getprototypeof: 1.0.10-- dependencies:- '@typescript-eslint/eslint-plugin': 8.59.3(@typescript-eslint/[email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])- '@typescript-eslint/typescript-estree': 8.59.3([email protected])- eslint: 9.39.4([email protected])- typescript: 5.9.3- transitivePeerDependencies:- - supports-color-- [email protected]: {}-- dependencies:- call-bound: 1.0.4- has-bigints: 1.1.0- has-symbols: 1.1.0- which-boxed-primitive: 1.1.1-- [email protected]: {}-- [email protected]: {}-- dependencies:- '@types/unist': 3.0.3- bail: 2.0.2- devlop: 1.1.0- extend: 3.0.2- is-plain-obj: 4.1.0- trough: 2.2.0- vfile: 6.0.3-- dependencies:- '@types/unist': 3.0.3-- dependencies:- '@types/unist': 3.0.3-- dependencies:- '@types/unist': 3.0.3-- dependencies:- '@types/unist': 3.0.3- unist-util-is: 6.0.1-- dependencies:- '@types/unist': 3.0.3- unist-util-is: 6.0.1- unist-util-visit-parents: 6.0.2-- dependencies:- napi-postinstall: 0.3.4- optionalDependencies:- '@unrs/resolver-binding-android-arm-eabi': 1.11.1- '@unrs/resolver-binding-android-arm64': 1.11.1- '@unrs/resolver-binding-darwin-arm64': 1.11.1- '@unrs/resolver-binding-darwin-x64': 1.11.1- '@unrs/resolver-binding-freebsd-x64': 1.11.1- '@unrs/resolver-binding-linux-arm-gnueabihf': 1.11.1- '@unrs/resolver-binding-linux-arm-musleabihf': 1.11.1- '@unrs/resolver-binding-linux-arm64-gnu': 1.11.1- '@unrs/resolver-binding-linux-arm64-musl': 1.11.1- '@unrs/resolver-binding-linux-ppc64-gnu': 1.11.1- '@unrs/resolver-binding-linux-riscv64-gnu': 1.11.1- '@unrs/resolver-binding-linux-riscv64-musl': 1.11.1- '@unrs/resolver-binding-linux-s390x-gnu': 1.11.1- '@unrs/resolver-binding-linux-x64-gnu': 1.11.1- '@unrs/resolver-binding-linux-x64-musl': 1.11.1- '@unrs/resolver-binding-wasm32-wasi': 1.11.1- '@unrs/resolver-binding-win32-arm64-msvc': 1.11.1- '@unrs/resolver-binding-win32-ia32-msvc': 1.11.1- '@unrs/resolver-binding-win32-x64-msvc': 1.11.1-- dependencies:- browserslist: 4.28.2- escalade: 3.2.0- picocolors: 1.1.1-- dependencies:- punycode: 2.3.1-- dependencies:- react: 19.2.6- tslib: 2.8.1- optionalDependencies:- '@types/react': 19.2.14-- dependencies:- detect-node-es: 1.1.0- react: 19.2.6- tslib: 2.8.1- optionalDependencies:- '@types/react': 19.2.14-- dependencies:- react: 19.2.6-- [email protected]: {}-- dependencies:- '@types/unist': 3.0.3- unist-util-stringify-position: 4.0.0-- dependencies:- '@types/unist': 3.0.3- vfile-message: 4.0.3-- [email protected](@types/[email protected])([email protected])([email protected])([email protected]):- dependencies:- lightningcss: 1.32.0- picomatch: 4.0.4- postcss: 8.5.14- rolldown: 1.0.1- tinyglobby: 0.2.16- optionalDependencies:- '@types/node': 22.19.19- esbuild: 0.28.0- fsevents: 2.3.3- jiti: 2.7.0- tsx: 4.22.1-- [email protected](@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])):- dependencies:- '@vitest/expect': 4.1.10- '@vitest/mocker': 4.1.10([email protected](@types/[email protected])([email protected])([email protected])([email protected]))- '@vitest/pretty-format': 4.1.10- '@vitest/runner': 4.1.10- '@vitest/snapshot': 4.1.10- '@vitest/spy': 4.1.10- '@vitest/utils': 4.1.10- es-module-lexer: 2.3.1- expect-type: 1.4.0- magic-string: 0.30.21- obug: 2.1.3- pathe: 2.0.3- picomatch: 4.0.4- std-env: 4.2.0- tinybench: 2.9.0- tinyexec: 1.2.4- tinyglobby: 0.2.16- tinyrainbow: 3.1.0- why-is-node-running: 2.3.0- optionalDependencies:- '@opentelemetry/api': 1.9.0- '@types/node': 22.19.19- '@vitest/coverage-v8': 4.1.10([email protected])- jsdom: 29.1.1- transitivePeerDependencies:- - msw-- dependencies:- xml-name-validator: 5.0.0-- [email protected]: {}-- [email protected]: {}-- dependencies:- '@exodus/bytes': 1.15.1- tr46: 6.0.0- webidl-conversions: 8.0.1- transitivePeerDependencies:- - '@noble/hashes'-- dependencies:- is-bigint: 1.1.0- is-boolean-object: 1.2.2- is-number-object: 1.1.1- is-string: 1.1.1- is-symbol: 1.1.1-- dependencies:- call-bound: 1.0.4- function.prototype.name: 1.1.8- has-tostringtag: 1.0.2- is-async-function: 2.1.1- is-date-object: 1.1.0- is-finalizationregistry: 1.1.1- is-generator-function: 1.1.2- is-regex: 1.2.1- is-weakref: 1.1.1- isarray: 2.0.5- which-boxed-primitive: 1.1.1- which-collection: 1.0.2- which-typed-array: 1.1.20-- dependencies:- is-map: 2.0.3- is-set: 2.0.3- is-weakmap: 2.0.2- is-weakset: 2.0.4-- dependencies:- available-typed-arrays: 1.0.7- call-bind: 1.0.9- call-bound: 1.0.4- for-each: 0.3.5- get-proto: 1.0.1- gopd: 1.2.0- has-tostringtag: 1.0.2-- dependencies:- isexe: 2.0.0-- dependencies:- siginfo: 2.0.0- stackback: 0.0.2-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- is-wsl: 3.1.1-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- [email protected]: {}-- dependencies:- zod: 3.25.76-- [email protected]: {}-- [email protected]: {}diff --git a/notfair/postcss.config.mjs b/notfair/postcss.config.mjsdeleted file mode 100644index c7bcb4b1..00000000--- a/notfair/postcss.config.mjs+++ /dev/null@@ -1,5 +0,0 @@-const config = {- plugins: ["@tailwindcss/postcss"],-};--export default config;diff --git a/notfair/public/mcp-logos/google-ads-icon.svg b/notfair/public/mcp-logos/google-ads-icon.svgdeleted file mode 100644index 37cfdb0e..00000000--- a/notfair/public/mcp-logos/google-ads-icon.svg+++ /dev/null@@ -1 +0,0 @@-<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="64" height="64"><style><![CDATA[.E{clip-path:url(#A)}]]></style><defs><clipPath id="A"><use xlink:href="#B"/></clipPath><path id="B" d="M0 0h250.9v312.8H0z"/></defs><g transform="matrix(.257748 0 0 .257745 -.361416 2.515516)" class="E"><path d="M85.9 28.6c2.4-6.3 5.7-12.1 10.6-16.8 19.6-19.1 52-14.3 65.3 9.7 10 18.2 20.6 36 30.9 54l51.6 89.8c14.3 25.1-1.2 56.8-29.6 61.1-17.4 2.6-33.7-5.4-42.7-21l-45.4-78.8c-.3-.6-.7-1.1-1.1-1.6-1.6-1.3-2.3-3.2-3.3-4.9L88.8 62.2c-3.9-6.8-5.7-14.2-5.5-22 .3-4 .8-8 2.6-11.6" fill="#3c8bd9"/><path d="M85.9 28.6c-.9 3.6-1.7 7.2-1.9 11-.3 8.4 1.8 16.2 6 23.5l32.9 56.9c1 1.7 1.8 3.4 2.8 5l-18.1 31.1-25.3 43.6c-.4 0-.5-.2-.6-.5-.1-.8.2-1.5.4-2.3 4.1-15 .7-28.3-9.6-39.7-6.3-6.9-14.3-10.8-23.5-12.1-12-1.7-22.6 1.4-32.1 8.9-1.7 1.3-2.8 3.2-4.8 4.2-.4 0-.6-.2-.7-.5l14.3-24.9L85.2 29.7c.2-.4.5-.7.7-1.1" fill="#fabc04"/><path d="M11.8 158l5.7-5.1c24.3-19.2 60.8-5.3 66.1 25.1 1.3 7.3.6 14.3-1.6 21.3-.1.6-.2 1.1-.4 1.7-.9 1.6-1.7 3.3-2.7 4.9-8.9 14.7-22 22-39.2 20.9C20 225.4 4.5 210.6 1.8 191c-1.3-9.5.6-18.4 5.5-26.6 1-1.8 2.2-3.4 3.3-5.2.5-.4.3-1.2 1.2-1.2" fill="#34a852"/><path d="M11.8 158c-.4.4-.4 1.1-1.1 1.2-.1-.7.3-1.1.7-1.6l.4.4" fill="#fabc04"/><path d="M81.6 201c-.4-.7 0-1.2.4-1.7l.4.4-.8 1.3" fill="#e1c025"/></g></svg>\ No newline at end of filediff --git a/notfair/public/mcp-logos/google-analytics-icon.svg b/notfair/public/mcp-logos/google-analytics-icon.svgdeleted file mode 100644index 2a812c5f..00000000--- a/notfair/public/mcp-logos/google-analytics-icon.svg+++ /dev/null@@ -1,5 +0,0 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">- <rect x="16.4" y="3" width="4.6" height="18" rx="2.3" fill="#F9AB00"/>- <rect x="9.7" y="10.5" width="4.6" height="10.5" rx="2.3" fill="#E37400"/>- <circle cx="5.3" cy="18.7" r="2.3" fill="#E37400"/>-</svg>diff --git a/notfair/public/mcp-logos/meta-icon.svg b/notfair/public/mcp-logos/meta-icon.svgdeleted file mode 100644index a8a8d948..00000000--- a/notfair/public/mcp-logos/meta-icon.svg+++ /dev/null@@ -1 +0,0 @@-<svg height="1em" style="flex:none;line-height:1" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>Meta</title><path d="M6.897 4h-.024l-.031 2.615h.022c1.715 0 3.046 1.357 5.94 6.246l.175.297.012.02 1.62-2.438-.012-.019a48.763 48.763 0 00-1.098-1.716 28.01 28.01 0 00-1.175-1.629C10.413 4.932 8.812 4 6.896 4z" fill="url(#lobe-icons-meta-0-_R_0_)"></path><path d="M6.873 4C4.95 4.01 3.247 5.258 2.02 7.17a4.352 4.352 0 00-.01.017l2.254 1.231.011-.017c.718-1.083 1.61-1.774 2.568-1.785h.021L6.896 4h-.023z" fill="url(#lobe-icons-meta-1-_R_0_)"></path><path d="M2.019 7.17l-.011.017C1.2 8.447.598 9.995.274 11.664l-.005.022 2.534.6.004-.022c.27-1.467.786-2.828 1.456-3.845l.011-.017L2.02 7.17z" fill="url(#lobe-icons-meta-2-_R_0_)"></path><path d="M2.807 12.264l-2.533-.6-.005.022c-.177.918-.267 1.851-.269 2.786v.023l2.598.233v-.023a12.591 12.591 0 01.21-2.44z" fill="url(#lobe-icons-meta-3-_R_0_)"></path><path d="M2.677 15.537a5.462 5.462 0 01-.079-.813v-.022L0 14.468v.024a8.89 8.89 0 00.146 1.652l2.535-.585a4.106 4.106 0 01-.004-.022z" fill="url(#lobe-icons-meta-4-_R_0_)"></path><path d="M3.27 16.89c-.284-.31-.484-.756-.589-1.328l-.004-.021-2.535.585.004.021c.192 1.01.568 1.85 1.106 2.487l.014.017 2.018-1.745a2.106 2.106 0 01-.015-.016z" fill="url(#lobe-icons-meta-5-_R_0_)"></path><path d="M10.78 9.654c-1.528 2.35-2.454 3.825-2.454 3.825-2.035 3.2-2.739 3.917-3.871 3.917a1.545 1.545 0 01-1.186-.508l-2.017 1.744.014.017C2.01 19.518 3.058 20 4.356 20c1.963 0 3.374-.928 5.884-5.33l1.766-3.13a41.283 41.283 0 00-1.227-1.886z" fill="#0082FB"></path><path d="M13.502 5.946l-.016.016c-.4.43-.786.908-1.16 1.416.378.483.768 1.024 1.175 1.63.48-.743.928-1.345 1.367-1.807l.016-.016-1.382-1.24z" fill="url(#lobe-icons-meta-6-_R_0_)"></path><path d="M20.918 5.713C19.853 4.633 18.583 4 17.225 4c-1.432 0-2.637.787-3.723 1.944l-.016.016 1.382 1.24.016-.017c.715-.747 1.408-1.12 2.176-1.12.826 0 1.6.39 2.27 1.075l.015.016 1.589-1.425-.016-.016z" fill="#0082FB"></path><path d="M23.998 14.125c-.06-3.467-1.27-6.566-3.064-8.396l-.016-.016-1.588 1.424.015.016c1.35 1.392 2.277 3.98 2.361 6.971v.023h2.292v-.022z" fill="url(#lobe-icons-meta-7-_R_0_)"></path><path d="M23.998 14.15v-.023h-2.292v.022c.004.14.006.282.006.424 0 .815-.121 1.474-.368 1.95l-.011.022 1.708 1.782.013-.02c.62-.96.946-2.293.946-3.91 0-.083 0-.165-.002-.247z" fill="url(#lobe-icons-meta-8-_R_0_)"></path><path d="M21.344 16.52l-.011.02c-.214.402-.519.67-.917.787l.778 2.462a3.493 3.493 0 00.438-.182 3.558 3.558 0 001.366-1.218l.044-.065.012-.02-1.71-1.784z" fill="url(#lobe-icons-meta-9-_R_0_)"></path><path d="M19.92 17.393c-.262 0-.492-.039-.718-.14l-.798 2.522c.449.153.927.222 1.46.222.492 0 .943-.073 1.352-.215l-.78-2.462c-.167.05-.341.075-.517.073z" fill="url(#lobe-icons-meta-10-_R_0_)"></path><path d="M18.323 16.534l-.014-.017-1.836 1.914.016.017c.637.682 1.246 1.105 1.937 1.337l.797-2.52c-.291-.125-.573-.353-.9-.731z" fill="url(#lobe-icons-meta-11-_R_0_)"></path><path d="M18.309 16.515c-.55-.642-1.232-1.712-2.303-3.44l-1.396-2.336-.011-.02-1.62 2.438.012.02.989 1.668c.959 1.61 1.74 2.774 2.493 3.585l.016.016 1.834-1.914a2.353 2.353 0 01-.014-.017z" fill="url(#lobe-icons-meta-12-_R_0_)"></path><defs><linearGradient id="lobe-icons-meta-0-_R_0_" x1="75.897%" x2="26.312%" y1="89.199%" y2="12.194%"><stop offset=".06%" stop-color="#0867DF"></stop><stop offset="45.39%" stop-color="#0668E1"></stop><stop offset="85.91%" stop-color="#0064E0"></stop></linearGradient><linearGradient id="lobe-icons-meta-1-_R_0_" x1="21.67%" x2="97.068%" y1="75.874%" y2="23.985%"><stop offset="13.23%" stop-color="#0064DF"></stop><stop offset="99.88%" stop-color="#0064E0"></stop></linearGradient><linearGradient id="lobe-icons-meta-2-_R_0_" x1="38.263%" x2="60.895%" y1="89.127%" y2="16.131%"><stop offset="1.47%" stop-color="#0072EC"></stop><stop offset="68.81%" stop-color="#0064DF"></stop></linearGradient><linearGradient id="lobe-icons-meta-3-_R_0_" x1="47.032%" x2="52.15%" y1="90.19%" y2="15.745%"><stop offset="7.31%" stop-color="#007CF6"></stop><stop offset="99.43%" stop-color="#0072EC"></stop></linearGradient><linearGradient id="lobe-icons-meta-4-_R_0_" x1="52.155%" x2="47.591%" y1="58.301%" y2="37.004%"><stop offset="7.31%" stop-color="#007FF9"></stop><stop offset="100%" stop-color="#007CF6"></stop></linearGradient><linearGradient id="lobe-icons-meta-5-_R_0_" x1="37.689%" x2="61.961%" y1="12.502%" y2="63.624%"><stop offset="7.31%" stop-color="#007FF9"></stop><stop offset="100%" stop-color="#0082FB"></stop></linearGradient><linearGradient id="lobe-icons-meta-6-_R_0_" x1="34.808%" x2="62.313%" y1="68.859%" y2="23.174%"><stop offset="27.99%" stop-color="#007FF8"></stop><stop offset="91.41%" stop-color="#0082FB"></stop></linearGradient><linearGradient id="lobe-icons-meta-7-_R_0_" x1="43.762%" x2="57.602%" y1="6.235%" y2="98.514%"><stop offset="0%" stop-color="#0082FB"></stop><stop offset="99.95%" stop-color="#0081FA"></stop></linearGradient><linearGradient id="lobe-icons-meta-8-_R_0_" x1="60.055%" x2="39.88%" y1="4.661%" y2="69.077%"><stop offset="6.19%" stop-color="#0081FA"></stop><stop offset="100%" stop-color="#0080F9"></stop></linearGradient><linearGradient id="lobe-icons-meta-9-_R_0_" x1="30.282%" x2="61.081%" y1="59.32%" y2="33.244%"><stop offset="0%" stop-color="#027AF3"></stop><stop offset="100%" stop-color="#0080F9"></stop></linearGradient><linearGradient id="lobe-icons-meta-10-_R_0_" x1="20.433%" x2="82.112%" y1="50.001%" y2="50.001%"><stop offset="0%" stop-color="#0377EF"></stop><stop offset="99.94%" stop-color="#0279F1"></stop></linearGradient><linearGradient id="lobe-icons-meta-11-_R_0_" x1="40.303%" x2="72.394%" y1="35.298%" y2="57.811%"><stop offset=".19%" stop-color="#0471E9"></stop><stop offset="100%" stop-color="#0377EF"></stop></linearGradient><linearGradient id="lobe-icons-meta-12-_R_0_" x1="32.254%" x2="68.003%" y1="19.719%" y2="84.908%"><stop offset="27.65%" stop-color="#0867DF"></stop><stop offset="100%" stop-color="#0471E9"></stop></linearGradient></defs></svg>\ No newline at end of filediff --git a/notfair/public/mcp-logos/search-console-icon.svg b/notfair/public/mcp-logos/search-console-icon.svgdeleted file mode 100644index a2c30653..00000000--- a/notfair/public/mcp-logos/search-console-icon.svg+++ /dev/null@@ -1 +0,0 @@-<svg height="2500" viewBox="6.239 2.66350997 503.09749003 503.10849003" width="2500" xmlns="http://www.w3.org/2000/svg"><g fill="none"><path d="m113.296 424.432-75.52 75.536c-5.825 5.804-15.247 5.804-21.072 0l-4.672-4.672c-5.793-5.823-5.793-15.233 0-21.056l75.52-75.536c5.827-5.814 15.26-5.814 21.088 0l4.656 4.656a14.88 14.88 0 0 1 0 21.072z" fill="#fbbc04"/><path d="m316 456h96.672a96.64 96.64 0 0 0 96.656-96.672v-260a96.64 96.64 0 0 0 -96.656-96.656 96.64 96.64 0 0 0 -96.672 96.656z" fill="#4285f4"/><path d="m156 456a96.64 96.64 0 0 0 96.672-96.672 96.64 96.64 0 0 0 -96.672-96.656 96.64 96.64 0 0 0 -96.672 96.656 96.64 96.64 0 0 0 96.672 96.672z" fill="#fbbc04"/><path d="m383.52 456h-94.192a96.64 96.64 0 0 1 -96.656-96.672v-126.656a96.64 96.64 0 0 1 96.656-96.672 96.64 96.64 0 0 1 96.672 96.672v220.864a2.464 2.464 0 0 1 -2.464 2.464z" fill="#34a853"/><path d="m386 453.536v-220.864c-.003-43.115-28.558-81.016-70-92.912v316.24h67.52a2.464 2.464 0 0 0 2.48-2.464z" fill="#1967d2"/><path d="m252.672 361.2c.006-39.228-23.701-74.567-60-89.44v89.44c0 27.52 11.52 52.368 30 69.968a96.384 96.384 0 0 0 30-69.968z" fill="#ea4335"/></g></svg>\ No newline at end of filediff --git a/notfair/public/mcp-logos/x-ads-icon.svg b/notfair/public/mcp-logos/x-ads-icon.svgdeleted file mode 100644index 3e889482..00000000--- a/notfair/public/mcp-logos/x-ads-icon.svg+++ /dev/null@@ -1 +0,0 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" aria-hidden="true"><rect width="24" height="24" rx="4" fill="#000000"/><path fill="#FFFFFF" transform="translate(4.8 4.8) scale(0.6)" d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231 5.45-6.231Zm-1.161 17.52h1.833L7.084 4.126H5.117L17.083 19.77Z"/></svg>diff --git a/notfair/public/notfair-mark-dark.svg b/notfair/public/notfair-mark-dark.svgdeleted file mode 100644index fa507ccd..00000000--- a/notfair/public/notfair-mark-dark.svg+++ /dev/null@@ -1,4 +0,0 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="-12 -155.6 178.036 168.6" width="178.036" height="168.6">- <path d="M52.200-143.600L43-46.800L17.200-46.800L8.200-143.600L52.200-143.600ZM46.300-35.200Q52.600-29.200 52.600-20Q52.600-10.800 46.200-4.900Q39.800 1 30.200 1Q20.600 1 14.300-4.900Q8-10.800 8-20Q8-29.200 14.200-35.200Q20.400-41.200 30.200-41.200Q40-41.200 46.300-35.200Z" fill="#4CAF6E" transform="translate(-8 0)"></path>- <path d="M51.800-51.400L51.800 0L14 0L14-143.600L111.800-143.600L111.800-110.800L51.800-110.800L51.800-84.200L102-84.200L102-51.400L51.800-51.400Z" fill="#ECECEE" transform="translate(42.236363636363635 0)"></path>-</svg>\ No newline at end of filediff --git a/notfair/public/notfair-mark.svg b/notfair/public/notfair-mark.svgdeleted file mode 100644index 2b9a42df..00000000--- a/notfair/public/notfair-mark.svg+++ /dev/null@@ -1,4 +0,0 @@-<svg xmlns="http://www.w3.org/2000/svg" viewBox="-12 -155.6 178.036 168.6" width="178.036" height="168.6">- <path d="M52.200-143.600L43-46.800L17.200-46.800L8.200-143.600L52.200-143.600ZM46.300-35.200Q52.600-29.200 52.600-20Q52.600-10.800 46.200-4.900Q39.800 1 30.200 1Q20.600 1 14.300-4.900Q8-10.800 8-20Q8-29.200 14.200-35.200Q20.400-41.200 30.200-41.200Q40-41.200 46.300-35.200Z" fill="#4CAF6E" transform="translate(-8 0)"></path>- <path d="M51.800-51.400L51.800 0L14 0L14-143.600L111.800-143.600L111.800-110.800L51.800-110.800L51.800-84.200L102-84.200L102-51.400L51.800-51.400Z" fill="#1A1917" transform="translate(42.236363636363635 0)"></path>-</svg>\ No newline at end of filediff --git a/notfair/scripts/copy-standalone-assets.mjs b/notfair/scripts/copy-standalone-assets.mjsdeleted file mode 100644index 0f68ba5d..00000000--- a/notfair/scripts/copy-standalone-assets.mjs+++ /dev/null@@ -1,129 +0,0 @@-#!/usr/bin/env node-// Next.js standalone output (`output: "standalone"`) intentionally does NOT-// include `.next/static/` or `public/` so they can be served from a CDN in-// production. We ship as a local-first npm package, so we copy them into the-// standalone tree where `server.js` will serve them automatically.-//-// We also dereference every symlink under .next/standalone/. With pnpm, the-// standalone tree is full of symlinks into .pnpm/<pkg>@<ver>/... and-// .next/node_modules/<pkg>-<hash> aliases that Turbopack emits for externals.-// `npm pack` drops these symlinks, so the published tarball can't resolve-// modules like better-sqlite3. Replacing them with real copies makes the-// tarball self-contained at the cost of some size.--import { existsSync, cpSync, lstatSync, readdirSync, realpathSync, rmSync, renameSync } from "node:fs";-import { execSync } from "node:child_process";-import { basename, dirname, join } from "node:path";-import { fileURLToPath } from "node:url";-import { findPlaywrightDirsMissingBrowsersJson } from "./lib/standalone-integrity.mjs";--const __dirname = dirname(fileURLToPath(import.meta.url));-const ROOT = dirname(__dirname);-const STANDALONE = join(ROOT, ".next", "standalone");--if (!existsSync(STANDALONE)) {- console.error(`No standalone output found at ${STANDALONE}. Did 'next build' run?`);- process.exit(1);-}--const targets = [- { src: join(ROOT, ".next", "static"), dest: join(STANDALONE, ".next", "static") },- { src: join(ROOT, "public"), dest: join(STANDALONE, "public") },-];--for (const { src, dest } of targets) {- if (!existsSync(src)) continue;- cpSync(src, dest, { recursive: true });- console.log(`Copied ${src.replace(ROOT + "/", "")} → ${dest.replace(ROOT + "/", "")}`);-}--// Dereference symlinks in-place so npm pack ships real files. We pipe `tar-// -ch | tar -x` because it follows chained pnpm symlinks correctly during-// archive creation. Earlier approaches (`cp -RL`, `rsync -aL`) silently-// dropped entries whose symlink chain had any dangling link, which produced-// broken standalone bundles missing transitive deps like `@swc/helpers` and-// `@next/env`.-const DEREF = STANDALONE + ".deref-tmp";-rmSync(DEREF, { recursive: true, force: true });-const parent = dirname(STANDALONE);-const standaloneName = basename(STANDALONE);-const derefName = basename(DEREF);-// tar -h dereferences symlinks during archive creation; the second tar-// extracts. Both run inside the parent dir so relative paths stay clean.-// 2>/dev/null on the first tar swallows the warnings about dangling pnpm-// links that we intentionally want to skip.-execSync(- `mkdir -p "${derefName}" && tar -ch -f - -C "${standaloneName}" . 2>/dev/null | tar -x -C "${derefName}"`,- { cwd: parent, stdio: "inherit", shell: "/bin/bash" },-);-rmSync(STANDALONE, { recursive: true, force: true });-renameSync(DEREF, STANDALONE);-console.log(`Dereferenced symlinks under ${STANDALONE.replace(ROOT + "/", "")}`);--// Hoist native-module loaders to a resolvable location. better-sqlite3 is a-// serverExternalPackage, so Next leaves its `require('bindings')` as a runtime-// resolve. pnpm nests `bindings` (and its dep `file-uri-to-path`) under-// node_modules/.pnpm/<pkg>@<ver>/..., where Node's resolver — walking up from-// better-sqlite3's own dir — never looks. Copying them to the top-level-// node_modules/ makes them resolvable from every better-sqlite3 copy (both the-// top-level one and Turbopack's hashed .next/node_modules alias). Without this,-// the published tarball boots straight into `Cannot find module 'bindings'`.-const STANDALONE_NM = join(STANDALONE, "node_modules");-for (const pkg of ["bindings", "file-uri-to-path"]) {- const dest = join(STANDALONE_NM, pkg);- if (existsSync(dest)) continue;- const src = findInPnpm(pkg, STANDALONE_NM) ?? findInPnpm(pkg, join(ROOT, "node_modules"));- if (!src) {- console.warn(`Warning: could not locate '${pkg}' to hoist; standalone may fail to load better-sqlite3.`);- continue;- }- cpSync(src, dest, { recursive: true });- console.log(`Hoisted ${pkg} → ${dest.replace(ROOT + "/", "")}`);-}--// Locate a package's real directory inside a pnpm store-// (<nm>/.pnpm/<pkg>@<ver>/node_modules/<pkg>). Returns the first match or null.-function findInPnpm(pkg, nodeModules) {- const pnpmDir = join(nodeModules, ".pnpm");- if (!existsSync(pnpmDir)) return null;- for (const entry of readdirSync(pnpmDir)) {- if (!entry.startsWith(`${pkg}@`)) continue;- const candidate = join(pnpmDir, entry, "node_modules", pkg);- if (existsSync(candidate)) return candidate;- }- return null;-}--// Sanity check: there should be no symlinks left in standalone after dereferencing.-const remaining = countSymlinks(STANDALONE);-if (remaining > 0) {- console.warn(`Warning: ${remaining} symlinks still present under .next/standalone/`);-}--function countSymlinks(dir) {- let count = 0;- const entries = readdirSync(dir, { withFileTypes: true });- for (const entry of entries) {- const p = join(dir, entry.name);- const st = lstatSync(p);- if (st.isSymbolicLink()) {- count += 1;- } else if (st.isDirectory()) {- count += countSymlinks(p);- }- }- return count;-}--// playwright-core requires its own browsers.json at runtime. next.config.ts-// force-includes it; fail the build if any copy in the tree is still missing-// it, since the workspace browser cannot launch from such a package.-const missingBrowsersJson = findPlaywrightDirsMissingBrowsersJson(STANDALONE);-if (missingBrowsersJson.length > 0) {- console.error(- `playwright-core is missing browsers.json in the standalone tree:\n${missingBrowsersJson- .map((dir) => ` ${dir.replace(ROOT + "/", "")}`)- .join("\n")}\nCheck outputFileTracingIncludes in next.config.ts.`,- );- process.exit(1);-}diff --git a/notfair/scripts/e2e-provision.ts b/notfair/scripts/e2e-provision.tsdeleted file mode 100644index f539e2d2..00000000--- a/notfair/scripts/e2e-provision.ts+++ /dev/null@@ -1,32 +0,0 @@-import { createProject, getProject } from "../src/server/db/projects";-import { createGoal } from "../src/server/db/goals";-import { goalAgentIdFor, provisionGoalAgent } from "../src/server/goals/provision";--/**- * Dev helper: provision a test project with one goal agent so the UI has- * something to render without walking through onboarding. Agent = goal —- * the goal starts in `intake` and gets defined in the agent's chat.- *- * pnpm tsx scripts/e2e-provision.ts- */-async function main() {- const slug = "e2e-test-brand";- if (!getProject(slug)) {- const r = createProject({ display_name: "E2E Test Brand" });- if (!r.ok) throw new Error(r.reason);- console.log("project created:", r.project.slug);- }- const agent_id = goalAgentIdFor(slug, 1);- const goal = createGoal({- project_slug: slug,- agent_id,- statement: "Keep test wasted spend at $0",- });- await provisionGoalAgent({ goal, urlSlug: "goal-1" });- console.log("goal agent provisioned:", agent_id, "goal:", goal.id);-}--main().catch((err) => {- console.error(err);- process.exit(1);-});diff --git a/notfair/scripts/force-refresh-mcp-tokens.ts b/notfair/scripts/force-refresh-mcp-tokens.tsdeleted file mode 100644index 28db4b19..00000000--- a/notfair/scripts/force-refresh-mcp-tokens.ts+++ /dev/null@@ -1,115 +0,0 @@-/**- * One-off: force the MCP refresh path against live tokens.- *- * For each (project_slug, server_name) pair on argv (or a default set), this- * loads the stored row, calls refreshMcpToken(), and prints a short summary- * showing whether the access token actually rotated and whether the refresh- * token rotated alongside it.- *- * Usage:- * pnpm tsx scripts/force-refresh-mcp-tokens.ts- * pnpm tsx scripts/force-refresh-mcp-tokens.ts demo1 stripe demo1 supabase- */-import { findMcpToken } from "../src/server/mcp/tokens";-import { refreshMcpToken, isExpiringSoon } from "../src/server/mcp/refresh";--const DEFAULT_TARGETS: Array<[string, string]> = [- ["demo1", "supabase"],- ["demo1", "mixpanel"],- ["demo1", "stripe"],- ["demo1", "posthog"],- ["demo1", "notfair-googleads"],- ["demo1", "notfair-meta-ads"],-];--function tailMask(s: string | null, head = 6, tail = 4): string {- if (!s) return "<null>";- if (s.length <= head + tail + 1) return `${s.slice(0, head)}…`;- return `${s.slice(0, head)}…${s.slice(-tail)} (len=${s.length})`;-}--function ms(value: string | null): string {- if (!value) return "<null>";- const t = Date.parse(value);- if (Number.isNaN(t)) return value;- const deltaMs = t - Date.now();- const mins = Math.round(deltaMs / 60_000);- return `${value} (${deltaMs >= 0 ? "+" : ""}${mins}m)`;-}--async function refreshOne(project_slug: string, server_name: string): Promise<void> {- console.log(`\n── ${project_slug}/${server_name} ────────────────────`);- const before = findMcpToken(project_slug, server_name);- if (!before) {- console.log(" no row stored — skip");- return;- }-- console.log(" before:");- console.log(` access_token = ${tailMask(before.access_token_enc)}`);- console.log(` refresh_token = ${tailMask(before.refresh_token_enc)}`);- console.log(` expires_at = ${ms(before.expires_at)}`);- console.log(` token_endpoint= ${before.token_endpoint ?? "<null>"}`);- console.log(` client_id = ${before.client_id ?? "<null>"}`);- console.log(` has client_secret = ${before.client_secret ? "yes" : "no"}`);- console.log(` is expiring soon (default 60s) = ${isExpiringSoon(before)}`);-- if (!before.refresh_token_enc || !before.token_endpoint || !before.client_id) {- console.log(- " ⇒ refresh path will short-circuit (missing refresh_token/token_endpoint/client_id)",- );- }-- const refreshed = await refreshMcpToken(before);-- if (!refreshed) {- console.log(" ❌ refreshMcpToken returned null");- return;- }-- const accessRotated = refreshed.access_token_enc !== before.access_token_enc;- const refreshRotated =- refreshed.refresh_token_enc !== before.refresh_token_enc;-- console.log(" after:");- console.log(- ` access_token = ${tailMask(refreshed.access_token_enc)} ${- accessRotated ? "✅ ROTATED" : "(same)"- }`,- );- console.log(- ` refresh_token = ${tailMask(refreshed.refresh_token_enc)} ${- refreshRotated ? "🔁 ROTATED" : "(same)"- }`,- );- console.log(` expires_at = ${ms(refreshed.expires_at)}`);- console.log(` ✅ refresh succeeded`);-}--async function main(): Promise<void> {- const argv = process.argv.slice(2);- const targets: Array<[string, string]> = [];- if (argv.length === 0) {- targets.push(...DEFAULT_TARGETS);- } else if (argv.length % 2 !== 0) {- console.error("Args must come in (project_slug, server_name) pairs");- process.exit(2);- } else {- for (let i = 0; i < argv.length; i += 2) {- targets.push([argv[i]!, argv[i + 1]!]);- }- }-- for (const [slug, name] of targets) {- try {- await refreshOne(slug, name);- } catch (err) {- console.error(` ❌ threw: ${err instanceof Error ? err.message : String(err)}`);- }- }-}--main().catch((err) => {- console.error(err);- process.exit(1);-});diff --git a/notfair/scripts/lib/standalone-integrity.mjs b/notfair/scripts/lib/standalone-integrity.mjsdeleted file mode 100644index 1b00f4df..00000000--- a/notfair/scripts/lib/standalone-integrity.mjs+++ /dev/null@@ -1,38 +0,0 @@-// Runtime files that Next.js output file tracing cannot see (they are read via-// require()/fs at runtime, not imported), but that the standalone tarball-// needs. Checked after scripts/copy-standalone-assets.mjs builds the tree so a-// broken package fails the build instead of failing on a user's machine.--import { existsSync, readdirSync } from "node:fs";-import { join } from "node:path";--/**- * Return every playwright-core package directory under `standaloneRoot`- * (including pnpm store copies and Turbopack's hashed `.next/node_modules`- * aliases) that is missing `browsers.json`.- */-export function findPlaywrightDirsMissingBrowsersJson(standaloneRoot) {- const missing = [];- const walk = (dir, depth) => {- if (depth > 8 || !existsSync(dir)) return;- let entries;- try {- entries = readdirSync(dir, { withFileTypes: true });- } catch {- return;- }- for (const entry of entries) {- if (!entry.isDirectory()) continue;- const full = join(dir, entry.name);- if (entry.name === "playwright-core" || entry.name.startsWith("playwright-core-")) {- if (existsSync(join(full, "package.json")) && !existsSync(join(full, "browsers.json"))) {- missing.push(full);- }- continue;- }- walk(full, depth + 1);- }- };- walk(standaloneRoot, 0);- return missing;-}diff --git a/notfair/src/app/(app)/[project]/connections/page.tsx b/notfair/src/app/(app)/[project]/connections/page.tsxdeleted file mode 100644index fc6bf081..00000000--- a/notfair/src/app/(app)/[project]/connections/page.tsx+++ /dev/null@@ -1,140 +0,0 @@-import { notFound } from "next/navigation";-import { getProject } from "@/server/db/projects";-import { getMcpCatalog } from "@/server/mcp-catalog";-import { getMcpStatus } from "@/server/mcp/state";-import { summarizeBuiltinTools } from "@/server/mcp-server/tool-summaries";-import { McpCard } from "@/components/mcp-card";-import { BuiltinMcpCard } from "@/components/builtin-mcp-card";-import { McpFlashBanner } from "@/components/mcp-flash-banner";-import { AddMcpServerMenu } from "@/components/add-mcp-server-card";-import { normalizeResourceUrl } from "@/server/mcp/discovery-url";-import { projectHref } from "@/lib/project-href";-import { accountPickerFor } from "@/lib/mcp-account-pickers";-import { prefetchAccountChoice } from "@/server/mcp/account-selection";--type Search = {- mcp_connected?: string;- mcp_error?: string;- mcp_analyzing?: string;- /** Catalog key of the MCP that just finished OAuth — drives the- * post-connect account/property picker on the matching card. */- mcp_key?: string;-};--export default async function ConnectionsPage({- searchParams,- params,-}: {- searchParams: Promise<Search>;- params: Promise<{ project: string }>;-}) {- const { project: slug } = await params;- const project = getProject(slug);- const { mcp_connected, mcp_error, mcp_analyzing, mcp_key } =- await searchParams;- if (!project || project.archived_at) notFound();-- const catalog = getMcpCatalog(project.slug);- const statuses = await Promise.all(- catalog.map((s) => getMcpStatus(project.slug, s.key)),- );-- // Post-OAuth account/property picker: when the callback flagged a- // multi-account MCP (`?mcp_key=`), prefetch its list here on the server- // and hand it to the card, which auto-opens the picker dialog with it.- const pendingChoice = mcp_key- ? await prefetchAccountChoice(project, mcp_key)- : null;- const autoOpenPickerKey = pendingChoice ? mcp_key : null;-- const builtinTools = summarizeBuiltinTools();- const connectedCount = statuses.filter((s) => s.state === "connected").length;- const connectedSpecs = catalog.filter(- (_, i) => statuses[i].state === "connected",- );- const connectedKeys = connectedSpecs.map((s) => s.key);- const connectedResourceUrls = connectedSpecs.map((s) =>- normalizeResourceUrl(s.resource_url),- );-- return (- <div className="ns-app-narrow">- <header className="ns-page-head">- <div className="ns-page-head-stack">- <h1 className="ns-page-title">Connections</h1>- <p className="ns-page-sub">- MCP servers are the tools your agents call. Browse the curated list- or paste any <b>OAuth 2.0</b> URL.- </p>- </div>- <div className="ns-page-actions">- <AddMcpServerMenu- connectedKeys={connectedKeys}- connectedResourceUrls={connectedResourceUrls}- />- </div>- </header>-- <McpFlashBanner- connected={mcp_connected}- error={mcp_error}- analyzing={mcp_analyzing === "1"}- goalsHref={projectHref(project.slug, "")}- />-- <section>- <h2 className="ns-h2">- <span>Built-in</span>- <span className="ns-h2-meta">Ships with NotFair</span>- </h2>- <div className="ns-group">- <BuiltinMcpCard- name="Goals"- description="Built-in tools each goal agent runs its loop with: read the goal, verify metrics, log actions and learnings, and keep the shared context current."- tools={builtinTools}- />- </div>- </section>-- <section>- <h2 className="ns-h2">- <span>Servers</span>- <span className="ns-h2-meta">- {catalog.length === 0- ? "None yet"- : `${connectedCount} of ${catalog.length} connected`}- </span>- </h2>- {catalog.length === 0 ? (- <div className="ns-empty">- <p className="ns-empty-title">No MCP servers yet.</p>- <p className="ns-empty-sub">- Use <span className="font-medium text-foreground">Add server</span>{" "}- above to browse trusted connectors or paste a URL.- </p>- </div>- ) : (- <ol className="ns-group">- {catalog.map((spec, i) => (- <li key={spec.key}>- <McpCard- spec={spec}- status={statuses[i]}- projectSlug={project.slug}- selectedAccountId={- accountPickerFor(spec.key)?.selectedId(project) ?? null- }- pickerPrefetch={- spec.key === autoOpenPickerKey- ? (pendingChoice?.prefetch ?? null)- : null- }- />- </li>- ))}- </ol>- )}- </section>- </div>- );-}diff --git a/notfair/src/app/(app)/[project]/context/page.tsx b/notfair/src/app/(app)/[project]/context/page.tsxdeleted file mode 100644index 4ac4f742..00000000--- a/notfair/src/app/(app)/[project]/context/page.tsx+++ /dev/null@@ -1,49 +0,0 @@-import { notFound } from "next/navigation";-import { getProject } from "@/server/db/projects";-import { readProjectBrief, projectBriefPath } from "@/server/onboarding/project-brief";-import { listProjectAgents } from "@/server/agent-meta";-import { SharedContextEditor } from "@/components/shared-context-editor";--export const dynamic = "force-dynamic";--/**- * The shared workspace context (PROJECT.md): one brief every goal agent- * inherits. Agents keep it current via `set_shared_context`; this page is- * the user's direct line to the same document.- */-export default async function SharedContextPage({- params,-}: {- params: Promise<{ project: string }>;-}) {- const { project: slug } = await params;- const project = getProject(slug);- if (!project || project.archived_at) notFound();-- const brief = await readProjectBrief(slug);- const agents = await listProjectAgents(slug);-- return (- <div className="ns-app-narrow">- <header className="ns-page-head">- <div className="ns-page-head-stack">- <h1 className="ns-page-title">Shared context</h1>- <p className="ns-page-sub">- What every goal agent knows about {project.display_name} — who you- are, what you sell, what matters. Shared with{" "}- {agents.length === 0- ? "every future goal agent"- : `all ${agents.length} goal agent${agents.length === 1 ? "" : "s"}`}- ; agents update it too when they learn something workspace-wide.- </p>- </div>- </header>-- <SharedContextEditor projectSlug={slug} initialContent={brief ?? ""} />-- <p className="mt-4 text-[11.5px] text-[hsl(var(--notfair-ink-4))]">- Stored at <span className="font-mono">{projectBriefPath(slug)}</span>- </p>- </div>- );-}diff --git a/notfair/src/app/(app)/[project]/goals/[agent]/checks/[thread]/page.test.tsx b/notfair/src/app/(app)/[project]/goals/[agent]/checks/[thread]/page.test.tsxdeleted file mode 100644index 2b23d54a..00000000--- a/notfair/src/app/(app)/[project]/goals/[agent]/checks/[thread]/page.test.tsx+++ /dev/null@@ -1,96 +0,0 @@-// @vitest-environment jsdom-import { render, screen } from "@testing-library/react";-import { beforeEach, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- getProject: vi.fn(),- resolveAgentBySlug: vi.fn(),- getGoalForAgent: vi.fn(),- getLatestGoalForAgent: vi.fn(),- listGoalLearnings: vi.fn(),- readTranscriptTail: vi.fn(),- getMcpCatalog: vi.fn(),- listModels: vi.fn(),-}));--vi.mock("next/link", () => ({- default: ({ children, href }: { children: React.ReactNode; href: string }) => (- <a href={href}>{children}</a>- ),-}));-vi.mock("next/navigation", () => ({- notFound: vi.fn(() => {- throw new Error("not found");- }),-}));-vi.mock("@/server/db/projects", () => ({ getProject: mocks.getProject }));-vi.mock("@/server/agent-meta", () => ({ resolveAgentBySlug: mocks.resolveAgentBySlug }));-vi.mock("@/server/db/goals", () => ({- getGoalForAgent: mocks.getGoalForAgent,- getLatestGoalForAgent: mocks.getLatestGoalForAgent,- listGoalLearnings: mocks.listGoalLearnings,-}));-vi.mock("@/server/sessions/transcript-tail", () => ({ readTranscriptTail: mocks.readTranscriptTail }));-vi.mock("@/server/mcp-catalog", () => ({ getMcpCatalog: mocks.getMcpCatalog }));-vi.mock("@/server/adapters/registry", () => ({- DEFAULT_HARNESS_ADAPTER: "codex-local",- requireAdapter: () => ({ listModels: mocks.listModels }),-}));-vi.mock("@/lib/project-href", () => ({ projectHref: (_slug: string, path: string) => path }));-vi.mock("@/lib/goal-label", () => ({ goalLabel: () => "Goal label" }));-vi.mock("@/components/goal-context-dialog", () => ({ GoalContextDialog: () => null }));-vi.mock("@/components/goal-memory-dialog", () => ({ GoalMemoryDialog: () => null }));-vi.mock("@/components/live-transcript", () => ({- LiveTranscript: (props: Record<string, unknown>) => (- <div- data-testid="transcript"- data-thread={String(props.threadId)}- data-completed={String(props.showCompletedStatus)}- data-models={String((props.modelOptions as unknown[]).length)}- >- <textarea- aria-label="Tick chat composer"- disabled={Boolean(props.composerDisabled)}- placeholder={- typeof props.disabledComposerPlaceholder === "string"- ? props.disabledComposerPlaceholder- : "Message this goal's agent…"- }- />- </div>- ),-}));--import CheckTranscriptPage from "./page";--beforeEach(() => {- vi.clearAllMocks();- mocks.getProject.mockReturnValue({ archived_at: null, harness_adapter: "codex-local" });- mocks.resolveAgentBySlug.mockResolvedValue({ agent_id: "agent-1", name: "Agent" });- mocks.getGoalForAgent.mockReturnValue({ id: "goal-1" });- mocks.getLatestGoalForAgent.mockReturnValue(null);- mocks.listGoalLearnings.mockReturnValue([]);- mocks.readTranscriptTail.mockReturnValue({ events: [], cursor: 17 });- mocks.getMcpCatalog.mockReturnValue([]);- mocks.listModels.mockResolvedValue([- { value: "fast", label: "Fast", is_default: true },- { value: "deep", label: "Deep" },- ]);-});--// Regression: ISSUE-001 — completed tick transcripts disabled follow-up chat-// Found by /qa on 2026-07-21-// Report: .gstack/qa-reports/qa-report-localhost-2026-07-21.md-it("keeps a completed tick conversation chat-enabled with model selection", async () => {- const page = await CheckTranscriptPage({- params: Promise.resolve({ project: "acme", agent: "goal-1", thread: "tick-11" }),- });- render(page);-- expect(screen.getByRole("heading", { name: "Goal label — check chat" })).toBeInTheDocument();- expect(screen.getByRole("textbox", { name: "Tick chat composer" })).toBeEnabled();- expect(screen.getByPlaceholderText("Message this goal's agent…")).toBeInTheDocument();- expect(screen.getByTestId("transcript")).toHaveAttribute("data-thread", "tick-11");- expect(screen.getByTestId("transcript")).toHaveAttribute("data-completed", "true");- expect(screen.getByTestId("transcript")).toHaveAttribute("data-models", "2");-});diff --git a/notfair/src/app/(app)/[project]/goals/[agent]/checks/[thread]/page.tsx b/notfair/src/app/(app)/[project]/goals/[agent]/checks/[thread]/page.tsxdeleted file mode 100644index d68ba8d2..00000000--- a/notfair/src/app/(app)/[project]/goals/[agent]/checks/[thread]/page.tsx+++ /dev/null@@ -1,110 +0,0 @@-import Link from "next/link";-import { notFound } from "next/navigation";-import { ArrowLeft } from "lucide-react";-import { getProject } from "@/server/db/projects";-import { resolveAgentBySlug } from "@/server/agent-meta";-import {- getGoalForAgent,- getLatestGoalForAgent,- listGoalLearnings,-} from "@/server/db/goals";-import { readTranscriptTail } from "@/server/sessions/transcript-tail";-import { getMcpCatalog } from "@/server/mcp-catalog";-import { DEFAULT_HARNESS_ADAPTER, requireAdapter } from "@/server/adapters/registry";-import { projectHref } from "@/lib/project-href";-import { goalLabel } from "@/lib/goal-label";-import { LiveTranscript } from "@/components/live-transcript";-import { GoalContextDialog } from "@/components/goal-context-dialog";-import { GoalMemoryDialog } from "@/components/goal-memory-dialog";--export const dynamic = "force-dynamic";--/**- * Conversation for one loop check (tick). Reached from the goal screen's- * Checks list; follow-up turns resume the same harness session so the agent- * keeps the check's exact context, tools, and transcript.- */-export default async function CheckTranscriptPage({- params,-}: {- params: Promise<{ agent: string; thread: string; project: string }>;-}) {- const { agent: agentSlug, thread: threadId, project: slug } = await params;- const project = getProject(slug);- if (!project || project.archived_at) notFound();- const resolved = await resolveAgentBySlug(slug, agentSlug);- if (!resolved) notFound();- const goal =- getGoalForAgent(resolved.agent_id) ?? getLatestGoalForAgent(resolved.agent_id);-- const { events: initialEvents, cursor: initialCursor } = readTranscriptTail(- slug,- resolved.agent_id,- threadId,- 0,- );- const mcpCatalog = getMcpCatalog(slug).map((m) => ({- key: m.key,- display_name: m.display_name,- resource_url: m.resource_url,- }));- const modelOptions = await requireAdapter(- project.harness_adapter ?? DEFAULT_HARNESS_ADAPTER,- ).listModels();- // A check runs as the same agent as the goal chat: identical identity,- // tools, and learnings ledger — only the conversation is the tick's own.- const learnings = goal ? listGoalLearnings(goal.id, 100) : [];-- return (- <div className="flex min-h-0 flex-1 flex-col">- <header className="flex items-center gap-3 px-5 py-2.5">- <Link- href={projectHref(slug, `/goals/${agentSlug}`)}- className="ns-btn ns-btn-outline ns-btn-sm shrink-0"- >- <ArrowLeft className="size-3.5" />- Back to goal- </Link>- <h1 className="m-0 min-w-0 truncate text-[14px] font-semibold">- {goal ? goalLabel(goal) : resolved.name} — check chat- </h1>- <div className="ml-auto flex shrink-0 items-center gap-2">- <GoalContextDialog- projectSlug={slug}- agentSlug={agentSlug}- agentId={resolved.agent_id}- threadId={threadId}- models={modelOptions.map((m) => ({- value: m.value,- label: m.label,- context_window: m.context_window,- is_default: m.is_default,- }))}- />- <GoalMemoryDialog- entries={learnings.map((l) => ({- id: l.id,- body: l.body,- confidence: l.confidence,- created_at: l.created_at,- }))}- />- </div>- </header>- <div className="min-h-0 flex-1">- <LiveTranscript- key={threadId}- projectSlug={slug}- agentSlug={agentSlug}- agentDisplayName={goal ? goalLabel(goal) : resolved.name}- threadId={threadId}- initialEvents={initialEvents}- initialCursor={initialCursor}- showCompletedStatus- mcpCatalog={mcpCatalog}- modelOptions={modelOptions}- />- </div>- </div>- );-}diff --git a/notfair/src/app/(app)/[project]/goals/[agent]/layout.tsx b/notfair/src/app/(app)/[project]/goals/[agent]/layout.tsxdeleted file mode 100644index d8c55a6d..00000000--- a/notfair/src/app/(app)/[project]/goals/[agent]/layout.tsx+++ /dev/null@@ -1,22 +0,0 @@-import { notFound } from "next/navigation";-import { getProject } from "@/server/db/projects";-import { resolveAgentBySlug } from "@/server/agent-meta";--type Params = { agent: string; project: string };--export default async function GoalLayout({- children,- params,-}: {- children: React.ReactNode;- params: Promise<Params>;-}) {- const { agent: agentSlug, project: projectSlug } = await params;- const project = getProject(projectSlug);- if (!project || project.archived_at) notFound();- const resolved = await resolveAgentBySlug(project.slug, agentSlug);- if (!resolved) notFound();-- // One screen per goal — no tabs. Children own the full viewport region.- return <div className="absolute inset-0 flex flex-col">{children}</div>;-}diff --git a/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx b/notfair/src/app/(app)/[project]/goals/[agent]/page.tsxdeleted file mode 100644index cff3e0f6..00000000--- a/notfair/src/app/(app)/[project]/goals/[agent]/page.tsx+++ /dev/null@@ -1,592 +0,0 @@-import Link from "next/link";-import { notFound } from "next/navigation";-import { Sparkles } from "lucide-react";-import { getProject } from "@/server/db/projects";-import { resolveAgentBySlug } from "@/server/agent-meta";-import {- getGoalForAgent,- getLatestGoalForAgent,- isGoalArchived,- listGoalActions,- listOpenGoalActions,- listUserActionRequests,- loggedSpendTotal,- listGoalLearnings,- listGoalTicks,- listMetricSnapshots,- isTargetMet,- USER_ACTION_PREFIX,- type Goal,-} from "@/server/db/goals";-import { GoalNeedsYouDialog, type NeedsYouItem } from "@/components/goal-needs-you";-import { listCheckRows } from "@/server/goals/checks";-import {- listSessionsForAgent,- pickLatestChatSession,-} from "@/server/sessions/view";-import { readTranscriptTail } from "@/server/sessions/transcript-tail";-import { getMcpCatalog } from "@/server/mcp-catalog";-import { DEFAULT_HARNESS_ADAPTER, requireAdapter } from "@/server/adapters/registry";-import { projectHref } from "@/lib/project-href";-import { goalLabel } from "@/lib/goal-label";-import { formatMetric } from "@/lib/format-metric";-import { GoalMemoryDialog } from "@/components/goal-memory-dialog";-import { Markdown } from "@/components/markdown";-import { GoalContextDialog } from "@/components/goal-context-dialog";-import { cadenceLabel } from "@/lib/goal-cadence";-import { cn } from "@/lib/utils";-import { LiveTranscript } from "@/components/live-transcript";-import { GoalControls } from "@/components/goal-controls";-import { GoalAutoRefresh } from "@/components/goal-auto-refresh";-import { GoalProgressChart } from "@/components/goal-progress-chart";-import { GoalMetricCard, type MetricVariant } from "@/components/goal-metric-card";-import { GoalChecksStrip } from "@/components/goal-checks-strip";-import { GoalChecksList } from "@/components/goal-checks-list";-import { RailSection } from "@/components/rail-section";-import { listGoalPrs } from "@/server/db/goal-prs";-import {- listSupportMetrics,- listSupportMetricSnapshots,- type GoalSupportMetric,-} from "@/server/db/goal-support-metrics";-import { MetricMethodDialog } from "@/components/metric-method-dialog";-import { timeUntil } from "@/lib/time-ago";-import { GoalMovesDialog } from "@/components/goal-moves-dialog";-import { type MoveRow } from "@/components/goal-moves";-import { GoalPrsDialog, type PrRow } from "@/components/goal-prs-dialog";-import { maybeSyncGoalPrs } from "@/server/goals/pr-sync";-import { buildCheckSquares, currentStreak } from "@/lib/goal-streak";-import { GoalCompletionDialog } from "@/components/goal-completion-dialog";--export const dynamic = "force-dynamic";--function fmtDate(iso: string | null): string {- return iso ? iso.slice(0, 10) : "—";-}--/** Local wall-clock for a timestamp: "7:00 PM" today, "Jul 25, 9:00 AM" beyond. */-function fmtClock(iso: string): string {- const date = new Date(iso);- const withinDay = Math.abs(date.getTime() - Date.now()) < 86_400_000;- return date.toLocaleString(- [],- withinDay- ? { hour: "numeric", minute: "2-digit" }- : { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" },- );-}----const STATUS_CHIP: Record<Goal["status"], string> = {- intake: "setting up",- proposed: "confirm the plan",- active: "running",- paused: "paused",- achieved: "achieved",- failed: "failed",- killed: "closed",-};--/**- * THE goal screen — everything about one goal on a single page. Chat is- * the primary surface (goals are defined and steered in conversation);- * the right rail is the loop dashboard: metric hero, supporting metrics- * on the same chart grammar, check diary. No tabs, no thread management —- * one goal, one conversation, one screen.- */-export default async function GoalPage({- params,-}: {- params: Promise<{ agent: string; project: string }>;-}) {- const { agent: agentSlug, project: slug } = await params;- const project = getProject(slug);- if (!project || project.archived_at) notFound();- const resolved = await resolveAgentBySlug(slug, agentSlug);- if (!resolved) notFound();-- const goal =- getGoalForAgent(resolved.agent_id) ?? getLatestGoalForAgent(resolved.agent_id);- if (!goal) notFound();-- // One conversation per goal: the newest chat-origin session (the intake- // kickoff creates it), or "main" for a fresh fallback.- const sessions = listSessionsForAgent(slug, resolved.agent_id);- const threadId = pickLatestChatSession(sessions)?.sessionId ?? "main";- const existing = sessions.find((s) => s.sessionId === threadId);- const { events: initialEvents, cursor: initialCursor } = readTranscriptTail(- slug,- resolved.agent_id,- threadId,- 0,- );- const modelOptions = await requireAdapter(- project.harness_adapter ?? DEFAULT_HARNESS_ADAPTER,- ).listModels();- const mcpCatalog = getMcpCatalog(slug).map((m) => ({- key: m.key,- display_name: m.display_name,- resource_url: m.resource_url,- }));-- const live = goal.status === "intake" || goal.status === "proposed" || goal.status === "active" || goal.status === "paused";- const achievementArchived =- goal.status === "achieved" ? isGoalArchived(goal.id) : false;- const learnings = listGoalLearnings(goal.id, 100);-- // Header dialogs: the moves journal (every open action, whatever its- // stage) and open PRs. Kick a background GitHub sync when PR rows look- // stale — the page's auto-refresh poll picks up the fresh state.- const moveRows: MoveRow[] = listOpenGoalActions(goal.id).map((a) => ({- action_id: a.id,- kind: a.kind,- description: a.description,- resources: JSON.parse(a.resources_touched_json || "[]") as string[],- made_at: a.created_at,- observe_until: a.review_after,- }));- // Open escalations only the user can resolve — the amber header button.- const needsYou: NeedsYouItem[] = listUserActionRequests(goal.id).map((a) => ({- action_id: a.id,- ask: a.description- .slice(USER_ACTION_PREFIX.length)- .replace(/^[\s:—–-]+/, ""),- tick_number: a.tick_number,- raised_at: a.created_at,- }));- const openPrs = listGoalPrs(goal.id, 100).filter((pr) => pr.state === "open");- if (openPrs.length > 0) maybeSyncGoalPrs(goal.id);- const prRows: PrRow[] = openPrs.map((pr) => ({- id: pr.id,- url: pr.url,- title: pr.title,- state: pr.state,- review_decision: pr.review_decision,- comment_count: pr.comment_count,- is_draft: Boolean(pr.is_draft),- branch: pr.branch,- created_at: pr.created_at,- sync_error: pr.sync_error,- }));-- return (- <div className="flex min-h-0 flex-1 flex-col">- {/* Every pre-terminal state changes server-side via agent tool- calls: intake verifies the metric (→ proposed), and the user's- confirmation in chat lands via propose_target (→ active, first- check running). Without polling, the rail keeps showing the- previous stage until a manual reload. */}- {(goal.status === "intake" ||- goal.status === "proposed" ||- goal.status === "active") && <GoalAutoRefresh intervalMs={8000} />}-- {/* Header: the goal is the title. */}- <header className="flex min-w-0 flex-wrap items-center gap-2 py-2.5 pr-3 pl-16 sm:pr-5 md:pl-5 lg:flex-nowrap lg:gap-3">- <span className="ns-tag-mono shrink-0">{STATUS_CHIP[goal.status]}</span>- <h1 className="m-0 min-w-0 flex-1 truncate text-[14px] font-semibold">- {goalLabel(goal)}- </h1>- <div className="order-last flex w-full shrink-0 items-center justify-end gap-2 lg:order-none lg:ml-auto lg:w-auto">- {/* Escalations stay visible at every width — they're the one- header item that is the user's job, not the agent's. */}- <GoalNeedsYouDialog- items={needsYou}- projectSlug={slug}- agentSlug={agentSlug}- />- <div className="hidden lg:contents">- <GoalContextDialog- projectSlug={slug}- agentSlug={agentSlug}- agentId={resolved.agent_id}- threadId={threadId}- models={modelOptions.map((m) => ({- value: m.value,- label: m.label,- context_window: m.context_window,- is_default: m.is_default,- }))}- />- <GoalMemoryDialog- entries={learnings.map((l) => ({- id: l.id,- body: l.body,- confidence: l.confidence,- created_at: l.created_at,- }))}- />- <GoalMovesDialog moves={moveRows} nextCheckAt={goal.next_tick_at} />- <GoalPrsDialog prs={prRows} />- </div>- {live && (- <GoalControls- goalId={goal.id}- status={goal.status as "intake" | "proposed" | "active" | "paused"}- />- )}- {goal.status === "achieved" && !achievementArchived && (- <GoalCompletionDialog- goalId={goal.id}- label={goalLabel(goal)}- metricName={goal.metric_name}- currentValue={goal.current_value}- targetValue={goal.target_value}- metricDirection={goal.metric_direction}- completionReason={goal.status_reason}- completedAt={goal.updated_at}- trigger={- <button- type="button"- className="ns-chip ns-completed-badge bg-[hsl(var(--notfair-accent-soft))] font-medium text-[hsl(var(--notfair-accent))] shadow-[inset_0_0_0_1px_hsl(var(--notfair-accent-border))] hover:text-[hsl(var(--notfair-accent))]"- aria-label="Celebrate this completed goal"- >- <Sparkles aria-hidden />- Celebrate- </button>- }- />- )}- </div>- </header>-- <div className="flex min-h-0 min-w-0 flex-1 overflow-hidden">- {/* Chat — the primary surface. */}- <section className="flex min-w-0 flex-1 flex-col">- <LiveTranscript- key={threadId}- projectSlug={slug}- agentSlug={agentSlug}- agentDisplayName={goalLabel(goal)}- threadId={threadId}- initialEvents={initialEvents}- initialCursor={initialCursor}- mcpCatalog={mcpCatalog}- modelOptions={modelOptions}- />- </section>-- {/* The loop dashboard rail — metric hero, supporting metrics on the- same chart grammar, check diary. Wide enough for real charts. */}- <aside className="hidden w-[440px] shrink-0 overflow-y-auto bg-[hsl(var(--notfair-surface-2)/0.4)] px-4 py-4 xl:block">- <div className="flex flex-col gap-5">- <GoalDashboard slug={slug} agentSlug={agentSlug} goal={goal} />- </div>- </aside>- </div>- </div>- );-}--function GoalDashboard({- slug,- agentSlug,- goal,-}: {- slug: string;- agentSlug: string;- goal: Goal;-}) {- const snapshots = listMetricSnapshots(goal.id, 400);- const ticks = listGoalTicks(goal.id, 60);- const allActions = listGoalActions(goal.id, 100);- const targetMet = isTargetMet(goal);- const tickRunning = ticks.some((t) => t.status === "running");- const supportMetrics = listSupportMetrics(goal.id);- // First diary page for the lazy checks list; older pages stream in on- // scroll via loadMoreGoalChecksAction.- const { rows: checkRows, hasMore: checksHaveMore } = listCheckRows(goal.id);-- // Chart data — plain-JSON props for the client component.- const chartPoints = snapshots.map((sn) => ({- t: Date.parse(sn.created_at),- v: sn.value,- source: sn.source,- }));- const chartActions = allActions- .filter((a) => a.kind === "mutation")- .map((a) => ({- t: Date.parse(a.created_at),- kind: a.kind,- label: a.description,- expected: a.expected_effect,- observed: a.observed_outcome,- reviewUntil:- a.status === "open" && a.review_after ? Date.parse(a.review_after) : null,- }));- const chartFailures = ticks- .filter((t) => t.metric_error || t.status === "failed")- .map((t) => ({- t: Date.parse(t.started_at),- error: t.metric_error ?? t.summary ?? "check failed",- }));- const mutationTicks = new Set(- allActions.filter((a) => a.kind === "mutation").map((a) => a.tick_number),- );- // One metric, several windows: supporting metrics whose base name matches- // the goal metric fold into the hero card's window switcher; anything- // else remains a genuine supporting metric below.- const baseName = (name: string | null) =>- (name ?? "").replace(/\s*\([^)]*\)\s*$/, "").trim();- const windowLabel = (name: string | null) => {- const paren = /\(([^)]*)\)\s*$/.exec(name ?? "")?.[1] ?? "";- return paren.split(/[\s,]+/).filter(Boolean).pop() ?? "now";- };- const supportRows = supportMetrics.map((metric) => ({- metric,- points: listSupportMetricSnapshots(metric.id, 400).map((sn) => ({- t: Date.parse(sn.created_at),- v: sn.value,- source: sn.source,- })),- }));- const isWindowVariant = ({ metric }: (typeof supportRows)[number]) =>- baseName(metric.name) === baseName(goal.metric_name);- const extraSupports = supportRows.filter((row) => !isWindowVariant(row));- const metricVariants: MetricVariant[] = [- {- key: "goal",- label: windowLabel(goal.metric_name),- name: goal.metric_name ?? "Metric",- current: goal.current_value,- baseline: goal.baseline_value,- target: goal.target_value,- direction: goal.metric_direction,- sourceKey: goal.metric_source_key,- sourceTool: goal.metric_source_tool,- argsJson: goal.metric_source_args_json,- points: chartPoints,- },- ...supportRows.filter(isWindowVariant).map(({ metric, points }) => ({- key: metric.id,- label: windowLabel(metric.name),- name: metric.name,- current: metric.current_value,- baseline: metric.baseline_value,- target: null,- direction: metric.direction,- sourceKey: metric.source_key,- sourceTool: metric.source_tool,- argsJson: metric.source_args_json,- points,- })),- ];-- const squares = buildCheckSquares(- ticks- .filter((t) => t.status !== "running" && t.trigger_kind !== "intake")- .map((t) => ({- tick_number: t.tick_number,- started_at: t.started_at,- metric_value: t.metric_value,- status: t.status,- acted: mutationTicks.has(t.tick_number),- })),- goal.target_value,- goal.metric_direction,- );- const streak = currentStreak(squares);-- return (- <>- <RailSection title="Goal">- <p className="m-0 text-[12.5px] leading-relaxed text-[hsl(var(--notfair-ink-3))]">- “{goal.statement}”- </p>- </RailSection>-- {/* Lifecycle-specific card */}- {goal.status === "intake" && (- <RailSection title="Main metric">- <RailCard>- <p className="m-0 text-[12.5px] leading-relaxed">- The agent is working out how to <b>measure</b> this — watch the- chat. It will verify a metric, show you the baseline, and propose- a plan. Nothing touches your account yet.- </p>- </RailCard>- </RailSection>- )}-- {goal.status === "proposed" && (- <RailSection title="Main metric">- <RailCard>- <p className="m-0 text-[12.5px] leading-relaxed">- Baseline <b className="tabular-nums">{formatMetric(goal.baseline_value)}</b>,- verified against{" "}- <span className="font-mono text-[11px]">{goal.metric_source_key}</span>{" "}- <MetricMethodDialog- name={goal.metric_name ?? "Metric"}- sourceKey={goal.metric_source_key}- sourceTool={goal.metric_source_tool}- argsJson={goal.metric_source_args_json}- direction={goal.metric_direction}- />- . Agree the target in chat — the moment you confirm, the loop- starts and the first check runs.- </p>- </RailCard>- </RailSection>- )}-- {(goal.status === "active" ||- goal.status === "paused" ||- goal.status === "achieved" ||- goal.status === "failed" ||- goal.status === "killed") && (- <>- <RailSection title="Main metric">- <GoalMetricCard- variants={metricVariants}- mode={goal.mode}- badges={- <>- {targetMet && (- <span key="state" className="ns-tag">- {goal.mode === "maintain" ? "holding" : "target met"}- </span>- )}- {tickRunning && (- <span key="checking" className="ns-tag">- checking…- </span>- )}- </>- }- strip={- goal.mode === "maintain" ? (- <div key="strip" className="mt-3">- <GoalChecksStrip squares={squares} streak={streak} />- </div>- ) : undefined- }- footer={- <>- <p- key="cadence"- className="mt-1.5 mb-0 text-[11px] leading-relaxed text-[hsl(var(--notfair-ink-4))]"- >- {cadenceLabel(goal.cadence_cron)} · {goal.tick_count} check- {goal.tick_count === 1 ? "" : "s"} so far- {goal.spend_envelope_usd !== null &&- ` · spent $${loggedSpendTotal(goal.id)} of $${goal.spend_envelope_usd}`}- </p>- {goal.status_reason &&- (goal.status === "achieved" || goal.status === "failed" || goal.status === "killed") && (- <Markdown- key="reason"- className="mt-2 text-[12px] leading-relaxed text-[hsl(var(--notfair-ink-3))] [&_p]:m-0"- >- {goal.status_reason}- </Markdown>- )}- </>- }- actions={chartActions}- failures={chartFailures}- deadline={goal.deadline ? Date.parse(goal.deadline) : null}- />- </RailSection>-- {extraSupports.length > 0 && (- <RailSection title="Supporting metrics" count={extraSupports.length}>- <div className="flex flex-col gap-4">- {extraSupports.map(({ metric }) => (- <SupportMetricItem key={metric.id} metric={metric} />- ))}- </div>- </RailSection>- )}-- <RailSection- title="Checks"- count={goal.tick_count}- meta={- goal.status === "active"- ? tickRunning- ? "running now"- : goal.next_tick_at- ? (- <span title={`Scheduled for ${fmtClock(goal.next_tick_at)}`}>- next check {timeUntil(goal.next_tick_at)}- </span>- )- : "next check —"- : undefined- }- >- {checkRows.length === 0 ? (- <p className="m-0 text-[12px] text-[hsl(var(--notfair-ink-4))]">- None yet — the first runs{" "}- {goal.next_tick_at- ? `${timeUntil(goal.next_tick_at)} (${fmtClock(goal.next_tick_at)})`- : `at ${fmtDate(goal.next_tick_at)}`}- .- </p>- ) : (- <GoalChecksList- slug={slug}- agentSlug={agentSlug}- goalId={goal.id}- initialRows={checkRows}- initialHasMore={checksHaveMore}- />- )}- </RailSection>-- </>- )}- </>- );-}--function RailCard({ children }: { children: React.ReactNode }) {- return <div className="ns-card p-3.5">{children}</div>;-}--/** One supporting metric — the SAME card grammar as the main metric:- * name + ⓘ header, big current value with baseline context, and the- * same time chart (no target line: supports have no target). */-function SupportMetricItem({ metric }: { metric: GoalSupportMetric }) {- const points = listSupportMetricSnapshots(metric.id, 400).map((sn) => ({- t: Date.parse(sn.created_at),- v: sn.value,- source: sn.source,- }));- return (- <div className="ns-card p-3.5">- <div className="mb-1 flex items-baseline justify-between">- <span className="flex min-w-0 items-center gap-1.5 text-[11px] text-[hsl(var(--notfair-ink-4))]">- <span className="truncate">{metric.name}</span>- <MetricMethodDialog- name={metric.name}- sourceKey={metric.source_key}- sourceTool={metric.source_tool}- argsJson={metric.source_args_json}- direction={metric.direction}- />- </span>- </div>- <div className="flex items-baseline gap-3">- <span className="text-xl font-semibold tabular-nums">- {formatMetric(metric.current_value)}- </span>- <span className="text-[11.5px] tabular-nums text-[hsl(var(--notfair-ink-4))]">- baseline {formatMetric(metric.baseline_value)}- </span>- </div>- {points.length >= 2 && (- <div className="mt-3">- <GoalProgressChart- points={points}- actions={[]}- failures={[]}- target={null}- baseline={metric.baseline_value}- deadline={null}- />- </div>- )}- </div>- );-}diff --git a/notfair/src/app/(app)/[project]/goals/page.tsx b/notfair/src/app/(app)/[project]/goals/page.tsxdeleted file mode 100644index 9cb8a8e4..00000000--- a/notfair/src/app/(app)/[project]/goals/page.tsx+++ /dev/null@@ -1,153 +0,0 @@-import Link from "next/link";-import { notFound } from "next/navigation";-import { Plus } from "lucide-react";-import { getProject } from "@/server/db/projects";-import { listProjectAgents } from "@/server/agent-meta";-import { getPinnedGoalIds, listGoals, listMetricSnapshots } from "@/server/db/goals";-import { projectHref } from "@/lib/project-href";-import { goalLabel } from "@/lib/goal-label";-import {- GoalsBoard,- type BoardGoal,- type GoalDashboardSection,-} from "@/components/goals-board";-import {- listGoalGroupMemberships,- listGoalGroups,-} from "@/server/db/goal-groups";-import { GoalGroupEditor, type GoalGroupEditorGoal } from "@/components/goal-group-editor";-import { GoalAutoRefresh } from "@/components/goal-auto-refresh";--export const dynamic = "force-dynamic";--/**- * The workspace goal dashboard: every main metric and its history, arranged- * into the same goal groups users manage in the sidebar.- */-export default async function AllGoalsPage({- params,-}: {- params: Promise<{ project: string }>;-}) {- const { project: slug } = await params;- const project = getProject(slug);- if (!project || project.archived_at) notFound();-- const agents = await listProjectAgents(slug);- const agentById = new Map(agents.map((a) => [a.agent_id, a]));- const pinnedIds = getPinnedGoalIds(slug);- const projectGoals = listGoals(slug);- const groups = listGoalGroups(slug);- const membershipByGoal = new Map(- listGoalGroupMemberships(slug).map((membership) => [membership.goal_id, membership.group_id]),- );- const groupById = new Map(groups.map((group) => [group.id, group.name]));-- // Plain-JSON card props for the dashboard. Goals whose agent sidecar is- // missing (half-deleted workspace) have no page to link to, so skip them.- const goals = projectGoals.flatMap<BoardGoal>((g) => {- const agent = agentById.get(g.agent_id);- if (!agent) return [];- return [- {- id: g.id,- href: projectHref(slug, `/goals/${agent.slug}`),- label: goalLabel(g),- statement: g.statement,- status: g.status,- status_reason: g.status_reason,- metric_name: g.metric_name,- current_value: g.current_value,- target_value: g.target_value,- metric_direction: g.metric_direction,- mode: g.mode,- tick_count: g.tick_count,- pinned: pinnedIds.has(g.id),- updated_at: g.updated_at,- snapshots: listMetricSnapshots(g.id, 120).map((snapshot) => snapshot.value),- },- ];- });-- const goalById = new Map(goals.map((goal) => [goal.id, goal]));- const goalsByGroup = new Map<string, BoardGoal[]>();- for (const [goalId, groupId] of membershipByGoal) {- const goal = goalById.get(goalId);- if (!goal) continue;- const groupGoals = goalsByGroup.get(groupId) ?? [];- groupGoals.push(goal);- goalsByGroup.set(groupId, groupGoals);- }- const sections: GoalDashboardSection[] = groups.map((group) => ({- id: group.id,- href: projectHref(slug, `/groups/${group.id}`),- name: group.name,- description: group.description || "A shared dashboard for related goals.",- goals: goalsByGroup.get(group.id) ?? [],- }));- const ungroupedGoals = goals.filter((goal) => !membershipByGoal.has(goal.id));- if (ungroupedGoals.length > 0) {- sections.push({- id: "ungrouped",- href: null,- name: "Ungrouped",- description: "Independent goals that are not part of a shared dashboard.",- goals: ungroupedGoals,- });- }- const editorGoals: GoalGroupEditorGoal[] = projectGoals.map((goal) => {- const groupId = membershipByGoal.get(goal.id) ?? null;- return {- id: goal.id,- label: goalLabel(goal),- status: goal.status,- current_group_id: groupId,- current_group_name: groupId ? groupById.get(groupId) ?? null : null,- };- });-- return (- <>- {goals.some((goal) => goal.status === "active") && (- <GoalAutoRefresh intervalMs={60_000} />- )}- <div className="absolute inset-0 overflow-y-auto">- <main className="mx-auto w-full max-w-[1320px] px-4 pt-8 pb-20 sm:px-7">- <header className="mb-8 flex flex-col gap-5 lg:flex-row lg:items-start lg:justify-between">- <div className="ns-page-head-stack">- <h1 className="ns-page-title">Goals dashboard</h1>- <p className="ns-page-sub">- Every main metric in {project.display_name}, grouped by the work it belongs to.- </p>- </div>- <div className="ns-page-actions">- <GoalGroupEditor projectSlug={slug} goals={editorGoals} />- <Link href={projectHref(slug, "")} className="ns-btn ns-btn-ghost shrink-0">- <Plus className="size-3.5" />- New goal- </Link>- </div>- </header>-- {goals.length === 0 ? (- <div className="ns-card p-8 text-center">- <p className="m-0 text-[13.5px] text-[hsl(var(--notfair-ink-3))]">- No goals yet. State an ambition and NotFair will figure out how to- measure and chase it.- </p>- <Link- href={projectHref(slug, "")}- className="ns-btn ns-btn-primary mt-4 inline-flex"- >- <Plus className="size-3.5" />- Create your first goal- </Link>- </div>- ) : (- <GoalsBoard sections={sections} />- )}- </main>- </div>- </>- );-}diff --git a/notfair/src/app/(app)/[project]/groups/[group]/page.tsx b/notfair/src/app/(app)/[project]/groups/[group]/page.tsxdeleted file mode 100644index 2f135afc..00000000--- a/notfair/src/app/(app)/[project]/groups/[group]/page.tsx+++ /dev/null@@ -1,116 +0,0 @@-import { notFound } from "next/navigation";-import { getProject } from "@/server/db/projects";-import {- getGoalGroup,- listGoalGroupMemberships,- listGoalGroups,- listGoalsInGroup,-} from "@/server/db/goal-groups";-import { listGoals, listGoalTicks, listMetricSnapshots } from "@/server/db/goals";-import { listProjectAgents } from "@/server/agent-meta";-import { goalLabel } from "@/lib/goal-label";-import { projectHref } from "@/lib/project-href";-import { GoalGroupEditor, type GoalGroupEditorGoal } from "@/components/goal-group-editor";-import {- GoalGroupDashboard,- type GoalGroupActivity,- type GoalGroupDashboardGoal,-} from "@/components/goal-group-dashboard";-import { GoalAutoRefresh } from "@/components/goal-auto-refresh";--export const dynamic = "force-dynamic";--export default async function GoalGroupPage({- params,-}: {- params: Promise<{ project: string; group: string }>;-}) {- const { project: slug, group: groupId } = await params;- const project = getProject(slug);- const group = getGoalGroup(groupId);- if (!project || project.archived_at || !group || group.project_slug !== slug) notFound();-- const agents = await listProjectAgents(slug);- const agentById = new Map(agents.map((agent) => [agent.agent_id, agent]));- const members = listGoalsInGroup(group.id);- const dashboardGoals = members.flatMap<GoalGroupDashboardGoal>((goal) => {- const agent = agentById.get(goal.agent_id);- if (!agent) return [];- return [{- id: goal.id,- href: projectHref(slug, `/goals/${agent.slug}`),- label: goalLabel(goal),- statement: goal.statement,- status: goal.status,- status_reason: goal.status_reason,- metric_name: goal.metric_name,- current_value: goal.current_value,- target_value: goal.target_value,- metric_direction: goal.metric_direction,- cadence_cron: goal.cadence_cron,- last_tick_at: goal.last_tick_at,- next_tick_at: goal.next_tick_at,- tick_count: goal.tick_count,- snapshots: listMetricSnapshots(goal.id, 120).map((snapshot) => snapshot.value),- }];- });-- const dashboardById = new Map(dashboardGoals.map((goal) => [goal.id, goal]));- const activity = members- .flatMap<GoalGroupActivity>((goal) => {- const display = dashboardById.get(goal.id);- if (!display) return [];- return listGoalTicks(goal.id, 8).map((tick) => ({- id: tick.id,- goal_id: goal.id,- goal_href: display.href,- goal_label: display.label,- tick_number: tick.tick_number,- status: tick.status,- metric_value: tick.metric_value,- metric_error: tick.metric_error,- summary: tick.summary,- started_at: tick.started_at,- }));- })- .sort((a, b) => b.started_at.localeCompare(a.started_at))- .slice(0, 20);-- const groups = listGoalGroups(slug);- const groupById = new Map(groups.map((item) => [item.id, item.name]));- const membershipByGoal = new Map(- listGoalGroupMemberships(slug).map((membership) => [membership.goal_id, membership.group_id]),- );- const editorGoals: GoalGroupEditorGoal[] = listGoals(slug).map((goal) => {- const currentGroupId = membershipByGoal.get(goal.id) ?? null;- return {- id: goal.id,- label: goalLabel(goal),- status: goal.status,- current_group_id: currentGroupId,- current_group_name: currentGroupId ? groupById.get(currentGroupId) ?? null : null,- };- });-- return (- <>- {dashboardGoals.some((goal) => goal.status === "active") && (- <GoalAutoRefresh intervalMs={60_000} />- )}- <GoalGroupDashboard- name={group.name}- description={group.description}- allGoalsHref={projectHref(slug, "/goals")}- goals={dashboardGoals}- activity={activity}- actions={- <GoalGroupEditor- projectSlug={slug}- goals={editorGoals}- group={{ id: group.id, name: group.name, description: group.description }}- />- }- />- </>- );-}diff --git a/notfair/src/app/(app)/[project]/layout.tsx b/notfair/src/app/(app)/[project]/layout.tsxdeleted file mode 100644index 9244f47c..00000000--- a/notfair/src/app/(app)/[project]/layout.tsx+++ /dev/null@@ -1,29 +0,0 @@-import { notFound } from "next/navigation";-import { getProject } from "@/server/db/projects";-import { ProjectCookieSync } from "@/components/project-cookie-sync";--/**- * Validates that the URL's project slug actually exists. Live-syncing the- * cookie used by `getActiveProject()` (which the sidebar + API routes still- * read) is handled by a thin client component so we can stay inside server- * render. The actual sidebar / chrome is mounted by the parent `(app)/layout`.- */-export default async function ProjectScopedLayout({- children,- params,-}: {- children: React.ReactNode;- params: Promise<{ project: string }>;-}) {- const { project: slug } = await params;- const project = getProject(slug);- if (!project || project.archived_at) {- notFound();- }- return (- <>- <ProjectCookieSync slug={slug} />- {children}- </>- );-}diff --git a/notfair/src/app/(app)/[project]/page.tsx b/notfair/src/app/(app)/[project]/page.tsxdeleted file mode 100644index 9c6864cf..00000000--- a/notfair/src/app/(app)/[project]/page.tsx+++ /dev/null@@ -1,246 +0,0 @@-import Link from "next/link";-import { notFound } from "next/navigation";-import { MessageSquare } from "lucide-react";-import { getProject } from "@/server/db/projects";-import { listProjectAgents } from "@/server/agent-meta";-import {- getGoalForAgent,- getLatestGoalForAgent,- listMetricSnapshots,- type Goal,-} from "@/server/db/goals";-import { listProjectMcpTokens } from "@/server/mcp/tokens";-import { listPrsAwaitingReview } from "@/server/db/goal-prs";-import { listOpenSuggestions } from "@/server/db/suggestions";-import {- listSuggestionRuns,- maybeAutoGenerate,-} from "@/server/suggestions/engine";-import { projectHref } from "@/lib/project-href";-import { colorForAgentSlug } from "@/lib/agent-colors";-import { cn } from "@/lib/utils";-import { NewGoalForm } from "@/components/new-goal-form";-import { goalLabel } from "@/lib/goal-label";-import { formatMetric } from "@/lib/format-metric";-import { GoalSparkline } from "@/components/goal-sparkline";-import {- GoalSuggestionCard,- RetryAnalysisButton,-} from "@/components/goal-suggestions";-import { GoalAutoRefresh } from "@/components/goal-auto-refresh";--export const dynamic = "force-dynamic";--const STATUS_LABEL: Record<Goal["status"], string> = {- intake: "defining the goal",- proposed: "awaiting your target",- active: "loop running",- paused: "paused",- achieved: "achieved",- failed: "failed",- killed: "closed",-};--/**- * Project root = the goals index. Agent = goal: each row is an agent and- * the goal it owns. Minting a new agent is the only creation flow — the- * goal itself gets defined in that agent's chat.- */-export default async function ProjectGoalsPage({- params,-}: {- params: Promise<{ project: string }>;-}) {- const { project: slug } = await params;- const project = getProject(slug);- if (!project || project.archived_at) notFound();-- const agents = await listProjectAgents(slug);- const rows = agents.map((a) => {- const goal = getGoalForAgent(a.agent_id) ?? getLatestGoalForAgent(a.agent_id);- const snapshots = goal ? listMetricSnapshots(goal.id, 120) : [];- // 7-day delta: latest vs the closest snapshot at least 7 days old- // (else the earliest we have).- let delta: number | null = null;- if (goal && snapshots.length >= 2) {- const latest = snapshots[snapshots.length - 1]!;- const cutoff = Date.parse(latest.created_at) - 7 * 86_400_000;- const past =- [...snapshots].reverse().find((sn) => Date.parse(sn.created_at) <= cutoff) ??- snapshots[0]!;- delta = latest.value - past.value;- }- return { agent: a, goal, snapshots, delta };- });- const connectedMcpKeys = listProjectMcpTokens(slug).map((t) => t.server_name);- const connectedCount = connectedMcpKeys.length;- // Goals with a PR sitting on the user's side of the net — surfaced as a- // badge on the row so review requests are visible from the index.- const goalIdsAwaitingPrReview = new Set(- listPrsAwaitingReview(slug).map((pr) => pr.goal_id),- );-- // Account analysis → suggested goals. First index visit after a connect- // (or after a restart dropped a run) kicks the audit in the background;- // the page then live-refreshes until the cards land.- maybeAutoGenerate(slug);- const suggestions = listOpenSuggestions(slug);- const suggestionRuns = listSuggestionRuns(slug);- const analyzing = suggestionRuns.filter((r) => r.status === "running");- const failedRuns = suggestionRuns.filter((r) => r.status === "failed");-- return (- <div className="ns-app-wide">- <header className="ns-page-head">- <div className="ns-page-head-stack">- <h1 className="ns-page-title">{project.display_name}</h1>- <p className="ns-page-sub">- State a goal. It gets measured, you confirm the plan, the loop runs.- </p>- </div>- </header>-- <div className="mb-6">- <NewGoalForm projectSlug={slug} connectedMcpKeys={connectedMcpKeys} />- </div>-- {connectedCount === 0 && (- <Link- href={projectHref(slug, "/connections")}- className="mb-6 block rounded-[14px] bg-[hsl(var(--notfair-accent)/0.08)] px-4 py-3 text-[13px]"- >- No data sources connected yet — connect Google Ads, Meta Ads, or Search- Console so your agents can measure anything. Connect →- </Link>- )}-- {(analyzing.length > 0 || suggestions.length > 0 || failedRuns.length > 0) && (- <section className="mb-6">- <h2 className="m-0 mb-2 text-[12px] font-medium uppercase tracking-wide text-[hsl(var(--notfair-ink-4))]">- Suggested from your account- </h2>- <div className="flex flex-col gap-3">- {analyzing.map((run) => (- <div- key={run.source_key}- className="ns-card flex items-center gap-2.5 p-4 text-[13px] text-[hsl(var(--notfair-ink-3))]"- >- <span- className="size-2 animate-pulse rounded-full bg-[hsl(var(--notfair-accent))]"- aria-hidden- />- Analyzing your {run.label} account for goal ideas…- </div>- ))}- {suggestions.map((s) => (- <GoalSuggestionCard key={s.id} suggestion={s} projectSlug={slug} />- ))}- {failedRuns.map((run) => (- <div- key={run.source_key}- className="ns-card flex items-center justify-between gap-3 p-4 text-[12.5px] text-[hsl(var(--notfair-ink-3))]"- >- <span>- Couldn’t analyze your {run.label} account- {run.error ? ` — ${run.error}` : "."}- </span>- <RetryAnalysisButton projectSlug={slug} />- </div>- ))}- </div>- {analyzing.length > 0 && <GoalAutoRefresh intervalMs={2500} />}- </section>- )}-- {rows.length === 0 ? (- <div className="ns-empty">- <p className="ns-empty-title">No goals yet.</p>- <p className="ns-empty-sub">- State an ambition above and an agent takes it from there.- </p>- </div>- ) : (- <ol className="ns-group">- {rows.map(({ agent, goal, snapshots, delta }) => {- const color = colorForAgentSlug(agent.slug);- const deltaGood =- goal && delta !== null- ? goal.metric_direction === "decrease"- ? delta <= 0- : delta >= 0- : null;- return (- <li key={agent.agent_id}>- <Link- href={projectHref(slug, `/goals/${agent.slug}`)}- className="ns-row-button"- >- <span className="ns-glyph" aria-hidden>- <span className={cn("size-2.5 rounded-full", color.dot)} />- </span>- <span className="ns-row-body">- <span className="ns-row-title-row">- <span className="ns-row-title">{goal ? goalLabel(goal) : agent.name}</span>- {goal && <span className="ns-tag">{STATUS_LABEL[goal.status]}</span>}- {goal && goalIdsAwaitingPrReview.has(goal.id) && (- <span className="ns-tag-accent">PR needs your review</span>- )}- </span>- <span className="ns-row-desc block">- {goal?.statement?.trim()- ? goal.statement- : "Getting started — the agent is working on it."}- </span>- {goal?.status === "active" &&- goal.current_value !== null &&- goal.target_value !== null && (- <span className="ns-row-desc block tabular-nums">- {goal.metric_name}: {formatMetric(goal.current_value)} → target {formatMetric(goal.target_value)}- </span>- )}- </span>- <span className="ns-row-meta items-center gap-3">- {goal && snapshots.length >= 2 && (- <span className="hidden w-28 sm:block" aria-hidden>- <GoalSparkline- values={snapshots.map((sn) => sn.value)}- target={goal.target_value}- direction={goal.metric_direction}- width={112}- height={28}- />- </span>- )}- {delta !== null && (- <span- className={- "text-[11.5px] tabular-nums " +- (deltaGood- ? "text-[hsl(var(--notfair-accent))]"- : "text-[hsl(0_60%_55%)]")- }- title="Change over the last 7 days"- >- {delta > 0 ? "▲" : delta < 0 ? "▼" : "—"}{" "}- {Math.abs(delta) >= 1000- ? `${(Math.abs(delta) / 1000).toFixed(1)}k`- : Number.isInteger(delta)- ? Math.abs(delta)- : Math.abs(delta).toFixed(2)}{" "}- /7d- </span>- )}- <MessageSquare className="size-4 text-[hsl(var(--notfair-ink-4))]" />- <span className="chev" aria-hidden>- ›- </span>- </span>- </Link>- </li>- );- })}- </ol>- )}- </div>- );-}diff --git a/notfair/src/app/(app)/[project]/settings/page.tsx b/notfair/src/app/(app)/[project]/settings/page.tsxdeleted file mode 100644index 8833c927..00000000--- a/notfair/src/app/(app)/[project]/settings/page.tsx+++ /dev/null@@ -1,90 +0,0 @@-import { notFound } from "next/navigation";-import { getProject } from "@/server/db/projects";-import { DangerZone } from "@/components/danger-zone";-import { ProjectRenameCard } from "@/components/project-rename-card";-import { CodebasePathCard } from "@/components/codebase-path-card";-import { WorkspaceBrowserCard } from "@/components/workspace-browser-card";--export default async function SettingsPage({- params,-}: {- params: Promise<{ project: string }>;-}) {- const { project: slug } = await params;- const project = getProject(slug);- if (!project || project.archived_at) notFound();-- return (- <div className="ns-app-narrow">- <header className="ns-page-head">- <div className="ns-page-head-stack">- <h1 className="ns-page-title">Settings</h1>- <p className="ns-page-sub">- Manage <b>{project.display_name}</b> — name, slug, and the danger- zone.- </p>- </div>- </header>-- <section>- <h2 className="ns-h2">- <span>General</span>- </h2>- <ProjectRenameCard- currentSlug={project.slug}- currentDisplayName={project.display_name}- />- </section>-- <section>- <h2 className="ns-h2">- <span>Workspace details</span>- </h2>- <div className="ns-card">- <dl className="grid grid-cols-[auto_1fr] gap-x-6 gap-y-3 p-[18px]">- <dt className="text-[12.5px] text-[hsl(var(--notfair-ink-4))]">- Display name- </dt>- <dd className="text-[13px] font-medium text-[hsl(var(--notfair-ink-2))]">- {project.display_name}- </dd>- <dt className="text-[12.5px] text-[hsl(var(--notfair-ink-4))]">URL slug</dt>- <dd>- <span className="ns-tag-mono">{project.slug}</span>- </dd>- <dt className="text-[12.5px] text-[hsl(var(--notfair-ink-4))]">- AI agent runtime- </dt>- <dd className="text-[13px] text-[hsl(var(--notfair-ink-2))]">- {project.harness_adapter === "codex-local" ? "Codex" : "Claude Code"}- </dd>- </dl>- </div>- </section>-- <section>- <h2 className="ns-h2">- <span>Codebase</span>- </h2>- <CodebasePathCard- projectSlug={project.slug}- currentPath={project.codebase_path}- />- </section>-- <section>- <h2 className="ns-h2">- <span>Workspace browser</span>- </h2>- <WorkspaceBrowserCard projectSlug={project.slug} />- </section>-- <section>- <h2 className="ns-h2">- <span>Danger zone</span>- </h2>- <DangerZone projectSlug={project.slug} projectName={project.display_name} />- </section>- </div>- );-}diff --git a/notfair/src/app/(app)/layout.tsx b/notfair/src/app/(app)/layout.tsxdeleted file mode 100644index e1dd8650..00000000--- a/notfair/src/app/(app)/layout.tsx+++ /dev/null@@ -1,34 +0,0 @@-import {- SidebarInset,- SidebarProvider,- SidebarTrigger,-} from "@/components/ui/sidebar";-import { AppSidebar } from "@/components/app-sidebar";-import { ClientMountGate } from "@/components/client-mount-gate";--export default async function AppLayout({ children }: { children: React.ReactNode }) {- return (- <ClientMountGate- fallback={- <div className="min-h-screen bg-background" suppressHydrationWarning>- {/* Empty shell during hydration — children mount client-side */}- </div>- }- >- <SidebarProvider>- <AppSidebar />- <SidebarInset>- <header className="sticky top-0 z-30 flex h-12 shrink-0 items-center bg-background/95 px-3 backdrop-blur md:hidden">- <SidebarTrigger aria-label="Open navigation" />- </header>- <a href="#main-content" className="sr-only focus:not-sr-only">- Skip to content- </a>- <main id="main-content" className="relative flex-1">- {children}- </main>- </SidebarInset>- </SidebarProvider>- </ClientMountGate>- );-}diff --git a/notfair/src/app/(app)/page.tsx b/notfair/src/app/(app)/page.tsxdeleted file mode 100644index 8cd2d406..00000000--- a/notfair/src/app/(app)/page.tsx+++ /dev/null@@ -1,16 +0,0 @@-import { redirect } from "next/navigation";-import { getActiveProject } from "@/server/active-project";-import { projectHref } from "@/lib/project-href";--/**- * Root entry. Project-scoped routes now live under `/<slug>/...`, so the- * bare root just resolves the user's active (or first) project and bounces- * them to that home. With no projects at all, kick into onboarding.- */-export default async function RootRedirect() {- const project = await getActiveProject();- if (project) {- redirect(projectHref(project.slug));- }- redirect("/onboarding");-}diff --git a/notfair/src/app/(app)/projects/new/page.tsx b/notfair/src/app/(app)/projects/new/page.tsxdeleted file mode 100644index 70a7566a..00000000--- a/notfair/src/app/(app)/projects/new/page.tsx+++ /dev/null@@ -1,10 +0,0 @@-import { redirect } from "next/navigation";--/**- * Per D3 of the onboarding rework: /projects/new is replaced by the unified- * /onboarding flow. This redirect keeps existing bookmarks + any in-flight- * call sites that still link here working until they're updated.- */-export default function NewProjectPage(): never {- redirect("/onboarding");-}diff --git a/notfair/src/app/(app)/projects/page.tsx b/notfair/src/app/(app)/projects/page.tsxdeleted file mode 100644index 805fd3d3..00000000--- a/notfair/src/app/(app)/projects/page.tsx+++ /dev/null@@ -1,84 +0,0 @@-import Link from "next/link";-import { Archive } from "lucide-react";-import { listProjects } from "@/server/db/projects";--function initials(name: string): string {- const parts = name.trim().split(/\s+/).filter(Boolean);- if (parts.length >= 2) return (parts[0]![0]! + parts[1]![0]!).toUpperCase();- return name.slice(0, 2).toUpperCase();-}--export default function ProjectsListPage() {- const projects = listProjects({ includeArchived: true });-- return (- <div className="ns-app-narrow">- <header className="ns-page-head">- <div className="ns-page-head-stack">- <h1 className="ns-page-title">Workspaces</h1>- <p className="ns-page-sub">- <b>{projects.length}</b>{" "}- {projects.length === 1 ? "workspace" : "workspaces"} on this- machine.- </p>- </div>- <div className="ns-page-actions">- <Link href="/onboarding" className="ns-btn ns-btn-primary">- New workspace- </Link>- </div>- </header>-- {projects.length === 0 ? (- <div className="ns-empty">- <p className="ns-empty-title">No workspaces yet.</p>- <p className="ns-empty-sub">- Create your first workspace to get started.- </p>- <Link- href="/onboarding"- className="ns-btn ns-btn-primary ns-empty-action"- >- Create workspace- </Link>- </div>- ) : (- <ol className="ns-group">- {projects.map((p) => (- <li key={p.slug}>- <Link href={`/${p.slug}`} className="ns-row-button">- <span- aria-hidden- className="grid size-[38px] shrink-0 place-items-center rounded-[9px] bg-[hsl(var(--notfair-accent-soft))] text-[13px] font-semibold tracking-tight text-[hsl(var(--notfair-accent))]"- >- {initials(p.display_name)}- </span>- <span className="ns-row-body">- <span className="ns-row-title-row">- <span className="ns-row-title">{p.display_name}</span>- {p.archived_at && (- <span className="ns-tag inline-flex items-center gap-1">- <Archive className="size-3" />- archived- </span>- )}- </span>- <span className="ns-row-desc block">- <span className="font-mono">{p.slug}</span>- {" · Created "}- {new Date(p.created_at).toLocaleDateString()}- </span>- </span>- <span className="ns-row-meta">- <span className="chev" aria-hidden>- ›- </span>- </span>- </Link>- </li>- ))}- </ol>- )}- </div>- );-}diff --git a/notfair/src/app/api/agents/[agent]/threads/[thread]/live/route.ts b/notfair/src/app/api/agents/[agent]/threads/[thread]/live/route.tsdeleted file mode 100644index 2942860e..00000000--- a/notfair/src/app/api/agents/[agent]/threads/[thread]/live/route.ts+++ /dev/null@@ -1,191 +0,0 @@-import { NextResponse } from "next/server";-import { getActiveProject } from "@/server/active-project";-import { resolveAgentBySlug } from "@/server/agent-meta";-import { getProject } from "@/server/db/projects";-import {- readTranscriptTail,- resolveSessionForThread,-} from "@/server/sessions/transcript-tail";-import { subscribeSessionEvents } from "@/server/live-events/emitter";-import type { TranscriptEvent as RawTranscriptEvent } from "@/server/sessions";-import { readTranscriptTail as tailFromCursor } from "@/server/sessions/transcript-tail";--export const dynamic = "force-dynamic";-export const runtime = "nodejs";--const DEBUG = process.env.NOTFAIR_LIVE_BRIDGE_DEBUG !== "0";-function log(...args: unknown[]): void {- if (DEBUG) console.log("[live-bridge]", ...args);-}--/**- * SSE bridge that streams a session's transcript live.- *- * Mechanism (paperclip-style pub/sub):- * 1. Resolve the session row from (project_slug, agent_id, label).- * 2. Backfill events the client hasn't seen yet by reading- * `transcript_events` from `?cursor=` (default 0) forward.- * 3. Subscribe to the in-process emitter for this session_id. From this- * point, every `appendTranscriptEvent` call fires this listener and- * we forward the event to the client in milliseconds — no polling.- *- * Reattach safety: the backfill + subscribe pair brackets the gap between- * page render and SSE connect. Any event written during that window lands- * in the backfill or in the live stream; the client filters by `seq` so- * an event that crosses the boundary is deduped.- */-export async function GET(- request: Request,- { params }: { params: Promise<{ agent: string; thread: string }> },-): Promise<Response> {- const { agent: agentSlug, thread: threadId } = await params;-- const url = new URL(request.url);- const projectSlug = url.searchParams.get("project");- const projectRow = projectSlug ? getProject(projectSlug) : await getActiveProject();- if (!projectRow || projectRow.archived_at) {- return NextResponse.json({ error: "Unknown project" }, { status: 404 });- }- const resolved = await resolveAgentBySlug(projectRow.slug, agentSlug);- if (!resolved) {- return NextResponse.json({ error: "Unknown agent" }, { status: 404 });- }- const agentFullId = resolved.agent_id;- const cursorParam = url.searchParams.get("cursor");- const startCursor = cursorParam ? Math.max(0, Number(cursorParam)) : 0;-- // Resolve the underlying NotFair session row so we can subscribe on- // its id (the EventEmitter key). A pending thread that hasn't received- // any turn yet has no row — we still hold the SSE open and rely on the- // subscribe-on-create branch below (the first turn creates the row and- // pushes the first event, which we'd miss). To handle that case, we- // also poll-fallback for the row every 1s while it's missing.- let session = resolveSessionForThread(projectRow.slug, agentFullId, threadId);-- const encoder = new TextEncoder();-- const stream = new ReadableStream<Uint8Array>({- async start(controller) {- let closed = false;- let unsubscribe: (() => void) | null = null;- let bufferedDuringBackfill: RawTranscriptEvent[] | null = [];- let lastSeqEmitted = startCursor;- let pendingProbe: ReturnType<typeof setInterval> | null = null;-- function send(event: string, data: unknown): void {- if (closed) return;- try {- controller.enqueue(- encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`),- );- } catch {- // torn down- }- }-- function teardown(): void {- if (closed) return;- closed = true;- if (pendingProbe) clearInterval(pendingProbe);- if (unsubscribe) {- unsubscribe();- unsubscribe = null;- }- try {- controller.close();- } catch {- // already closed- }- }-- request.signal.addEventListener("abort", teardown);-- /**- * Convert a single transcript_events row into the UI event shape and- * forward over SSE. Dedupes by seq so events delivered both via- * backfill and live stream don't render twice.- */- function forwardRow(row: RawTranscriptEvent): void {- if (row.seq <= lastSeqEmitted) return;- lastSeqEmitted = row.seq;- // Reuse readTranscriptTail's mapping to keep the UI shape in one- // place; it accepts a cursor strictly less than the row's seq.- const { events } = tailFromCursor(- projectRow!.slug,- agentFullId,- threadId,- row.seq - 1,- );- if (events.length > 0) {- send("transcript", { events });- }- }-- function liveListener(row: RawTranscriptEvent): void {- if (closed) return;- if (bufferedDuringBackfill) {- // Backfill is still draining — queue and replay after it finishes- // to preserve order and let dedup-by-seq do its job.- bufferedDuringBackfill.push(row);- return;- }- forwardRow(row);- }-- function attachSubscription(sessionId: string): void {- unsubscribe = subscribeSessionEvents(sessionId, liveListener);- }-- function backfill(): void {- if (closed) return;- const { events, cursor } = readTranscriptTail(- projectRow!.slug,- agentFullId,- threadId,- lastSeqEmitted,- );- if (events.length > 0) {- lastSeqEmitted = cursor;- send("transcript", { events });- }- // Drain anything that arrived while we were reading the DB.- const buf = bufferedDuringBackfill ?? [];- bufferedDuringBackfill = null;- for (const row of buf) forwardRow(row);- }-- send("ready", { thread: threadId, cursor: startCursor });-- if (session) {- // Standard path: row exists. Subscribe FIRST so events written- // during the backfill land in the buffer, then read the DB.- attachSubscription(session.id);- backfill();- } else {- // Pending thread with no first turn yet. Poll-fallback for the row- // every 1s. When it appears, attach and backfill. Keep the SSE- // open meanwhile so the client doesn't reconnect uselessly.- log("waiting for session row", { threadId });- pendingProbe = setInterval(() => {- if (closed) return;- session = resolveSessionForThread(projectRow!.slug, agentFullId, threadId);- if (session) {- clearInterval(pendingProbe!);- pendingProbe = null;- attachSubscription(session.id);- backfill();- }- }, 1000);- }- },- });-- return new Response(stream, {- headers: {- "Content-Type": "text/event-stream",- "Cache-Control": "no-cache, no-transform",- Connection: "keep-alive",- "X-Accel-Buffering": "no",- },- });-}diff --git a/notfair/src/app/api/agents/[agent]/threads/[thread]/transcript/route.ts b/notfair/src/app/api/agents/[agent]/threads/[thread]/transcript/route.tsdeleted file mode 100644index fe8c308a..00000000--- a/notfair/src/app/api/agents/[agent]/threads/[thread]/transcript/route.ts+++ /dev/null@@ -1,56 +0,0 @@-import { NextResponse } from "next/server";-import { getActiveProject } from "@/server/active-project";-import { getProject } from "@/server/db/projects";-import { resolveAgentBySlug } from "@/server/agent-meta";-import { readTranscriptTail } from "@/server/sessions/transcript-tail";--export const dynamic = "force-dynamic";-export const runtime = "nodejs";--/**- * Generic transcript tail endpoint — agent + thread, no task lookup.- *- * Both surfaces (the task workspace and the free-form /chat/[thread] view)- * poll this with the byte offset they last saw; we return any events- * written since. Threads have no terminal state, so callers manage their- * own "stop polling" signal (the task workspace gates on task.status).- *- * Project resolution: prefer the explicit `project` query param (the page- * knows its URL slug and passes it through), fall back to the- * active-project cookie. The cookie can lag the URL on first paint after a- * project switch or direct deep-link, so the explicit param is the source- * of truth when present.- */-export async function GET(- request: Request,- context: { params: Promise<{ agent: string; thread: string }> },-) {- const { agent: agentSlug, thread: threadId } = await context.params;-- const url = new URL(request.url);- const projectParam = url.searchParams.get("project");- const project = projectParam- ? getProject(projectParam)- : await getActiveProject();- if (!project) {- return NextResponse.json({ error: "no active project" }, { status: 400 });- }-- const resolved = await resolveAgentBySlug(project.slug, agentSlug);- if (!resolved) {- return NextResponse.json({ error: "unknown agent" }, { status: 404 });- }-- const offsetParam = url.searchParams.get("offset");- const cursor = offsetParam ? Number(offsetParam) : 0;- const validOffset = Number.isFinite(cursor) && cursor >= 0 ? cursor : 0;-- const { events, cursor: newCursor } = readTranscriptTail(- project.slug,- resolved.agent_id,- threadId,- validOffset,- );-- return NextResponse.json({ events, cursor: newCursor });-}diff --git a/notfair/src/app/api/browser/launch/route.ts b/notfair/src/app/api/browser/launch/route.tsdeleted file mode 100644index 24bb076a..00000000--- a/notfair/src/app/api/browser/launch/route.ts+++ /dev/null@@ -1,57 +0,0 @@-import { NextResponse } from "next/server";--import { getOrLaunchBrowser, getSessionStatus } from "@/server/browser/session";-import { openTab } from "@/server/browser/tabs";--export const dynamic = "force-dynamic";-export const runtime = "nodejs";--/**- * Launch (or attach to) the workspace browser for a project.- *- * Headed by default — onboarding uses this to pop Chrome open so the user- * can sign into Google, Meta, etc. Once cookies persist in the workspace- * user-data-dir, agents on subsequent runs inherit the logged-in state- * automatically.- *- * POST body:- * { project_slug: string, signin_url?: string, headless?: boolean }- *- * Returns: { status, signin_tab? }- */-export async function POST(req: Request) {- const body = (await req.json().catch(() => ({}))) as {- project_slug?: string;- signin_url?: string;- headless?: boolean;- };- if (!body.project_slug) {- return NextResponse.json(- { error: "project_slug required" },- { status: 400 },- );- }-- try {- // Shutdown hooks + idle checker are auto-registered inside- // getOrLaunchBrowser, so this route does not need explicit setup.- await getOrLaunchBrowser(body.project_slug, { headless: body.headless ?? false });- const status = getSessionStatus(body.project_slug);-- let signinTab: { id: string; url: string } | undefined;- if (body.signin_url) {- const handle = await openTab(body.project_slug, {- label: "signin",- url: body.signin_url,- });- signinTab = { id: handle.id, url: handle.url };- }-- return NextResponse.json({ status, signin_tab: signinTab });- } catch (err) {- return NextResponse.json(- { error: err instanceof Error ? err.message : String(err) },- { status: 500 },- );- }-}diff --git a/notfair/src/app/api/browser/shutdown/route.ts b/notfair/src/app/api/browser/shutdown/route.tsdeleted file mode 100644index cb014d8f..00000000--- a/notfair/src/app/api/browser/shutdown/route.ts+++ /dev/null@@ -1,31 +0,0 @@-import { NextResponse } from "next/server";--import { stopBrowser } from "@/server/browser/session";--export const dynamic = "force-dynamic";-export const runtime = "nodejs";--/**- * Stop the workspace browser for a project.- *- * Cookies persist in the workspace user-data-dir, so the next launch- * picks up the same login state. Used by Settings → "Restart browser"- * and from the agent-facing browser_shutdown tool.- *- * POST body: { project_slug: string }- */-export async function POST(req: Request) {- const body = (await req.json().catch(() => ({}))) as { project_slug?: string };- if (!body.project_slug) {- return NextResponse.json({ error: "project_slug required" }, { status: 400 });- }- try {- await stopBrowser(body.project_slug);- return NextResponse.json({ ok: true });- } catch (err) {- return NextResponse.json(- { error: err instanceof Error ? err.message : String(err) },- { status: 500 },- );- }-}diff --git a/notfair/src/app/api/browser/status/route.ts b/notfair/src/app/api/browser/status/route.tsdeleted file mode 100644index 41cef09c..00000000--- a/notfair/src/app/api/browser/status/route.ts+++ /dev/null@@ -1,33 +0,0 @@-import { NextResponse } from "next/server";--import { getSessionStatus } from "@/server/browser/session";-import { listTabs } from "@/server/browser/tabs";--export const dynamic = "force-dynamic";-export const runtime = "nodejs";--/**- * Check whether the workspace browser is running and list its tabs.- *- * Cheap; safe to poll from the Settings page.- *- * GET /api/browser/status?project_slug=<slug>- */-export async function GET(req: Request) {- const url = new URL(req.url);- const slug = url.searchParams.get("project_slug");- if (!slug) {- return NextResponse.json({ error: "project_slug query param required" }, { status: 400 });- }- const status = getSessionStatus(slug);- let tabs: Array<{ id: string; url: string; title: string }> = [];- if (status.running) {- try {- const handles = await listTabs(slug);- tabs = handles.map((h) => ({ id: h.id, url: h.url, title: h.title }));- } catch {- // listing failed — return status without tabs rather than blowing up- }- }- return NextResponse.json({ status, tabs });-}diff --git a/notfair/src/app/api/chat/route.test.ts b/notfair/src/app/api/chat/route.test.tsdeleted file mode 100644index 35fcca53..00000000--- a/notfair/src/app/api/chat/route.test.ts+++ /dev/null@@ -1,146 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--import type {- HarnessAdapter,- HarnessExecuteContext,- HarnessModelOption,-} from "@/server/adapters/types";--const mocks = vi.hoisted(() => ({- getProject: vi.fn(),- getActiveProject: vi.fn(),- resolveAgentBySlug: vi.fn(),- requireAdapter: vi.fn(),- workspaceDirFor: vi.fn(() => "/tmp/notfair-agent"),- getOrCreateSession: vi.fn(),- appendTranscriptEvent: vi.fn(),- touchSession: vi.fn(),- registerLiveTurn: vi.fn(),- releaseLiveTurn: vi.fn(),-}));--vi.mock("@/server/active-project", () => ({- getActiveProject: mocks.getActiveProject,-}));-vi.mock("@/server/db/projects", () => ({ getProject: mocks.getProject }));-vi.mock("@/server/agent-meta", () => ({- resolveAgentBySlug: mocks.resolveAgentBySlug,-}));-vi.mock("@/server/adapters/registry", () => ({- requireAdapter: mocks.requireAdapter,-}));-vi.mock("@/server/agents/provisioning", () => ({- workspaceDirFor: mocks.workspaceDirFor,-}));-vi.mock("@/server/sessions", () => ({- getOrCreateSession: mocks.getOrCreateSession,- appendTranscriptEvent: mocks.appendTranscriptEvent,- touchSession: mocks.touchSession,-}));-vi.mock("@/server/sessions/live-turns", () => ({- registerLiveTurn: mocks.registerLiveTurn,- releaseLiveTurn: mocks.releaseLiveTurn,-}));--import { POST } from "./route";--const models: HarnessModelOption[] = [- {- value: "gpt-dynamic",- label: "Dynamic model",- is_default: true,- default_reasoning_effort: "low",- reasoning_efforts: [- { value: "low", label: "Low" },- { value: "high", label: "High" },- ],- },-];--function request(body: unknown) {- return new Request("http://localhost/api/chat", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(body),- });-}--describe("POST /api/chat reasoning effort", () => {- let executeContext: HarnessExecuteContext | null;- let adapter: Pick<HarnessAdapter, "listModels" | "execute">;-- beforeEach(() => {- vi.clearAllMocks();- executeContext = null;- adapter = {- listModels: vi.fn(async () => models),- execute: vi.fn(async function* (ctx: HarnessExecuteContext) {- executeContext = ctx;- }),- };- mocks.getProject.mockReturnValue({- slug: "acme",- harness_adapter: "codex-local",- });- mocks.resolveAgentBySlug.mockResolvedValue({ agent_id: "goal-agent" });- mocks.requireAdapter.mockReturnValue(adapter);- mocks.getOrCreateSession.mockReturnValue({- id: "session-1",- harness_session_id: null,- });- mocks.registerLiveTurn.mockReturnValue(new AbortController());- });-- it("validates and forwards a provider-supported effort without forcing a model", async () => {- const response = await POST(- request({- project: "acme",- agent: "goal-1",- message: "hello",- reasoning_effort: "high",- }),- );- await response.text();-- expect(response.status).toBe(200);- expect(adapter.listModels).toHaveBeenCalledOnce();- expect(executeContext).toMatchObject({- model: null,- reasoningEffort: "high",- });- });-- it("rejects an effort the selected model did not publish", async () => {- const response = await POST(- request({- project: "acme",- agent: "goal-1",- message: "hello",- reasoning_effort: "ultra-secret",- }),- );-- expect(response.status).toBe(400);- await expect(response.json()).resolves.toMatchObject({- error: "Unknown reasoning effort 'ultra-secret' for model 'gpt-dynamic'",- });- expect(adapter.execute).not.toHaveBeenCalled();- });-- it("returns a 400 for a non-string effort instead of throwing", async () => {- const response = await POST(- request({- project: "acme",- agent: "goal-1",- message: "hello",- reasoning_effort: 42,- }),- );-- expect(response.status).toBe(400);- await expect(response.json()).resolves.toEqual({- error: "reasoning_effort must be a string",- });- expect(adapter.listModels).not.toHaveBeenCalled();- });-});diff --git a/notfair/src/app/api/chat/route.ts b/notfair/src/app/api/chat/route.tsdeleted file mode 100644index 45a3fd0c..00000000--- a/notfair/src/app/api/chat/route.ts+++ /dev/null@@ -1,238 +0,0 @@-import { NextResponse } from "next/server";-import { getActiveProject } from "@/server/active-project";-import { getProject } from "@/server/db/projects";-import { resolveAgentBySlug } from "@/server/agent-meta";-import { requireAdapter } from "@/server/adapters/registry";-import { workspaceDirFor } from "@/server/agents/provisioning";-import {- getOrCreateSession,- appendTranscriptEvent,- touchSession,-} from "@/server/sessions";-import {- registerLiveTurn,- releaseLiveTurn,-} from "@/server/sessions/live-turns";--export const dynamic = "force-dynamic";-export const runtime = "nodejs";--type ChatPostBody = {- message: string;- agent?: string;- /** URL slug of the project this chat belongs to. */- project?: string;- /**- * Thread label — stable identifier for the chat thread. The route maps- * (project, agent, label) → a sessions row; if none exists it's created.- * Defaults to "main" when omitted.- */- thread?: string;- /**- * Per-turn model override from the composer's model selector. Must be- * one of HARNESS_MODEL_OPTIONS for the project's adapter — anything- * else is a 400 (values become CLI spawn args, so no passthrough).- */- model?: string;- /** Provider-supported per-turn reasoning effort override. */- reasoning_effort?: string;-};--export async function POST(request: Request) {- let body: ChatPostBody;- try {- body = (await request.json()) as ChatPostBody;- } catch {- return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });- }- if (!body?.message?.trim()) {- return NextResponse.json({ error: "message is required" }, { status: 400 });- }-- const project = body.project ? getProject(body.project) : await getActiveProject();- if (!project) {- return NextResponse.json(- { error: "No active project. Create one first." },- { status: 400 },- );- }-- const requestedSlug = (body.agent ?? "").trim();- if (!requestedSlug) {- return NextResponse.json({ error: "agent is required" }, { status: 400 });- }- const resolved = await resolveAgentBySlug(project.slug, requestedSlug);- if (!resolved) {- return NextResponse.json(- { error: `Unknown agent: '${requestedSlug}'` },- { status: 404 },- );- }-- // Whitelist the model against the adapter's provider-fed list — the- // value becomes a CLI spawn arg, so arbitrary client strings never- // pass through unchecked.- if (body.model !== undefined && typeof body.model !== "string") {- return NextResponse.json({ error: "model must be a string" }, { status: 400 });- }- if (- body.reasoning_effort !== undefined &&- typeof body.reasoning_effort !== "string"- ) {- return NextResponse.json(- { error: "reasoning_effort must be a string" },- { status: 400 },- );- }- const model = body.model?.trim() || null;- const reasoningEffort = body.reasoning_effort?.trim() || null;- if (model || reasoningEffort) {- const available = await requireAdapter(project.harness_adapter).listModels();- if (model && !available.some((m) => m.value === model)) {- return NextResponse.json(- { error: `Unknown model '${model}' for adapter '${project.harness_adapter}'` },- { status: 400 },- );- }- const selectedModel = model- ? available.find((option) => option.value === model)- : available.find((option) => option.is_default) ?? available[0];- if (- reasoningEffort &&- !selectedModel?.reasoning_efforts?.some(- (option) => option.value === reasoningEffort,- )- ) {- return NextResponse.json(- {- error: `Unknown reasoning effort '${reasoningEffort}' for model '${selectedModel?.value ?? "default"}'`,- },- { status: 400 },- );- }- }-- const label =- body.thread?.trim() || "main";- const session = getOrCreateSession({- project_slug: project.slug,- agent_id: resolved.agent_id,- label,- harness_adapter: project.harness_adapter,- });- appendTranscriptEvent(session.id, "user", { text: body.message });-- const adapter = requireAdapter(project.harness_adapter);- const encoder = new TextEncoder();-- const stream = new ReadableStream({- async start(controller) {- let clientOpen = true;- const send = (event: string, data: unknown) => {- if (!clientOpen) return;- try {- controller.enqueue(- encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`),- );- } catch {- clientOpen = false;- }- };-- // Disconnect != cancel: the harness keeps running and persisting- // events to the transcript; the user sees them on next attach. Only- // the explicit stop endpoint (POST /api/chat/stop) aborts this- // controller, which SIGTERMs the harness subprocess.- const ctrl = registerLiveTurn(session.id);-- try {- send("meta", {- project_slug: project.slug,- agent: resolved.agent_id,- session_id: session.id,- harness_adapter: project.harness_adapter,- message_chars: body.message.length,- });-- for await (const evt of adapter.execute({- projectSlug: project.slug,- agentId: resolved.agent_id,- workspaceDir: workspaceDirFor(resolved.agent_id),- message: body.message,- threadId: session.id,- harnessSessionId: session.harness_session_id,- model,- reasoningEffort,- signal: ctrl.signal,- })) {- if (evt.kind === "session") {- // Remember the harness's own session id so the next turn can- // pass it back via --resume / `exec resume`. Don't persist as- // a transcript event — it's metadata, not chat content.- touchSession(session.id, evt.harnessSessionId);- continue;- }- // A user-requested stop SIGTERMs the harness, which surfaces as a- // nonzero-exit error from the adapter. That's the stop working,- // not a failure — swallow it; the clean marker lands below.- if (evt.kind === "error" && ctrl.signal.aborted) continue;- try {- appendTranscriptEvent(session.id, evt.kind, evt);- } catch (err) {- console.error("[api/chat] transcript persist failed:", err);- }-- if (evt.kind === "delta") {- send("text", { chunk: evt.text });- } else if (evt.kind === "tool") {- send("tool", {- phase: evt.phase,- tool_call_id: evt.toolCallId,- name: evt.name,- label: evt.label,- });- } else if (evt.kind === "lifecycle") {- send("lifecycle", { phase: evt.phase });- } else if (evt.kind === "error") {- send("error", { message: evt.message });- }- }-- if (ctrl.signal.aborted) {- // Honest marker: the turn ended because the user stopped it, not- // because the agent finished. The done lifecycle ends the- // transcript's "still thinking" state for late attachers.- appendTranscriptEvent(session.id, "error", {- kind: "error",- message: "Stopped by user.",- });- appendTranscriptEvent(session.id, "lifecycle", {- kind: "lifecycle",- phase: "done",- });- }- touchSession(session.id);-- send("done", {});- } catch (err) {- const message = err instanceof Error ? err.message : String(err);- send("error", { message });- } finally {- releaseLiveTurn(session.id, ctrl);- try {- controller.close();- } catch {- // already closed- }- }- },- });-- return new Response(stream, {- headers: {- "Content-Type": "text/event-stream",- "Cache-Control": "no-cache",- Connection: "keep-alive",- },- });-}diff --git a/notfair/src/app/api/chat/stop/route.ts b/notfair/src/app/api/chat/stop/route.tsdeleted file mode 100644index 94fbc9b3..00000000--- a/notfair/src/app/api/chat/stop/route.ts+++ /dev/null@@ -1,50 +0,0 @@-import { NextResponse } from "next/server";-import { getActiveProject } from "@/server/active-project";-import { getProject } from "@/server/db/projects";-import { resolveAgentBySlug } from "@/server/agent-meta";-import { findSession } from "@/server/sessions";-import { stopLiveTurn } from "@/server/sessions/live-turns";--export const dynamic = "force-dynamic";-export const runtime = "nodejs";--type StopPostBody = {- agent?: string;- project?: string;- thread?: string;-};--/**- * The user's explicit stop click. Aborts the thread's in-flight chat turn- * server-side (SIGTERM to the harness subprocess) — unlike a client- * disconnect, which deliberately never cancels a running turn.- */-export async function POST(request: Request) {- let body: StopPostBody;- try {- body = (await request.json()) as StopPostBody;- } catch {- return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });- }-- const project = body.project ? getProject(body.project) : await getActiveProject();- if (!project) {- return NextResponse.json({ error: "No active project." }, { status: 400 });- }- const requestedSlug = (body.agent ?? "").trim();- if (!requestedSlug) {- return NextResponse.json({ error: "agent is required" }, { status: 400 });- }- const resolved = await resolveAgentBySlug(project.slug, requestedSlug);- if (!resolved) {- return NextResponse.json(- { error: `Unknown agent: '${requestedSlug}'` },- { status: 404 },- );- }-- const label = body.thread?.trim() || "main";- const session = findSession(project.slug, resolved.agent_id, label);- const stopped = session ? stopLiveTurn(session.id) : false;- return NextResponse.json({ stopped });-}diff --git a/notfair/src/app/api/fs/pick-folder/route.ts b/notfair/src/app/api/fs/pick-folder/route.tsdeleted file mode 100644index 5fb52a14..00000000--- a/notfair/src/app/api/fs/pick-folder/route.ts+++ /dev/null@@ -1,43 +0,0 @@-import { homedir } from "node:os";-import { NextResponse } from "next/server";-import { pickFolder } from "@/server/fs/pick-folder";--export const dynamic = "force-dynamic";-export const runtime = "nodejs";--/**- * Open the OS-native folder picker on the local machine and return the- * chosen absolute path. The client calls this once when the user clicks- * "Browse..." in the onboarding form — the dialog appears on the user's- * own screen because this server runs locally (loopback-only).- *- * Method: POST (state-changing in the sense that it spawns a UI dialog).- * No request body — the prompt/default location are baked in here so the- * surface stays minimal. Future extension can accept a JSON body.- */-export async function POST(_request: Request) {- const result = await pickFolder({- prompt: "Select your project's codebase folder",- defaultLocation: homedir(),- });- if (result.ok) {- return NextResponse.json({ ok: true, path: result.path });- }- if (result.kind === "cancelled") {- return NextResponse.json({ ok: false, kind: "cancelled" });- }- if (result.kind === "unsupported") {- return NextResponse.json(- {- ok: false,- kind: "unsupported",- message: `Native folder picker not implemented for ${result.platform}. Type the path manually for now.`,- },- { status: 501 },- );- }- return NextResponse.json(- { ok: false, kind: "error", message: result.message },- { status: 500 },- );-}diff --git a/notfair/src/app/api/mcp-oauth/callback/route.ts b/notfair/src/app/api/mcp-oauth/callback/route.tsdeleted file mode 100644index 533ab310..00000000--- a/notfair/src/app/api/mcp-oauth/callback/route.ts+++ /dev/null@@ -1,243 +0,0 @@-import { NextResponse } from "next/server";-import { consumePending } from "@/server/mcp-pending";-import { setMcpBearer } from "@/server/mcp/state";--export const dynamic = "force-dynamic";-export const runtime = "nodejs";--/**- * OAuth 2.0 redirect URI for the one-click MCP connect flow. The browser- * lands here after the user authorizes upstream. We look up the pending- * flow by `state`, exchange the code for an access token, write the- * harness MCP config, and bounce the user back to the- * agent's MCP tab.- *- * On failure we still redirect (so the browser doesn't end up on a raw- * JSON page); the destination carries `?mcp_error=…` for the page to- * surface. The pending entry is always consumed.- */-export async function GET(request: Request) {- const url = new URL(request.url);- const code = url.searchParams.get("code");- const state = url.searchParams.get("state");- const upstreamError = url.searchParams.get("error");-- if (!state) {- return htmlErrorPage("Missing state parameter; cannot resume the OAuth flow.");- }-- const pending = consumePending(state);- if (!pending) {- return htmlErrorPage("This authorization link has expired or was already used.");- }-- // The pending state may carry a `return_to` (e.g. the chat URL the user- // started from). Default to / so the root redirect bounces them to their- // active project's home if no caller asked for a specific destination.- // `return_to` is already sanitized in startMcpConnect to be a same-origin- // path; URL() with a base will additionally reject anything malformed.- const back = new URL(pending.return_to ?? "/", request.url);-- if (upstreamError) {- back.searchParams.set(- "mcp_error",- `Authorization rejected: ${upstreamError}`,- );- return NextResponse.redirect(back);- }- if (!code) {- back.searchParams.set("mcp_error", "Authorization callback returned no code.");- return NextResponse.redirect(back);- }-- // Token exchange. Send PKCE + (defensively) the secret. Servers that- // honor token_endpoint_auth_method=none ignore the secret; servers that- // require it still accept this request. Either way PKCE is validated.- const body = new URLSearchParams({- grant_type: "authorization_code",- code,- client_id: pending.client_id,- redirect_uri: pending.redirect_uri,- code_verifier: pending.code_verifier,- resource: pending.resource_url,- });- if (pending.client_secret) body.set("client_secret", pending.client_secret);-- let tokenEnvelope: {- access_token: string;- refresh_token?: string;- expires_in?: number;- scope?: string;- };- try {- const res = await fetch(pending.token_endpoint, {- method: "POST",- headers: {- "Content-Type": "application/x-www-form-urlencoded",- Accept: "application/json",- },- body: body.toString(),- });- const text = await res.text();- if (!res.ok) {- back.searchParams.set(- "mcp_error",- `Token exchange failed (HTTP ${res.status}): ${truncate(text, 200)}`,- );- return NextResponse.redirect(back);- }- const parsed = JSON.parse(text) as {- access_token?: string;- refresh_token?: string;- expires_in?: number;- scope?: string;- };- if (!parsed.access_token) {- back.searchParams.set("mcp_error", "Token endpoint returned no access_token.");- return NextResponse.redirect(back);- }- tokenEnvelope = {- access_token: parsed.access_token,- refresh_token: parsed.refresh_token,- expires_in: parsed.expires_in,- scope: parsed.scope,- };- } catch (err) {- back.searchParams.set(- "mcp_error",- `Token exchange error: ${err instanceof Error ? err.message : String(err)}`,- );- return NextResponse.redirect(back);- }-- // Compute absolute expiry only when the provider advertised expires_in.- // For providers that omit it (rare, but legal under RFC 6749), we leave- // expires_at NULL and rely on reactive refresh-on-401.- const expires_at =- typeof tokenEnvelope.expires_in === "number"- ? new Date(Date.now() + tokenEnvelope.expires_in * 1000).toISOString()- : undefined;-- try {- await setMcpBearer(- pending.project_slug,- pending.catalog_key,- tokenEnvelope.access_token,- {- refresh_token: tokenEnvelope.refresh_token,- expires_at,- scope: tokenEnvelope.scope,- // Stash everything the refresh helper needs so it can rotate the- // access token later without bouncing through consent again.- token_endpoint: pending.token_endpoint,- client_id: pending.client_id,- client_secret: pending.client_secret,- },- );- } catch (err) {- const raw = err instanceof Error ? err.message : String(err);- // Scrub bearers + any oat_ token shape before exposing in the URL —- // the redirect lands in browser history, server logs, and Referer- // headers on the destination page. Leaking the access token there- // would let any local-machine reader replay calls against the MCP.- const scrubbed = raw- .replace(/Bearer\s+[A-Za-z0-9._-]+/gi, "Bearer [redacted]")- .replace(/oat_[A-Za-z0-9_]+/gi, "oat_[redacted]");- back.searchParams.set("mcp_error", `Saving MCP config failed: ${scrubbed}`);- return NextResponse.redirect(back);- }-- // Wire the new token into every agent's harness config so running- // agents actually see the MCP tool surface. Without this step the- // Connections page reads "Connected" (because the probe finds the- // token) but Greg / Ana can't call any of the catalog's tools because- // the adapter config file was never updated.- try {- const { registerCatalogMcpForProject } = await import(- "@/server/mcp-server/registration"- );- const results = await registerCatalogMcpForProject(- pending.project_slug,- pending.catalog_key,- );- const failed = results.filter((r) => !r.ok);- if (failed.length > 0) {- console.warn(- `[mcp-oauth] ${failed.length}/${results.length} agents failed to register ${pending.catalog_key}:`,- failed.map((f) => (f.ok ? null : f.error)).filter(Boolean),- );- }- } catch (err) {- console.error("[mcp-oauth] registerCatalogMcpForProject threw:", err);- }-- // Kick off account analysis for platforms we can propose goals from.- // Fire-and-forget: the goals index shows the run's progress and the- // resulting suggestion cards.- try {- const { generateSuggestionsForSource, suggestionSourceLabel } = await import(- "@/server/suggestions/engine"- );- if (suggestionSourceLabel(pending.catalog_key)) {- void generateSuggestionsForSource(pending.project_slug, pending.catalog_key);- back.searchParams.set("mcp_analyzing", "1");- }- } catch (err) {- console.error("[mcp-oauth] suggestion generation kickoff failed:", err);- }-- // Multi-account MCPs (Google Ads, Meta Ads, GSC): resolve the workspace's- // account/property selection now, server-side. A still-valid existing- // selection is kept, a bearer with exactly one account is persisted- // silently, and only a genuine choice appends `mcp_key` — which makes the- // Connections page open the picker dialog on the matching card.- try {- const { resolvePostConnectSelection } = await import(- "@/server/mcp/account-selection"- );- const selection = await resolvePostConnectSelection(- pending.project_slug,- pending.catalog_key,- );- if (selection.kind === "choice_required") {- back.searchParams.set("mcp_key", pending.catalog_key);- }- } catch (err) {- console.error("[mcp-oauth] post-connect account resolution threw:", err);- const { accountPickerFor } = await import("@/lib/mcp-account-pickers");- if (accountPickerFor(pending.catalog_key)) {- back.searchParams.set("mcp_key", pending.catalog_key);- }- }-- // Flash banner uses the catalog name (what the user recognizes), not the- // project-prefixed server key.- back.searchParams.set("mcp_connected", pending.display_name);- return NextResponse.redirect(back);-}--function htmlErrorPage(message: string): Response {- // Shown only when we can't even resolve the pending flow, so we have no- // agent slug to redirect to. Bare minimal HTML — Tailwind isn't loaded.- const body = `<!doctype html><html><body style="font-family:system-ui;padding:2rem;max-width:36rem;margin:auto">-<h1 style="margin:0 0 1rem;font-size:1.25rem">Couldn’t complete MCP connection</h1>-<p style="color:#666">${escapeHtml(message)}</p>-<p style="margin-top:2rem"><a href="/">← Back to app</a></p>-</body></html>`;- return new Response(body, {- status: 400,- headers: { "Content-Type": "text/html; charset=utf-8" },- });-}--function escapeHtml(s: string): string {- return s- .replace(/&/g, "&")- .replace(/</g, "<")- .replace(/>/g, ">")- .replace(/"/g, """);-}--function truncate(s: string, n: number): string {- return s.length > n ? `${s.slice(0, n)}…` : s;-}diff --git a/notfair/src/app/api/mcp/browser/route.ts b/notfair/src/app/api/mcp/browser/route.tsdeleted file mode 100644index 407daea2..00000000--- a/notfair/src/app/api/mcp/browser/route.ts+++ /dev/null@@ -1,96 +0,0 @@-import { NextResponse } from "next/server";--import { BROWSER_TOOLS } from "@/server/mcp-server/browser-tools";-import { handleJsonRpc, type JsonRpcRequest } from "@/server/mcp-server/jsonrpc";-import { verifyMcpServerSecret } from "@/server/mcp-server/secret";--export const dynamic = "force-dynamic";-export const runtime = "nodejs";--/**- * Standalone MCP server for the workspace browser tools.- *- * Split out from notfair-goals so the goal-tool surface stays- * focused on task/approval/project tools, and so users can think about- * "the browser MCP" as its own thing in the Connections / Codex MCP list.- *- * Same transport (streamable-http, JSON-only) and same shared bearer as- * the goals MCP — single-user CLI on loopback so we don't need- * per-MCP secrets.- */--const SERVER_INFO = {- name: "notfair-browser",- version: "0.1.0",- tools: BROWSER_TOOLS,-};--function unauthorized(): Response {- return new NextResponse("Unauthorized", { status: 401 });-}--function bearerFrom(req: Request): string | null {- const header = req.headers.get("authorization") ?? req.headers.get("Authorization");- if (!header) return null;- const m = header.match(/^Bearer\s+(.+)$/i);- return m ? m[1]!.trim() : null;-}--export async function POST(req: Request): Promise<Response> {- const bearer = bearerFrom(req);- if (!verifyMcpServerSecret(bearer)) return unauthorized();-- let body: unknown;- try {- body = await req.json();- } catch {- return NextResponse.json(- {- jsonrpc: "2.0",- id: null,- error: { code: -32700, message: "Parse error" },- },- { status: 200 },- );- }-- if (Array.isArray(body)) {- return NextResponse.json(- {- jsonrpc: "2.0",- id: null,- error: {- code: -32600,- message: "Batched requests are not supported by this server.",- },- },- { status: 200 },- );- }-- const request = body as JsonRpcRequest;- if (!request || typeof request !== "object" || request.jsonrpc !== "2.0") {- return NextResponse.json(- {- jsonrpc: "2.0",- id: request?.id ?? null,- error: { code: -32600, message: "Invalid Request" },- },- { status: 200 },- );- }-- const response = await handleJsonRpc(request, SERVER_INFO);- if (response === null) {- return new Response(null, { status: 204 });- }- return NextResponse.json(response, { status: 200 });-}--export async function GET(): Promise<Response> {- return NextResponse.json({- name: SERVER_INFO.name,- transport: "streamable-http",- note: "POST JSON-RPC with Bearer auth. See ~/.notfair/mcp-server-secret.",- });-}diff --git a/notfair/src/app/api/mcp/goals/route.ts b/notfair/src/app/api/mcp/goals/route.tsdeleted file mode 100644index 8443a62b..00000000--- a/notfair/src/app/api/mcp/goals/route.ts+++ /dev/null@@ -1,104 +0,0 @@-import { NextResponse } from "next/server";--import { handleJsonRpc, type JsonRpcRequest } from "@/server/mcp-server/jsonrpc";-import { verifyMcpServerSecret } from "@/server/mcp-server/secret";-import { TOOLS } from "@/server/mcp-server/tools";--const SERVER_INFO = {- name: "notfair-goals",- version: "0.2.0",- tools: TOOLS,-};--export const dynamic = "force-dynamic";-export const runtime = "nodejs";--/**- * MCP server endpoint for goal agents (the notfair-goals server).- *- * Transport: streamable-http with single-shot JSON responses (no SSE; the- * goal tools are short-lived and don't stream). Clients accept- * either; plain JSON keeps the code small.- *- * Auth: shared secret in ~/.notfair/mcp-server-secret. Loopback-only +- * single-user CLI, so a shared bearer is sufficient. Agents pick up the- * secret written at agent-provision time.- */--function unauthorized(): Response {- return new NextResponse("Unauthorized", { status: 401 });-}--function bearerFrom(req: Request): string | null {- const header = req.headers.get("authorization") ?? req.headers.get("Authorization");- if (!header) return null;- const m = header.match(/^Bearer\s+(.+)$/i);- return m ? m[1]!.trim() : null;-}--export async function POST(req: Request): Promise<Response> {- const bearer = bearerFrom(req);- if (!verifyMcpServerSecret(bearer)) return unauthorized();-- let body: unknown;- try {- body = await req.json();- } catch {- return NextResponse.json(- {- jsonrpc: "2.0",- id: null,- error: { code: -32700, message: "Parse error" },- },- { status: 200 },- );- }-- // Batched calls are part of JSON-RPC but MCP's tool flow is one-at-a-time;- // we don't need to support arrays today. Reject explicitly so callers see- // a clean error rather than a silent miss.- if (Array.isArray(body)) {- return NextResponse.json(- {- jsonrpc: "2.0",- id: null,- error: {- code: -32600,- message: "Batched requests are not supported by this server.",- },- },- { status: 200 },- );- }-- const request = body as JsonRpcRequest;- if (!request || typeof request !== "object" || request.jsonrpc !== "2.0") {- return NextResponse.json(- {- jsonrpc: "2.0",- id: request?.id ?? null,- error: { code: -32600, message: "Invalid Request" },- },- { status: 200 },- );- }-- const response = await handleJsonRpc(request, SERVER_INFO);- if (response === null) {- // Notification — JSON-RPC mandates no body. Return 204 so the client- // doesn't try to parse anything.- return new Response(null, { status: 204 });- }- return NextResponse.json(response, { status: 200 });-}--export async function GET(): Promise<Response> {- // Some MCP clients ping with GET first to discover the endpoint. Return a- // tiny shape so they know this is an MCP HTTP server (without leaking the- // secret-check; auth still applies to POST).- return NextResponse.json({- name: SERVER_INFO.name,- transport: "streamable-http",- note: "POST JSON-RPC with Bearer auth. See ~/.notfair/mcp-server-secret.",- });-}diff --git a/notfair/src/app/api/remote-control/route.test.ts b/notfair/src/app/api/remote-control/route.test.tsdeleted file mode 100644index 8fabc504..00000000--- a/notfair/src/app/api/remote-control/route.test.ts+++ /dev/null@@ -1,91 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- getStatus: vi.fn(),- start: vi.fn(),- stop: vi.fn(),-}));--vi.mock("@/server/remote-control", () => ({- getRemoteControlStatus: mocks.getStatus,- startRemoteControl: mocks.start,- stopRemoteControl: mocks.stop,-}));--import { GET, POST } from "./route";--beforeEach(() => {- vi.clearAllMocks();-});--describe("/api/remote-control", () => {- it("returns the current uncached status", async () => {- mocks.getStatus.mockReturnValue({ status: "inactive" });-- const response = await GET();-- expect(response.status).toBe(200);- expect(response.headers.get("cache-control")).toBe("no-store");- await expect(response.json()).resolves.toEqual({ status: "inactive" });- });-- it("starts and stops remote control through explicit actions", async () => {- const active = {- status: "active",- public_url: "https://phone.trycloudflare.com",- access_url:- "https://phone.trycloudflare.com/#notfair-remote=private-token",- started_at: "2026-07-30T17:00:00.000Z",- };- mocks.start.mockResolvedValue(active);- mocks.stop.mockResolvedValue({ status: "inactive" });-- const startResponse = await POST(request({ action: "start" }));- expect(startResponse.status).toBe(200);- expect(mocks.start).toHaveBeenCalledOnce();- await expect(startResponse.json()).resolves.toEqual(active);-- const stopResponse = await POST(request({ action: "stop" }));- expect(stopResponse.status).toBe(200);- expect(mocks.stop).toHaveBeenCalledOnce();- await expect(stopResponse.json()).resolves.toEqual({ status: "inactive" });- });-- it("uses a server error status when tunnel startup fails", async () => {- mocks.start.mockResolvedValue({- status: "error",- error: "Cloudflare Tunnel is unavailable.",- });-- const response = await POST(request({ action: "start" }));-- expect(response.status).toBe(500);- await expect(response.json()).resolves.toEqual({- status: "error",- error: "Cloudflare Tunnel is unavailable.",- });- });-- it("rejects unknown and malformed actions without changing state", async () => {- const unknown = await POST(request({ action: "restart" }));- expect(unknown.status).toBe(400);-- const malformed = await POST(- new Request("http://localhost/api/remote-control", {- method: "POST",- body: "{",- }),- );- expect(malformed.status).toBe(400);- expect(mocks.start).not.toHaveBeenCalled();- expect(mocks.stop).not.toHaveBeenCalled();- });-});--function request(body: unknown): Request {- return new Request("http://localhost/api/remote-control", {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify(body),- });-}diff --git a/notfair/src/app/api/remote-control/route.ts b/notfair/src/app/api/remote-control/route.tsdeleted file mode 100644index fa6f0e3d..00000000--- a/notfair/src/app/api/remote-control/route.ts+++ /dev/null@@ -1,36 +0,0 @@-import { NextResponse } from "next/server";--import {- getRemoteControlStatus,- startRemoteControl,- stopRemoteControl,-} from "@/server/remote-control";--export const dynamic = "force-dynamic";-export const runtime = "nodejs";--export async function GET() {- return NextResponse.json(getRemoteControlStatus(), {- headers: { "cache-control": "no-store" },- });-}--export async function POST(req: Request) {- const body = (await req.json().catch(() => ({}))) as { action?: unknown };- if (body.action === "start") {- const status = await startRemoteControl();- return NextResponse.json(status, {- status: status.status === "error" ? 500 : 200,- headers: { "cache-control": "no-store" },- });- }- if (body.action === "stop") {- return NextResponse.json(await stopRemoteControl(), {- headers: { "cache-control": "no-store" },- });- }- return NextResponse.json(- { error: "action must be `start` or `stop`" },- { status: 400 },- );-}diff --git a/notfair/src/app/api/restart/route.test.ts b/notfair/src/app/api/restart/route.test.tsdeleted file mode 100644index 86ecb4d4..00000000--- a/notfair/src/app/api/restart/route.test.ts+++ /dev/null@@ -1,57 +0,0 @@-import { EventEmitter } from "node:events";-import { homedir } from "node:os";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- spawn: vi.fn(),-}));--vi.mock("node:child_process", () => ({ spawn: mocks.spawn }));--import { POST } from "./route";--function fakeChild() {- const child = new EventEmitter() as EventEmitter & {- stdout: EventEmitter;- };- child.stdout = new EventEmitter();- return child;-}--describe("POST /api/restart", () => {- const originalManaged = process.env.NOTFAIR_MANAGED;-- beforeEach(() => {- vi.clearAllMocks();- process.env.NOTFAIR_MANAGED = "daemon";- });-- afterEach(() => {- if (originalManaged === undefined) {- delete process.env.NOTFAIR_MANAGED;- } else {- process.env.NOTFAIR_MANAGED = originalManaged;- }- });-- it("looks up the global CLI from the stable home directory", async () => {- const child = fakeChild();- mocks.spawn.mockReturnValue(child);-- const responsePromise = POST();-- expect(mocks.spawn).toHaveBeenCalledWith(- "npm",- ["root", "-g"],- expect.objectContaining({ cwd: homedir() }),- );-- child.emit("close", 1);- const response = await responsePromise;- expect(response.status).toBe(409);- await expect(response.json()).resolves.toMatchObject({- ok: false,- error: "Could not locate the globally-installed notfair CLI.",- });- });-});diff --git a/notfair/src/app/api/restart/route.ts b/notfair/src/app/api/restart/route.tsdeleted file mode 100644index 2a92b205..00000000--- a/notfair/src/app/api/restart/route.ts+++ /dev/null@@ -1,111 +0,0 @@-import { spawn } from "node:child_process";-import { existsSync } from "node:fs";-import { homedir } from "node:os";-import { join } from "node:path";-import { NextResponse } from "next/server";--export const dynamic = "force-dynamic";-export const runtime = "nodejs";--/**- * POST /api/restart- *- * Restart the server so a just-installed upgrade actually loads. How- * depends on who supervises us (NOTFAIR_MANAGED, set by the CLI):- *- * - launchd: exit(0) — KeepAlive brings us straight back on the same- * plist, whose global-install path npm just updated in place.- * - daemon: no supervisor, so hand off to a detached waiter process that- * watches for our pid to die, then starts the freshly-installed CLI on- * the same port and data dir.- * - foreground/dev: refuse — killing the process under a user's terminal- * (or `pnpm dev`) is their call, not ours.- */-export async function POST() {- const managed = process.env.NOTFAIR_MANAGED ?? null;-- if (managed === "launchd") {- scheduleExit();- return NextResponse.json({ ok: true, note: "Restarting via launchd…" });- }-- if (managed === "daemon") {- const cli = await globalCliPath();- if (!cli) {- return NextResponse.json(- {- ok: false,- error: "Could not locate the globally-installed notfair CLI.",- hint: "Restart from your terminal: notfair stop && notfair start",- },- { status: 409 },- );- }- const port = process.env.PORT ?? "3327";- const dataDir = process.env.NOTFAIR_DATA_DIR ?? "";- // The waiter must outlive us and only bind the port once we're gone.- const waiter = `- const [pid, cli, port, dataDir] = process.argv.slice(1);- const deadline = Date.now() + 30000;- const timer = setInterval(() => {- let dead = false;- try { process.kill(Number(pid), 0); } catch { dead = true; }- if (!dead && Date.now() < deadline) return;- clearInterval(timer);- if (dead) {- const { spawn } = require("node:child_process");- const args = [cli, "start", "--no-open", "--port", port];- if (dataDir) args.push("--data-dir", dataDir);- spawn(process.execPath, args, { detached: true, stdio: "ignore" }).unref();- }- process.exit(0);- }, 300);- `;- spawn(- process.execPath,- ["-e", waiter, String(process.pid), cli, port, dataDir],- { cwd: homedir(), detached: true, stdio: "ignore" },- ).unref();- scheduleExit();- return NextResponse.json({ ok: true, note: "Restarting…" });- }-- return NextResponse.json(- {- ok: false,- error: `Not restartable from the app (mode: ${managed ?? "unknown"}).`,- hint: "Restart NotFair from the terminal that runs it.",- },- { status: 409 },- );-}--function scheduleExit() {- // Let the response flush before dying.- setTimeout(() => process.exit(0), 500).unref();-}--async function globalCliPath(): Promise<string | null> {- const root = await new Promise<string | null>((resolve) => {- let out = "";- let child;- try {- child = spawn("npm", ["root", "-g"], {- cwd: homedir(),- stdio: ["ignore", "pipe", "ignore"],- });- } catch {- resolve(null);- return;- }- child.stdout.on("data", (c) => {- out += c.toString();- });- child.on("error", () => resolve(null));- child.on("close", (code) => resolve(code === 0 ? out.trim() : null));- setTimeout(() => resolve(null), 10_000).unref();- });- if (!root) return null;- const cli = join(root, "notfair", "bin", "cli.mjs");- return existsSync(cli) ? cli : null;-}diff --git a/notfair/src/app/api/upgrade/route.test.ts b/notfair/src/app/api/upgrade/route.test.tsdeleted file mode 100644index deb936c1..00000000--- a/notfair/src/app/api/upgrade/route.test.ts+++ /dev/null@@ -1,173 +0,0 @@-import { EventEmitter } from "node:events";-import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";-import { homedir, tmpdir } from "node:os";-import { join } from "node:path";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- spawn: vi.fn(),-}));--vi.mock("node:child_process", () => ({ spawn: mocks.spawn }));-vi.mock("@/server/version", () => ({- _resetLatestCache: vi.fn(),- getCurrentVersion: vi.fn(() => "0.9.7"),- getLatestVersion: vi.fn(async () => "0.9.8"),- isSemverGreater: vi.fn(() => true),-}));--import { POST, syncInstalledNativeBindings } from "./route";--function fakeChild() {- const child = new EventEmitter() as EventEmitter & {- stdout: EventEmitter;- stderr: EventEmitter;- kill: ReturnType<typeof vi.fn>;- };- child.stdout = new EventEmitter();- child.stderr = new EventEmitter();- child.kill = vi.fn();- return child;-}--describe("POST /api/upgrade", () => {- let dataDir: string;- const originalDataDir = process.env.NOTFAIR_DATA_DIR;-- beforeEach(() => {- vi.clearAllMocks();- return mkdtemp(join(tmpdir(), "notfair-update-data-")).then((dir) => {- dataDir = dir;- process.env.NOTFAIR_DATA_DIR = dir;- });- });-- afterEach(async () => {- if (originalDataDir === undefined) delete process.env.NOTFAIR_DATA_DIR;- else process.env.NOTFAIR_DATA_DIR = originalDataDir;- await rm(dataDir, { recursive: true, force: true });- });-- it("downloads the package without modifying the installed version", async () => {- const child = fakeChild();- mocks.spawn.mockReturnValue(child);-- const responsePromise = POST();-- await vi.waitFor(() => {- expect(mocks.spawn).toHaveBeenCalledWith(- "npm",- [- "pack",- "[email protected]",- "--pack-destination",- join(dataDir, "updates", "0.9.8"),- "--silent",- ],- expect.objectContaining({ cwd: homedir() }),- );- });- expect(mocks.spawn).not.toHaveBeenCalledWith(- "npm",- expect.arrayContaining(["-g"]),- expect.anything(),- );-- await mkdir(join(dataDir, "updates", "0.9.8"), { recursive: true });- await writeFile(join(dataDir, "updates", "0.9.8", "notfair-0.9.8.tgz"), "package");- child.emit("exit", 0);- const response = await responsePromise;- expect(response.status).toBe(200);- await expect(response.json()).resolves.toMatchObject({- ok: true,- downloaded_version: "0.9.8",- });- });-- it("runs npm install only for an explicit apply action", async () => {- const updateDir = join(dataDir, "updates", "0.9.8");- const tarball = join(updateDir, "notfair-0.9.8.tgz");- await mkdir(updateDir, { recursive: true });- await writeFile(tarball, "package");- await writeFile(- join(dataDir, "updates", "pending.json"),- JSON.stringify({- version: "0.9.8",- tarball,- downloaded_at: new Date().toISOString(),- }),- );- const child = fakeChild();- mocks.spawn.mockReturnValue(child);-- const responsePromise = POST(- new Request("http://localhost/api/upgrade", {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify({ action: "apply" }),- }),- );-- await vi.waitFor(() => {- expect(mocks.spawn).toHaveBeenCalledWith(- "npm",- ["i", "-g", tarball],- expect.objectContaining({ cwd: homedir() }),- );- });- child.emit("exit", 7);- const response = await responsePromise;- expect(response.status).toBe(500);- await expect(response.json()).resolves.toMatchObject({- ok: false,- error: "npm install exited with code 7",- });- });-- it("replaces standalone native bindings with npm's runtime-compatible copy", async () => {- const packageRoot = await mkdtemp(join(tmpdir(), "notfair-upgrade-"));- const runtimeDir = join(packageRoot, "node_modules", "better-sqlite3", "build", "Release");- const tracedDir = join(- packageRoot,- ".next",- "standalone",- ".next",- "node_modules",- "better-sqlite3-build-copy",- "build",- "Release",- );- const nestedDir = join(- packageRoot,- ".next",- "standalone",- "node_modules",- "better-sqlite3",- "build",- "Release",- );-- try {- await Promise.all([- mkdir(runtimeDir, { recursive: true }),- mkdir(tracedDir, { recursive: true }),- mkdir(nestedDir, { recursive: true }),- ]);- await writeFile(join(runtimeDir, "better_sqlite3.node"), "node-25-binding");- await Promise.all([- writeFile(join(tracedDir, "better_sqlite3.node"), "node-24-binding"),- writeFile(join(nestedDir, "better_sqlite3.node"), "node-24-binding"),- ]);-- await expect(syncInstalledNativeBindings(packageRoot)).resolves.toBe(2);- await expect(readFile(join(tracedDir, "better_sqlite3.node"), "utf8")).resolves.toBe(- "node-25-binding",- );- await expect(readFile(join(nestedDir, "better_sqlite3.node"), "utf8")).resolves.toBe(- "node-25-binding",- );- } finally {- await rm(packageRoot, { recursive: true, force: true });- }- });-});diff --git a/notfair/src/app/api/upgrade/route.ts b/notfair/src/app/api/upgrade/route.tsdeleted file mode 100644index 02500089..00000000--- a/notfair/src/app/api/upgrade/route.ts+++ /dev/null@@ -1,369 +0,0 @@-import { spawn } from "node:child_process";-import { copyFile, mkdir, readFile, readdir, rename, stat, writeFile } from "node:fs/promises";-import { homedir } from "node:os";-import { dirname, join, resolve } from "node:path";-import { NextResponse } from "next/server";--import {- _resetLatestCache,- getCurrentVersion,- getLatestVersion,- isSemverGreater,-} from "@/server/version";--export const dynamic = "force-dynamic";-export const runtime = "nodejs";--const UPGRADE_TIMEOUT_MS = 5 * 60 * 1000;-const TAIL_BYTES = 4_000;-const VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;--type UpgradeAction = "prepare" | "apply";--type PendingUpdate = {- version: string;- tarball: string;- downloaded_at: string;-};--type CommandResult = {- code: number | null;- elapsed_ms: number;- stdout: string;- stderr: string;- spawn_error?: string;-};--/**- * POST /api/upgrade- *- * `prepare` is intentionally download-only: it asks npm to pack the exact- * registry version into NotFair's data directory and records the staged- * tarball. It never changes the running installation.- *- * `apply` is only sent after the user clicks Update. It installs that exact- * staged tarball globally. The client immediately follows a successful apply- * with /api/restart when NotFair owns its background process.- */-export async function POST(request?: Request) {- const action = await requestedAction(request);- if (!action) {- return NextResponse.json(- { ok: false, error: "Unknown upgrade action." },- { status: 400 },- );- }- return action === "apply" ? applyUpdate() : prepareUpdate();-}--async function requestedAction(request?: Request): Promise<UpgradeAction | null> {- if (!request) return "prepare";- try {- const body = (await request.json()) as { action?: unknown };- if (body.action === undefined || body.action === "prepare") return "prepare";- if (body.action === "apply") return "apply";- return null;- } catch {- return "prepare";- }-}--async function prepareUpdate(): Promise<Response> {- const latest = await getLatestVersion(true);- const current = getCurrentVersion();- if (!latest) {- return NextResponse.json(- { ok: false, error: "Could not reach the npm registry." },- { status: 503 },- );- }- if (!VERSION_PATTERN.test(latest)) {- return NextResponse.json(- { ok: false, error: "The npm registry returned an invalid version." },- { status: 502 },- );- }- if (!isSemverGreater(latest, current)) {- return NextResponse.json({- ok: true,- downloaded_version: latest,- running_version: current,- already_current: true,- });- }-- const tarball = stagedTarballPath(latest);- const existing = await isFile(tarball);- if (!existing) {- await mkdir(dirname(tarball), { recursive: true });- const result = await runNpm([- "pack",- `notfair@${latest}`,- "--pack-destination",- dirname(tarball),- "--silent",- ]);- if (result.spawn_error) {- return npmUnavailableResponse(result.spawn_error, "download");- }- if (result.code !== 0 || !(await isFile(tarball))) {- return npmFailureResponse(result, "download", latest);- }- }-- await writePendingUpdate({- version: latest,- tarball,- downloaded_at: new Date().toISOString(),- });-- return NextResponse.json({- ok: true,- downloaded_version: latest,- running_version: current,- note: `v${latest} downloaded and ready to install.`,- });-}--async function applyUpdate(): Promise<Response> {- const pending = await readPendingUpdate();- if (!pending || !(await isFile(pending.tarball))) {- return NextResponse.json(- {- ok: false,- error: "The downloaded update is missing. Download it again before applying.",- },- { status: 409 },- );- }-- const result = await runNpm(["i", "-g", pending.tarball]);- if (result.spawn_error) {- return npmUnavailableResponse(result.spawn_error, "install", pending.version);- }- if (result.code !== 0) {- return npmFailureResponse(result, "install", pending.version);- }-- try {- await syncGlobalNativeBindings();- } catch (error) {- return NextResponse.json(- {- ok: false,- error:- "NotFair was installed, but its native database module could not be prepared for this Node.js version.",- hint: error instanceof Error ? error.message : String(error),- command: `npm i -g notfair@${pending.version}`,- },- { status: 500 },- );- }-- _resetLatestCache();- const managed = process.env.NOTFAIR_MANAGED ?? null;- const canRestart = managed === "launchd" || managed === "daemon";- return NextResponse.json({- ok: true,- installed_version: pending.version,- running_version: getCurrentVersion(),- can_restart: canRestart,- note: canRestart- ? "Installed — restarting loads the new version."- : "Installed. Restart NotFair to load the new version (`notfair` in your terminal).",- elapsed_ms: result.elapsed_ms,- stdout_tail: result.stdout.slice(-1000),- });-}--function updateRoot(): string {- const dataDir = process.env.NOTFAIR_DATA_DIR ?? join(homedir(), ".notfair");- return resolve(dataDir, "updates");-}--function stagedTarballPath(version: string): string {- return join(updateRoot(), version, `notfair-${version}.tgz`);-}--function pendingUpdatePath(): string {- return join(updateRoot(), "pending.json");-}--async function writePendingUpdate(update: PendingUpdate): Promise<void> {- const target = pendingUpdatePath();- const temporary = `${target}.${process.pid}.tmp`;- await mkdir(dirname(target), { recursive: true });- await writeFile(temporary, `${JSON.stringify(update)}\n`, { mode: 0o600 });- await rename(temporary, target);-}--async function readPendingUpdate(): Promise<PendingUpdate | null> {- try {- const parsed = JSON.parse(await readFile(pendingUpdatePath(), "utf8")) as Partial<PendingUpdate>;- if (- typeof parsed.version !== "string" ||- !VERSION_PATTERN.test(parsed.version) ||- typeof parsed.tarball !== "string" ||- typeof parsed.downloaded_at !== "string"- ) {- return null;- }- const expected = stagedTarballPath(parsed.version);- if (resolve(parsed.tarball) !== resolve(expected)) return null;- return parsed as PendingUpdate;- } catch {- return null;- }-}--async function isFile(path: string): Promise<boolean> {- try {- return (await stat(path)).isFile();- } catch {- return false;- }-}--function runNpm(args: string[]): Promise<CommandResult> {- // A running standalone bundle can be replaced by a source rebuild or an- // explicit install. Never inherit a now-missing server working directory:- // npm aborts in process.cwd() with ENOENT (exit code 7) before doing work.- return new Promise((resolveCommand) => {- const startedAt = Date.now();- let stdout = "";- let stderr = "";- let settled = false;- let child;- try {- child = spawn("npm", args, {- stdio: ["ignore", "pipe", "pipe"],- env: process.env,- cwd: homedir(),- });- } catch (error) {- resolveCommand({- code: null,- elapsed_ms: Date.now() - startedAt,- stdout,- stderr,- spawn_error: error instanceof Error ? error.message : String(error),- });- return;- }-- const append = (target: "out" | "err") => (chunk: Buffer) => {- const text = chunk.toString("utf8");- if (target === "out") stdout = (stdout + text).slice(-TAIL_BYTES);- else stderr = (stderr + text).slice(-TAIL_BYTES);- };- child.stdout?.on("data", append("out"));- child.stderr?.on("data", append("err"));-- const finish = (result: CommandResult) => {- if (settled) return;- settled = true;- clearTimeout(killTimer);- resolveCommand(result);- };- const killTimer = setTimeout(() => {- try {- child.kill("SIGTERM");- } catch {- // best-effort- }- }, UPGRADE_TIMEOUT_MS);-- child.on("error", (error) => {- finish({- code: null,- elapsed_ms: Date.now() - startedAt,- stdout,- stderr,- spawn_error: error.message,- });- });- child.on("exit", (code) => {- finish({ code, elapsed_ms: Date.now() - startedAt, stdout, stderr });- });- });-}--function npmUnavailableResponse(error: string, operation: "download" | "install", version?: string) {- const command = version ? `npm i -g notfair@${version}` : "npm i -g notfair@latest";- return NextResponse.json(- {- ok: false,- error,- hint: `Could not run npm to ${operation} the update. Run \`${command}\` in your terminal instead.`,- command,- },- { status: 500 },- );-}--function npmFailureResponse(- result: CommandResult,- operation: "download" | "install",- version: string,-) {- return NextResponse.json(- {- ok: false,- error: `npm ${operation} exited with code ${result.code}`,- elapsed_ms: result.elapsed_ms,- stdout_tail: result.stdout.slice(-1000),- stderr_tail: result.stderr.slice(-1000),- command: `npm i -g notfair@${version}`,- },- { status: 500 },- );-}--async function syncGlobalNativeBindings() {- const root = await npmGlobalRoot();- await syncInstalledNativeBindings(join(root, "notfair"));-}--async function npmGlobalRoot(): Promise<string> {- const result = await runNpm(["root", "-g"]);- const root = result.stdout.trim();- if (result.code === 0 && root) return root;- throw new Error(`Could not locate npm's global package directory (exit ${result.code}).`);-}--/**- * Next.js standalone output contains a traced copy of better-sqlite3. That- * copy was compiled on the release builder, while npm installs the package's- * top-level dependency for the user's current Node ABI. Replace every traced- * native binding with that runtime-correct copy before restarting the server.- */-export async function syncInstalledNativeBindings(packageRoot: string) {- const runtimeBinding = join(- packageRoot,- "node_modules",- "better-sqlite3",- "build",- "Release",- "better_sqlite3.node",- );- const standaloneRoot = join(packageRoot, ".next", "standalone");- const targets = await findNativeBindings(standaloneRoot);-- if (targets.length === 0) return 0;-- await Promise.all(targets.map((target) => copyFile(runtimeBinding, target)));- return targets.length;-}--async function findNativeBindings(directory: string): Promise<string[]> {- const entries = await readdir(directory, { withFileTypes: true });- const nested = await Promise.all(- entries.map(async (entry): Promise<string[]> => {- const path = join(directory, entry.name);- if (entry.isDirectory()) return findNativeBindings(path);- if (entry.isFile() && entry.name === "better_sqlite3.node") return [path];- return [];- }),- );- return nested.flat();-}diff --git a/notfair/src/app/api/version/route.ts b/notfair/src/app/api/version/route.tsdeleted file mode 100644index 9703ec28..00000000--- a/notfair/src/app/api/version/route.ts+++ /dev/null@@ -1,19 +0,0 @@-import { NextResponse } from "next/server";--import { getVersionStatus } from "@/server/version";--export const dynamic = "force-dynamic";-export const runtime = "nodejs";--/**- * GET /api/version- *- * Returns the installed NotFair version + the latest version on npm- * + whether an update is available. The sidebar polls this once on mount;- * the latest-version lookup is cached for 1 hour in-process so this is- * cheap to call.- */-export async function GET() {- const status = await getVersionStatus();- return NextResponse.json(status);-}diff --git a/notfair/src/app/globals.css b/notfair/src/app/globals.cssdeleted file mode 100644index 057e77d5..00000000--- a/notfair/src/app/globals.css+++ /dev/null@@ -1,1032 +0,0 @@-@import "tailwindcss";--@custom-variant dark (&:is(.dark *));--@layer base {- :root {- /* ── NotFair design system (see DESIGN.md) ───────────────────- Codex-flavored monochrome chrome, dark-first with a light mode.- Depth comes from elevation (surface steps + soft shadows), not- border lines. Color is reserved for semantics: green = live/- connected, amber = attention, red = error. Primary actions are- inverted (black-on-light / white-on-dark).-- shadcn primitives are mapped onto these tokens so existing- Card/Button/etc. components inherit the system automatically. */-- /* surfaces */- --background: 240 7% 97%; /* #F7F7F8 */- --foreground: 240 7% 8%; /* #131316 */- --card: 0 0% 100%;- --card-foreground: 240 7% 8%;- --popover: 0 0% 100%;- --popover-foreground: 240 7% 8%;-- /* primary CTA — inverted monochrome (Codex signature) */- --primary: 240 7% 8%; /* #131316 */- --primary-foreground: 0 0% 100%;-- /* secondary surface (used by Button variant=secondary, etc.) */- --secondary: 240 4% 94%; /* #F0F0F1 */- --secondary-foreground: 240 7% 8%;-- /* muted text + surfaces */- --muted: 240 4% 94%;- --muted-foreground: 240 3% 54%; /* #85858C */-- /* shadcn "accent" surface (hover bg on dropdowns, etc.) — NOT the- brand accent. Keep neutral so brand green stays uncrowded. */- --accent: 240 4% 94%;- --accent-foreground: 240 7% 8%;-- --destructive: 0 72% 51%;- --destructive-foreground: 0 0% 100%;-- --border: 240 5% 90%;- --input: 240 4% 94%;- --ring: 240 3% 54%; /* neutral focus ring */-- --radius: 0.625rem; /* 10px — between sm and md per DESIGN.md */-- /* ── DESIGN.md tokens (non-shadcn) ───────────────────────────────- Use these directly in custom components when the shadcn mapping- above isn't expressive enough. Comment names match DESIGN.md. */- --notfair-ink: 240 7% 8%; /* #131316 — primary text */- --notfair-ink-2: 240 4% 18%; /* #2C2C30 — strong body */- --notfair-ink-3: 240 3% 35%; /* #55555B — body text */- --notfair-ink-4: 240 3% 54%; /* #85858C — labels, support */- --notfair-surface-2: 240 4% 94%; /* #F0F0F1 — inset / glyph bg */- --notfair-sidebar: 240 3% 94%; /* #EFEFF0 — sidebar rail */- --notfair-hover: 240 4% 96%; /* row hover wash */- --notfair-border-strong: 240 4% 82%;- /* Inverted primary action (Codex CTA) */- --notfair-cta: 240 7% 8%; /* #131316 */- --notfair-cta-text: 0 0% 100%;- /* NotFair green — semantic "live/connected" only, never chrome */- --notfair-accent: 138 43% 43%; /* #3F9E60 (darker for light bg) */- --notfair-accent-soft: 138 31% 94%;- --notfair-accent-border: 137 35% 75%;- --notfair-warn: 39 76% 38%; /* amber text */- --notfair-warn-soft: 39 70% 94%; /* amber wash */-- /* Elevation — layered soft shadows, no rings. */- --notfair-shadow-sm: 0 1px 2px rgba(0,0,0,.04), 0 2px 6px rgba(0,0,0,.04);- --notfair-shadow: 0 1px 2px rgba(0,0,0,.05), 0 3px 10px rgba(0,0,0,.06);- --notfair-shadow-lg: 0 2px 4px rgba(0,0,0,.06), 0 20px 50px -12px rgba(0,0,0,.16);- }-- .dark {- /* Codex dark: content #161618, sidebar darker, cards a step- lighter than content so elevation reads without borders. */- --background: 240 4% 9%; /* #161618 */- --foreground: 240 6% 93%; /* #ECECEE */- --card: 240 6% 13%; /* #202024 */- --card-foreground: 240 6% 93%;- --popover: 240 6% 13%;- --popover-foreground: 240 6% 93%;- --primary: 0 0% 93%; /* inverted: white CTA */- --primary-foreground: 240 6% 7%;- --secondary: 240 5% 16%; /* #26262A */- --secondary-foreground: 240 6% 93%;- --muted: 240 5% 16%;- --muted-foreground: 240 3% 48%; /* #77777E */- --accent: 240 5% 16%;- --accent-foreground: 240 6% 93%;- --destructive: 0 62% 52%;- --destructive-foreground: 0 0% 98%;- --border: 240 5% 18%;- --input: 240 5% 16%;- --ring: 240 4% 60%;-- --notfair-ink: 240 6% 93%; /* #ECECEE */- --notfair-ink-2: 240 4% 85%; /* #D6D6DA */- --notfair-ink-3: 240 4% 67%; /* #A6A6AD */- --notfair-ink-4: 240 3% 48%; /* #77777E */- --notfair-surface-2: 240 5% 16%; /* #26262A */- --notfair-sidebar: 240 3% 6%; /* #0F0F10 */- --notfair-hover: 240 5% 15%;- --notfair-border-strong: 240 4% 30%;- --notfair-cta: 0 0% 93%; /* #ECECEC */- --notfair-cta-text: 240 6% 7%; /* #101012 */- --notfair-accent: 138 39% 49%; /* #4CAF6E */- --notfair-accent-soft: 138 24% 14%; /* dark green-tinted well */- --notfair-accent-border: 138 30% 32%;- --notfair-warn: 39 65% 55%; /* #D9A13F */- --notfair-warn-soft: 39 45% 14%;-- /* Dark elevation: stronger shadows; the lighter card surface does- half the work. */- --notfair-shadow-sm: 0 1px 2px rgba(0,0,0,.40), 0 2px 6px rgba(0,0,0,.24);- --notfair-shadow: 0 1px 2px rgba(0,0,0,.45), 0 3px 10px rgba(0,0,0,.30);- --notfair-shadow-lg: 0 2px 4px rgba(0,0,0,.5), 0 20px 50px -12px rgba(0,0,0,.55);- }-}--@theme inline {- --color-background: hsl(var(--background));- --color-foreground: hsl(var(--foreground));- --color-card: hsl(var(--card));- --color-card-foreground: hsl(var(--card-foreground));- --color-popover: hsl(var(--popover));- --color-popover-foreground: hsl(var(--popover-foreground));- --color-primary: hsl(var(--primary));- --color-primary-foreground: hsl(var(--primary-foreground));- --color-secondary: hsl(var(--secondary));- --color-secondary-foreground: hsl(var(--secondary-foreground));- --color-muted: hsl(var(--muted));- --color-muted-foreground: hsl(var(--muted-foreground));- --color-accent: hsl(var(--accent));- --color-accent-foreground: hsl(var(--accent-foreground));- --color-destructive: hsl(var(--destructive));- --color-destructive-foreground: hsl(var(--destructive-foreground));- --color-border: hsl(var(--border));- --color-input: hsl(var(--input));- --color-ring: hsl(var(--ring));- --radius-lg: var(--radius);- --radius-md: calc(var(--radius) - 2px);- --radius-sm: calc(var(--radius) - 4px);- --color-sidebar-ring: var(--sidebar-ring);- --color-sidebar-border: var(--sidebar-border);- --color-sidebar-accent-foreground: var(--sidebar-accent-foreground);- --color-sidebar-accent: var(--sidebar-accent);- --color-sidebar-primary-foreground: var(--sidebar-primary-foreground);- --color-sidebar-primary: var(--sidebar-primary);- --color-sidebar-foreground: var(--sidebar-foreground);- --color-sidebar: var(--sidebar);-}--@layer base {- * {- border-color: hsl(var(--border));- }- html, body {- /* SF Pro via system stack on Apple platforms, Inter elsewhere.- See DESIGN.md → Typography. */- font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Text',- 'SF Pro Display', 'Inter', ui-sans-serif, system-ui, sans-serif;- -webkit-font-smoothing: antialiased;- -moz-osx-font-smoothing: grayscale;- text-rendering: optimizeLegibility;- /* Codex: near-neutral tracking (Apple-tight was -0.01em) */- letter-spacing: -0.006em;- }-}--/* ────────────────────────────────────────────────────────────────────- WorkingIndicator animations.-- Four custom keyframes drive the live "agent is working" card in the- chat. Each is intentionally narrow in scope so the indicator reads- as one coordinated piece rather than a jittery collection of- independent loops.-- - aurora-sweep: thin gradient bar travels L→R across the top edge.- Establishes "alive" without taking attention. Slow.- - shimmer-bar: identical pattern at the bottom edge, slightly- faster + thinner, creates a sense of forward motion- when the model is between events.- - heartbeat: two-stage scale on the mood dot — a quick squeeze- followed by a soft swell, ~1.4s cycle. Reads as- a living pulse rather than a steady spinner.- - phase-glow: subtle glow + lift on the currently-active phase- chip. Repeats at 2s so it's clearly the active one.- ──────────────────────────────────────────────────────────────────── */--@keyframes aurora-sweep {- 0% { transform: translateX(-110%); opacity: 0.4; }- 50% { opacity: 1; }- 100% { transform: translateX(220%); opacity: 0.4; }-}--@keyframes shimmer-bar {- 0% { transform: translateX(-120%); }- 100% { transform: translateX(260%); }-}--@keyframes ns-text-shimmer {- 0% { background-position: 180% 0; }- 100% { background-position: -180% 0; }-}--@keyframes heartbeat {- 0%, 100% { transform: scale(0.92); opacity: 0.85; }- 20% { transform: scale(1.18); opacity: 1; }- 35% { transform: scale(0.96); opacity: 0.9; }- 60% { transform: scale(1.08); opacity: 1; }-}--@keyframes phase-glow {- 0%, 100% { box-shadow: 0 0 0 0 currentColor; }- 50% { box-shadow: 0 0 0 4px transparent; }-}--@keyframes ns-celebration-pop {- 0% { transform: scale(0.5) rotate(-10deg); opacity: 0; }- 62% { transform: scale(1.12) rotate(3deg); opacity: 1; }- 100% { transform: scale(1) rotate(0); opacity: 1; }-}--@keyframes ns-celebration-ring {- 0% { transform: scale(0.7); opacity: 0; }- 42% { opacity: 0.7; }- 100% { transform: scale(1.3); opacity: 0; }-}--@keyframes ns-confetti-burst {- 0% {- opacity: 0;- transform: translate(-50%, -50%) rotate(var(--angle)) translateY(0) scale(0.35);- }- 18% { opacity: 1; }- 100% {- opacity: 0;- transform: translate(-50%, -50%) rotate(var(--angle)) translateY(var(--distance)) scale(1);- }-}--@keyframes ns-completed-badge-arrive {- 0% { transform: translateY(2px) scale(0.78); opacity: 0; }- 58% { transform: translateY(-1px) scale(1.07); opacity: 1; }- 100% { transform: translateY(0) scale(1); opacity: 1; }-}--@theme inline {- --animate-aurora-sweep: aurora-sweep 2.6s linear infinite;- --animate-shimmer-bar: shimmer-bar 1.8s ease-in-out infinite;- --animate-heartbeat: heartbeat 1.4s ease-in-out infinite;- --animate-phase-glow: phase-glow 2s ease-in-out infinite;-}--@layer components {-.ns-completed-badge {- animation: ns-completed-badge-arrive 0.7s cubic-bezier(.22, .9, .25, 1.15) both;-}--.ns-celebration-stage {- position: relative;- min-height: 256px;- overflow: hidden;- display: flex;- flex-direction: column;- align-items: center;- justify-content: center;- padding: 32px 16px 14px;- background:- radial-gradient(circle at 50% 35%, hsl(var(--notfair-accent-soft)) 0, transparent 43%),- linear-gradient(180deg, hsl(var(--card)), hsl(var(--card)));-}--.ns-celebration-halo {- position: absolute;- top: 29px;- left: 50%;- width: 124px;- height: 124px;- margin-left: -62px;- border: 1px solid hsl(var(--notfair-accent-border));- border-radius: 999px;- animation: ns-celebration-ring 1.15s ease-out 0.15s both;-}--.ns-celebration-medal {- position: relative;- z-index: 2;- display: grid;- place-items: center;- width: 76px;- height: 76px;- margin-bottom: 18px;- border-radius: 23px;- color: white;- background: linear-gradient(145deg, #55b875, #328f55);- box-shadow:- 0 16px 38px -14px rgba(63, 158, 96, 0.72),- inset 0 1px 0 rgba(255, 255, 255, 0.32);- animation: ns-celebration-pop 0.65s cubic-bezier(.22, .9, .25, 1.2) both;-}--.ns-celebration-medal > svg {- width: 34px;- height: 34px;- stroke-width: 1.8;-}--.ns-celebration-medal > span {- position: absolute;- right: -6px;- bottom: -5px;- display: grid;- place-items: center;- width: 26px;- height: 26px;- border: 3px solid hsl(var(--card));- border-radius: 999px;- color: #277b45;- background: white;-}--.ns-celebration-medal > span svg {- width: 13px;- height: 13px;- stroke-width: 3;-}--.ns-celebration-confetti {- position: absolute;- top: 71px;- left: 50%;- width: 1px;- height: 1px;-}--.ns-celebration-confetti > span {- --distance: 100px;- position: absolute;- top: 0;- left: 0;- width: 7px;- height: 3px;- border-radius: 2px;- background: var(--piece-color);- opacity: 0;- animation: ns-confetti-burst 0.9s cubic-bezier(.16, .75, .28, 1) var(--delay) both;-}--@media (prefers-reduced-motion: reduce) {- .ns-completed-badge,- .ns-celebration-halo,- .ns-celebration-medal,- .ns-celebration-confetti > span {- animation: none;- }- .ns-celebration-confetti { display: none; }-}-}--:root {- --sidebar: hsl(var(--notfair-sidebar));- --sidebar-foreground: hsl(var(--notfair-ink-3));- --sidebar-primary: hsl(var(--notfair-cta));- --sidebar-primary-foreground: hsl(var(--notfair-cta-text));- --sidebar-accent: hsl(var(--notfair-surface-2));- --sidebar-accent-foreground: hsl(var(--notfair-ink));- --sidebar-border: transparent;- --sidebar-ring: hsl(var(--ring));-}--/* ────────────────────────────────────────────────────────────────────- NotFair design-system component classes.-- These are the named building blocks called out in DESIGN.md so- onboarding (and later, every other surface) can compose them- directly. Naming convention: `.ns-*` ("notfair system") to keep- them visually distinct from generic Tailwind utilities and from- shadcn primitives.- ──────────────────────────────────────────────────────────────────── */--@layer components {- /* Page container — compact: fits a standard 720–800px viewport without- scrolling so the Skip / Continue button is always visible. */- .ns-page { @apply mx-auto w-full max-w-[720px] px-6 pt-6 pb-10; }-- /* Hero — tightened from 56px to 34px so headline + sub + content +- footer all fit in one viewport. Still confident, just less luxurious. */- .ns-hero-title {- @apply text-foreground;- font-size: 30px; line-height: 1.1; letter-spacing: -0.022em;- font-weight: 600; margin: 0 0 8px;- }- .ns-hero-sub {- color: hsl(var(--notfair-ink-3));- font-size: 15px; line-height: 1.45; letter-spacing: -0.008em;- max-width: 560px; margin: 0;- }- .ns-hero-sub b { color: hsl(var(--notfair-ink)); font-weight: 500; }-- /* Section heading — quiet H2 above a grouped list. */- .ns-section-head {- @apply flex items-baseline justify-between gap-3;- margin-top: 24px;- }- .ns-section-head > :first-child {- @apply text-foreground;- font-size: 14px; font-weight: 600; letter-spacing: -0.012em;- }- .ns-section-head > :last-child {- color: hsl(var(--notfair-ink-4));- font-size: 12px; font-weight: 500; letter-spacing: -0.005em;- }-- /* Grouped list — separated elevated cards, no divider lines.- Each direct child (usually an `<li>`) becomes its own raised- surface; depth does the separating work borders used to do. */- .ns-list {- @apply flex flex-col;- gap: 9px;- margin-top: 20px;- }- .ns-list > * {- @apply bg-card overflow-hidden;- border-radius: 12px;- box-shadow: var(--notfair-shadow);- }- .ns-tile {- @apply flex items-center gap-3 border-0 cursor-pointer transition-colors;- background: transparent;- padding: 12px 16px;- text-align: left;- width: 100%;- }- .ns-tile:hover { background: hsl(var(--notfair-hover)); }- /* [aria-disabled] variant: the connect tile is a div[role=button] now- (a real <button> can't legally contain the "Select account"- sub-action button), so :disabled never matches it. */- .ns-tile:disabled, .ns-tile[aria-disabled="true"] { cursor: not-allowed; opacity: 0.6; }- .ns-tile-glyph {- @apply grid place-items-center flex-shrink-0 font-semibold uppercase;- width: 32px; height: 32px; border-radius: 8px;- background: hsl(var(--notfair-surface-2));- color: hsl(var(--notfair-ink-2));- font-size: 14px; letter-spacing: -0.018em;- }- .ns-tile-body { @apply flex-1 min-w-0; }- /* Title row hosts the MCP name + the "Required for X agent" badge so- they sit on the same baseline. Wraps to a new line on narrow tiles. */- .ns-tile-name-row {- @apply flex flex-wrap items-baseline gap-x-2 gap-y-1;- margin: 0;- }- .ns-tile-name {- @apply text-foreground m-0;- font-weight: 500; font-size: 14.5px; letter-spacing: -0.012em;- line-height: 1.3;- }- /* "Required for X agent" badge — quiet inset chip that makes the- MCP↔agent dependency visible at a glance. Monochrome; green is- reserved for live/connected status. */- .ns-tile-badge {- display: inline-flex; align-items: center;- font-size: 10.5px; font-weight: 500; letter-spacing: 0;- line-height: 1; padding: 3.5px 9px; border-radius: 999px;- background: hsl(var(--notfair-surface-2));- color: hsl(var(--notfair-ink-4));- white-space: nowrap;- }- .ns-tile-desc {- color: hsl(var(--notfair-ink-4));- font-size: 12.5px; line-height: 1.35; letter-spacing: -0.003em;- margin: 1px 0 0;- }- .ns-tile-status {- @apply flex flex-col items-end flex-shrink-0;- gap: 4px;- color: hsl(var(--notfair-ink-4));- font-size: 12.5px; font-weight: 500; letter-spacing: -0.005em;- }- .ns-tile-status .arrow { font-size: 16px; font-weight: 300; line-height: 1; }-- /* "Connected" indicator — small dot + word in accent green. */- .ns-status-connected {- color: hsl(var(--notfair-accent));- font-weight: 500; font-size: 12.5px; letter-spacing: -0.005em;- display: inline-flex; align-items: center; gap: 6px;- }- .ns-status-connected::before {- content: ""; display: inline-block; width: 6px; height: 6px;- border-radius: 50%; background: hsl(var(--notfair-accent));- }-- /* Connected tile — green-tinted glyph well (semantic accent). */- .ns-tile.is-connected .ns-tile-glyph {- background: hsl(var(--notfair-accent-soft));- color: hsl(var(--notfair-accent));- }-- /* Sub-action — quiet text link with chevron. Ink, not green:- green is status-only in the Codex system. */- .ns-subaction {- @apply inline-flex items-center;- color: hsl(var(--notfair-ink-2));- font-weight: 500; font-size: 12.5px; letter-spacing: -0.005em;- margin-top: 4px; gap: 4px;- background: transparent; border: 0; cursor: pointer; padding: 0;- }- .ns-subaction:hover { opacity: 0.85; }- .ns-subaction::after {- content: "\203A"; font-size: 16px; line-height: 1;- margin-left: 2px; font-weight: 400;- }-- /* Footer — bottom row of a wizard step. Sticks below the list, no- huge top margin. */- .ns-foot {- @apply flex flex-wrap items-center justify-between gap-4;- margin-top: 20px;- }- .ns-footnote {- color: hsl(var(--notfair-ink-4));- font-size: 12px; line-height: 1.45; letter-spacing: -0.005em;- max-width: 440px; margin: 0;- }- .ns-footnote a { color: hsl(var(--notfair-ink-2)); text-decoration: underline; }- .ns-footnote a:hover { color: hsl(var(--notfair-ink)); }-- /* Buttons — Codex shape: soft 8px radius, inverted primary fill,- borderless filled secondary. */- .ns-btn {- @apply inline-flex items-center gap-2 cursor-pointer;- font: inherit; font-size: 13.5px; font-weight: 500;- letter-spacing: -0.006em;- padding: 8px 15px; border-radius: 8px; border: 0;- transition: 0.15s ease;- }- .ns-btn-primary {- background: hsl(var(--notfair-cta));- color: hsl(var(--notfair-cta-text));- }- .ns-btn-primary:hover { opacity: 0.9; }- .ns-btn-primary:disabled { opacity: 0.45; cursor: not-allowed; }- .ns-btn-ghost {- background: transparent; color: hsl(var(--notfair-ink-3));- padding: 8px 12px;- }- .ns-btn-ghost:hover { background: hsl(var(--notfair-surface-2)); }- /* Compact pill used inside grouped-list rows as the right-side action.- Not a button element — the whole row is the clickable target. */- .ns-btn-sm {- font-size: 12.5px; padding: 5px 12px;- }-- /* Header chip — the ONE size for every goal-header control (dialog- triggers, run-check, overflow). Consistency is the point: never mix- this row with ns-btn or shadcn Button sizes. */- .ns-chip {- @apply inline-flex shrink-0 items-center gap-1.5 cursor-pointer;- font: inherit; font-size: 12px; font-weight: 450;- padding: 4px 10px; border-radius: 6px; border: 0;- background: hsl(var(--notfair-surface-2));- color: hsl(var(--notfair-ink-3));- transition: 0.15s ease;- }- .ns-chip:hover { color: hsl(var(--notfair-ink)); }- .ns-chip:disabled { opacity: 0.5; cursor: not-allowed; }-- /* Working-state text shimmer — the Claude/ChatGPT "thinking" sweep.- A light band travels across the label via background-clip: text.- Apply only while genuinely live; static text must never shimmer. */- .ns-shimmer-text {- background: linear-gradient(- 90deg,- hsl(var(--notfair-ink-4)) 0%,- hsl(var(--notfair-ink-4)) 35%,- hsl(var(--notfair-ink)) 50%,- hsl(var(--notfair-ink-4)) 65%,- hsl(var(--notfair-ink-4)) 100%- );- background-size: 220% 100%;- -webkit-background-clip: text;- background-clip: text;- color: transparent;- animation: ns-text-shimmer 1.8s linear infinite;- }- @media (prefers-reduced-motion: reduce) {- .ns-shimmer-text {- animation: none;- background: none;- color: hsl(var(--notfair-ink-2));- }- }- .ns-chip > svg { width: 14px; height: 14px; flex-shrink: 0; }-- /* Progress pips — small numbered circles + hairlines. */- .ns-progress {- @apply flex items-center;- gap: 10px;- color: hsl(var(--notfair-ink-4));- font-size: 12px; font-weight: 500; letter-spacing: -0.006em;- }- .ns-pip { @apply flex items-center; gap: 7px; }- .ns-pip-dot {- @apply grid place-items-center;- width: 18px; height: 18px; border-radius: 50%;- background: hsl(var(--notfair-surface-2));- color: hsl(var(--notfair-ink-4));- font-size: 10px; font-weight: 500;- }- .ns-pip.is-done .ns-pip-dot {- background: hsl(var(--notfair-accent-soft));- color: hsl(var(--notfair-accent));- }- .ns-pip.is-active .ns-pip-dot {- background: hsl(var(--notfair-cta));- color: hsl(var(--notfair-cta-text));- font-weight: 600;- }- .ns-pip.is-active { color: hsl(var(--notfair-ink)); }- .ns-pip-line {- display: inline-block; width: 20px; height: 1px;- background: hsl(var(--notfair-surface-2));- }-- /* Top brand bar — Notfair mark + per-page label, no nav. */- .ns-topbar {- @apply flex items-center;- gap: 12px;- margin-bottom: 16px;- }- .ns-topbar img { height: 18px; width: auto; }- .ns-topbar-label {- color: hsl(var(--notfair-ink-4));- font-size: 12px; letter-spacing: -0.005em; font-weight: 400;- }-- /* ── App-shell tokens (every authenticated page) ─────────────────- The onboarding `.ns-page` is intentionally compact (720px). The- app shell wants more breathing room — Apple settings + product- pages are wide but never edge-to-edge. */-- /* Page wrappers. The narrow variant matches Settings / Approvals;- the wide one is the default for product surfaces (Home, Tasks,- Crons, Activity, Connections, Agents). */- .ns-app {- margin-inline: auto; width: 100%;- padding: 32px 28px 96px;- }- .ns-app-narrow {- margin-inline: auto; width: 100%;- padding: 32px 28px 96px;- max-width: 720px;- }- .ns-app-wide {- margin-inline: auto; width: 100%;- padding: 32px 28px 96px;- max-width: 1100px;- }-- /* Page header — left-aligned title + meta, right-aligned actions.- Apple's settings-page convention: large h1, quiet meta line, no- decorative chrome. Action lives in the right slot. */- .ns-page-head {- @apply flex items-start justify-between gap-6;- margin-bottom: 28px;- }- .ns-page-head-stack { @apply min-w-0; }- .ns-page-title {- @apply text-foreground m-0;- font-size: 28px; line-height: 1.15; font-weight: 600;- letter-spacing: -0.026em;- }- .ns-page-sub {- color: hsl(var(--notfair-ink-4));- font-size: 13.5px; line-height: 1.45; letter-spacing: -0.006em;- margin: 6px 0 0;- }- .ns-page-sub b { color: hsl(var(--notfair-ink-2)); font-weight: 500; }- .ns-page-actions { @apply flex shrink-0 items-center gap-2; }-- /* Section heading inside a page (above a grouped list). Apple- uses small, semibold caps for these, not mono uppercase. */- .ns-h2 {- @apply flex items-baseline justify-between gap-3 m-0;- font-size: 13px; font-weight: 600; letter-spacing: -0.012em;- color: hsl(var(--notfair-ink-2));- margin-top: 32px; margin-bottom: 10px;- }- .ns-h2 .ns-h2-meta {- color: hsl(var(--notfair-ink-4));- font-size: 12px; font-weight: 400; letter-spacing: -0.005em;- }-- /* Grouped list (app-scope variant of .ns-list — same separated-- cards shape, no auto top-margin so it can sit directly under a- section head). Each direct child — `<article class="ns-row">` is- often wrapped in `<li>` — becomes its own elevated card; no- divider lines anywhere. */- .ns-group {- @apply flex flex-col;- gap: 9px;- }- .ns-group > * {- @apply bg-card overflow-hidden;- border-radius: 12px;- box-shadow: var(--notfair-shadow);- }- .ns-row {- @apply flex items-center gap-3;- padding: 14px 18px;- text-align: left;- }- .ns-row-button {- @apply flex items-center gap-3 w-full cursor-pointer transition-colors;- padding: 14px 18px;- text-align: left;- border: 0;- background: transparent;- }- .ns-row-button:hover { background: hsl(var(--notfair-hover)); }- .ns-row-button:disabled { cursor: not-allowed; opacity: 0.55; }-- /* Glyph tile next to a row's title — 38px iOS-app-icon shape. */- .ns-glyph {- @apply grid place-items-center flex-shrink-0 font-semibold uppercase;- width: 38px; height: 38px; border-radius: 9px;- background: hsl(var(--notfair-surface-2));- color: hsl(var(--notfair-ink-2));- font-size: 14.5px; letter-spacing: -0.018em;- }- .ns-glyph-sm {- @apply grid place-items-center flex-shrink-0 font-semibold uppercase;- width: 30px; height: 30px; border-radius: 7px;- background: hsl(var(--notfair-surface-2));- color: hsl(var(--notfair-ink-2));- font-size: 12.5px; letter-spacing: -0.018em;- }- .ns-glyph-accent {- background: hsl(var(--notfair-accent-soft));- color: hsl(var(--notfair-accent));- }-- /* Row body — title + description stacked. */- .ns-row-body { @apply min-w-0 flex-1; }- .ns-row-title {- @apply text-foreground m-0;- font-size: 14.5px; font-weight: 500; letter-spacing: -0.012em;- line-height: 1.3;- }- .ns-row-desc {- color: hsl(var(--notfair-ink-4));- font-size: 12.5px; line-height: 1.4; letter-spacing: -0.003em;- margin: 2px 0 0;- }- .ns-row-title-row {- @apply flex flex-wrap items-baseline gap-x-2 gap-y-1;- }-- /* Right-side meta / action column. */- .ns-row-meta {- @apply flex shrink-0 items-center;- gap: 10px;- color: hsl(var(--notfair-ink-4));- font-size: 12.5px; font-weight: 500; letter-spacing: -0.005em;- }- .ns-row-meta .chev {- font-size: 18px; font-weight: 300; line-height: 1;- color: hsl(var(--notfair-ink-4));- }-- /* Quiet metadata pill (used to label IDs, slugs, role names without- stealing focus). Soft surface, no border. Apple's "tag" look. */- .ns-tag {- @apply inline-flex items-center;- background: hsl(var(--notfair-surface-2));- color: hsl(var(--notfair-ink-3));- font-size: 11.5px; font-weight: 500; letter-spacing: -0.002em;- line-height: 1; padding: 4px 9px; border-radius: 6px;- }- .ns-tag-mono {- @apply inline-flex items-center font-mono;- background: hsl(var(--notfair-surface-2));- color: hsl(var(--notfair-ink-3));- font-size: 11px; font-weight: 500; letter-spacing: 0;- line-height: 1; padding: 4px 9px; border-radius: 6px;- }- .ns-tag-accent {- background: hsl(var(--notfair-accent-soft));- color: hsl(var(--notfair-accent));- }- .ns-tag-amber {- background: hsl(var(--notfair-warn-soft));- color: hsl(var(--notfair-warn));- }- .ns-tag-red {- background: hsl(0 92% 96%);- color: hsl(0 72% 42%);- }- .dark .ns-tag-red {- background: hsl(0 45% 15%);- color: hsl(0 70% 65%);- }-- /* Status dot — small filled circle in semantic color. Pair with a- short label for inline status lines. */- .ns-dot {- display: inline-block; flex-shrink: 0;- width: 7px; height: 7px; border-radius: 50%;- background: hsl(var(--notfair-ink-4));- }- .ns-dot-on { background: hsl(var(--notfair-accent)); }- .ns-dot-warn { background: hsl(38 92% 50%); }- .ns-dot-err { background: hsl(0 72% 51%); }- .ns-dot-mute { background: hsl(var(--notfair-border-strong)); }-- /* Thread-rail marquee — single-line title that slides horizontally on- row hover to reveal overflow. The row's mouseenter handler measures- the overflow and sets --ns-marquee-shift in px (0 when the title- fits); CSS only animates it: slow reveal on hover, quick snap-back- on leave. (Kept JS-measured: container-query units in transform got- silently dropped by the CSS pipeline.) */- .ns-marquee {- overflow: hidden;- white-space: nowrap;- }- .ns-marquee > span {- display: inline-block;- min-width: 100%;- transform: translateX(0);- transition: transform 0.25s ease-out;- }- .ns-thread-row:hover .ns-marquee > span {- transform: translateX(var(--ns-marquee-shift, 0px));- transition: transform var(--ns-marquee-duration, 2s) linear 0.35s;- }-- /* Pulsing live dot — for "running" / "live" indicators. */- .ns-dot-live {- background: hsl(var(--notfair-accent));- box-shadow: 0 0 0 0 hsl(var(--notfair-accent) / 0.45);- animation: ns-pulse 1.8s ease-out infinite;- }- @keyframes ns-pulse {- 0% { box-shadow: 0 0 0 0 hsl(var(--notfair-accent) / 0.45); }- 70% { box-shadow: 0 0 0 6px hsl(var(--notfair-accent) / 0); }- 100% { box-shadow: 0 0 0 0 hsl(var(--notfair-accent) / 0); }- }-- /* Tabs — Codex pill pattern: no underline rule, no border line;- the active tab is an inset filled pill. */- .ns-tabs {- @apply flex items-center gap-1;- }- .ns-tab {- @apply relative inline-flex items-center gap-1.5 cursor-pointer;- padding: 6px 12px; border-radius: 7px;- color: hsl(var(--notfair-ink-4));- font-size: 13px; font-weight: 500; letter-spacing: -0.006em;- background: transparent; border: 0;- transition: color 0.15s ease, background-color 0.15s ease;- }- .ns-tab:hover { color: hsl(var(--notfair-ink-2)); }- .ns-tab[data-active="true"],- .ns-tab[aria-selected="true"] {- color: hsl(var(--notfair-ink));- background: hsl(var(--notfair-surface-2));- }- /* Accent variant kept as an alias — pill style is identical. */-- /* KPI card — small surface with quiet label + large metric. */- .ns-kpi {- @apply block bg-card rounded-[14px] transition-colors;- padding: 16px 18px;- box-shadow: var(--notfair-shadow-sm);- }- a.ns-kpi:hover, button.ns-kpi:hover { background: hsl(var(--notfair-hover)); }- .ns-kpi-label {- color: hsl(var(--notfair-ink-4));- font-size: 12px; font-weight: 500; letter-spacing: -0.005em;- margin: 0 0 6px;- }- .ns-kpi-value {- @apply text-foreground m-0 tabular-nums;- font-size: 26px; font-weight: 600; letter-spacing: -0.024em;- line-height: 1.1;- }- .ns-kpi-hint {- color: hsl(var(--notfair-ink-4));- font-size: 11.5px; line-height: 1.4; letter-spacing: -0.003em;- margin: 6px 0 0;- }-- /* Empty state — for sections that need a no-results placeholder. */- .ns-empty {- @apply flex flex-col items-center justify-center text-center bg-card rounded-[14px];- padding: 48px 24px;- box-shadow: var(--notfair-shadow-sm);- }- .ns-empty-title {- @apply text-foreground m-0;- font-size: 15.5px; font-weight: 600; letter-spacing: -0.012em;- }- .ns-empty-sub {- color: hsl(var(--notfair-ink-4));- font-size: 13px; line-height: 1.5; letter-spacing: -0.005em;- margin: 6px 0 0; max-width: 380px;- }- .ns-empty .ns-empty-action { margin-top: 16px; }-- /* Card — plain surface with shadow, used when grouped-list isn't- the right shape (e.g. forms, detail panes). */- .ns-card {- @apply bg-card rounded-[14px] overflow-hidden;- box-shadow: var(--notfair-shadow);- }- .ns-card-body { padding: 18px 22px; }-- /* Inline action link — ink with underline, no chrome. Green stays- status-only. */- .ns-link {- color: hsl(var(--notfair-ink-2));- font-weight: 500;- text-decoration: none;- }- .ns-link:hover { text-decoration: underline; }-- /* Secondary button — borderless inset fill (Codex gray button). */- .ns-btn-secondary {- background: hsl(var(--notfair-surface-2));- color: hsl(var(--notfair-ink-2));- }- .ns-btn-secondary:hover { filter: brightness(0.96); }- .dark .ns-btn-secondary:hover { filter: brightness(1.2); }-- /* "Outline" kept as a name only — same borderless inset fill. */- .ns-btn-outline {- background: hsl(var(--notfair-surface-2));- color: hsl(var(--notfair-ink-2));- }- .ns-btn-outline:hover { filter: brightness(0.96); }- .dark .ns-btn-outline:hover { filter: brightness(1.2); }-- /* Destructive pill — used in danger-zone buttons. */- .ns-btn-danger {- background: hsl(0 72% 51%); color: #fff;- }- .ns-btn-danger:hover { filter: brightness(0.94); }- .ns-btn-danger:disabled { opacity: 0.55; cursor: not-allowed; }-- /* ── Sidebar (Codex override of shadcn sidebar) ──────────────────- Darker-than-content rail, no border line against the content —- the surface step does the separation. Active row is a monochrome- inset pill; green stays reserved for live status. */- [data-sidebar="sidebar"] {- background: hsl(var(--notfair-sidebar));- border-color: transparent;- /* Edge elevation instead of a border-r line: a soft rightward- shadow lifts the content plane off the rail. */- box-shadow: 4px 0 16px -6px rgba(0, 0, 0, 0.10);- }- .dark [data-sidebar="sidebar"] {- box-shadow: 4px 0 16px -6px rgba(0, 0, 0, 0.45);- }- [data-sidebar="header"] {- padding: 10px 8px;- }- [data-sidebar="group-label"] {- font-size: 10.5px; font-weight: 500; letter-spacing: 0.07em;- color: hsl(var(--notfair-ink-4));- text-transform: uppercase;- padding-inline: 12px;- margin-top: 4px;- }- [data-sidebar="menu-button"] {- color: hsl(var(--notfair-ink-3));- font-weight: 500; font-size: 13px; letter-spacing: -0.006em;- border-radius: 8px; height: 32px;- transition: background-color 0.12s ease, color 0.12s ease;- }- [data-sidebar="menu-button"]:hover {- background: hsl(var(--notfair-surface-2));- color: hsl(var(--notfair-ink));- }- [data-sidebar="menu-button"][data-active="true"] {- background: hsl(var(--notfair-surface-2));- color: hsl(var(--notfair-ink));- }- [data-sidebar="menu-button"][data-active="true"] svg {- color: hsl(var(--notfair-ink));- }- [data-sidebar="menu-button"] svg {- color: hsl(var(--notfair-ink-4));- }-- /* App topbar — for in-app surfaces (separate from the wizard topbar).- Translucent wash of the page background; no border line. */- .ns-app-topbar {- @apply sticky top-0 z-30 flex items-center;- height: 44px;- background: hsl(var(--background) / 0.82);- backdrop-filter: saturate(180%) blur(20px);- -webkit-backdrop-filter: saturate(180%) blur(20px);- padding: 0 16px;- gap: 8px;- }- .ns-app-topbar-title {- color: hsl(var(--notfair-ink));- font-size: 13.5px; font-weight: 600; letter-spacing: -0.01em;- }- .ns-app-topbar-sub {- color: hsl(var(--notfair-ink-4));- font-size: 12px; letter-spacing: -0.005em;- }- .ns-app-topbar-divider {- width: 1px; height: 18px;- background: hsl(var(--notfair-surface-2));- margin: 0 4px;- }-- /* Mono metadata — hosts, counts, ids, usage meters. The terminal-- adjacent detail that anchors the Codex feel. */- .ns-mono {- font-family: ui-monospace, 'SF Mono', 'JetBrains Mono', Menlo, monospace;- letter-spacing: 0;- }-}diff --git a/notfair/src/app/layout.tsx b/notfair/src/app/layout.tsxdeleted file mode 100644index 737869cc..00000000--- a/notfair/src/app/layout.tsx+++ /dev/null@@ -1,27 +0,0 @@-import type { Metadata } from "next";-import { TooltipProvider } from "@/components/ui/tooltip";-import { Toaster } from "@/components/ui/sonner";-import { ThemeProvider } from "@/components/theme-provider";-import "./globals.css";--export const metadata: Metadata = {- title: "NotFair",- description: "Goal-driven, loop-powered marketing agents on your machine.",-};--export default function RootLayout({- children,-}: {- children: React.ReactNode;-}) {- return (- <html lang="en" suppressHydrationWarning>- <body className="min-h-screen bg-background text-foreground antialiased">- <ThemeProvider>- <TooltipProvider delayDuration={200}>{children}</TooltipProvider>- <Toaster position="top-right" richColors closeButton duration={5000} />- </ThemeProvider>- </body>- </html>- );-}diff --git a/notfair/src/app/onboarding/layout.tsx b/notfair/src/app/onboarding/layout.tsxdeleted file mode 100644index fe022130..00000000--- a/notfair/src/app/onboarding/layout.tsx+++ /dev/null@@ -1,4 +0,0 @@-// Standalone layout: no sidebar, no chrome. The onboarding flow is the entire screen.-export default function OnboardingLayout({ children }: { children: React.ReactNode }) {- return <div className="min-h-screen bg-background p-6">{children}</div>;-}diff --git a/notfair/src/app/onboarding/page.tsx b/notfair/src/app/onboarding/page.tsxdeleted file mode 100644index 534a5605..00000000--- a/notfair/src/app/onboarding/page.tsx+++ /dev/null@@ -1,41 +0,0 @@-import { Suspense } from "react";-import { OnboardingFlow } from "@/components/onboarding-flow";-import { getProject } from "@/server/db/projects";-import { prefetchAccountChoice } from "@/server/mcp/account-selection";-import { listProjectMcpTokens } from "@/server/mcp/tokens";--export const dynamic = "force-dynamic";--type Search = { slug?: string; mcp_key?: string };--export default async function OnboardingPage({- searchParams,-}: {- searchParams: Promise<Search>;-}) {- const { slug, mcp_key } = await searchParams;-- // Same post-OAuth picker flow as the Connections page: when the callback- // flagged a multi-account MCP (`?mcp_key=`), prefetch the account list- // server-side so the connect step opens the picker dialog with data —- // never a client fetch racing the flash banner's URL cleanup.- const project = slug ? getProject(slug) : null;- const pendingChoice =- project && mcp_key ? await prefetchAccountChoice(project, mcp_key) : null;-- // The first-goal step's focus chips derive from what got connected.- // Fresh on every render — stepping Connect → Goal is a full RSC pass.- const connectedMcpKeys = project- ? listProjectMcpTokens(project.slug).map((t) => t.server_name)- : [];-- return (- <Suspense fallback={null}>- <OnboardingFlow- pickerMcpKey={pendingChoice && mcp_key ? mcp_key : null}- pickerPrefetch={pendingChoice?.prefetch ?? null}- connectedMcpKeys={connectedMcpKeys}- />- </Suspense>- );-}diff --git a/notfair/src/components/add-mcp-server-card.test.tsx b/notfair/src/components/add-mcp-server-card.test.tsxdeleted file mode 100644index 7fac6dc6..00000000--- a/notfair/src/components/add-mcp-server-card.test.tsx+++ /dev/null@@ -1,106 +0,0 @@-// @vitest-environment jsdom-import { beforeEach, describe, expect, it, vi } from "vitest";-import { fireEvent, render, screen, waitFor } from "@testing-library/react";--import { AddMcpServerMenu } from "@/components/add-mcp-server-card";--// Mock at the server-action boundary, per repo test conventions.-const addServer = vi.hoisted(() => vi.fn());-const startConnect = vi.hoisted(() => vi.fn());-vi.mock("@/server/actions/mcp", () => ({- addUserMcpServerAction: addServer,- startMcpConnect: startConnect,-}));--const refresh = vi.hoisted(() => vi.fn());-vi.mock("next/navigation", () => ({- useRouter: () => ({ refresh, push: vi.fn(), replace: vi.fn() }),-}));--const toastSuccess = vi.hoisted(() => vi.fn());-const toastError = vi.hoisted(() => vi.fn());-vi.mock("sonner", () => ({- toast: { success: toastSuccess, error: toastError },-}));--beforeEach(() => {- vi.clearAllMocks();-});--function openBrowser() {- fireEvent.click(screen.getByRole("button", { name: /add server/i }));-}--describe("AddMcpServerMenu", () => {- it("opens Browse connectors directly from the default trigger", () => {- render(<AddMcpServerMenu />);- openBrowser();- expect(- screen.getByRole("heading", { name: "Browse connectors" }),- ).toBeInTheDocument();- expect(- screen.getByRole("button", { name: /add custom connector/i }),- ).toBeInTheDocument();- expect(screen.queryByRole("menu")).toBeNull();- });-- it("opens Browse connectors directly from a custom trigger", () => {- render(- <AddMcpServerMenu- trigger={<button type="button">More tools</button>}- />,- );- expect(screen.getByRole("button", { name: "More tools" })).toBeInTheDocument();- expect(screen.queryByRole("button", { name: /add server/i })).toBeNull();- fireEvent.click(screen.getByRole("button", { name: "More tools" }));- expect(- screen.getByRole("heading", { name: "Browse connectors" }),- ).toBeInTheDocument();- });-- it("adds a custom OAuth connector and refreshes on success", async () => {- addServer.mockResolvedValue({ ok: true, key: "stripe" });- render(<AddMcpServerMenu />);- openBrowser();- fireEvent.click(screen.getByRole("button", { name: /add custom connector/i }));- fireEvent.change(await screen.findByLabelText("Name"), {- target: { value: "Stripe" },- });- fireEvent.change(screen.getByLabelText("Remote MCP server URL"), {- target: { value: "https://mcp.stripe.com/" },- });- fireEvent.submit(screen.getByRole("button", { name: /^add server$/i }));-- await waitFor(() => {- expect(addServer).toHaveBeenCalledWith({- display_name: "Stripe",- resource_url: "https://mcp.stripe.com/",- });- expect(toastSuccess).toHaveBeenCalledWith(- "Added MCP server 'stripe'. Click Connect to authorize.",- );- expect(refresh).toHaveBeenCalled();- });- });-- it("shows the probe failure inline and keeps the dialog open", async () => {- addServer.mockResolvedValue({ ok: false, error: "No OAuth discovery." });- render(<AddMcpServerMenu />);- openBrowser();- fireEvent.click(screen.getByRole("button", { name: /add custom connector/i }));- fireEvent.change(await screen.findByLabelText("Name"), {- target: { value: "Broken" },- });- fireEvent.change(screen.getByLabelText("Remote MCP server URL"), {- target: { value: "https://broken.example.com/" },- });- fireEvent.submit(screen.getByRole("button", { name: /^add server$/i }));-- expect(await screen.findByRole("alert")).toHaveTextContent(- "No OAuth discovery.",- );- // Dialog stays open for a retry — the name field is still there.- expect(screen.getByLabelText("Name")).toBeInTheDocument();- expect(refresh).not.toHaveBeenCalled();- });-});diff --git a/notfair/src/components/add-mcp-server-card.tsx b/notfair/src/components/add-mcp-server-card.tsxdeleted file mode 100644index 3a6e10c3..00000000--- a/notfair/src/components/add-mcp-server-card.tsx+++ /dev/null@@ -1,212 +0,0 @@-"use client";--import { type ReactElement, useState } from "react";-import { useRouter } from "next/navigation";-import { Plus, Loader2 } from "lucide-react";-import { Slot } from "radix-ui";--import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import { Label } from "@/components/ui/label";-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from "@/components/ui/dialog";-import { toast } from "sonner";-import { addUserMcpServerAction } from "@/server/actions/mcp";-import { BrowseConnectorsDialog } from "@/components/browse-connectors-dialog";--/**- * "Add server" trigger for the Connections page header. It opens the- * connector browser directly, where users can choose either path:- *- * - **Browse connectors** → curated grid of trusted MCPs (Stripe,- * PostHog, NotFair, etc.). Click adds it to this project via the- * same OAuth probe + persistence path as a custom URL.- * - **Add custom connector** → paste-a-URL dialog for any OAuth 2.0- * MCP that publishes RFC 9728 discovery + DCR.- *- * No bearer-paste path: OAuth 2.0 only. The probe in- * `addUserMcpServerAction` rejects servers that won't connect before- * the user even sees a Connect button.- */-export function AddMcpServerMenu({- connectedKeys = [],- connectedResourceUrls = [],- hideKeys = [],- trigger,-}: {- /** Catalog keys whose runtime status is `connected`. Browse tiles for- * these are filtered out of the grid entirely. */- connectedKeys?: string[];- /** Normalized resource URLs of connected entries — paired with- * `connectedKeys` so legacy rows (where the key was slugified- * differently than the trusted-connector id) still match by URL. */- connectedResourceUrls?: string[];- /** Browse-dialog `hideKeys` passthrough — exclude specific catalog- * entries from the grid (used by onboarding's connect step to hide- * the recommended trio that already has first-class tiles). */- hideKeys?: string[];- /** Optional custom trigger. When omitted, renders the default pill- * "Add server" button used by the Connections page header. Pass a- * custom button-shaped node when slotting this into a list row,- * grouped list, or other in-line surface. */- trigger?: ReactElement;-}) {- const [browseOpen, setBrowseOpen] = useState(false);- const [customOpen, setCustomOpen] = useState(false);-- return (- <>- {trigger ? (- <Slot.Root onClick={() => setBrowseOpen(true)}>{trigger}</Slot.Root>- ) : (- <button- type="button"- className="ns-btn ns-btn-primary"- onClick={() => setBrowseOpen(true)}- >- <Plus className="size-3.5" />- Add server- </button>- )}-- <BrowseConnectorsDialog- open={browseOpen}- onOpenChange={setBrowseOpen}- connectedKeys={connectedKeys}- connectedResourceUrls={connectedResourceUrls}- hideKeys={hideKeys}- onAddCustom={() => {- setBrowseOpen(false);- setCustomOpen(true);- }}- />- <CustomConnectorDialog open={customOpen} onOpenChange={setCustomOpen} />- </>- );-}--function CustomConnectorDialog({- open,- onOpenChange,-}: {- open: boolean;- onOpenChange: (open: boolean) => void;-}) {- const [submitting, setSubmitting] = useState(false);- const [displayName, setDisplayName] = useState("");- const [resourceUrl, setResourceUrl] = useState("");- const [error, setError] = useState<string | null>(null);- const router = useRouter();-- function reset() {- setDisplayName("");- setResourceUrl("");- setError(null);- }-- async function onSubmit(e: React.FormEvent) {- e.preventDefault();- setError(null);- setSubmitting(true);- try {- const result = await addUserMcpServerAction({- display_name: displayName,- resource_url: resourceUrl,- });- if (!result.ok) {- setError(result.error);- return;- }- toast.success(- `Added MCP server '${result.key}'. Click Connect to authorize.`,- );- onOpenChange(false);- reset();- router.refresh();- } catch (err) {- setError(err instanceof Error ? err.message : String(err));- } finally {- setSubmitting(false);- }- }-- return (- <Dialog- open={open}- onOpenChange={(next) => {- onOpenChange(next);- if (!next) reset();- }}- >- <DialogContent>- <DialogHeader>- <DialogTitle>Add custom connector</DialogTitle>- <DialogDescription>- Paste the MCP server's resource URL. We'll verify it- advertises OAuth 2.0 dynamic client registration before saving.- </DialogDescription>- </DialogHeader>- <form onSubmit={onSubmit} className="space-y-4">- <div className="space-y-1.5">- <Label htmlFor="mcp-display-name">Name</Label>- <Input- id="mcp-display-name"- placeholder="Stripe"- value={displayName}- onChange={(e) => setDisplayName(e.target.value)}- disabled={submitting}- required- autoFocus- />- </div>- <div className="space-y-1.5">- <Label htmlFor="mcp-resource-url">Remote MCP server URL</Label>- <Input- id="mcp-resource-url"- type="url"- placeholder="https://mcp.stripe.com/"- value={resourceUrl}- onChange={(e) => setResourceUrl(e.target.value)}- disabled={submitting}- required- />- <p className="text-xs text-muted-foreground">- The HTTPS endpoint your agents will call. We derive the OAuth- discovery URL from this automatically.- </p>- </div>- {error ? (- <p- className="rounded border border-destructive/30 bg-destructive/5 p-2 text-xs text-destructive"- role="alert"- >- {error}- </p>- ) : null}- <DialogFooter>- <Button- type="button"- variant="ghost"- onClick={() => onOpenChange(false)}- disabled={submitting}- >- Cancel- </Button>- <Button type="submit" disabled={submitting}>- {submitting ? (- <Loader2 className="size-3.5 animate-spin" />- ) : null}- Add server- </Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>- );-}diff --git a/notfair/src/components/app-sidebar.tsx b/notfair/src/components/app-sidebar.tsxdeleted file mode 100644index ac7211ce..00000000--- a/notfair/src/components/app-sidebar.tsx+++ /dev/null@@ -1,282 +0,0 @@-import Link from "next/link";-import {- Sidebar,- SidebarContent,- SidebarFooter,- SidebarGroup,- SidebarGroupAction,- SidebarGroupContent,- SidebarGroupLabel,- SidebarHeader,- SidebarMenu,- SidebarMenuButton,- SidebarMenuItem,- SidebarTrigger,-} from "@/components/ui/sidebar";-import { SidebarBrand } from "@/components/sidebar-brand";-import { BookOpen, FolderPlus, LayoutGrid, Plug, Plus, Settings, type LucideIcon } from "lucide-react";-import { listProjects } from "@/server/db/projects";-import { getActiveProject } from "@/server/active-project";-import { listProjectAgents } from "@/server/agent-meta";-import {- countUserActionRequests,- getPinnedGoalIds,- listGoals,- listSidebarGoals,-} from "@/server/db/goals";-import { colorForAgentSlug } from "@/lib/agent-colors";-import { SidebarGoalItem } from "@/components/sidebar-goal-item";-import { SidebarGoalGroup } from "@/components/sidebar-goal-group";-import { GoalGroupEditor, type GoalGroupEditorGoal } from "@/components/goal-group-editor";-import { readHarnessUsage } from "@/server/harness-usage";-import { projectHref } from "@/lib/project-href";-import { goalLabel } from "@/lib/goal-label";-import { ProjectSwitcher } from "./project-switcher";-import { HarnessFooter } from "./harness-footer";-import { SidebarVersion } from "./sidebar-version";-import { ThemeToggle } from "./theme-toggle";-import { listGoalGroupMemberships, listGoalGroups } from "@/server/db/goal-groups";-import { RemoteControl } from "@/components/remote-control";--type NavItem = {- href: string;- label: string;- icon: LucideIcon;-};--const NAV: NavItem[] = [- { href: "/context", label: "Shared context", icon: BookOpen },- { href: "/connections", label: "Connections", icon: Plug },- { href: "/settings", label: "Settings", icon: Settings },-];--export async function AppSidebar() {- const projects = listProjects();- const active = await getActiveProject();- const agentEntries = active ? await listProjectAgents(active.slug) : [];- // Achievements remain in the rail until the user explicitly chooses to- // archive or continue them. Pinned live goals float within the live set;- // newly completed goals stay first so the payoff cannot be missed.- const sidebarGoals = active ? listSidebarGoals(active.slug) : [];- const pinnedIds = active ? getPinnedGoalIds(active.slug) : new Set<string>();- const completedGoals = sidebarGoals.filter((goal) => goal.status === "achieved");- const liveGoals = sidebarGoals.filter((goal) => goal.status !== "achieved");- const railGoals = [- ...completedGoals,- ...liveGoals.filter((g) => pinnedIds.has(g.id)),- ...liveGoals.filter((g) => !pinnedIds.has(g.id)),- ];- const allGoals = active ? listGoals(active.slug) : [];- const totalGoals = allGoals.length;- const goalGroups = active ? listGoalGroups(active.slug) : [];- const memberships = active ? listGoalGroupMemberships(active.slug) : [];- const groupIdByGoal = new Map(memberships.map((membership) => [membership.goal_id, membership.group_id]));- const ungroupedRailGoals = railGoals.filter((goal) => !groupIdByGoal.has(goal.id));- const agentBySlug = new Map(agentEntries.map((a) => [a.agent_id, a]));- // Move-to-group menu targets on every goal row.- const groupTargets = goalGroups.map((group) => ({ id: group.id, name: group.name }));- // Open "Needs you" escalations per goal — amber mark on the rail rows.- const attentionByGoal = active ? countUserActionRequests(active.slug) : new Map<string, number>();- // Full goal list for the create-group dialog behind the + header action.- const groupNameById = new Map(goalGroups.map((group) => [group.id, group.name]));- const editorGoals: GoalGroupEditorGoal[] = allGoals.map((goal) => {- const memberOf = groupIdByGoal.get(goal.id) ?? null;- return {- id: goal.id,- label: goalLabel(goal),- status: goal.status,- current_group_id: memberOf,- current_group_name: memberOf ? groupNameById.get(memberOf) ?? null : null,- };- });- // Best-effort fetch of harness usage. For Codex this hits the- // chatgpt.com wham/usage endpoint (cached 60s in-process); for- // Claude Code it just reads the local stats-cache. Either failure- // mode collapses to a quieter chip.- const harnessUsage = active- ? await readHarnessUsage(active.harness_adapter)- : null;-- return (- <Sidebar collapsible="icon">- <SidebarHeader>- {/* Brand mark + project switcher. The mark doubles as the expand- toggle when collapsed (SidebarBrand handles both modes);- SidebarTrigger only renders in the expanded state so the icon- rail isn't doubled up. */}- <div className="flex items-center gap-1">- <SidebarBrand homeHref={active ? projectHref(active.slug, "") : "/"} />- <div className="min-w-0 flex-1 group-data-[collapsible=icon]:hidden">- <SidebarMenu>- <SidebarMenuItem>- <ProjectSwitcher- projects={projects}- activeSlug={active?.slug ?? null}- />- </SidebarMenuItem>- </SidebarMenu>- </div>- <SidebarTrigger className="shrink-0 group-data-[collapsible=icon]:hidden" />- </div>- </SidebarHeader>-- <SidebarContent>- {active && (- <SidebarGroup>- <SidebarGroupLabel>Goals</SidebarGroupLabel>- <GoalGroupEditor- projectSlug={active.slug}- goals={editorGoals}- trigger={- <SidebarGroupAction title="New group">- <FolderPlus />- <span className="sr-only">New group</span>- </SidebarGroupAction>- }- />- <SidebarGroupContent>- <SidebarMenu>- <SidebarMenuItem>- <SidebarMenuButton asChild>- <Link href={projectHref(active.slug, "")}>- <Plus />- <span>New goal…</span>- </Link>- </SidebarMenuButton>- </SidebarMenuItem>- {ungroupedRailGoals.map((goal) => {- const agent = agentBySlug.get(goal.agent_id);- if (!agent) return null;- const color = colorForAgentSlug(agent.slug);- return (- <SidebarGoalItem- key={goal.id}- href={projectHref(active.slug, `/goals/${agent.slug}`)}- homeHref={projectHref(active.slug, "")}- goalId={goal.id}- label={goalLabel(goal)}- status={goal.status as "intake" | "proposed" | "active" | "paused" | "achieved"}- pinned={pinnedIds.has(goal.id)}- labelClass={color.label}- projectSlug={active.slug}- groups={groupTargets}- groupId={null}- needsAttention={(attentionByGoal.get(goal.id) ?? 0) > 0}- completion={- goal.status === "achieved"- ? {- metricName: goal.metric_name,- currentValue: goal.current_value,- targetValue: goal.target_value,- metricDirection: goal.metric_direction,- completionReason: goal.status_reason,- completedAt: goal.updated_at,- }- : undefined- }- />- );- })}- {goalGroups.map((group) => {- const groupGoals = railGoals.filter((goal) => groupIdByGoal.get(goal.id) === group.id);- return (- <SidebarGoalGroup- key={group.id}- groupId={group.id}- name={group.name}- href={projectHref(active.slug, `/groups/${group.id}`)}- completedCount={groupGoals.filter((goal) => goal.status === "achieved").length}- >- {groupGoals.map((goal) => {- const agent = agentBySlug.get(goal.agent_id);- if (!agent) return null;- const color = colorForAgentSlug(agent.slug);- return (- <SidebarGoalItem- key={goal.id}- href={projectHref(active.slug, `/goals/${agent.slug}`)}- homeHref={projectHref(active.slug, "")}- goalId={goal.id}- label={goalLabel(goal)}- status={goal.status as "intake" | "proposed" | "active" | "paused" | "achieved"}- pinned={pinnedIds.has(goal.id)}- labelClass={color.label}- projectSlug={active.slug}- groups={groupTargets}- groupId={group.id}- needsAttention={(attentionByGoal.get(goal.id) ?? 0) > 0}- completion={- goal.status === "achieved"- ? {- metricName: goal.metric_name,- currentValue: goal.current_value,- targetValue: goal.target_value,- metricDirection: goal.metric_direction,- completionReason: goal.status_reason,- completedAt: goal.updated_at,- }- : undefined- }- />- );- })}- </SidebarGoalGroup>- );- })}- {totalGoals > 0 && (- <SidebarMenuItem>- <SidebarMenuButton asChild>- <Link href={projectHref(active.slug, "/goals")}>- <LayoutGrid />- <span>All goals</span>- <span className="ml-auto text-[11px] tabular-nums text-[hsl(var(--notfair-ink-4))]">- {totalGoals}- </span>- </Link>- </SidebarMenuButton>- </SidebarMenuItem>- )}- </SidebarMenu>- </SidebarGroupContent>- </SidebarGroup>- )}-- {active && (- <SidebarGroup>- <SidebarGroupLabel>Workspace</SidebarGroupLabel>- <SidebarGroupContent>- <SidebarMenu>- {NAV.map((item) => (- <SidebarMenuItem key={item.href || "home"}>- <SidebarMenuButton asChild>- <Link href={projectHref(active.slug, item.href)}>- <item.icon />- <span>{item.label}</span>- </Link>- </SidebarMenuButton>- </SidebarMenuItem>- ))}- <RemoteControl />- </SidebarMenu>- </SidebarGroupContent>- </SidebarGroup>- )}- </SidebarContent>-- <SidebarFooter className="px-3 py-2 group-data-[collapsible=icon]:hidden">- {active && harnessUsage && (- <HarnessFooter- adapter={active.harness_adapter}- usage={harnessUsage}- />- )}- <div className="flex items-center justify-between gap-2">- <div className="min-w-0 flex-1">- <SidebarVersion />- </div>- <ThemeToggle />- </div>- </SidebarFooter>- </Sidebar>- );-}diff --git a/notfair/src/components/browse-connectors-dialog.test.tsx b/notfair/src/components/browse-connectors-dialog.test.tsxdeleted file mode 100644index bf4769a3..00000000--- a/notfair/src/components/browse-connectors-dialog.test.tsx+++ /dev/null@@ -1,189 +0,0 @@-// @vitest-environment jsdom-import { beforeEach, describe, expect, it, vi } from "vitest";-import { fireEvent, render, screen, waitFor } from "@testing-library/react";--import { BrowseConnectorsDialog } from "@/components/browse-connectors-dialog";-import { TRUSTED_CONNECTORS } from "@/server/trusted-connectors";--// Mock at the server-action boundary, per repo test conventions.-const addServer = vi.hoisted(() => vi.fn());-const startConnect = vi.hoisted(() => vi.fn());-vi.mock("@/server/actions/mcp", () => ({- addUserMcpServerAction: addServer,- startMcpConnect: startConnect,-}));--const refresh = vi.hoisted(() => vi.fn());-vi.mock("next/navigation", () => ({- useRouter: () => ({ refresh, push: vi.fn(), replace: vi.fn() }),-}));--const toastError = vi.hoisted(() => vi.fn());-vi.mock("sonner", () => ({- toast: { success: vi.fn(), error: toastError },-}));--beforeEach(() => {- vi.clearAllMocks();-});--const ALL_IDS = TRUSTED_CONNECTORS.map((c) => c.id);--describe("BrowseConnectorsDialog", () => {- it("lists every trusted connector that is not yet connected", () => {- render(- <BrowseConnectorsDialog- open- onOpenChange={vi.fn()}- onAddCustom={vi.fn()}- />,- );- expect(screen.getByText("NotFair Google Ads")).toBeInTheDocument();- expect(screen.getByText("Stripe")).toBeInTheDocument();- });-- it("hides connected connectors by key and by normalized resource URL", () => {- render(- <BrowseConnectorsDialog- open- onOpenChange={vi.fn()}- onAddCustom={vi.fn()}- connectedKeys={["notfair-googleads"]}- // Trailing slash + uppercase host still match after normalization.- connectedResourceUrls={["https://mcp.stripe.com"]}- />,- );- expect(screen.queryByText("NotFair Google Ads")).toBeNull();- expect(screen.queryByText("Stripe")).toBeNull();- expect(screen.getByText("NotFair Meta Ads")).toBeInTheDocument();- });-- it("hides every NotFair tile once the canonical resource URL is connected", () => {- render(- <BrowseConnectorsDialog- open- onOpenChange={vi.fn()}- onAddCustom={vi.fn()}- connectedResourceUrls={["https://notfair.co/api/mcp/notfair"]}- />,- );- expect(screen.queryByText("NotFair Google Ads")).toBeNull();- expect(screen.queryByText("NotFair Meta Ads")).toBeNull();- expect(screen.queryByText("NotFair Google Search Console")).toBeNull();- expect(screen.queryByText("NotFair Google Analytics")).toBeNull();- expect(screen.getByText("Stripe")).toBeInTheDocument();- });-- it("shows an empty state when everything is already connected", () => {- render(- <BrowseConnectorsDialog- open- onOpenChange={vi.fn()}- onAddCustom={vi.fn()}- hideKeys={ALL_IDS}- />,- );- expect(- screen.getByText("All available connectors are already connected."),- ).toBeInTheDocument();- expect(- screen.getByRole("button", { name: /add custom connector/i }),- ).toBeInTheDocument();- });-- it("renders the custom connector path after the trusted connectors", () => {- const onAddCustom = vi.fn();- render(- <BrowseConnectorsDialog- open- onOpenChange={vi.fn()}- onAddCustom={onAddCustom}- />,- );-- const stripe = screen.getByRole("button", { name: /Stripe/ });- const custom = screen.getByRole("button", {- name: /add custom connector/i,- });- expect(- stripe.compareDocumentPosition(custom) & Node.DOCUMENT_POSITION_FOLLOWING,- ).toBeTruthy();- expect(screen.getByText("Paste an OAuth 2.0 MCP URL")).toBeInTheDocument();-- fireEvent.click(custom);- expect(onAddCustom).toHaveBeenCalledOnce();- });-- it("adds with the canonical key and passes return_to into OAuth", async () => {- addServer.mockResolvedValue({ ok: true, key: "notfair-googleads" });- // Fail the connect step so the test never assigns window.location.href.- startConnect.mockResolvedValue({ ok: false, error: "issuer down" });- const onOpenChange = vi.fn();- render(- <BrowseConnectorsDialog- open- onOpenChange={onOpenChange}- onAddCustom={vi.fn()}- />,- );-- fireEvent.click(- screen.getByRole("button", { name: /NotFair Google Ads/ }),- );-- await waitFor(() => {- expect(addServer).toHaveBeenCalledWith({- display_name: "NotFair Google Ads",- resource_url: "https://notfair.co/api/mcp/notfair",- key: "notfair-googleads",- });- expect(startConnect).toHaveBeenCalledWith({- mcp_key: "notfair-googleads",- return_to: window.location.pathname + window.location.search,- });- });- });-- it("closes and refreshes when add succeeds but OAuth cannot start", async () => {- addServer.mockResolvedValue({ ok: true, key: "notfair-googleads" });- startConnect.mockResolvedValue({ ok: false, error: "issuer down" });- const onOpenChange = vi.fn();- render(- <BrowseConnectorsDialog- open- onOpenChange={onOpenChange}- onAddCustom={vi.fn()}- />,- );-- fireEvent.click(- screen.getByRole("button", { name: /NotFair Google Ads/ }),- );-- await waitFor(() => {- expect(toastError).toHaveBeenCalledWith(- "Added NotFair Google Ads, but couldn't start OAuth: issuer down",- );- expect(refresh).toHaveBeenCalled();- expect(onOpenChange).toHaveBeenCalledWith(false);- });- });-- it("surfaces an add failure without starting OAuth", async () => {- addServer.mockResolvedValue({ ok: false, error: "probe failed" });- render(- <BrowseConnectorsDialog- open- onOpenChange={vi.fn()}- onAddCustom={vi.fn()}- />,- );-- fireEvent.click(screen.getByRole("button", { name: /Stripe/ }));-- await waitFor(() => {- expect(toastError).toHaveBeenCalledWith("probe failed");- });- expect(startConnect).not.toHaveBeenCalled();- });-});diff --git a/notfair/src/components/browse-connectors-dialog.tsx b/notfair/src/components/browse-connectors-dialog.tsxdeleted file mode 100644index 145e6294..00000000--- a/notfair/src/components/browse-connectors-dialog.tsx+++ /dev/null@@ -1,203 +0,0 @@-"use client";--import { useState, useTransition } from "react";-import { useRouter } from "next/navigation";-import { Loader2, Plus } from "lucide-react";--import {- Dialog,- DialogContent,- DialogDescription,- DialogHeader,- DialogTitle,-} from "@/components/ui/dialog";-import { toast } from "sonner";-import {- addUserMcpServerAction,- startMcpConnect,-} from "@/server/actions/mcp";-import {- TRUSTED_CONNECTORS,- type TrustedConnector,-} from "@/server/trusted-connectors";-import { McpIcon } from "@/components/mcp-icon";-import { normalizeResourceUrl } from "@/server/mcp/discovery-url";--type Props = {- open: boolean;- onOpenChange: (open: boolean) => void;- /** Catalog keys whose runtime status is `connected`. */- connectedKeys?: string[];- /** Normalized resource URLs of connected entries — used to detect- * legacy rows whose key doesn't match the trusted-connector id. */- connectedResourceUrls?: string[];- /**- * Catalog keys to exclude entirely from the grid. Used by the- * onboarding connect step, which surfaces the three recommended- * MCPs (Google Ads, Meta Ads, GSC) as first-class tiles and only- * uses this dialog for the "More" overflow. Without this filter the- * dialog would render duplicates of the tiles the user already sees.- */- hideKeys?: string[];- /** Opens the custom MCP URL flow. This is always the final option in the- * connector grid, including when every trusted connector is connected. */- onAddCustom: () => void;-};--/**- * Two-column grid of trusted MCP connectors that aren't yet connected for- * this project. Clicking a tile is a one-shot setup:- * `addUserMcpServerAction` writes the row (idempotent — re-clicking a- * stale row is fine), then `startMcpConnect` is fired immediately and the- * browser is redirected to the issuer's authorize URL.- *- * Already-connected connectors are filtered out entirely (rather than- * rendered greyed-out) so the dialog only ever surfaces actionable- * options. When every available connector is already wired, the dialog- * shows an empty-state message.- */-export function BrowseConnectorsDialog({- open,- onOpenChange,- connectedKeys = [],- connectedResourceUrls = [],- hideKeys = [],- onAddCustom,-}: Props) {- const connectedKeySet = new Set(connectedKeys);- const connectedUrlSet = new Set(connectedResourceUrls);- const hideKeySet = new Set(hideKeys);- const availableConnectors = TRUSTED_CONNECTORS.filter((c) => {- if (hideKeySet.has(c.id)) return false;- if (connectedKeySet.has(c.id)) return false;- if (connectedUrlSet.has(normalizeResourceUrl(c.resource_url))) return false;- return true;- });- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent className="sm:max-w-2xl">- <DialogHeader>- <DialogTitle>Browse connectors</DialogTitle>- <DialogDescription>- Pick a trusted MCP server. We'll add it and start the OAuth- flow in one step.- </DialogDescription>- </DialogHeader>- <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">- {availableConnectors.length === 0 ? (- <p className="py-8 text-center text-sm text-muted-foreground sm:col-span-2">- All available connectors are already connected.- </p>- ) : (- availableConnectors.map((c) => (- <ConnectorTile- key={c.id}- connector={c}- onAdded={() => onOpenChange(false)}- />- ))- )}- <button- type="button"- onClick={onAddCustom}- className="flex items-start gap-3 rounded-md border border-dashed border-border bg-muted/20 p-3 text-left transition-colors hover:bg-muted/50 sm:col-span-2"- >- <span className="flex size-10 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground">- <Plus className="size-5" />- </span>- <span className="min-w-0 flex-1">- <span className="block text-sm font-medium">- Add custom connector- </span>- <span className="mt-0.5 block text-xs text-muted-foreground">- Paste an OAuth 2.0 MCP URL- </span>- </span>- </button>- </div>- </DialogContent>- </Dialog>- );-}--function ConnectorTile({- connector,- onAdded,-}: {- connector: TrustedConnector;- onAdded: () => void;-}) {- const [pending, startTransition] = useTransition();- const [adding, setAdding] = useState(false);- const router = useRouter();- const busy = adding || pending;-- function onPick() {- setAdding(true);- startTransition(async () => {- const addResult = await addUserMcpServerAction({- display_name: connector.display_name,- resource_url: connector.resource_url,- // Force the canonical preset/connector key so adding "NotFair- // Google Ads" hits the preset (`notfair-googleads`) rather than- // slugifying into a different identifier.- key: connector.id,- });- if (!addResult.ok) {- toast.error(addResult.error);- setAdding(false);- return;- }- // Chain straight into OAuth so the user only clicks once. The- // upcoming full-page redirect is the visible feedback — we- // intentionally don't toast a separate "added" success.- //- // Pass `return_to` so the OAuth callback lands the user back on- // the connections page they started from. Without it the callback- // falls back to `/`, which bounces to the active project's home.- const return_to = window.location.pathname + window.location.search;- const connectResult = await startMcpConnect({- mcp_key: addResult.key,- return_to,- });- if (!connectResult.ok) {- toast.error(- `Added ${connector.display_name}, but couldn't start OAuth: ${connectResult.error}`,- );- router.refresh();- onAdded();- setAdding(false);- return;- }- // Full-page navigation: the authorize URL is on the issuer's- // origin, so we can't push() into Next's router.- window.location.href = connectResult.authorize_url;- });- }-- return (- <button- type="button"- onClick={onPick}- disabled={busy}- className="flex items-start gap-3 rounded-md border border-border bg-background p-3 text-left transition-colors hover:bg-muted/50 disabled:cursor-not-allowed disabled:opacity-60"- >- <McpIcon- resourceUrl={connector.resource_url}- alt={connector.display_name}- size="lg"- />- <div className="min-w-0 flex-1">- <div className="flex items-center gap-2">- <p className="text-sm font-medium">{connector.display_name}</p>- {busy ? (- <Loader2 className="size-3 animate-spin text-muted-foreground" />- ) : null}- </div>- <p className="mt-0.5 line-clamp-2 text-xs text-muted-foreground">- {connector.description}- </p>- </div>- </button>- );-}diff --git a/notfair/src/components/builtin-mcp-card.tsx b/notfair/src/components/builtin-mcp-card.tsxdeleted file mode 100644index 00c26a7e..00000000--- a/notfair/src/components/builtin-mcp-card.tsx+++ /dev/null@@ -1,64 +0,0 @@-"use client";--import { useState } from "react";-import { Workflow } from "lucide-react";--import { McpToolsDialog } from "@/components/mcp-tools-dialog";-import type { ToolSummary } from "@/server/mcp-server/tool-summaries";--/**- * Row for an MCP that ships with NotFair itself — no OAuth, no- * connect/disconnect. Settings-row shaped to match McpCard. We drop- * the "Built-in" pill because the section heading and the metadata- * line ("self-hosted · 21 tools · no setup") already convey it; one- * label is enough.- */-type Props = {- name: string;- description: string;- tools: ToolSummary[];-};--export function BuiltinMcpCard({ name, description, tools }: Props) {- const [open, setOpen] = useState(false);-- return (- <>- <article className="ns-row">- <span className="ns-glyph ns-glyph-accent" aria-hidden>- <Workflow className="size-[18px]" />- </span>-- <div className="ns-row-body">- <h3 className="ns-row-title">{name}</h3>- <p className="ns-row-desc line-clamp-1">{description}</p>- <p className="mt-1 truncate font-mono text-[10.5px] text-[hsl(var(--notfair-ink-4))]">- self-hosted- <span className="mx-1.5 opacity-50">·</span>- {tools.length} tool{tools.length === 1 ? "" : "s"}- <span className="mx-1.5 opacity-50">·</span>- no setup- </p>- </div>-- <div className="ns-row-meta">- <button- type="button"- className="ns-btn ns-btn-outline ns-btn-sm"- onClick={() => setOpen(true)}- >- View tools- </button>- </div>- </article>-- <McpToolsDialog- open={open}- onOpenChange={setOpen}- mcpName={name}- mcpDescription={description}- tools={tools}- />- </>- );-}diff --git a/notfair/src/components/chat/composer.test.tsx b/notfair/src/components/chat/composer.test.tsxdeleted file mode 100644index 6f8668e0..00000000--- a/notfair/src/components/chat/composer.test.tsx+++ /dev/null@@ -1,178 +0,0 @@-// @vitest-environment jsdom-import { fireEvent, render, screen } from "@testing-library/react";-import { afterEach, beforeEach, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({ filter: vi.fn() }));--vi.mock("@/lib/slash-commands", () => ({- filterSlashCommands: mocks.filter,-}));-vi.mock("@/components/slash-command-popover", () => ({- SlashCommandPopover: ({ commands, selectedIndex, onSelect, onHover }: {- commands: Array<{ name: string; insert?: string }>;- selectedIndex: number;- onSelect: (command: { name: string; insert?: string }) => void;- onHover: (index: number) => void;- }) => (- <div data-testid="slash" data-selected={selectedIndex}>- {commands.map((command, index) => (- <button key={command.name} onMouseEnter={() => onHover(index)} onClick={() => onSelect(command)}>- {command.name}- </button>- ))}- </div>- ),-}));-vi.mock("@/components/running-dot", () => ({ RunningDot: () => <span data-testid="running-dot" /> }));-vi.mock("@/components/ui/dropdown-menu", () => ({- DropdownMenu: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,- DropdownMenuTrigger: ({ children }: { children: React.ReactNode }) => <>{children}</>,- DropdownMenuContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,- DropdownMenuLabel: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,- DropdownMenuSeparator: () => <hr />,- DropdownMenuRadioGroup: ({ children, value }: { children: React.ReactNode; value: string }) => <div data-testid="radio-group" data-value={value}>{children}</div>,- DropdownMenuRadioItem: ({ children, value }: { children: React.ReactNode; value: string }) => <span data-testid="radio-item" data-value={value}>{children}</span>,-}));--import { ChatComposer } from "./composer";--const props = {- busy: false,- sendingChat: false,- placeholder: "Message agent",- model: "",- reasoningEffort: "",- onPickModel: vi.fn(),- onPickReasoningEffort: vi.fn(),- onSubmit: vi.fn(),- onStop: vi.fn(),-};--beforeEach(() => {- vi.clearAllMocks();- mocks.filter.mockImplementation(() => [- { name: "new" },- { name: "clear", insert: "/clear" },- ]);- vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {- callback(0);- return 1;- });-});--afterEach(() => vi.unstubAllGlobals());--it("submits trimmed text by form submit and Enter, then clears", () => {- render(<ChatComposer {...props} />);- const textbox = screen.getByPlaceholderText("Message agent");- Object.defineProperty(textbox, "scrollHeight", { configurable: true, value: 80 });- fireEvent.change(textbox, { target: { value: " hello " } });- expect(textbox).toHaveStyle({ height: "80px" });- fireEvent.submit(textbox.closest("form")!);- expect(props.onSubmit).toHaveBeenCalledWith("hello");- expect(textbox).toHaveValue("");- fireEvent.change(textbox, { target: { value: "again" } });- fireEvent.keyDown(textbox, { key: "Enter", shiftKey: false });- expect(props.onSubmit).toHaveBeenLastCalledWith("again");-});--it("allows Shift+Enter and blocks empty submissions", () => {- render(<ChatComposer {...props} />);- const textbox = screen.getByRole("textbox");- fireEvent.keyDown(textbox, { key: "Enter", shiftKey: true });- fireEvent.submit(textbox.closest("form")!);- expect(props.onSubmit).not.toHaveBeenCalled();- expect(screen.getByRole("button", { name: "Send" })).toBeDisabled();-});--it("shows model labels for selected, default, and stale values", () => {- const options = [- { value: "fast", label: "Fast", is_default: true },- { value: "deep", label: "Deep" },- ];- const { rerender } = render(<ChatComposer {...props} modelOptions={options} model="deep" />);- expect(screen.getByRole("button", { name: "Model and effort" })).toHaveTextContent("Deep");- rerender(<ChatComposer {...props} modelOptions={options} model="missing" />);- expect(screen.getByRole("button", { name: "Model and effort" })).toHaveTextContent("Fast");- rerender(<ChatComposer {...props} modelOptions={[{ value: "x", label: "X" }]} model="" />);- expect(screen.getByRole("button", { name: "Model and effort" })).toHaveTextContent("Default");-});--it("renders the provider default model once and exposes its dynamic effort choices", () => {- const options = [- {- value: "fast",- label: "Fast",- is_default: true,- default_reasoning_effort: "low",- reasoning_efforts: [- { value: "low", label: "Low", description: "Faster" },- { value: "high", label: "High", description: "Deeper" },- ],- },- { value: "deep", label: "Deep" },- ];-- render(<ChatComposer {...props} modelOptions={options} />);-- expect(screen.queryByText("Fast (default)")).not.toBeInTheDocument();- const items = screen.getAllByTestId("radio-item");- expect(items.filter((item) => item.textContent === "Fast")).toHaveLength(1);- expect(items.filter((item) => item.textContent === "Low")).toHaveLength(1);- expect(items.filter((item) => item.textContent === "High")).toHaveLength(1);- expect(screen.getByRole("button", { name: "Model and effort" })).toHaveTextContent(- "Fast · Low",- );-});--it("navigates slash matches with arrows and inserts via Tab", () => {- render(<ChatComposer {...props} />);- const textbox = screen.getByRole("textbox");- fireEvent.change(textbox, { target: { value: "/" } });- expect(screen.getByTestId("slash")).toHaveAttribute("data-selected", "0");- fireEvent.keyDown(textbox, { key: "ArrowDown" });- expect(screen.getByTestId("slash")).toHaveAttribute("data-selected", "1");- fireEvent.keyDown(textbox, { key: "ArrowDown" });- expect(screen.getByTestId("slash")).toHaveAttribute("data-selected", "0");- fireEvent.keyDown(textbox, { key: "ArrowUp" });- expect(screen.getByTestId("slash")).toHaveAttribute("data-selected", "1");- fireEvent.keyDown(textbox, { key: "Tab" });- expect(textbox).toHaveValue("/clear");- expect(textbox).toHaveFocus();-});--it("inserts slash choices via click/Enter and dismisses with Escape", () => {- render(<ChatComposer {...props} />);- const textbox = screen.getByRole("textbox");- fireEvent.change(textbox, { target: { value: "/" } });- fireEvent.mouseEnter(screen.getByRole("button", { name: "clear" }));- expect(screen.getByTestId("slash")).toHaveAttribute("data-selected", "1");- fireEvent.click(screen.getByRole("button", { name: "new" }));- expect(textbox).toHaveValue("/new ");- fireEvent.change(textbox, { target: { value: "/" } });- fireEvent.keyDown(textbox, { key: "Enter" });- expect(textbox).toHaveValue("/new ");- fireEvent.change(textbox, { target: { value: "/" } });- fireEvent.keyDown(textbox, { key: "Escape" });- expect(textbox).toHaveValue("");-});--it("hides slash choices after a space, while sending, or when disabled", () => {- const { rerender } = render(<ChatComposer {...props} />);- const textbox = screen.getByRole("textbox");- fireEvent.change(textbox, { target: { value: "/new title" } });- expect(screen.queryByTestId("slash")).not.toBeInTheDocument();- rerender(<ChatComposer {...props} sendingChat busy />);- expect(screen.queryByTestId("slash")).not.toBeInTheDocument();- rerender(<ChatComposer {...props} disabled />);- expect(screen.queryByText(/Enter to send/)).not.toBeInTheDocument();-});--it("renders local/remote busy copy and stops the turn", () => {- const { rerender } = render(<ChatComposer {...props} busy sendingChat />);- expect(screen.getByText(/Streaming/)).toBeInTheDocument();- fireEvent.click(screen.getByRole("button", { name: "Stop" }));- expect(props.onStop).toHaveBeenCalled();- rerender(<ChatComposer {...props} busy sendingChat={false} />);- expect(screen.getByText(/Agent is working/)).toBeInTheDocument();-});diff --git a/notfair/src/components/chat/composer.tsx b/notfair/src/components/chat/composer.tsxdeleted file mode 100644index ddb3986f..00000000--- a/notfair/src/components/chat/composer.tsx+++ /dev/null@@ -1,290 +0,0 @@-"use client";--import { useEffect, useMemo, useRef, useState } from "react";-import { ArrowUp, ChevronDown, StopCircle } from "lucide-react";--import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuLabel,- DropdownMenuRadioGroup,- DropdownMenuRadioItem,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu";-import { RunningDot } from "@/components/running-dot";-import { SlashCommandPopover } from "@/components/slash-command-popover";-import {- filterSlashCommands,- type SlashCommand,-} from "@/lib/slash-commands";--export type ModelOption = {- value: string;- label: string;- is_default?: boolean;- reasoning_efforts?: Array<{- value: string;- label: string;- description?: string;- }>;- default_reasoning_effort?: string;-};--/**- * The chat composer: one floating rounded well with a borderless- * multiline textarea, slash-command autocomplete, a quiet model picker,- * and the circular send/stop control. Owns its input + slash state;- * everything that changes the conversation goes through `onSubmit` /- * `onStop`. The busy affordances mirror the app-grade chat pattern:- * while ANY turn is live (local send or a remote turn detected from the- * transcript), send flips to stop and the footer says so.- */-export function ChatComposer({- disabled = false,- busy,- sendingChat,- placeholder,- modelOptions = [],- model,- reasoningEffort,- onPickModel,- onPickReasoningEffort,- onSubmit,- onStop,-}: {- disabled?: boolean;- /** Any live turn — local send or detected remote turn. */- busy: boolean;- /** This tab's own streaming send (subset of busy). */- sendingChat: boolean;- placeholder: string;- modelOptions?: ModelOption[];- model: string;- reasoningEffort: string;- onPickModel: (value: string) => void;- onPickReasoningEffort: (value: string) => void;- /** Dispatch a user submission (slash routing happens upstream). */- onSubmit: (text: string) => void;- onStop: () => void;-}) {- const [input, setInput] = useState("");- const [slashIndex, setSlashIndex] = useState(0);- const textareaRef = useRef<HTMLTextAreaElement>(null);-- const defaultModel = modelOptions.find((option) => option.is_default);- const selectedModel =- modelOptions.find((option) => option.value === model) ?? defaultModel;- const selectedModelLabel = selectedModel?.label ?? "Default";- const effortOptions = selectedModel?.reasoning_efforts ?? [];- const defaultEffort =- selectedModel?.default_reasoning_effort ?? effortOptions[0]?.value;- const selectedEffort =- effortOptions.find((option) => option.value === reasoningEffort) ??- effortOptions.find((option) => option.value === defaultEffort) ??- effortOptions[0];-- // Slash command autocomplete: open while input starts with "/" and the- // user is still composing the command name (no space yet). After they- // pick or type a space, the popover closes.- const slashQuery =- input.startsWith("/") && !input.includes(" ") ? input : null;- const slashOpen = slashQuery !== null && !sendingChat && !disabled;- const slashMatches = useMemo<SlashCommand[]>(- () => (slashOpen ? filterSlashCommands(slashQuery!) : []),- [slashOpen, slashQuery],- );- const safeSlashIndex =- slashMatches.length === 0 ? 0 : Math.min(slashIndex, slashMatches.length - 1);-- function insertSlashCommand(cmd: SlashCommand) {- // Catalog `name` is the command without the leading slash ("new",- // "clear"). Insert ends with a trailing space so the popover closes —- // a second Enter then submits.- const insert = cmd.insert ?? `/${cmd.name} `;- setInput(insert);- setSlashIndex(0);- requestAnimationFrame(() => {- const ta = textareaRef.current;- if (ta) {- ta.focus();- ta.setSelectionRange(insert.length, insert.length);- }- });- }-- // Multiline auto-grow: track the content height (capped by max-h-52 via- // CSS) so the composer expands as the user types and snaps back when- // the input clears.- useEffect(() => {- const ta = textareaRef.current;- if (!ta) return;- ta.style.height = "auto";- ta.style.height = `${ta.scrollHeight}px`;- }, [input]);-- function submit() {- const text = input.trim();- if (!text || busy) return;- setInput("");- setSlashIndex(0);- onSubmit(text);- }-- return (- <div className="relative">- {slashOpen && (- <SlashCommandPopover- commands={slashMatches}- selectedIndex={safeSlashIndex}- onSelect={insertSlashCommand}- onHover={setSlashIndex}- />- )}- <form- className="rounded-[24px] bg-card shadow-[var(--notfair-shadow)] ring-1 ring-transparent transition-shadow focus-within:shadow-[var(--notfair-shadow-lg,var(--notfair-shadow))] focus-within:ring-foreground/10"- onSubmit={(e) => {- e.preventDefault();- submit();- }}- >- <textarea- ref={textareaRef}- value={input}- onChange={(e) => {- setInput(e.target.value);- setSlashIndex(0);- }}- onKeyDown={(e) => {- // Slash autocomplete: arrow keys cycle, Tab/Enter insert.- if (slashOpen && slashMatches.length > 0) {- if (e.key === "ArrowDown") {- e.preventDefault();- setSlashIndex((i) => (i + 1) % slashMatches.length);- return;- }- if (e.key === "ArrowUp") {- e.preventDefault();- setSlashIndex(- (i) => (i - 1 + slashMatches.length) % slashMatches.length,- );- return;- }- if (e.key === "Tab" || (e.key === "Enter" && !e.shiftKey)) {- e.preventDefault();- const picked = slashMatches[safeSlashIndex];- if (picked) insertSlashCommand(picked);- return;- }- if (e.key === "Escape") {- e.preventDefault();- setInput("");- setSlashIndex(0);- return;- }- }- if (e.key === "Enter" && !e.shiftKey) {- e.preventDefault();- submit();- }- }}- disabled={disabled}- placeholder={placeholder}- rows={1}- className="block max-h-52 w-full resize-none bg-transparent px-4.5 pt-3.5 text-sm leading-relaxed placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"- />- <div className="flex items-center justify-end gap-1.5 px-2.5 pb-2.5 pt-1.5">- {/* Model picker sits right next to the send button: quiet- "<model> ⌄" text trigger, dropdown opening above. */}- {modelOptions.length > 0 && (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <button- type="button"- aria-label="Model and effort"- disabled={disabled || sendingChat}- className="inline-flex max-w-44 items-center gap-1 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"- >- <span className="truncate">- {selectedModelLabel}- {selectedEffort ? ` · ${selectedEffort.label}` : ""}- </span>- <ChevronDown className="size-3 shrink-0" aria-hidden />- </button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end" side="top">- <DropdownMenuLabel>Model</DropdownMenuLabel>- <DropdownMenuRadioGroup value={model} onValueChange={onPickModel}>- {!defaultModel && (- <DropdownMenuRadioItem value="">Default</DropdownMenuRadioItem>- )}- {modelOptions.map((m) => (- <DropdownMenuRadioItem- key={m.value}- value={m.is_default ? "" : m.value}- >- {m.label}- </DropdownMenuRadioItem>- ))}- </DropdownMenuRadioGroup>- {effortOptions.length > 0 && (- <>- <DropdownMenuSeparator />- <DropdownMenuLabel>Reasoning effort</DropdownMenuLabel>- <DropdownMenuRadioGroup- value={reasoningEffort}- onValueChange={onPickReasoningEffort}- >- {effortOptions.map((option) => (- <DropdownMenuRadioItem- key={option.value}- value={option.value === defaultEffort ? "" : option.value}- title={option.description}- >- {option.label}- </DropdownMenuRadioItem>- ))}- </DropdownMenuRadioGroup>- </>- )}- </DropdownMenuContent>- </DropdownMenu>- )}- {busy ? (- <button- type="button"- onClick={onStop}- aria-label="Stop"- className="flex size-9 items-center justify-center rounded-full bg-[hsl(var(--notfair-surface-2))] text-foreground transition-colors hover:bg-[hsl(var(--notfair-hover))] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- >- <StopCircle className="size-4.5" />- </button>- ) : (- <button- type="submit"- disabled={disabled || !input.trim()}- aria-label="Send"- className="flex size-9 items-center justify-center rounded-full bg-foreground text-background transition-opacity hover:opacity-85 disabled:opacity-25 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- >- <ArrowUp className="size-4.5" />- </button>- )}- </div>- </form>- {(busy || !disabled) && (- <p className="pt-1.5 text-center text-[10px] text-muted-foreground">- {busy ? (- <span className="inline-flex items-center gap-1.5">- <RunningDot size="sm" aria-label="" />- {sendingChat- ? "Streaming — click stop to abort"- : "Agent is working — click stop to interrupt"}- </span>- ) : (- <>Enter to send · Shift+Enter for newline</>- )}- </p>- )}- </div>- );-}diff --git a/notfair/src/components/chat/live-working-indicator.test.tsx b/notfair/src/components/chat/live-working-indicator.test.tsxdeleted file mode 100644index 8c10dc08..00000000--- a/notfair/src/components/chat/live-working-indicator.test.tsx+++ /dev/null@@ -1,123 +0,0 @@-// @vitest-environment jsdom-import { act, render, screen } from "@testing-library/react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--import { LiveWorkingIndicator } from "@/components/chat/live-working-indicator";-import type { TranscriptEvent } from "@/server/sessions/transcript-tail";--const BASE = 1_800_000_000_000;--const call = (id: string, ts: number, tcid: string): TranscriptEvent => ({- kind: "tool_call",- id,- ts,- tool_call_id: tcid,- name: "shell",- label: "pnpm test",-});-const lifecycle = (id: string, ts: number, phase: string): TranscriptEvent => ({- kind: "lifecycle",- id,- ts,- phase,-});--beforeEach(() => {- vi.useFakeTimers();- vi.setSystemTime(BASE);-});-afterEach(() => {- vi.useRealTimers();-});--describe("LiveWorkingIndicator", () => {- it("shows the in-flight committed tool and ticks the elapsed clock", () => {- render(- <LiveWorkingIndicator- agentDisplayName="Growth agent"- events={[call("c1", BASE - 5_000, "t1")]}- turnStartedAt={BASE - 10_000}- />,- );- // Elapsed anchors on the later of turn start and last event ts.- // "Ran tests" shows as both the headline and the trajectory chip label.- expect(screen.getAllByText("Ran tests").length).toBeGreaterThan(0);- expect(screen.getByText("0:05")).toBeInTheDocument();- act(() => {- vi.advanceTimersByTime(2_000);- });- expect(screen.getByText("0:07")).toBeInTheDocument();- });-- it("freezes into the completed state when the turn's done event lands", () => {- render(- <LiveWorkingIndicator- agentDisplayName="Growth agent"- events={[lifecycle("l1", BASE - 1_000, "done")]}- turnStartedAt={BASE - 5_000}- />,- );- const status = screen.getByRole("status", {- name: "Growth agent Turn complete",- });- expect(status).toHaveAttribute("data-run-state", "complete");- // Ended: no elapsed timer rendered or ticking.- expect(status.querySelector(".tabular-nums")).toBeNull();- });-- it("ignores a done event from before the current turn", () => {- render(- <LiveWorkingIndicator- agentDisplayName="Growth agent"- events={[- lifecycle("l1", BASE - 60_000, "done"),- call("c1", BASE - 2_000, "t1"),- ]}- turnStartedAt={BASE - 5_000}- />,- );- expect(- screen.getByRole("status", { name: "Growth agent Ran tests" }),- ).toHaveAttribute("data-run-state", "running");- });-- it("stays visibly running while pending SSE work outlives the done event", () => {- render(- <LiveWorkingIndicator- agentDisplayName="Growth agent"- events={[lifecycle("l1", BASE - 1_000, "done")]}- turnStartedAt={BASE - 5_000}- pendingTools={[- {- toolCallId: "t9",- name: "mcp__X__runScript",- label: null,- result: null,- ok: true,- done: false,- },- ]}- />,- );- expect(- screen.getByRole("status", { name: "Growth agent Ran script" }),- ).toHaveAttribute("data-run-state", "running");- });-- it("surfaces the lifecycle phase during the pre-token wait", () => {- render(- <LiveWorkingIndicator- agentDisplayName="Growth agent"- events={[]}- turnStartedAt={BASE - 3_000}- lifecyclePhase="run.warming"- hasPendingAssistant={false}- />,- );- expect(- screen.getByRole("status", { name: "Growth agent Warming up" }),- ).toBeInTheDocument();- // No events at all → elapsed anchors on turnStartedAt.- expect(screen.getByText("0:03")).toBeInTheDocument();- });-});diff --git a/notfair/src/components/chat/live-working-indicator.tsx b/notfair/src/components/chat/live-working-indicator.tsxdeleted file mode 100644index c0a0acd5..00000000--- a/notfair/src/components/chat/live-working-indicator.tsx+++ /dev/null@@ -1,85 +0,0 @@-"use client";--import { useEffect, useState } from "react";--import { WorkingIndicator } from "@/components/working-indicator";-import type { TranscriptEvent } from "@/server/sessions/transcript-tail";-import type { ToolEntry } from "./transcript-model";-import { deriveWorkingView } from "./working-view";--/**- * The bottom-anchored "agent is working" status. Wraps the presentational- * WorkingIndicator with the live derivation: headline/subtitle/mood/phases- * from a mix of SSE-leading pending state and DB-trailing committed- * events, plus the 1Hz elapsed counter.- */-export function LiveWorkingIndicator({- agentDisplayName,- events,- turnStartedAt,- lifecyclePhase,- pendingTools,- hasPendingAssistant,-}: {- agentDisplayName: string;- events: TranscriptEvent[];- turnStartedAt: number | null;- lifecyclePhase?: string | null;- pendingTools?: ToolEntry[];- hasPendingAssistant?: boolean;-}) {- const [now, setNow] = useState<number>(() => Date.now());- // Scope the "done" check to the current turn — an earlier completed- // turn's done event must not freeze the clock on a live later turn.- const visiblyEnded =- events.some(- (e) =>- e.kind === "lifecycle" &&- e.phase === "done" &&- (turnStartedAt == null || e.ts >= turnStartedAt),- ) &&- !pendingTools?.some((t) => !t.done) &&- !hasPendingAssistant;- useEffect(() => {- if (visiblyEnded) return;- const id = setInterval(() => setNow(Date.now()), 1000);- return () => clearInterval(id);- }, [visiblyEnded]);-- const view = deriveWorkingView({- agentDisplayName,- events,- lifecyclePhase: lifecyclePhase ?? null,- pendingTools: pendingTools ?? [],- hasPendingAssistant: hasPendingAssistant ?? false,- // The indicator must only reflect the current turn — without this- // filter, the trajectory chips show every tool call from the chat's- // entire history (e.g. a fresh "hi" lit up runScript / runScript /- // listConnectedAccounts from prior audit turns).- turnStartedAt,- now,- });-- // Anchor elapsed to whichever is later: the turn-start wallclock the- // composer recorded, or the last event's timestamp. Keeps the counter- // honest during the SSE-only window where events are still empty.- const lastEvent = events.length > 0 ? events[events.length - 1] : null;- const anchorTs = (() => {- const lastTs = lastEvent?.ts ?? null;- if (turnStartedAt && lastTs) return Math.max(turnStartedAt, lastTs);- return turnStartedAt ?? lastTs;- })();- const elapsedMs =- view.mood !== "ended" && anchorTs != null ? Math.max(0, now - anchorTs) : null;-- return (- <WorkingIndicator- agentDisplayName={agentDisplayName}- headline={view.headline}- subtitle={view.subtitle}- phases={view.phases}- mood={view.mood}- elapsedMs={elapsedMs}- />- );-}diff --git a/notfair/src/components/chat/messages.test.tsx b/notfair/src/components/chat/messages.test.tsxdeleted file mode 100644index 97d4b33e..00000000--- a/notfair/src/components/chat/messages.test.tsx+++ /dev/null@@ -1,140 +0,0 @@-// @vitest-environment jsdom-import { fireEvent, render, within } from "@testing-library/react";-import { describe, expect, it } from "vitest";--import { AssistantText, RenderItem, ToolGroup } from "./messages";-import type { RenderedItem, ToolEntry } from "./transcript-model";--const runningTool: ToolEntry = {- toolCallId: "tool-1",- name: "shell",- label: "pwd",- result: null,- ok: true,- done: false,-};--describe("AssistantText", () => {- it("does not add a standalone streaming cursor below the message", () => {- const { container } = render(- <AssistantText body="The answer is still streaming." />,- );-- expect(container).toHaveTextContent("The answer is still streaming.");- expect(container.querySelector(".animate-pulse")).toBeNull();- expect(container.querySelector('span[aria-hidden="true"]')).toBeNull();- });-});--describe("ToolGroup", () => {- it("stays collapsed by default and preserves a user's expansion when the tool finishes", () => {- const { container, rerender } = render(- <ToolGroup tools={[runningTool]} />,- );- const details = container.querySelector("details");- const summary = container.querySelector("summary");-- expect(details).not.toHaveAttribute("open");- fireEvent.click(summary!);- expect(details).toHaveAttribute("open");-- rerender(- <ToolGroup- tools={[- {- ...runningTool,- result: "done",- done: true,- },- ]}- />,- );-- expect(container.querySelector("details")).toBe(details);- expect(details).toHaveAttribute("open");- });-- it("puts the disclosure control after the activity text and expands a flat scrollable list", () => {- const { container } = render(- <ToolGroup- tools={[- {- ...runningTool,- toolCallId: "edit-1",- name: "Edit",- label: "src/page.tsx",- done: true,- },- {- ...runningTool,- toolCallId: "read-1",- name: "Read",- label: "DESIGN.md",- done: true,- },- {- ...runningTool,- toolCallId: "shell-1",- label: "rg -n ToolGroup src",- done: true,- },- ]}- />,- );-- const summary = container.querySelector("summary")!;- const label = summary.querySelector("[data-tool-summary]")!;- const toggle = summary.querySelector("[data-tool-toggle]")!;- const list = container.querySelector("[data-tool-list]")!;-- expect(label).toHaveTextContent("Edited file, read file, ran command");- expect(label.nextElementSibling).toBe(toggle);- expect(toggle).toHaveClass("opacity-0");- expect(summary).toHaveClass("relative");- expect(list).toHaveClass("max-h-64", "overflow-y-auto");- expect(list.querySelectorAll("[data-tool-row]")).toHaveLength(3);- for (const row of list.querySelectorAll("[data-tool-row]")) {- expect(row).toHaveClass("relative");- }- expect(list.querySelector("[data-tool-row] .ml-5")).toBeNull();- });-});--describe("check prompt disclosure", () => {- it("lets the user expand the exact prompt that started a check", () => {- const prompt = [- "[TICK] Goal heartbeat #49 — 2026-07-21T20:00:00.000Z",- "",- "## Metric (measured by the platform just now)",- "- Lead-form failures: **2**",- ].join("\n");- const item: RenderedItem = {- kind: "user_message",- key: "tick-prompt",- body: prompt,- system: true,- };-- const { container } = render(<RenderItem item={item} />);- const details = container.querySelector("details");-- expect(details).not.toHaveAttribute("open");- const summary = container.querySelector("summary")!;- expect(summary).toHaveTextContent("View exact prompt");- expect(summary).toHaveClass("focus-visible:ring-2", "focus-visible:ring-ring");- const promptMessage = container.querySelector(- "[data-check-trigger-prompt]",- ) as HTMLElement;- expect(- within(promptMessage).getByRole("heading", {- level: 2,- name: "Metric (measured by the platform just now)",- }),- ).toBeInTheDocument();- expect(promptMessage.querySelector("strong")).toHaveTextContent("2");- expect(container).not.toHaveTextContent("Exact prompt sent to the agent");-- fireEvent.click(container.querySelector("summary")!);- expect(details).toHaveAttribute("open");- });-});diff --git a/notfair/src/components/chat/messages.tsx b/notfair/src/components/chat/messages.tsxdeleted file mode 100644index bb1f0e6c..00000000--- a/notfair/src/components/chat/messages.tsx+++ /dev/null@@ -1,445 +0,0 @@-"use client";--import { useState } from "react";-import {- AlertCircle,- BookOpen,- ChevronRight,- MessageCircle,- Search,- Terminal,- Wrench,-} from "lucide-react";--import { Markdown } from "@/components/markdown";-import { brandDomain } from "@/components/mcp-icon";-import { cn } from "@/lib/utils";-import {- humanizeTool,- iconForTool,- looksLikeShellInvocation,- matchMcpServerKey,- type McpCatalogEntryLite,-} from "./tool-intent";-import type { RenderedItem, ToolEntry } from "./transcript-model";--/**- * Presentational chat pieces — no stream state in this file. Styling- * follows the Claude/ChatGPT chat grammar: user turns are compact- * right-aligned bubbles, agent turns are unboxed prose, tool activity is- * a quiet collapsible line between them, and surfaces separate by- * elevation and tint rather than borders.- */--export function RenderItem({- item,- mcpCatalog,-}: {- item: RenderedItem;- mcpCatalog?: McpCatalogEntryLite[];-}) {- if (item.kind === "user_message") {- // Platform-generated briefs (goal intake kickoff, tick briefs) are- // not something the user typed — render a compact system line so the- // chat reads as "the agent got to work", not "who wrote this?".- if (item.system) {- const isCheckPrompt = item.body.startsWith("[TICK]");- const label = isCheckPrompt- ? "Check started — prompt delivered to the agent"- : item.body.startsWith("[INTAKE]")- ? "Goal created — your ambition was handed to the agent"- : "Scheduled brief delivered to the agent";- return (- <SystemLine- label={label}- prompt={isCheckPrompt ? item.body : undefined}- />- );- }- return <UserBubble body={item.body} />;- }- if (item.kind === "assistant_text") {- return <AssistantText body={item.body} />;- }- if (item.kind === "tool_group") {- return <ToolGroup tools={item.tools} mcpCatalog={mcpCatalog} />;- }- return null;-}--export function SystemLine({- label,- prompt,-}: {- label: string;- /** Verbatim platform prompt that initiated this check. */- prompt?: string;-}) {- if (prompt) {- return (- <details className="group/check-prompt mx-auto w-full max-w-2xl">- <summary className="flex cursor-pointer list-none justify-center rounded-full ring-offset-background select-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 [&::-webkit-details-marker]:hidden">- <span className="flex items-center gap-1.5 rounded-full bg-[hsl(var(--notfair-surface-2))] px-3.5 py-1 text-[11.5px] text-[hsl(var(--notfair-ink-4))]">- <span>{label}</span>- <span className="font-medium text-[hsl(var(--notfair-accent))]">- View exact prompt- </span>- <ChevronRight- className="size-3.5 transition-transform group-open/check-prompt:rotate-90"- aria-hidden- />- </span>- </summary>- <div className="mt-3 flex justify-end">- <div- data-check-trigger-prompt- className="max-h-96 max-w-[88%] overflow-y-auto rounded-[20px] rounded-br-md bg-[hsl(var(--notfair-surface-2))] px-4 py-3 text-foreground/95 shadow-sm"- >- <Markdown>{prompt}</Markdown>- </div>- </div>- </details>- );- }-- return (- <div className="flex justify-center">- <span className="rounded-full bg-[hsl(var(--notfair-surface-2))] px-3.5 py-1 text-[11.5px] text-[hsl(var(--notfair-ink-4))]">- {label}- </span>- </div>- );-}--export function UserBubble({ body }: { body: string }) {- return (- <div className="flex justify-end">- <div className="max-w-[82%] rounded-[20px] rounded-br-md bg-[hsl(var(--notfair-surface-2))] px-4 py-2.5 text-[14.5px] leading-relaxed text-foreground/95 shadow-sm whitespace-pre-wrap break-words">- {body}- </div>- </div>- );-}--export function AssistantText({- body,-}: {- body: string;-}) {- if (body.trim() === "") return null;- return (- <div className="text-[15px] leading-[1.75] text-foreground/95">- <Markdown>{body}</Markdown>- </div>- );-}--export function ToolGroup({- tools,- mcpCatalog,-}: {- tools: ToolEntry[];- mcpCatalog?: McpCatalogEntryLite[];-}) {- const inFlightCount = tools.filter((t) => !t.done).length;- const isLive = inFlightCount > 0;- const lastDone = [...tools].reverse().find((t) => t.done);- const hasError = !!(lastDone && !lastDone.ok);- const headline = representativeTool(tools);- const headMcp = headline- ? matchMcpServerKey(headline.name, mcpCatalog)- : null;- const HeadIcon = headline ? iconForSummary(headline) : Wrench;- const summaryLabel = summarizeTools(tools);- const statusLabel = isLive ? "Running" : hasError ? "Failed" : "Complete";-- return (- <details- data-activity-kind={headMcp ? "mcp" : "tool"}- className="group/details"- >- <summary- className={cn(- "group/summary relative flex min-h-8 cursor-pointer list-none select-none items-center gap-2 py-0.5 text-[15px] leading-6",- "text-[hsl(var(--notfair-ink-3))] focus-visible:outline-none [&::-webkit-details-marker]:hidden",- )}- >- <span className="flex size-4 shrink-0 items-center justify-center">- {headMcp ? (- <ToolBrandFavicon- resourceUrl={headMcp.resource_url}- alt={headMcp.display_name}- />- ) : (- <HeadIcon className="size-4" aria-hidden />- )}- </span>- <span- data-tool-summary- className={cn(- "min-w-0 truncate",- isLive && "ns-shimmer-text",- )}- >- {summaryLabel}- </span>- <ChevronRight- data-tool-toggle- className="size-4 shrink-0 opacity-0 transition-[transform,opacity] group-hover/summary:opacity-100 group-focus-visible/summary:opacity-100 group-open/details:rotate-90 group-open/details:opacity-100"- aria-hidden- />- <span className="sr-only">{statusLabel}</span>- </summary>- <div- data-tool-list- className="mt-1 max-h-64 overflow-y-auto overscroll-contain text-[15px] leading-6 text-[hsl(var(--notfair-ink-3))]"- >- {tools.map((t, index) => (- <ToolRow- key={`${t.toolCallId}:${index}`}- entry={t}- mcpCatalog={mcpCatalog}- />- ))}- </div>- </details>- );-}--function ToolRow({- entry,- mcpCatalog,-}: {- entry: ToolEntry;- mcpCatalog?: McpCatalogEntryLite[];-}) {- const intent = humanizeTool(entry.name, entry.label);- const mcp = matchMcpServerKey(entry.name, mcpCatalog);- const Icon = iconForActivity(entry);- const rowLabel = formatActivityLabel(intent.verb, intent.target);- const statusLabel = !entry.done- ? "Running"- : entry.ok- ? "Complete"- : "Failed";-- return (- <div- data-tool-row- data-tool-status={statusLabel.toLowerCase()}- className="relative flex min-h-7 items-center gap-2 py-0.5"- title={entry.label ?? rowLabel}- >- <span className="flex size-4 shrink-0 items-center justify-center">- {mcp ? (- <ToolBrandFavicon- resourceUrl={mcp.resource_url}- alt={mcp.display_name}- />- ) : (- <Icon className="size-4" aria-hidden />- )}- </span>- <span className="min-w-0 truncate">{rowLabel}</span>- <span className="sr-only">{statusLabel}</span>- </div>- );-}--type ActivityCategory = "edit" | "read" | "command" | "other";--function activityCategory(entry: ToolEntry): ActivityCategory {- const name = entry.name.toLowerCase();- if (name === "write" || name === "edit" || name === "patch") return "edit";- if (name === "read" || name === "cat" || name === "open") return "read";- if (- name === "shell" ||- name === "bash" ||- name === "exec" ||- looksLikeShellInvocation(entry.name) ||- looksLikeShellInvocation(entry.label ?? "")- ) {- return "command";- }- return "other";-}--/**- * Use the same quiet, category-level summary as the reference transcript:- * "Edited files, read files, ran commands" rather than a tool count.- */-function summarizeTools(tools: ToolEntry[]): string {- if (tools.length === 0) return "Tool activity";- const phrases: string[] = [];- const editCount = tools.filter(- (tool) => activityCategory(tool) === "edit",- ).length;- const readCount = tools.filter(- (tool) => activityCategory(tool) === "read",- ).length;- const commandCount = tools.filter(- (tool) => activityCategory(tool) === "command",- ).length;-- if (editCount > 0)- phrases.push(editCount === 1 ? "Edited file" : "Edited files");- if (readCount > 0)- phrases.push(readCount === 1 ? "Read file" : "Read files");- if (commandCount > 0)- phrases.push(commandCount === 1 ? "Ran command" : "Ran commands");-- for (const tool of tools) {- if (activityCategory(tool) !== "other") continue;- const verb = humanizeTool(tool.name, tool.label).verb;- if (!phrases.some((phrase) => phrase.toLowerCase() === verb.toLowerCase())) {- phrases.push(verb);- }- }-- return phrases- .map((phrase, index) =>- index === 0 ? phrase : phrase.charAt(0).toLowerCase() + phrase.slice(1),- )- .join(", ");-}--function representativeTool(tools: ToolEntry[]): ToolEntry | null {- for (const category of ["edit", "read", "command", "other"] as const) {- const match = tools.find((tool) => activityCategory(tool) === category);- if (match) return match;- }- return null;-}--function iconForActivity(entry: ToolEntry) {- const verb = humanizeTool(entry.name, entry.label).verb.toLowerCase();- if (verb.startsWith("searched")) return Search;- if (verb.startsWith("read")) return BookOpen;- return iconForTool(entry.name);-}--function iconForSummary(entry: ToolEntry) {- const category = activityCategory(entry);- if (category === "read") return BookOpen;- if (category === "command") return Terminal;- return iconForActivity(entry);-}--function formatActivityLabel(verb: string, target?: string): string {- if (!target) return verb;- // The intent already supplies the noun through the target, so avoid- // stilted rows such as "Read file DESIGN.md".- const compactVerb = verb.replace(/\s+(?:file|url)$/i, "");- return `${compactVerb} ${target}`;-}--/**- * Tiny inline favicon for an MCP tool row — sized to fit the same 3.5- * grid slot as the lucide icons next to it, so MCP and built-in tools- * align cleanly in the same column.- */-function ToolBrandFavicon({- resourceUrl,- alt,-}: {- resourceUrl: string;- alt: string;-}) {- const [errored, setErrored] = useState(false);- let host: string | null = null;- try {- host = new URL(resourceUrl).hostname;- } catch {- host = null;- }- const brand = host ? brandDomain(host) : null;- if (!brand || errored) {- return <Wrench className="size-3.5 shrink-0 text-muted-foreground" />;- }- return (- // eslint-disable-next-line @next/next/no-img-element- <img- src={`https://t3.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=http://${brand}&size=16`}- alt={alt}- width={14}- height={14}- className="size-3.5 shrink-0 rounded-[3px]"- referrerPolicy="no-referrer"- onError={() => setErrored(true)}- />- );-}--/**- * Replaces the working indicator when the task is parked in `blocked`.- * The agent isn't currently running — it's dormant until the gating- * condition (most often a pending approval) resolves.- */-export function BlockedStatus({ reason }: { reason: string }) {- return (- <div className="flex items-start gap-2.5 rounded-xl bg-[hsl(var(--notfair-warn)/0.1)] px-3.5 py-2.5 text-xs">- <span- className="mt-1 inline-block size-2 shrink-0 rounded-full bg-[hsl(var(--notfair-warn))]"- aria-hidden- />- <div className="min-w-0 flex-1">- <div className="font-medium text-[hsl(var(--notfair-warn))]">- Paused — {reason}- </div>- <div className="mt-0.5 text-[11px] text-[hsl(var(--notfair-ink-3))]">- The agent will resume automatically when the gating condition- resolves. You can also reply below to give context or answer a- question.- </div>- </div>- </div>- );-}--export function ErrorRow({- agentDisplayName,- body,-}: {- agentDisplayName: string;- body: string;-}) {- return (- <div className="flex items-start gap-2.5 rounded-xl bg-destructive/10 px-3.5 py-3 text-sm">- <AlertCircle className="mt-0.5 size-4 shrink-0 text-destructive" />- <div className="min-w-0 flex-1">- <div className="font-medium text-destructive">- Couldn’t reach {agentDisplayName}.- </div>- <div className="mt-1 text-xs text-muted-foreground whitespace-pre-wrap break-words">- {body}- </div>- </div>- </div>- );-}--export function TranscriptEmptyState({- agentDisplayName,-}: {- agentDisplayName: string;-}) {- return (- <div className="flex flex-col items-center gap-3 py-20 text-center">- <div className="flex size-11 items-center justify-center rounded-full bg-[hsl(var(--notfair-surface-2))] shadow-sm">- <MessageCircle- className="size-5 text-[hsl(var(--notfair-ink-3))]"- aria-hidden- />- </div>- <div>- <p className="m-0 text-[14px] font-medium text-foreground/90">- Chat with {agentDisplayName}- </p>- <p className="m-0 mt-1 text-[12.5px] text-muted-foreground">- Ask about its metric, steer the plan, or hand it new context —- type <span className="font-mono">/</span> for commands.- </p>- </div>- </div>- );-}diff --git a/notfair/src/components/chat/tool-intent.test.ts b/notfair/src/components/chat/tool-intent.test.tsdeleted file mode 100644index e82feffc..00000000--- a/notfair/src/components/chat/tool-intent.test.ts+++ /dev/null@@ -1,275 +0,0 @@-import { Edit3, FileText, Globe, Terminal, Wrench } from "lucide-react";-import { describe, expect, it } from "vitest";--import {- formatToolName,- humanizeShellCommand,- humanizeTool,- iconForTool,- looksLikeShellInvocation,- matchMcpServerKey,- shortenPathish,-} from "./tool-intent";--describe("formatToolName", () => {- it("keeps only the action after nested namespace separators", () => {- expect(formatToolName("mcp__NotFair-GoogleAds__createCampaign")).toBe(- "createCampaign",- );- expect(formatToolName("notfair_demo__notfair_goals.propose_target")).toBe(- "propose_target",- );- expect(formatToolName("runScript")).toBe("runScript");- expect(formatToolName("")).toBe("");- });-});--describe("looksLikeShellInvocation", () => {- it("recognizes wrapper prefixes, binary paths, and metacharacters", () => {- expect(looksLikeShellInvocation('bash -lc "ls -la"')).toBe(true);- expect(looksLikeShellInvocation("/usr/bin/find . -name x")).toBe(true);- expect(looksLikeShellInvocation("cat a.txt | grep foo")).toBe(true);- });-- it("leaves tool identifiers and short tokens alone", () => {- expect(looksLikeShellInvocation("runScript")).toBe(false);- expect(looksLikeShellInvocation("ls")).toBe(false);- expect(looksLikeShellInvocation("")).toBe(false);- });-});--describe("humanizeShellCommand", () => {- it("unwraps the bash -lc wrapper before mapping the verb", () => {- expect(humanizeShellCommand(`/bin/zsh -lc 'git status --short'`)).toEqual({- verb: "Ran git status",- });- });-- it("maps common leading binaries to verb phrases", () => {- expect(humanizeShellCommand("pwd")).toEqual({ verb: "Checked working directory" });- expect(humanizeShellCommand("ls src/lib")).toEqual({- verb: "Listed files",- target: "src/lib",- });- expect(humanizeShellCommand("find . -name '*.ts'")).toMatchObject({- verb: "Searched the filesystem",- });- expect(humanizeShellCommand(`rg -n "needle" src`)).toEqual({- verb: "Searched files",- target: `"needle"`,- });- expect(humanizeShellCommand("cat package.json")).toEqual({- verb: "Read file",- target: "package.json",- });- expect(humanizeShellCommand("git")).toMatchObject({ verb: "Ran git" });- });-- it("understands package-manager subcommands", () => {- expect(humanizeShellCommand("pnpm test")).toEqual({ verb: "Ran tests" });- expect(humanizeShellCommand("npm install left-pad")).toEqual({- verb: "Installed packages",- });- expect(humanizeShellCommand("pnpm run build")).toEqual({ verb: "Ran pnpm build" });- expect(humanizeShellCommand("pnpm run")).toEqual({ verb: "Ran pnpm" });- expect(humanizeShellCommand("yarn why react")).toEqual({ verb: "Ran yarn why" });- expect(humanizeShellCommand("bun")).toEqual({ verb: "Ran bun" });- });-- it("covers scripts, network fetches, and file mutations", () => {- expect(humanizeShellCommand("node scripts/seed.ts")).toEqual({- verb: "Ran script",- target: "scripts/seed.ts",- });- expect(humanizeShellCommand("curl -s https://example.com/api")).toEqual({- verb: "Fetched URL",- target: "https://example.com/api",- });- expect(humanizeShellCommand("mkdir -p out/dir")).toEqual({- verb: "Created directory",- target: "out/dir",- });- expect(humanizeShellCommand("touch a.txt")).toEqual({- verb: "Created file",- target: "a.txt",- });- expect(humanizeShellCommand("rm -rf build")).toEqual({- verb: "Removed file(s)",- target: "build",- });- expect(humanizeShellCommand("mv a b")).toEqual({ verb: "Moved file" });- expect(humanizeShellCommand("cp a b")).toEqual({ verb: "Copied file" });- expect(humanizeShellCommand("sed -i '' 's/a/b/' file.txt")).toMatchObject({- verb: "Edited text",- });- expect(humanizeShellCommand("which node")).toEqual({- verb: "Located binary",- target: "node",- });- expect(humanizeShellCommand("echo hi")).toEqual({ verb: "Printed text" });- expect(humanizeShellCommand("make build")).toEqual({ verb: "Ran make build" });- expect(humanizeShellCommand("make")).toEqual({ verb: "Ran make" });- expect(humanizeShellCommand("docker ps")).toEqual({ verb: "Ran docker ps" });- expect(humanizeShellCommand("kubectl get pods")).toEqual({- verb: "Ran kubectl get",- });- expect(humanizeShellCommand("gh pr list")).toEqual({ verb: "Ran gh pr" });- });-- it("only reads the leading command of a pipeline", () => {- expect(humanizeShellCommand("cat log.txt | tail -20")).toEqual({- verb: "Read file",- target: "log.txt",- });- });-- it("falls back to Ran <bin> with a truncated first line", () => {- const long = `weirdtool ${"x".repeat(100)}`;- const intent = humanizeShellCommand(long);- expect(intent.verb).toBe("Ran weirdtool");- expect(intent.target!.length).toBe(80);- expect(intent.target!.endsWith("…")).toBe(true);- });-- it("handles an empty command", () => {- expect(humanizeShellCommand("")).toEqual({ verb: "Ran shell command" });- });-});--describe("humanizeTool", () => {- it("routes shell-flavored names through the shell humanizer", () => {- expect(humanizeTool("Bash", "git diff --stat")).toEqual({ verb: "Ran git diff" });- // Legacy rows: the command line stored as the NAME, label empty.- expect(humanizeTool(`bash -lc "ls src"`, null)).toEqual({- verb: "Listed files",- target: "src",- });- });-- it("maps the built-in coding tools with pathish targets", () => {- expect(humanizeTool("Read", "/Users/x/repo/src/lib/slug.ts")).toEqual({- verb: "Read file",- target: "…/lib/slug.ts",- });- expect(humanizeTool("write", "notes.md")).toEqual({- verb: "Wrote file",- target: "notes.md",- });- expect(humanizeTool("edit", null)).toEqual({ verb: "Edited file", target: undefined });- expect(humanizeTool("patch", "a/b/c/d.ts")).toEqual({- verb: "Edited file",- target: "…/c/d.ts",- });- expect(humanizeTool("webfetch", "https://example.com")).toEqual({- verb: "Fetched URL",- target: "https://example.com",- });- expect(humanizeTool("websearch", "notfair pricing")).toEqual({- verb: "Searched the web",- target: "notfair pricing",- });- });-- it("speaks MCP verb-first action names in natural language", () => {- expect(humanizeTool("mcp__X__getInsights", null).verb).toBe("Fetched insights");- expect(humanizeTool("mcp__X__searchGeoTargets", null).verb).toBe(- "Searched geo targets",- );- expect(humanizeTool("mcp__X__addKeyword", null).verb).toBe("Created keyword");- expect(humanizeTool("mcp__X__deleteThing", null).verb).toBe("Removed thing");- expect(humanizeTool("mcp__X__enableCampaign", null).verb).toBe("Enabled campaign");- expect(humanizeTool("mcp__X__pauseAdGroup", null).verb).toBe("Paused ad group");- expect(humanizeTool("mcp__X__resumeAd", null).verb).toBe("Resumed ad");- expect(humanizeTool("mcp__X__renameCampaign", null).verb).toBe("Renamed campaign");- expect(humanizeTool("mcp__X__proposeTarget", null).verb).toBe("Proposed target");- expect(humanizeTool("mcp__X__logLearning", null).verb).toBe("Logged learning");- expect(humanizeTool("mcp__X__reviewChangeImpact", null).verb).toBe(- "Reviewed change impact",- );- expect(humanizeTool("mcp__X__registerMetric", null).verb).toBe("Registered metric");- expect(humanizeTool("mcp__X__backfillHistory", null).verb).toBe(- "Backfilled history",- );- expect(humanizeTool("mcp__X__verifyDefinition", null).verb).toBe(- "Verified definition",- );- expect(humanizeTool("mcp__X__uploadClickConversions", null).verb).toBe(- "Uploaded click conversions",- );- expect(humanizeTool("mcp__X__sendReport", null).verb).toBe("Sent report");- expect(humanizeTool("mcp__X__list", null).verb).toBe("Listed records");- expect(humanizeTool("mcp__X__get", null).verb).toBe("Fetched data");- expect(humanizeTool("mcp__X__create", null).verb).toBe("Created a record");- expect(humanizeTool("mcp__X__set", null).verb).toBe("Updated a record");- });-- it("detects SQL-looking labels for exec-style tools", () => {- expect(humanizeTool("mcp__X__exec", "SELECT 1")).toEqual({- verb: "Ran a query",- target: "SELECT 1",- });- // exec with a non-SQL label reads as a generic command.- expect(humanizeTool("mcp__X__execute", "do the thing")).toEqual({- verb: "Ran a command",- target: "do the thing",- });- expect(humanizeTool("mcp__X__runScript", null).verb).toBe("Ran script");- });-- it("falls back to Called <action> for unknown verbs", () => {- expect(humanizeTool("mcp__X__frobnicateWidget", null).verb).toBe(- "Called frobnicate widget",- );- });-});--describe("shortenPathish", () => {- it("keeps short paths and URLs intact, compresses deep paths", () => {- expect(shortenPathish("a/b")).toBe("a/b");- expect(shortenPathish("https://example.com/a/b/c")).toBe(- "https://example.com/a/b/c",- );- expect(shortenPathish("/very/deep/nested/file.ts")).toBe("…/nested/file.ts");- expect(shortenPathish("")).toBe("");- });-});--describe("matchMcpServerKey", () => {- const catalog = [- {- key: "NotFair-GoogleAds",- display_name: "Google Ads",- resource_url: "https://notfair.co",- },- ];-- it("matches the Codex dotted shape with a namespaced server key", () => {- expect(- matchMcpServerKey("notfair_demo__notfair_googleads.runScript", catalog)- ?.display_name,- ).toBe("Google Ads");- // Bare dotted server key too.- expect(- matchMcpServerKey("notfair-googleads.runScript", catalog)?.display_name,- ).toBe("Google Ads");- });-- it("returns null without a recognizable prefix or catalog", () => {- expect(matchMcpServerKey("mcp__Unknown__tool", catalog)).toBeNull();- expect(matchMcpServerKey("plainTool", catalog)).toBeNull();- expect(matchMcpServerKey("", catalog)).toBeNull();- expect(matchMcpServerKey("mcp__NotFair-GoogleAds__x", [])).toBeNull();- expect(matchMcpServerKey("mcp__NotFair-GoogleAds__x", undefined)).toBeNull();- });-});--describe("iconForTool", () => {- it("picks the icon family by tool name", () => {- expect(iconForTool("shell")).toBe(Terminal);- expect(iconForTool("Bash")).toBe(Terminal);- expect(iconForTool("read")).toBe(FileText);- expect(iconForTool("edit")).toBe(Edit3);- expect(iconForTool("webfetch")).toBe(Globe);- expect(iconForTool("runScript")).toBe(Wrench);- });-});diff --git a/notfair/src/components/chat/tool-intent.ts b/notfair/src/components/chat/tool-intent.tsdeleted file mode 100644index e1a7f2d1..00000000--- a/notfair/src/components/chat/tool-intent.ts+++ /dev/null@@ -1,433 +0,0 @@-import {- Edit3,- FileText,- Globe,- Terminal,- Wrench,- type LucideIcon,-} from "lucide-react";--/**- * Tool-name humanization for the chat surface. Pure functions only —- * everything here maps raw harness tool identifiers and command lines to- * the short human phrases the transcript shows.- */--/**- * Minimum catalog shape the chat needs to render an MCP server's brand icon- * next to its tool calls. Mirrors `McpSpec` from `mcp-catalog.ts` — we- * accept the broader type but only use these fields here.- */-export type McpCatalogEntryLite = {- key: string;- display_name: string;- resource_url: string;-};--export type ToolIntent = { verb: string; target?: string };--/**- * Strip the project-slug prefix and the namespace path so the user sees- * the bare action name. Tools come in two conventions:- * `<mcp>.action` → e.g. `notfair.runScript`- * `<project>-<mcp>__action` → e.g. `demo1-notfair-googleads__runScript`- * Both should render as just the action. Falls back to the input untouched.- */-export function formatToolName(name: string): string {- if (!name) return name;- // Codex names can nest both separators (`notfair_<slug>__notfair_goals.propose_target`)- // — strip namespaces for BOTH, keeping only the action.- let out = name;- for (const sep of ["__", "."]) {- const idx = out.lastIndexOf(sep);- if (idx >= 0) {- const tail = out.slice(idx + sep.length);- if (tail) out = tail;- }- }- return out;-}--/**- * Human-readable intent for a tool call, used wherever we'd otherwise- * surface a raw command line or namespaced tool identifier in the chat.- *- * Two layers:- * 1. Shell-flavored names (`shell`, `bash`, `exec`, Claude's `Bash`):- * unwrap the standard `bash -lc "..."` wrapper, look at the leading- * binary, map common ones to verb phrases (`rg` → "Searched files",- * `git status` → "Ran git status", …). Falls back to `Ran <bin>`.- * 2. Built-in coding tools (Read, Write, Edit, fetch, …) and MCP tool- * names (`runScript`, `mcp__notfair__listAdAccounts`, …) get a- * tailored verb based on the tool name, with the label surfaced as- * the target detail (file path, URL, or short label string).- *- * The returned `verb` is what the collapsed tool group shows; `target`- * is the optional second-half detail truncated by the row's CSS. The- * raw command/label still lives in the expanded body so power users can- * see exactly what ran.- */-export function humanizeTool(name: string, label: string | null): ToolIntent {- const n = (name ?? "").toLowerCase();- // Shell / exec — Codex (`shell`) and Claude Code (`Bash` / `bash` / `exec`).- // Also catches the legacy transcript rows the v0.4.2 parser left behind:- // old codex `command_execution` items stored the raw command's first- // line as BOTH name and label, so we sniff the name/label for the- // characteristic shell wrapper (`bash -lc "…"`, leading `/bin/zsh`,- // etc.) and route them through the shell humanizer too.- if (- n === "shell" ||- n === "bash" ||- n === "exec" ||- looksLikeShellInvocation(name) ||- looksLikeShellInvocation(label ?? "")- ) {- // Prefer the label when present (newer events store the command- // there); fall back to the name for pre-fix rows where the command- // was written into the name field.- const cmdSource = label && label.trim().length > 0 ? label : name ?? "";- return humanizeShellCommand(cmdSource);- }- // File reads.- if (n === "read" || n === "cat" || n === "open") {- return { verb: "Read file", target: label ? shortenPathish(label) : undefined };- }- // File writes / edits.- if (n === "write")- return { verb: "Wrote file", target: label ? shortenPathish(label) : undefined };- if (n === "edit" || n === "patch")- return { verb: "Edited file", target: label ? shortenPathish(label) : undefined };- // Web.- if (n === "fetch" || n === "webfetch" || n.includes("http"))- return { verb: "Fetched URL", target: label ?? undefined };- if (n === "websearch" || n === "search" || n === "google")- return { verb: "Searched the web", target: label ?? undefined };- // MCP / generic tool — strip namespace prefixes and speak the action- // in natural language ("Listed ad accounts", "Ran a query", …).- return mcpActionIntent(formatToolName(name), label, name);-}--/**- * Natural-language intent for an MCP/generic action name. The convention- * across the catalog is verb-first camelCase (`listAdAccounts`,- * `updateCampaignBudget`, `exec`), so the leading token picks the verb- * phrase and the rest names the object. Unknown verbs fall back to- * "Called <action>" — honest, never wrong.- */-function mcpActionIntent(- action: string,- label: string | null,- fullName = "",-): ToolIntent {- const pretty = prettifyToolAction(action); // e.g. "list ad accounts"- const [head = "", ...rest] = pretty.split(" ");- const obj = rest.join(" ");- const target = label ?? undefined;- // SQL-looking labels beat name heuristics: whatever the tool is called,- // the user is looking at a query. Analytics servers whose exec IS a- // query engine (PostHog) qualify by name even for label-less legacy- // rows — their exec has no other meaning.- const sqlish =- (!!label &&- /^\s*(select|with|insert|delete\s+from|update\s+\w+\s+set)\b/i.test(label)) ||- fullName.toLowerCase().includes("posthog");- switch (head.toLowerCase()) {- case "exec":- case "execute":- case "query":- case "hogql":- return { verb: sqlish ? "Ran a query" : "Ran a command", target };- case "run":- return { verb: obj ? `Ran ${obj}` : sqlish ? "Ran a query" : "Ran a task", target };- case "list":- return { verb: obj ? `Listed ${obj}` : "Listed records", target };- case "get":- case "fetch":- case "read":- return { verb: obj ? `Fetched ${obj}` : "Fetched data", target };- case "search":- return { verb: obj ? `Searched ${obj}` : "Searched", target };- case "create":- case "add":- return { verb: obj ? `Created ${obj}` : "Created a record", target };- case "update":- case "set":- case "amend":- return { verb: obj ? `Updated ${obj}` : "Updated a record", target };- case "delete":- case "remove":- return { verb: obj ? `Removed ${obj}` : "Removed a record", target };- case "enable":- return { verb: `Enabled ${obj || "a resource"}`, target };- case "pause":- return { verb: `Paused ${obj || "a resource"}`, target };- case "resume":- return { verb: `Resumed ${obj || "a resource"}`, target };- case "rename":- return { verb: `Renamed ${obj || "a resource"}`, target };- case "propose":- return { verb: `Proposed ${obj || "a change"}`, target };- case "log":- return { verb: `Logged ${obj || "a record"}`, target };- case "review":- return { verb: `Reviewed ${obj || "a record"}`, target };- case "register":- return { verb: `Registered ${obj || "a record"}`, target };- case "backfill":- return { verb: `Backfilled ${obj || "history"}`, target };- case "verify":- return { verb: `Verified ${obj || "a definition"}`, target };- case "upload":- return { verb: `Uploaded ${obj || "data"}`, target };- case "send":- return { verb: `Sent ${obj || "a message"}`, target };- default:- return { verb: `Called ${pretty}`, target };- }-}--const SHELL_WRAPPER_RE =- /^(?:[/\w.-]+\/)?(?:zsh|bash|sh|dash|ksh)\s+(?:-[A-Za-z]*c|-c)\s+(['"])([\s\S]*)\1\s*$/;--/**- * Heuristic for "this string is a shell command, not a tool identifier."- * Used to rescue transcript rows from before v0.4.3, where the codex- * parser stored the raw command's first line as the tool `name`. Those- * rows were rendering with the catch-all "Called …" verb, often- * truncated to garbage like `Called md"` after `formatToolName` split- * on the trailing `.md"`. Conservative — only matches recognizable- * shell prefixes, command separators in non-trivial strings, or- * leading `/usr/bin`-style binary paths. Returns false on empty / short- * tokens so real MCP tool names like `runScript` don't get misrouted.- */-export function looksLikeShellInvocation(s: string): boolean {- if (!s) return false;- const t = s.trim();- if (t.length < 3) return false;- // Standard `bash -lc "..."`-style wrappers.- if (/^(?:[/\w.-]+\/)?(?:zsh|bash|sh|dash|ksh)\s+(?:-[A-Za-z]*c|-c)\b/.test(t))- return true;- // Leading absolute binary path (e.g. `/usr/bin/find`, `/bin/ls`).- if (/^\/(?:usr\/|bin\/|opt\/|sbin\/)/.test(t)) return true;- // Contains shell metacharacters in a way that's incompatible with any- // sane tool identifier — pipes, redirects, quoted args, command- // chains. Combined with a length guard above this skips short- // identifiers but catches multi-token command lines.- if (/\s\|\s|\s&&\s|\s>>?\s|^["']|["']\s|\s["']/.test(t)) return true;- return false;-}--function unwrapShellWrapper(cmd: string): string {- const m = cmd.trim().match(SHELL_WRAPPER_RE);- if (m) return m[2]!.trim();- return cmd.trim();-}--export function humanizeShellCommand(rawCmd: string): ToolIntent {- const inner = unwrapShellWrapper(rawCmd);- if (!inner) return { verb: "Ran shell command" };- // Take the leading effective command (before pipes / && / ;). Stops short- // of full shell parsing — good enough for the leading-verb mapping.- const lead = inner.split(/\s*(?:[|&;]|\|\|)\s*/)[0]!.trim();- const tokens = lead.split(/\s+/);- const head = (tokens[0] ?? "").toLowerCase();- const sub = tokens[1] ?? "";- const firstLine = inner.split("\n")[0]!;- const targetForExpand =- firstLine.length > 80 ? `${firstLine.slice(0, 79)}…` : firstLine;- switch (head) {- case "pwd":- return { verb: "Checked working directory" };- case "ls":- return { verb: "Listed files", target: extractPathArg(tokens) };- case "find":- return { verb: "Searched the filesystem", target: extractPathArg(tokens) };- case "rg":- case "grep":- case "ag":- case "ack":- return {- verb: "Searched files",- target: extractQuotedToken(inner) ?? extractPathArg(tokens),- };- case "cat":- case "head":- case "tail":- case "less":- case "more":- case "bat":- return { verb: "Read file", target: extractPathArg(tokens) };- case "git": {- if (!sub) return { verb: "Ran git", target: targetForExpand };- return { verb: `Ran git ${sub}` };- }- case "npm":- case "pnpm":- case "yarn":- case "bun": {- if (sub === "test" || sub === "t") return { verb: "Ran tests" };- if (sub === "install" || sub === "add" || sub === "i")- return { verb: "Installed packages" };- if (sub === "run") {- const script = tokens[2];- return { verb: script ? `Ran ${head} ${script}` : `Ran ${head}` };- }- return { verb: sub ? `Ran ${head} ${sub}` : `Ran ${head}` };- }- case "node":- case "python":- case "python3":- case "tsx":- case "deno":- case "ts-node":- return { verb: "Ran script", target: extractPathArg(tokens) };- case "curl":- case "wget":- case "http":- return { verb: "Fetched URL", target: extractUrl(inner) };- case "mkdir":- return { verb: "Created directory", target: extractPathArg(tokens) };- case "touch":- return { verb: "Created file", target: extractPathArg(tokens) };- case "rm":- return { verb: "Removed file(s)", target: extractPathArg(tokens) };- case "mv":- return { verb: "Moved file" };- case "cp":- return { verb: "Copied file" };- case "sed":- case "awk":- return { verb: "Edited text", target: extractPathArg(tokens) };- case "which":- case "type":- case "whereis":- return { verb: "Located binary", target: tokens[1] };- case "echo":- case "printf":- return { verb: "Printed text" };- case "make":- return { verb: sub ? `Ran make ${sub}` : "Ran make" };- case "docker":- return { verb: sub ? `Ran docker ${sub}` : "Ran docker" };- case "kubectl":- return { verb: sub ? `Ran kubectl ${sub}` : "Ran kubectl" };- case "gh":- return { verb: sub ? `Ran gh ${sub}` : "Ran gh" };- case "":- return { verb: "Ran shell command" };- default:- return { verb: `Ran ${head}`, target: targetForExpand };- }-}--function extractPathArg(tokens: string[]): string | undefined {- // Last token that isn't a flag and isn't the leading binary.- for (let i = tokens.length - 1; i >= 1; i--) {- const t = tokens[i]!;- if (!t.startsWith("-") && !/^[<>|&]+$/.test(t)) {- return shortenPathish(t.replace(/^['"]|['"]$/g, ""));- }- }- return undefined;-}--function extractUrl(inner: string): string | undefined {- const m = inner.match(/https?:\/\/[^\s'"]+/);- return m?.[0];-}--function extractQuotedToken(inner: string): string | undefined {- const m = inner.match(/['"]([^'"\n]{1,80})['"]/);- if (!m) return undefined;- return `"${m[1]}"`;-}--export function shortenPathish(p: string): string {- if (!p) return p;- // Don't compress URLs.- if (p.startsWith("http://") || p.startsWith("https://")) return p;- const segs = p.split("/").filter(Boolean);- if (segs.length <= 2) return p;- return `…/${segs.slice(-2).join("/")}`;-}--/**- * Map a tool action like `listAdAccounts` to a human-readable phrase- * (`list ad accounts`). Splits on camelCase and snake_case boundaries- * and lowercases — leaves single-word actions like `runScript` alone- * after the split. Returns the action unchanged when there's nothing- * to split.- */-function prettifyToolAction(action: string): string {- if (!action) return action;- const withSpaces = action- .replace(/([a-z])([A-Z])/g, "$1 $2")- .replace(/[_-]+/g, " ")- .trim();- if (!withSpaces) return action;- // Don't lowercase one-token names so single identifiers like "runScript"- // (already split to "run Script") read naturally as "run Script"; we- // only lowercase the tail to keep proper capitalization of the leading- // verb the model chose.- return withSpaces.charAt(0).toLowerCase() + withSpaces.slice(1).toLowerCase();-}--/**- * Walk the MCP catalog looking for a server key that matches the tool- * name's namespace prefix. The two harnesses use different schemes:- *- * - **Claude Code**: `mcp__<serverKey>__<tool>` (e.g. `mcp__NotFair-GoogleAds__createCampaign`)- * - **Codex**: `notfair_<projectSlug>__<serverNameUnderscored>__<tool>`- *- * We match by normalizing both sides to lowercase + collapsing `-` and- * `_` so `NotFair-GoogleAds`, `notfair_googleads`, and `notfair-googleads`- * all collide on the same catalog entry. Returns null when the tool- * name doesn't carry a recognizable MCP prefix or the prefix isn't in- * the catalog (e.g. an unprovisioned server, or a non-MCP built-in).- */-export function matchMcpServerKey(- toolName: string,- catalog: McpCatalogEntryLite[] | undefined,-): McpCatalogEntryLite | null {- if (!toolName || !catalog || catalog.length === 0) return null;- const candidates: string[] = [];- // Claude Code: mcp__<serverKey>__<tool>- const claude = toolName.match(/^mcp__([^_].*?)__/);- if (claude?.[1]) candidates.push(claude[1]);- // Codex MCP, namespaced + tool suffix:- // notfair_<projectSlug>__<serverNameUnderscored>__<tool>- const codexUnderscored = toolName.match(- /^notfair_[A-Za-z0-9_]+?__([A-Za-z0-9_]+?)__/,- );- if (codexUnderscored?.[1]) candidates.push(codexUnderscored[1]);- // Codex MCP via the `<server>.<tool>` shape this parser uses for- // `mcp_tool_call` items. The server is the FULL namespaced config key- // (e.g. `notfair_demo__notfair_googleads`), so peel the leading- // `notfair_<projectSlug>__` prefix off too — the catalog stores the- // bare server key.- const dot = toolName.match(/^([A-Za-z0-9_-]+)\./);- if (dot?.[1]) {- candidates.push(dot[1]);- const tail = dot[1].match(/^notfair_[A-Za-z0-9_]+?__(.+)$/);- if (tail?.[1]) candidates.push(tail[1]);- }- if (candidates.length === 0) return null;- const norm = (s: string) => s.toLowerCase().replace(/[-_]/g, "");- for (const cand of candidates) {- const target = norm(cand);- const hit = catalog.find((c) => norm(c.key) === target);- if (hit) return hit;- }- return null;-}--export function iconForTool(name: string): LucideIcon {- const n = name.toLowerCase();- if (n === "exec" || n === "shell" || n === "bash" || n.includes("bash"))- return Terminal;- if (n === "read" || n === "cat" || n === "open" || n.includes("read"))- return FileText;- if (n === "write" || n === "edit" || n === "patch") return Edit3;- if (n === "fetch" || n.includes("http") || n.includes("web")) return Globe;- return Wrench;-}diff --git a/notfair/src/components/chat/transcript-model.more.test.ts b/notfair/src/components/chat/transcript-model.more.test.tsdeleted file mode 100644index 9e83353f..00000000--- a/notfair/src/components/chat/transcript-model.more.test.ts+++ /dev/null@@ -1,195 +0,0 @@-import { describe, expect, it, vi } from "vitest";--import type { TranscriptEvent } from "@/server/sessions/transcript-tail";-import {- collapseEvents,- handleSseEvent,- upsertToolEntry,- type SseToolEvent,-} from "./transcript-model";--const t = 1_800_000_000_000;--function handlers() {- return {- onText: vi.fn(),- onTool: vi.fn(),- onError: vi.fn(),- onLifecycle: vi.fn(),- onMeta: vi.fn(),- onPerf: vi.fn(),- };-}--const frame = (evt: string, data: unknown) =>- `event: ${evt}\ndata: ${JSON.stringify(data)}`;--describe("handleSseEvent", () => {- it("dispatches text chunks", () => {- const h = handlers();- handleSseEvent(frame("text", { chunk: "Hello" }), h);- expect(h.onText).toHaveBeenCalledWith("Hello");- });-- it("ignores text frames without a string chunk", () => {- const h = handlers();- handleSseEvent(frame("text", { chunk: 42 }), h);- expect(h.onText).not.toHaveBeenCalled();- });-- it("dispatches tool events verbatim", () => {- const h = handlers();- const evt: SseToolEvent = {- phase: "start",- tool_call_id: "t1",- name: "shell",- label: "ls",- };- handleSseEvent(frame("tool", evt), h);- expect(h.onTool).toHaveBeenCalledWith(evt);- });-- it("dispatches lifecycle phases only when a handler is wired", () => {- const h = handlers();- handleSseEvent(frame("lifecycle", { phase: "run.warming" }), h);- expect(h.onLifecycle).toHaveBeenCalledWith("run.warming");- // Non-string phase is dropped.- handleSseEvent(frame("lifecycle", { phase: 3 }), h);- expect(h.onLifecycle).toHaveBeenCalledTimes(1);- // No handler — must not throw.- expect(() =>- handleSseEvent(frame("lifecycle", { phase: "x" }), {- onText: vi.fn(),- onTool: vi.fn(),- onError: vi.fn(),- }),- ).not.toThrow();- });-- it("dispatches meta and perf frames", () => {- const h = handlers();- handleSseEvent(frame("meta", { agent: "a1", message_chars: 5 }), h);- expect(h.onMeta).toHaveBeenCalledWith({ agent: "a1", message_chars: 5 });- const marks = [{ name: "first_token", at: 12.4, delta: 12.4 }];- handleSseEvent(frame("perf", { marks }), h);- expect(h.onPerf).toHaveBeenCalledWith(marks);- // Non-array marks are dropped.- handleSseEvent(frame("perf", { marks: "nope" }), h);- expect(h.onPerf).toHaveBeenCalledTimes(1);- });-- it("dispatches errors with a fallback message", () => {- const h = handlers();- handleSseEvent(frame("error", { message: "boom" }), h);- expect(h.onError).toHaveBeenCalledWith("boom");- handleSseEvent(frame("error", {}), h);- expect(h.onError).toHaveBeenCalledWith("unknown error");- });-- it("ignores malformed frames", () => {- const h = handlers();- handleSseEvent("data: {}", h); // no event line- handleSseEvent("event: text", h); // no data line- handleSseEvent("event: text\ndata: {not json", h); // bad JSON- handleSseEvent(frame("mystery", { x: 1 }), h); // unknown event type- expect(h.onText).not.toHaveBeenCalled();- expect(h.onTool).not.toHaveBeenCalled();- expect(h.onError).not.toHaveBeenCalled();- });-});--describe("upsertToolEntry (top-up)", () => {- it("inserts a result-phase event for an unseen tool as already done", () => {- const entries = upsertToolEntry([], {- phase: "result",- tool_call_id: "t1",- name: "shell",- });- expect(entries[0]).toMatchObject({ toolCallId: "t1", done: true, label: null });- });-- it("keeps the existing label when an update omits it", () => {- let entries = upsertToolEntry([], {- phase: "start",- tool_call_id: "t1",- name: "shell",- label: "ls -la",- });- entries = upsertToolEntry(entries, {- phase: "update",- tool_call_id: "t1",- name: "shell",- });- expect(entries[0]).toMatchObject({ label: "ls -la", done: false });- });-});--describe("collapseEvents (top-up)", () => {- const user = (id: string, body: string, system?: boolean): TranscriptEvent => ({- kind: "user_message",- id,- ts: t,- body,- ...(system ? { system } : {}),- });-- it("carries the system flag through to the rendered user message", () => {- const items = collapseEvents([user("u1", "[TICK] go", true)]);- expect(items[0]).toMatchObject({- kind: "user_message",- body: "[TICK] go",- system: true,- });- });-- it("renders unknown events as system_unknown rows", () => {- const items = collapseEvents([- { kind: "unknown", id: "x1", ts: t, raw_type: "telemetry" },- ]);- expect(items).toEqual([- { kind: "system_unknown", key: "x1", raw_type: "telemetry" },- ]);- });-- it("skips lifecycle events entirely", () => {- const items = collapseEvents([- { kind: "lifecycle", id: "l1", ts: t, phase: "start" },- { kind: "lifecycle", id: "l2", ts: t, phase: "done" },- ]);- expect(items).toEqual([]);- });-- it("completes an earlier call even when the result arrives after a message", () => {- const items = collapseEvents([- {- kind: "tool_call",- id: "c1",- ts: t,- tool_call_id: "t1",- name: "shell",- label: "ls",- },- { kind: "assistant_text", id: "a1", ts: t, body: "narrating" },- {- kind: "tool_result",- id: "r1",- ts: t,- tool_call_id: "t1",- name: "shell",- summary: "3 files",- ok: true,- },- ]);- expect(items.map((i) => i.kind)).toEqual(["tool_group", "assistant_text"]);- const group = items[0] as Extract<- ReturnType<typeof collapseEvents>[number],- { kind: "tool_group" }- >;- expect(group.tools[0]).toMatchObject({- toolCallId: "t1",- done: true,- ok: true,- result: "3 files",- });- });-});diff --git a/notfair/src/components/chat/transcript-model.test.ts b/notfair/src/components/chat/transcript-model.test.tsdeleted file mode 100644index ee5f6e0f..00000000--- a/notfair/src/components/chat/transcript-model.test.ts+++ /dev/null@@ -1,256 +0,0 @@-import { describe, expect, it } from "vitest";--import type { TranscriptEvent } from "@/server/sessions/transcript-tail";-import {- collapseEvents,- nextToolGroupKey,- upsertToolEntry,-} from "./transcript-model";-import { humanizeTool, matchMcpServerKey } from "./tool-intent";--const t = 1_800_000_000_000;-const user = (id: string, body: string): TranscriptEvent => ({- kind: "user_message",- id,- ts: t,- body,-});-const text = (id: string, body: string): TranscriptEvent => ({- kind: "assistant_text",- id,- ts: t,- body,-});-const call = (id: string, tcid: string, name = "shell"): TranscriptEvent => ({- kind: "tool_call",- id,- ts: t,- tool_call_id: tcid,- name,- label: null,-});-const result = (id: string, tcid: string, ok = true): TranscriptEvent => ({- kind: "tool_result",- id,- ts: t,- tool_call_id: tcid,- name: "shell",- summary: null,- ok,-});-const lifecycle = (- id: string,- phase: string,- ok?: boolean,-): TranscriptEvent => ({- kind: "lifecycle",- id,- ts: t,- phase,- ok,-});--describe("collapseEvents", () => {- it("pairs calls with results and groups contiguous tools", () => {- const items = collapseEvents([- user("u1", "hi"),- call("c1", "t1"),- result("r1", "t1"),- call("c2", "t2"),- text("a1", "done"),- ]);- expect(items.map((i) => i.kind)).toEqual([- "user_message",- "tool_group",- "assistant_text",- ]);- const group = items[1] as Extract<- ReturnType<typeof collapseEvents>[number],- { kind: "tool_group" }- >;- expect(group.key).toBe("tg:t1");- expect(group.tools).toHaveLength(2);- expect(group.tools[0]).toMatchObject({ toolCallId: "t1", done: true });- expect(group.tools[1]).toMatchObject({ toolCallId: "t2", done: false });- });-- it("splits tool groups across intervening messages", () => {- const items = collapseEvents([- call("c1", "t1"),- text("a1", "narration"),- call("c2", "t2"),- ]);- expect(items.map((i) => i.kind)).toEqual([- "tool_group",- "assistant_text",- "tool_group",- ]);- });-- it("keeps groups unique when a harness reuses tool ids across turns", () => {- const items = collapseEvents([- call("c1", "item_1"),- text("a1", "first turn"),- call("c2", "item_1"),- text("a2", "second turn"),- ]);- const groups = items.filter((item) => item.kind === "tool_group");-- expect(groups.map((group) => group.key)).toEqual([- "tg:item_1",- "tg:item_1:1",- ]);- expect(nextToolGroupKey(items, "item_1")).toBe("tg:item_1:2");- });-- it("keeps an orphan tool_result as its own done entry", () => {- const items = collapseEvents([result("r9", "t9", false)]);- expect(items).toHaveLength(1);- const group = items[0] as Extract<- ReturnType<typeof collapseEvents>[number],- { kind: "tool_group" }- >;- expect(group.tools[0]).toMatchObject({ toolCallId: "t9", done: true, ok: false });- });-- it("closes an unmatched tool call when the turn reaches a terminal boundary", () => {- const items = collapseEvents([- call("c1", "t1"),- text("a1", "finished"),- lifecycle("done-1", "done"),- ]);- const group = items[0] as Extract<- ReturnType<typeof collapseEvents>[number],- { kind: "tool_group" }- >;- expect(group.tools[0]).toMatchObject({ toolCallId: "t1", done: true });- });-- it("marks an unmatched tool failed when the terminal boundary is an error", () => {- const items = collapseEvents([- call("c1", "t1"),- text("err-1", "⚠ harness crashed"),- lifecycle("done-1", "done", false),- ]);- const group = items[0] as Extract<- ReturnType<typeof collapseEvents>[number],- { kind: "tool_group" }- >;- expect(group.tools[0]).toMatchObject({- toolCallId: "t1",- done: true,- ok: false,- });- });-- it("closes abandoned tools before a later turn reuses their id", () => {- const items = collapseEvents([- call("c1", "item_1"),- user("u2", "try again"),- lifecycle("start-2", "start"),- call("c2", "item_1"),- ]);- const groups = items.filter((item) => item.kind === "tool_group");- expect(groups).toHaveLength(2);- expect(groups[0]!.tools[0]).toMatchObject({- toolCallId: "item_1",- done: true,- ok: false,- });- expect(groups[1]!.tools[0]).toMatchObject({- toolCallId: "item_1",- done: false,- });- });-- it("closes an unmatched tool when a fresh lifecycle starts without a user row", () => {- const items = collapseEvents([- call("c1", "item_1"),- lifecycle("start-2", "start"),- call("c2", "item_1"),- ]);- const group = items[0] as Extract<- ReturnType<typeof collapseEvents>[number],- { kind: "tool_group" }- >;- expect(group.tools).toHaveLength(2);- expect(group.tools[0]).toMatchObject({- toolCallId: "item_1",- done: true,- ok: false,- });- expect(group.tools[1]).toMatchObject({- toolCallId: "item_1",- done: false,- });- });-});--describe("upsertToolEntry", () => {- it("inserts then completes an entry across phases", () => {- let entries = upsertToolEntry([], {- phase: "start",- tool_call_id: "t1",- name: "shell",- label: "ls",- });- expect(entries[0]).toMatchObject({ done: false, label: "ls" });- entries = upsertToolEntry(entries, {- phase: "result",- tool_call_id: "t1",- name: "shell",- });- expect(entries).toHaveLength(1);- expect(entries[0]).toMatchObject({ done: true, label: "ls" });- });-});--describe("humanizeTool", () => {- it("maps shell command lines to verb phrases", () => {- expect(humanizeTool("shell", "/bin/zsh -lc 'git status --short'")).toEqual({- verb: "Ran git status",- });- expect(humanizeTool("shell", `rg -n "needle" src`).verb).toBe(- "Searched files",- );- });-- it("speaks MCP actions in natural language", () => {- expect(- humanizeTool("notfair_growth__notfair_googleads__listAdAccounts", null)- .verb,- ).toBe("Listed ad accounts");- expect(humanizeTool("posthog.exec", "SELECT count() FROM events")).toEqual({- verb: "Ran a query",- target: "SELECT count() FROM events",- });- expect(humanizeTool("mcp__X__updateCampaignBudget", null).verb).toBe(- "Updated campaign budget",- );- expect(humanizeTool("mcp__X__frobnicateWidget", null).verb).toBe(- "Called frobnicate widget",- );- // PostHog's exec is a query engine — label-less legacy rows still- // deserve the honest specific verb.- expect(humanizeTool("notfair_growth__posthog.exec", null).verb).toBe(- "Ran a query",- );- });-});--describe("matchMcpServerKey", () => {- const catalog = [- { key: "NotFair-GoogleAds", display_name: "Google Ads", resource_url: "https://notfair.co" },- ];- it("matches both harness namespace schemes", () => {- expect(- matchMcpServerKey("mcp__NotFair-GoogleAds__createCampaign", catalog)- ?.display_name,- ).toBe("Google Ads");- expect(- matchMcpServerKey("notfair_demo1__notfair_googleads__runScript", catalog)- ?.display_name,- ).toBe("Google Ads");- expect(matchMcpServerKey("shell", catalog)).toBeNull();- });-});diff --git a/notfair/src/components/chat/transcript-model.ts b/notfair/src/components/chat/transcript-model.tsdeleted file mode 100644index bdba06e8..00000000--- a/notfair/src/components/chat/transcript-model.ts+++ /dev/null@@ -1,278 +0,0 @@-import type { TranscriptEvent } from "@/server/sessions/transcript-tail";--/**- * The chat's data model: how raw transcript events become the rendered- * conversation, plus the SSE wire-format parsing for an active send.- * Pure functions and types only — no React in this file.- */--export type ToolEntry = {- toolCallId: string;- name: string;- label: string | null;- result: string | null;- ok: boolean;- done: boolean;-};--export type RenderedItem =- | { kind: "user_message"; key: string; body: string; system?: boolean }- | { kind: "assistant_text"; key: string; body: string }- | { kind: "tool_group"; key: string; tools: ToolEntry[] }- | { kind: "system_unknown"; key: string; raw_type: string };--/**- * Stable across the optimistic SSE row and its committed transcript copy.- * Harnesses may restart tool ids (for example `item_1`) on every turn, so- * later occurrences need a suffix to remain unique within a long chat.- */-export function toolGroupKey(toolCallId: string, occurrence = 0): string {- return occurrence === 0- ? `tg:${toolCallId}`- : `tg:${toolCallId}:${occurrence}`;-}--/** Match the pending tool card to the key its committed group will receive. */-export function nextToolGroupKey(- rendered: RenderedItem[],- toolCallId: string,-): string {- const occurrence = rendered.filter(- (item) =>- item.kind === "tool_group" &&- item.tools[0]?.toolCallId === toolCallId,- ).length;- return toolGroupKey(toolCallId, occurrence);-}--/**- * The transcript stores `toolCall` and `toolResult` as separate parts,- * sometimes interleaved across multiple message rows in one turn. We:- * 1. Pair calls with their later results by tool_call_id so each tool- * renders as one logical entry (spinner → check).- * 2. Group runs of contiguous tool entries (no assistant_text or- * user_message between them) into a single collapsible "tool_group".- * Mirrors Claude.ai's pattern — one card per cluster, summary shows- * the most recent tool name, expand to see all of them.- */-export function collapseEvents(events: TranscriptEvent[]): RenderedItem[] {- type Step =- | { tag: "tool"; entry: ToolEntry }- | { tag: "msg"; item: RenderedItem };- const steps: Step[] = [];- const callIndex = new Map<string, number>();- const closeOpenTools = (ok: boolean) => {- for (const idx of callIndex.values()) {- const step = steps[idx];- if (step?.tag === "tool" && !step.entry.done) {- step.entry = { ...step.entry, done: true, ok };- }- }- callIndex.clear();- };- for (const e of events) {- if (e.kind === "tool_call") {- callIndex.set(e.tool_call_id, steps.length);- steps.push({- tag: "tool",- entry: {- toolCallId: e.tool_call_id,- name: e.name,- label: e.label,- result: null,- ok: true,- done: false,- },- });- continue;- }- if (e.kind === "tool_result") {- const idx = callIndex.get(e.tool_call_id);- const step = idx != null ? steps[idx] : null;- if (step && step.tag === "tool") {- step.entry = {- ...step.entry,- result: e.summary,- ok: e.ok,- done: true,- };- callIndex.delete(e.tool_call_id);- continue;- }- steps.push({- tag: "tool",- entry: {- toolCallId: e.tool_call_id,- name: e.name,- label: null,- result: e.summary,- ok: e.ok,- done: true,- },- });- continue;- }- if (e.kind === "user_message") {- // A new user turn is a hard boundary. If the previous harness turn- // vanished before emitting a tool result, keep that historical row- // static and failed instead of animating it forever or pairing a- // later turn's reused tool id with it.- closeOpenTools(false);- steps.push({- tag: "msg",- item: { kind: "user_message", key: e.id, body: e.body, system: e.system },- });- continue;- }- if (e.kind === "assistant_text") {- steps.push({- tag: "msg",- item: { kind: "assistant_text", key: e.id, body: e.body },- });- continue;- }- if (e.kind === "lifecycle") {- if (e.phase === "done") {- // A final/error event is surfaced as lifecycle "done" by- // transcript-tail. The turn is terminal even if a harness omitted- // one tool-result event, so no tool from it may remain "live".- closeOpenTools(e.ok !== false);- } else if (e.phase === "start") {- closeOpenTools(false);- }- continue;- }- if (e.kind === "unknown") {- steps.push({- tag: "msg",- item: { kind: "system_unknown", key: e.id, raw_type: e.raw_type },- });- continue;- }- }- const out: RenderedItem[] = [];- let buffer: ToolEntry[] = [];- const groupOccurrences = new Map<string, number>();- const flush = () => {- if (buffer.length === 0) return;- const firstToolCallId = buffer[0]!.toolCallId;- const occurrence = groupOccurrences.get(firstToolCallId) ?? 0;- out.push({- kind: "tool_group",- key: toolGroupKey(firstToolCallId, occurrence),- tools: buffer,- });- groupOccurrences.set(firstToolCallId, occurrence + 1);- buffer = [];- };- for (const step of steps) {- if (step.tag === "tool") {- buffer.push(step.entry);- } else {- flush();- out.push(step.item);- }- }- flush();- return out;-}--// ── SSE plumbing for the active send ────────────────────────────────────--export type SseToolEvent = {- phase: "start" | "update" | "result";- tool_call_id: string;- name: string;- label?: string;-};--export type SsePerfMark = { name: string; at: number; delta: number };-export type SseMeta = {- message_chars?: number;- is_kickoff?: boolean;- agent?: string;- session_id?: string;-};--export function handleSseEvent(- raw: string,- handlers: {- onText: (chunk: string) => void;- onTool: (evt: SseToolEvent) => void;- onError: (msg: string) => void;- onLifecycle?: (phase: string) => void;- onMeta?: (meta: SseMeta) => void;- onPerf?: (marks: SsePerfMark[]) => void;- },-) {- const lines = raw.split("\n");- const evtLine = lines.find((l) => l.startsWith("event: "));- const dataLine = lines.find((l) => l.startsWith("data: "));- if (!evtLine || !dataLine) return;- const evt = evtLine.slice("event: ".length);- let data: unknown;- try {- data = JSON.parse(dataLine.slice("data: ".length));- } catch {- return;- }- if (evt === "text") {- const chunk = (data as { chunk?: string }).chunk;- if (typeof chunk === "string") handlers.onText(chunk);- return;- }- if (evt === "tool") {- handlers.onTool(data as SseToolEvent);- return;- }- if (evt === "lifecycle") {- const phase = (data as { phase?: string }).phase;- if (typeof phase === "string" && handlers.onLifecycle) {- handlers.onLifecycle(phase);- }- return;- }- if (evt === "meta") {- if (handlers.onMeta) handlers.onMeta(data as SseMeta);- return;- }- if (evt === "perf") {- const marks = (data as { marks?: SsePerfMark[] }).marks;- if (Array.isArray(marks) && handlers.onPerf) handlers.onPerf(marks);- return;- }- if (evt === "error") {- const msg = (data as { message?: string }).message ?? "unknown error";- handlers.onError(msg);- return;- }-}--export function upsertToolEntry(- prev: ToolEntry[],- evt: SseToolEvent,-): ToolEntry[] {- const idx = prev.findIndex((t) => t.toolCallId === evt.tool_call_id);- if (idx < 0) {- return [- ...prev,- {- toolCallId: evt.tool_call_id,- name: evt.name,- label: evt.label ?? null,- result: null,- ok: true,- done: evt.phase === "result",- },- ];- }- const next = prev.slice();- const existing = next[idx]!;- next[idx] = {- ...existing,- name: evt.name,- label: evt.label ?? existing.label,- done: evt.phase === "result" ? true : existing.done,- };- return next;-}diff --git a/notfair/src/components/chat/use-chat-stream.test.tsx b/notfair/src/components/chat/use-chat-stream.test.tsxdeleted file mode 100644index e5dd0a76..00000000--- a/notfair/src/components/chat/use-chat-stream.test.tsx+++ /dev/null@@ -1,263 +0,0 @@-// @vitest-environment jsdom-import { act, cleanup, renderHook, waitFor } from "@testing-library/react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--import { useChatStream } from "./use-chat-stream";-import type { TranscriptEvent } from "@/server/sessions/transcript-tail";--const base = {- projectSlug: "acme co",- agentSlug: "goal-1",- threadId: "main",- initialEvents: [] as TranscriptEvent[],- initialCursor: 0,- model: "",- reasoningEffort: "",-};--class FakeEventSource {- static instances: FakeEventSource[] = [];- readonly url: string;- readyState = 1;- close = vi.fn();- private listeners = new Map<string, Array<(event: MessageEvent) => void>>();-- constructor(url: string) {- this.url = url;- FakeEventSource.instances.push(this);- }-- addEventListener(name: string, listener: EventListener) {- const entries = this.listeners.get(name) ?? [];- entries.push(listener as (event: MessageEvent) => void);- this.listeners.set(name, entries);- }-- emit(name: string, data = "") {- for (const listener of this.listeners.get(name) ?? []) {- listener(new MessageEvent(name, { data }));- }- }-}--function pollResponse(events: TranscriptEvent[] = [], cursor = 0) {- return {- ok: true,- json: vi.fn(async () => ({ events, cursor })),- };-}--function streamResponse(chunks: string[], afterChunks?: Promise<void>) {- const encoder = new TextEncoder();- let index = 0;- return {- ok: true,- status: 200,- body: {- getReader: () => ({- read: vi.fn(async () => {- if (index < chunks.length) return { value: encoder.encode(chunks[index++]!), done: false };- if (afterChunks) await afterChunks;- return { value: undefined, done: true };- }),- }),- },- };-}--beforeEach(() => {- vi.clearAllMocks();- FakeEventSource.instances = [];- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(pollResponse()));- vi.stubGlobal("EventSource", FakeEventSource);- vi.spyOn(console, "log").mockImplementation(() => {});- vi.spyOn(console, "groupCollapsed").mockImplementation(() => {});- vi.spyOn(console, "table").mockImplementation(() => {});- vi.spyOn(console, "groupEnd").mockImplementation(() => {});-});--afterEach(() => {- cleanup();- vi.useRealTimers();- vi.restoreAllMocks();- vi.unstubAllGlobals();-});--it("exposes initial events, derives remote-turn state, and clears the local view", () => {- const now = Date.now();- const initialEvents: TranscriptEvent[] = [- { kind: "lifecycle", id: "start", ts: now, phase: "start" },- { kind: "assistant_text", id: "delta", ts: now + 1, body: "working" },- ];- const { result } = renderHook(() => useChatStream({ ...base, initialEvents, initialCursor: 2 }));- expect(result.current.events).toEqual(initialEvents);- expect(result.current.openTurn).toMatchObject({ startedAt: now });- expect(result.current.remoteTurnActive).toBe(true);- act(() => result.current.clearLocal());- expect(result.current.events).toEqual([]);- expect(result.current.openTurn).toBeNull();-});--it("polls, advances the cursor, and only deduplicates durable event ids", async () => {- vi.useFakeTimers();- const original: TranscriptEvent = { kind: "assistant_text", id: "one", ts: 1, body: "same" };- const repeated: TranscriptEvent = { kind: "assistant_text", id: "two", ts: 2, body: "same" };- const fresh: TranscriptEvent = { kind: "assistant_text", id: "three", ts: 3, body: "fresh" };- vi.mocked(fetch).mockResolvedValue(- pollResponse([- original,- repeated,- fresh,- ], 3) as never,- );- const { result } = renderHook(() => useChatStream({ ...base, initialEvents: [original], initialCursor: 1 }));- await act(async () => { await vi.advanceTimersByTimeAsync(2_000); });- expect(result.current.events).toEqual([original, repeated, fresh]);- expect(fetch).toHaveBeenCalledWith(- "/api/agents/goal-1/threads/main/transcript?offset=1&project=acme%20co",- { cache: "no-store" },- );-});--it("ignores failed and throwing polls", async () => {- vi.useFakeTimers();- vi.mocked(fetch)- .mockResolvedValueOnce({ ok: false } as Response)- .mockRejectedValueOnce(new Error("offline"));- const { result } = renderHook(() => useChatStream(base));- await act(async () => { await vi.advanceTimersByTimeAsync(2_000); });- await act(async () => { await vi.advanceTimersByTimeAsync(2_000); });- expect(result.current.events).toEqual([]);-});--it("merges live bridge events, rejects bad payloads, logs lifecycle events, and closes", () => {- const { result, unmount } = renderHook(() => useChatStream(base));- const source = FakeEventSource.instances[0]!;- expect(source.url).toContain("/live?project=acme%20co");- act(() => {- source.emit("open");- source.emit("ready", "ready");- source.emit("transcript", "not json");- source.emit("transcript", JSON.stringify({ events: "bad" }));- source.emit("error", "oops");- source.emit("transcript", JSON.stringify({- events: [{ kind: "assistant_text", id: "live-1", ts: 1, body: "live" }],- }));- });- expect(result.current.events).toMatchObject([{ id: "live-1", body: "live" }]);- unmount();- expect(source.close).toHaveBeenCalled();-});--it("skips the bridge when EventSource is unavailable", () => {- vi.unstubAllGlobals();- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(pollResponse()));- renderHook(() => useChatStream(base));- expect(FakeEventSource.instances).toHaveLength(0);-});--it("streams text, tools, lifecycle, error, meta, and perf events", async () => {- let finish!: () => void;- const blocked = new Promise<void>((resolve) => { finish = resolve; });- const sse = [- 'event: text\ndata: {"chunk":"Hello "}',- 'event: text\ndata: {"chunk":"world"}',- 'event: tool\ndata: {"phase":"start","tool_call_id":"tc1","name":"search","label":"Searching"}',- 'event: tool\ndata: {"phase":"result","tool_call_id":"tc1","name":"search"}',- 'event: lifecycle\ndata: {"phase":"run.warming"}',- 'event: error\ndata: {"message":"soft warning"}',- 'event: meta\ndata: {"agent":"a","session_id":"s","message_chars":5,"is_kickoff":true}',- 'event: perf\ndata: {"marks":[{"name":"done","at":10.4,"delta":2.6}]}',- ].join("\n\n") + "\n\n";- vi.mocked(fetch).mockImplementation((url) => {- if (url === "/api/chat") return Promise.resolve(streamResponse([sse], blocked) as never);- return Promise.resolve(pollResponse() as never);- });- const { result } = renderHook(() =>- useChatStream({ ...base, model: "gpt-test", reasoningEffort: "xhigh" }),- );- let sendPromise!: ReturnType<typeof result.current.send>;- act(() => { sendPromise = result.current.send("hello"); });- await waitFor(() => expect(result.current.pendingAssistant).toBe("Hello world"));- expect(result.current.sendingChat).toBe(true);- expect(result.current.pendingUserMsg).toBe("hello");- expect(result.current.pendingTools).toMatchObject([{ toolCallId: "tc1", done: true }]);- expect(result.current.pendingLifecycle).toBe("run.warming");- expect(result.current.pendingError).toBe("soft warning");- expect(JSON.parse(String(vi.mocked(fetch).mock.calls.find(([u]) => u === "/api/chat")?.[1]?.body))).toMatchObject({- message: "hello",- model: "gpt-test",- reasoning_effort: "xhigh",- });- finish();- await act(async () => {- await sendPromise;- });- expect(result.current.sendingChat).toBe(false);- expect(result.current.pendingLifecycle).toBeNull();- expect(console.groupCollapsed).toHaveBeenCalled();-});--it("supports hidden sends and clears optimistic state when polling catches up", async () => {- vi.useFakeTimers();- const committed: TranscriptEvent = { kind: "assistant_text", id: "db-1", ts: 2, body: "done" };- vi.mocked(fetch)- .mockResolvedValueOnce(streamResponse([]) as never)- .mockResolvedValueOnce(pollResponse([committed], 1) as never);- const { result } = renderHook(() => useChatStream(base));- let promise!: ReturnType<typeof result.current.send>;- act(() => { promise = result.current.send("secret", { hidden: true }); });- expect(result.current.pendingUserMsg).toBeNull();- await act(async () => {- await vi.advanceTimersByTimeAsync(400);- await promise;- });- expect(result.current.events).toEqual([committed]);- expect(result.current.pendingAssistant).toBe("");-});--it("returns response and thrown errors to the caller", async () => {- vi.mocked(fetch).mockResolvedValueOnce({- ok: false,- status: 503,- body: {},- text: vi.fn(async () => "server sad"),- } as never);- const { result } = renderHook(() => useChatStream(base));- await act(async () => {- await expect(result.current.send("hello")).resolves.toEqual({ error: "server sad" });- });- expect(result.current.pendingError).toBe("server sad");-- vi.mocked(fetch).mockRejectedValueOnce("string failure");- await act(async () => {- await expect(result.current.send("again")).resolves.toEqual({ error: "string failure" });- });-});--it("ignores empty/concurrent sends and stops both the local and server turn", async () => {- let rejectChat!: (error: unknown) => void;- vi.mocked(fetch).mockImplementation((url, init) => {- if (url === "/api/chat/stop") return Promise.reject(new Error("best effort"));- if (url === "/api/chat") {- return new Promise((_resolve, reject) => {- rejectChat = reject;- init?.signal?.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")));- });- }- return Promise.resolve(pollResponse() as never);- });- const { result } = renderHook(() => useChatStream(base));- await expect(result.current.send("")).resolves.toBeUndefined();- let first!: ReturnType<typeof result.current.send>;- act(() => { first = result.current.send("go"); });- await waitFor(() => expect(result.current.sendingChat).toBe(true));- await expect(result.current.send("duplicate")).resolves.toBeUndefined();- act(() => result.current.stopTurn());- await act(async () => { await first; });- expect(result.current.sendingChat).toBe(false);- expect(fetch).toHaveBeenCalledWith("/api/chat/stop", expect.objectContaining({- body: JSON.stringify({ project: "acme co", agent: "goal-1", thread: "main" }),- }));- void rejectChat;-});diff --git a/notfair/src/components/chat/use-chat-stream.ts b/notfair/src/components/chat/use-chat-stream.tsdeleted file mode 100644index f552c2b2..00000000--- a/notfair/src/components/chat/use-chat-stream.ts+++ /dev/null@@ -1,364 +0,0 @@-"use client";--import { useCallback, useEffect, useMemo, useRef, useState } from "react";--import { findOpenTurn, isOpenTurnLive } from "@/lib/turn-state";-import type { TranscriptEvent } from "@/server/sessions/transcript-tail";-import {- handleSseEvent,- upsertToolEntry,- type ToolEntry,-} from "./transcript-model";--const POLL_INTERVAL_MS = 2_000;--/**- * The chat's streaming state machine, extracted whole from the original- * LiveTranscript. Owns: the committed event log (poll + SSE-bridge fed,- * deduped by durable event id), the optimistic pending state for an active- * send, the send/stop calls, and the remote-turn detection that keeps- * the UI honest about turns this tab didn't start.- *- * Deliberately contains NO rendering and NO slash-command logic — the- * orchestrator intercepts slash commands before calling `send`.- */-export function useChatStream({- projectSlug,- agentSlug,- threadId,- initialEvents,- initialCursor,- model,- reasoningEffort,-}: {- projectSlug: string;- agentSlug: string;- threadId: string;- initialEvents: TranscriptEvent[];- initialCursor: number;- /** Composer model override value ("" = harness default). */- model: string;- /** Composer effort override value ("" = harness default). */- reasoningEffort: string;-}) {- const [events, setEvents] = useState<TranscriptEvent[]>(initialEvents);- const [cursor, setCursor] = useState(initialCursor);- const [sendingChat, setSendingChat] = useState(false);- /**- * Wallclock when the current turn started, in ms. Drives the "elapsed"- * counter during the gap between hitting send and the agent's first- * transcript event landing — without this, elapsed reflects the- * *previous* turn's last event timestamp (often minutes/hours stale).- */- const [turnStartedAt, setTurnStartedAt] = useState<number | null>(null);-- // Optimistic state for the active /api/chat send. Rendered after- // committed events so the user sees their message + the streaming- // response before polling materializes them from the DB. Cleared once- // polling catches up.- const [pendingUserMsg, setPendingUserMsg] = useState<string | null>(null);- const [pendingAssistant, setPendingAssistant] = useState("");- const [pendingTools, setPendingTools] = useState<ToolEntry[]>([]);- const [pendingError, setPendingError] = useState<string | null>(null);- /**- * Most recent harness lifecycle phase for the in-flight turn (run.start,- * run.warming, etc.). Surfaced in the "thinking…" indicator so a long- * wait before the first model token at least shows forward motion.- */- const [pendingLifecycle, setPendingLifecycle] = useState<string | null>(null);-- const abortRef = useRef<AbortController | null>(null);-- // The stop click must reach the server: aborting the local fetch alone- // never stops the harness turn (disconnect != cancel), so the transcript- // would keep streaming the still-running reply via the poll.- const stopTurn = useCallback(() => {- abortRef.current?.abort();- void fetch("/api/chat/stop", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- project: projectSlug,- agent: agentSlug,- thread: threadId,- }),- }).catch(() => {- // Best-effort: the local abort already froze the composer's stream.- });- }, [agentSlug, projectSlug, threadId]);-- /**- * Ids of every transcript event we've already committed to state. Acts as- * a dedupe set for poll-result merging: two `pollOnce` calls can fire- * with the same `cursor` closure before React commits the next offset- * (e.g. the post-stream catch-up poll racing the background polling- * effect), so both fetches would return the same event slice and we'd- * end up with duplicate React keys. Lives in a ref so the dedupe is- * synchronous — `setEvents(prev => …)` updater functions don't run- * until React's next commit, so they can't be used to derive the count- * we return from `pollOnce`.- */- const seenEventIdsRef = useRef<Set<string>>(- new Set(initialEvents.map((e) => e.id)),- );-- const commitFresh = useCallback((incoming: TranscriptEvent[]) => {- const fresh = incoming.filter((e) => {- if (seenEventIdsRef.current.has(e.id)) return false;- return true;- });- for (const e of fresh) {- seenEventIdsRef.current.add(e.id);- }- if (fresh.length > 0) {- setEvents((prev) => [...prev, ...fresh]);- // Clear pending state: the DB now has the canonical events so the- // optimistic placeholders are no longer needed.- setPendingUserMsg(null);- setPendingAssistant("");- setPendingTools([]);- setPendingError(null);- setPendingLifecycle(null);- }- return fresh.length;- }, []);-- // ── Live tail polling. ─────────────────────────────────────────────- const pollOnce = useCallback(async () => {- try {- // Pass projectSlug explicitly: the API route would otherwise fall back- // to the active-project cookie, which can lag the URL on first paint- // after a project switch or direct deep-link.- const url = `/api/agents/${agentSlug}/threads/${threadId}/transcript?offset=${cursor}&project=${encodeURIComponent(projectSlug)}`;- const res = await fetch(url, { cache: "no-store" });- if (!res.ok) return { newEvents: 0 };- const data = (await res.json()) as {- events: TranscriptEvent[];- cursor: number;- };- const newEvents = commitFresh(data.events);- if (data.cursor !== cursor) setCursor(data.cursor);- return { newEvents };- } catch {- return { newEvents: 0 };- }- }, [agentSlug, commitFresh, cursor, projectSlug, threadId]);-- // Poll faster only during an active send. A disabled composer can also- // mean "read-only history," which should not be treated as live work.- const pollIntervalMs = sendingChat ? 800 : POLL_INTERVAL_MS;-- // Background polling: runs while mounted, paused during an active send so- // we don't double-render content we're already streaming via SSE.- useEffect(() => {- if (sendingChat) return;- let cancelled = false;- let timer: ReturnType<typeof setTimeout> | null = null;- const tick = async () => {- if (cancelled) return;- await pollOnce();- if (cancelled) return;- timer = setTimeout(tick, pollIntervalMs);- };- timer = setTimeout(tick, pollIntervalMs);- return () => {- cancelled = true;- if (timer) clearTimeout(timer);- };- }, [pollIntervalMs, pollOnce, sendingChat]);-- // ── Live re-attach: SSE bridge to committed transcript events. ──────- // The DB poll can lag a fast-streaming turn, so polling sees nothing- // mid-turn. Transcript inserts also emit the same durable row through- // an in-process live stream, so a tab switching back to a thread sees- // progress immediately instead of waiting for its next poll.- //- // The bridge runs on every thread mount, not just tasks. An idle thread- // simply emits nothing. Polling and the live bridge carry the same row- // id, so the synchronous id set prevents double-rendering.- //- // Skipped during an active /api/chat send — that path already streams- // its own deltas; layering re-attach on top would just duplicate work.- useEffect(() => {- const log = (...args: unknown[]) => console.log("[live-bridge]", ...args);- if (sendingChat) {- log("skip: sendingChat=true (/api/chat path owns streaming)", { threadId });- return;- }- if (typeof EventSource === "undefined") {- log("skip: no EventSource in env (jsdom test)");- return;- }- const url = `/api/agents/${agentSlug}/threads/${threadId}/live?project=${encodeURIComponent(projectSlug)}`;- log("opening", { url });- const es = new EventSource(url);- es.addEventListener("open", () => log("opened"));- es.addEventListener("ready", (e: MessageEvent) => log("ready", e.data));- es.addEventListener("transcript", (e: MessageEvent) => {- try {- const data = JSON.parse(e.data) as { events: TranscriptEvent[] };- if (!Array.isArray(data.events)) {- log("transcript payload not an array", data);- return;- }- const fresh = commitFresh(data.events);- log("transcript", { incoming: data.events.length, fresh });- } catch (err) {- log("transcript parse error", err);- }- });- es.addEventListener("error", (e) => {- log("error", { readyState: es.readyState, event: e });- });- return () => {- log("closing", { threadId });- es.close();- };- }, [agentSlug, commitFresh, projectSlug, sendingChat, threadId]);-- // ── Send: optimistic user message + SSE-driven streaming reply. ─────- const send = useCallback(- async (text: string, opts: { hidden?: boolean } = {}) => {- if (!text || sendingChat) return;-- setSendingChat(true);- setTurnStartedAt(Date.now());- setPendingUserMsg(opts.hidden ? null : text);- setPendingAssistant("");- setPendingTools([]);- setPendingError(null);-- const ctrl = new AbortController();- abortRef.current = ctrl;-- try {- const res = await fetch("/api/chat", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- message: text,- agent: agentSlug,- project: projectSlug,- thread: threadId,- ...(model ? { model } : {}),- ...(reasoningEffort ? { reasoning_effort: reasoningEffort } : {}),- }),- signal: ctrl.signal,- });- if (!res.ok || !res.body) {- throw new Error((await res.text()) || `HTTP ${res.status}`);- }- const reader = res.body.getReader();- const decoder = new TextDecoder();- let buffer = "";- for (;;) {- const { value, done } = await reader.read();- if (done) break;- buffer += decoder.decode(value, { stream: true });- const chunks = buffer.split("\n\n");- buffer = chunks.pop() ?? "";- for (const raw of chunks) {- handleSseEvent(raw, {- onText: (chunk) => setPendingAssistant((s) => s + chunk),- onTool: (evt) =>- setPendingTools((prev) => upsertToolEntry(prev, evt)),- onError: (msg) => setPendingError(msg),- onLifecycle: (phase) => setPendingLifecycle(phase),- onMeta: (meta) => {- if (process.env.NODE_ENV !== "production") {- // eslint-disable-next-line no-console- console.log(- `[chat-perf] turn start agent=${meta.agent} session=${meta.session_id} message_chars=${meta.message_chars}${meta.is_kickoff ? " (kickoff)" : ""}`,- );- }- },- onPerf: (marks) => {- if (process.env.NODE_ENV !== "production") {- // eslint-disable-next-line no-console- console.groupCollapsed(- `[chat-perf] turn complete (${marks.length} marks)`,- );- // eslint-disable-next-line no-console- console.table(- marks.map((m) => ({- name: m.name,- "at (ms)": Math.round(m.at),- "Δ (ms)": Math.round(m.delta),- })),- );- // eslint-disable-next-line no-console- console.groupEnd();- }- },- });- }- }- // Stream closed. Give the writer a moment to flush, then pull the- // committed events. pollOnce clears pending state when it returns- // new events; if it returns nothing yet, the regular polling- // effect picks it up on the next tick.- await new Promise((r) => setTimeout(r, 400));- const { newEvents } = await pollOnce();- if (newEvents === 0) {- // Re-try once more shortly. Avoids the case where the writer is- // slow to flush and the user briefly sees pending state with no- // backing rows.- setTimeout(() => {- void pollOnce();- }, 1200);- }- } catch (err) {- const isAbort = err instanceof DOMException && err.name === "AbortError";- if (!isAbort) {- const msg = err instanceof Error ? err.message : String(err);- setPendingError(msg);- return { error: msg } as const;- }- } finally {- setSendingChat(false);- setTurnStartedAt(null);- setPendingLifecycle(null);- abortRef.current = null;- }- return { error: null } as const;- },- [agentSlug, model, pollOnce, projectSlug, reasoningEffort, sendingChat, threadId],- );-- /** Local-view reset for the /clear slash command. */- const clearLocal = useCallback(() => {- setEvents([]);- setCursor(0);- }, []);-- // A turn can be running that THIS tab didn't start — another tab, a- // reload mid-turn, or a dropped SSE stream (the backend keeps going;- // disconnect ≠ cancel). Derive in-flight state from the committed- // events, with a staleness cutoff so a server crash can't strand a- // forever-spinner.- const openTurn = useMemo(() => findOpenTurn(events), [events]);- const [staleNow, setStaleNow] = useState(() => Date.now());- useEffect(() => {- if (!openTurn || sendingChat) return;- setStaleNow(Date.now());- const id = setInterval(() => setStaleNow(Date.now()), 30_000);- return () => clearInterval(id);- }, [openTurn, sendingChat]);- const remoteTurnActive = !sendingChat && isOpenTurnLive(openTurn, staleNow);-- return {- events,- sendingChat,- turnStartedAt,- openTurn,- remoteTurnActive,- pendingUserMsg,- pendingAssistant,- pendingTools,- pendingError,- pendingLifecycle,- send,- stopTurn,- clearLocal,- };-}diff --git a/notfair/src/components/chat/working-view.test.ts b/notfair/src/components/chat/working-view.test.tsdeleted file mode 100644index 596af3c9..00000000--- a/notfair/src/components/chat/working-view.test.ts+++ /dev/null@@ -1,246 +0,0 @@-import { describe, expect, it } from "vitest";--import type { TranscriptEvent } from "@/server/sessions/transcript-tail";-import type { ToolEntry } from "./transcript-model";-import {- WRAPPING_STALE_MS,- buildPhases,- deriveWorkingView,- humanLifecyclePhase,-} from "./working-view";--const NOW = 1_800_000_000_000;--const text = (id: string, ts: number, body = "hello"): TranscriptEvent => ({- kind: "assistant_text",- id,- ts,- body,-});-const userMsg = (id: string, ts: number): TranscriptEvent => ({- kind: "user_message",- id,- ts,- body: "hi",-});-const call = (- id: string,- ts: number,- tcid: string,- name = "shell",- label: string | null = "ls src",-): TranscriptEvent => ({ kind: "tool_call", id, ts, tool_call_id: tcid, name, label });-const result = (- id: string,- ts: number,- tcid: string,- ok = true,- name = "shell",-): TranscriptEvent => ({- kind: "tool_result",- id,- ts,- tool_call_id: tcid,- name,- summary: null,- ok,-});-const lifecycle = (id: string, ts: number, phase: string): TranscriptEvent => ({- kind: "lifecycle",- id,- ts,- phase,-});--const pendingTool = (over: Partial<ToolEntry> = {}): ToolEntry => ({- toolCallId: "p1",- name: "mcp__X__runScript",- label: null,- result: null,- ok: true,- done: false,- ...over,-});--function derive(over: Partial<Parameters<typeof deriveWorkingView>[0]> = {}) {- return deriveWorkingView({- agentDisplayName: "Agent",- events: [],- lifecyclePhase: null,- pendingTools: [],- hasPendingAssistant: false,- turnStartedAt: null,- now: NOW,- ...over,- });-}--describe("deriveWorkingView", () => {- it("reports Turn complete once the lifecycle done event lands", () => {- const view = derive({ events: [lifecycle("l1", NOW - 1000, "done")] });- expect(view).toMatchObject({ headline: "Turn complete", mood: "ended" });- });-- it("keeps working while a pending tool is still in flight past done", () => {- const view = derive({- events: [lifecycle("l1", NOW - 1000, "done")],- pendingTools: [pendingTool()],- });- expect(view.mood).toBe("tool");- });-- it("puts an in-flight SSE tool front and center", () => {- const view = derive({- pendingTools: [pendingTool({ name: "shell", label: "git status" })],- });- expect(view).toMatchObject({ headline: "Ran git status", mood: "tool" });- });-- it("shows Writing the response while assistant text streams, with last tool subtitle", () => {- const view = derive({- hasPendingAssistant: true,- pendingTools: [pendingTool({ done: true, ok: true, label: "pnpm test", name: "shell" })],- });- expect(view.headline).toBe("Writing the response");- expect(view.mood).toBe("writing");- expect(view.subtitle).toBe("Ran tests ✓");- });-- it("bridges the between-tools gap as Thinking with the last outcome", () => {- const ok = derive({- pendingTools: [pendingTool({ done: true, ok: true, name: "mcp__X__runScript" })],- });- expect(ok).toMatchObject({ headline: "Thinking", mood: "waiting" });- expect(ok.subtitle).toBe("Ran script ✓ — picking next step");-- const failed = derive({- pendingTools: [pendingTool({ done: true, ok: false, name: "mcp__X__runScript" })],- });- expect(failed.subtitle).toBe("Ran script failed — picking next step");- });-- it("promotes the lifecycle phase to the headline before any events", () => {- expect(derive({}).headline).toBe("Starting");- expect(derive({ lifecyclePhase: "run.start" }).headline).toBe(- "Calling the model",- );- expect(- derive({ events: [userMsg("u1", NOW - 500)], lifecyclePhase: "run.warming" })- .headline,- ).toBe("Warming up");- });-- it("treats a committed unanswered tool_call as the active phase", () => {- const view = derive({- events: [userMsg("u1", NOW - 3000), call("c1", NOW - 1000, "t1")],- });- expect(view).toMatchObject({ headline: "Listed files", mood: "tool" });- expect(view.subtitle).toBe("src");- });-- it("does not treat an answered tool_call as in flight", () => {- // result precedes the call in the log (out-of-order write) — the call is- // still the last event but it already has its result.- const view = derive({- events: [result("r1", NOW - 2000, "t1"), call("c1", NOW - 1000, "t1")],- });- expect(view.mood).not.toBe("tool");- });-- it("shows Thinking after a committed tool_result", () => {- const ok = derive({- events: [call("c1", NOW - 2000, "t1"), result("r1", NOW - 1000, "t1", true)],- });- expect(ok.headline).toBe("Thinking");- expect(ok.subtitle).toBe("Ran shell ✓ — picking next step");-- const failed = derive({- events: [call("c1", NOW - 2000, "t1"), result("r1", NOW - 1000, "t1", false)],- });- expect(failed.subtitle).toBe("Ran shell failed — retrying");- });-- it("wraps up on a fresh trailing assistant message", () => {- const view = derive({- events: [- call("c1", NOW - 5000, "t1"),- result("r1", NOW - 4000, "t1"),- text("a1", NOW - 1000),- ],- });- expect(view).toMatchObject({ headline: "Wrapping up", mood: "wrapping" });- // Subtitle falls back to the committed tool result.- expect(view.subtitle).toBe("Ran shell ✓");- });-- it("goes honest once the trailing message is stale", () => {- const view = derive({- events: [text("a1", NOW - WRAPPING_STALE_MS - 5_000)],- });- expect(view.headline).toBe("Still working");- expect(view.subtitle).toContain("quiet for 35s");-- const minutes = derive({ events: [text("a1", NOW - 240_000)] });- expect(minutes.subtitle).toContain("quiet for 4m");- });-- it("scopes events to the current turn via turnStartedAt", () => {- const view = derive({- // Old turn had a tool; the new turn hasn't produced events yet.- events: [call("c1", NOW - 100_000, "t1"), result("r1", NOW - 99_000, "t1")],- turnStartedAt: NOW - 1_000,- });- expect(view.headline).toBe("Starting");- expect(view.phases).toHaveLength(0);- });-});--describe("buildPhases", () => {- it("orders committed tools first and appends unseen pending tools", () => {- const phases = buildPhases(- [call("c1", NOW - 3000, "t1", "shell", "git status"), result("r1", NOW - 2000, "t1", true)],- [- pendingTool({ toolCallId: "t1" }), // already committed — skipped- pendingTool({ toolCallId: "t2", name: "mcp__X__runScript", label: "audit" }),- ],- );- expect(phases).toHaveLength(2);- expect(phases[0]).toMatchObject({ id: "t1", label: "Ran git status", state: "done" });- expect(phases[1]).toMatchObject({- id: "t2",- label: "Ran script",- state: "active",- detail: "audit",- });- });-- it("keeps an orphan committed result as a done phase and marks failures", () => {- const phases = buildPhases([result("r1", NOW, "t9", false, "shell")], []);- expect(phases).toEqual([- { id: "t9", label: "Ran shell", state: "failed" },- ]);- });-- it("demotes every active phase except the last", () => {- const phases = buildPhases(- [],- [- pendingTool({ toolCallId: "t1", done: false }),- pendingTool({ toolCallId: "t2", done: false }),- ],- );- expect(phases.map((p) => p.state)).toEqual(["done", "active"]);- });-});--describe("humanLifecyclePhase", () => {- it("maps known phases and falls back generically", () => {- expect(humanLifecyclePhase("run.warming")).toBe("Warming up");- expect(humanLifecyclePhase("context.compact")).toBe("Compacting context");- expect(humanLifecyclePhase("start")).toBe("Calling the model");- expect(humanLifecyclePhase("turn.start")).toBe("Calling the model");- expect(humanLifecyclePhase("run.end")).toBe("Finishing up");- expect(humanLifecyclePhase("turn.complete")).toBe("Finishing up");- expect(humanLifecyclePhase("v2.mystery")).toBe("Starting up");- });-});diff --git a/notfair/src/components/chat/working-view.ts b/notfair/src/components/chat/working-view.tsdeleted file mode 100644index d65bdc02..00000000--- a/notfair/src/components/chat/working-view.ts+++ /dev/null@@ -1,330 +0,0 @@-import type { TranscriptEvent } from "@/server/sessions/transcript-tail";-import type { WorkingMood, WorkingPhase } from "@/components/working-indicator";-import { humanizeTool } from "./tool-intent";-import type { ToolEntry } from "./transcript-model";--/**- * Derivation of the "agent is working" indicator's visible state from a- * mix of SSE-leading pending state and DB-trailing committed events.- * Pure functions only — the LiveWorkingIndicator component owns the- * clock and renders the result.- */--export type WorkingView = {- headline: string;- subtitle: string | null;- phases: WorkingPhase[];- mood: WorkingMood;-};--/**- * How long the last assistant message may sit as the newest event before- * "Wrapping up" stops being a credible description of the turn. Past- * this, the agent is demonstrably NOT wrapping up — it's working silently- * toward its next step (Codex emits nothing while reasoning).- */-export const WRAPPING_STALE_MS = 30_000;--/**- * Build the visible state for the working indicator.- *- * Precedence (most-specific first):- * 1. An SSE-pending tool start that hasn't reported a result → that's- * the active phase, mood "tool".- * 2. An SSE-pending assistant text stream → mood "writing".- * 3. No events yet (pre-first-token kickoff wait) → mood "waiting"- * with the gateway lifecycle hint as subtitle.- * 4. A committed in-flight tool_call → mood "tool" (polling caught up- * before the SSE state did, e.g. on rejoin from another tab).- * 5. Last committed event is a tool_result → mood "waiting".- * 6. Last committed event is assistant_text → mood "wrapping" while the- * message is fresh; once it goes stale (WRAPPING_STALE_MS) the agent- * is mid-work on its next step, not wrapping — mood "waiting" with- * an honest "quiet for Xm" subtitle.- *- * Phases are derived from BOTH sources so the trajectory chips include- * recent SSE tools the DB hasn't seen yet, then dedupe by tool name.- */-export function deriveWorkingView(input: {- agentDisplayName: string;- events: TranscriptEvent[];- lifecyclePhase: string | null;- pendingTools: ToolEntry[];- hasPendingAssistant: boolean;- /**- * Wallclock when the current turn started. We use it to scope the- * trajectory chips (and the in-flight tool detection) to the active- * turn — events from earlier turns in the same thread don't belong- * in "what is the agent doing right now?".- */- turnStartedAt: number | null;- /** Current wallclock (the caller's 1Hz tick) for staleness checks. */- now: number;-}): WorkingView {- const {- events,- lifecyclePhase,- pendingTools,- hasPendingAssistant,- turnStartedAt,- now,- } = input;- // Only consider events from the current turn. Anything older is part- // of the persistent transcript above this card, not the live status.- const turnEvents =- turnStartedAt != null ? events.filter((e) => e.ts >= turnStartedAt) : events;- // Turn-ended signal: the harness emits a `final` event when its run- // completes; transcript-tail surfaces it as `{ kind: "lifecycle",- // phase: "done" }`. Once we've seen it, the agent has stopped producing- // tokens. Keep the trajectory chips, but switch every live affordance- // to the static completed presentation.- const turnEnded = turnEvents.some(- (e) => e.kind === "lifecycle" && e.phase === "done",- );- const lastEvent =- turnEvents.length > 0 ? turnEvents[turnEvents.length - 1] : null;- const pendingInFlightTool = pendingTools.find((t) => !t.done) ?? null;- const inFlightCommittedToolCall: Extract<- TranscriptEvent,- { kind: "tool_call" }- > | null = (() => {- if (!lastEvent || lastEvent.kind !== "tool_call") return null;- const matched = turnEvents.some(- (e) => e.kind === "tool_result" && e.tool_call_id === lastEvent.tool_call_id,- );- return matched ? null : lastEvent;- })();- const phases = buildPhases(turnEvents, pendingTools);-- // Highest precedence: the harness has emitted its normal final event.- // This is a completed turn, not a parked task and not an error.- if (turnEnded && !pendingInFlightTool && !hasPendingAssistant) {- return { headline: "Turn complete", subtitle: null, phases, mood: "ended" };- }-- if (pendingInFlightTool) {- const intent = humanizeTool(- pendingInFlightTool.name,- pendingInFlightTool.label,- );- return {- headline: intent.verb,- subtitle: intent.target ?? pendingInFlightTool.label ?? null,- phases,- mood: "tool",- };- }- if (hasPendingAssistant) {- return {- headline: "Writing the response",- subtitle: subtitleForLastTool(pendingTools, turnEvents),- phases,- mood: "writing",- };- }- // Between-tools window: SSE has seen at least one tool finish this- // turn but the model hasn't started the next thing yet (no in-flight- // pending tool, no streaming text, no fresh transcript event because Codex- // buffers the file until end-of-turn). Without this branch we'd fall- // through to "Starting", which is wrong — the agent IS thinking, just- // about its next move. Surface the last tool so the user has context.- if (pendingTools.length > 0) {- const lastDone = [...pendingTools].reverse().find((t) => t.done);- return {- headline: "Thinking",- subtitle: lastDone- ? `${humanizeTool(lastDone.name, lastDone.label).verb} ${lastDone.ok ? "✓" : "failed"} — picking next step`- : null,- phases,- mood: "waiting",- };- }- if (- !lastEvent ||- lastEvent.kind === "user_message" ||- lastEvent.kind === "unknown"- ) {- // The gateway lifecycle phase IS the status when it arrives — showing- // "Starting" with a "Calling the model" subtitle stacked two- // contradictory descriptions of the same moment. Promote whichever- // signal we have to the headline; the generic "Starting" only fires- // before any lifecycle event lands.- const lifecycleSummary = lifecyclePhase- ? humanLifecyclePhase(lifecyclePhase)- : null;- return {- headline: lifecycleSummary ?? "Starting",- subtitle: null,- phases,- mood: "waiting",- };- }- if (inFlightCommittedToolCall) {- const intent = humanizeTool(- inFlightCommittedToolCall.name,- inFlightCommittedToolCall.label,- );- return {- headline: intent.verb,- subtitle: intent.target ?? inFlightCommittedToolCall.label ?? null,- phases,- mood: "tool",- };- }- if (lastEvent.kind === "tool_result") {- const verb = humanizeTool(lastEvent.name, null).verb;- return {- headline: "Thinking",- subtitle: lastEvent.ok- ? `${verb} ✓ — picking next step`- : `${verb} failed — retrying`,- phases,- mood: "waiting",- };- }- // assistant_text. "Wrapping up" is only true for the brief gap between- // the closing message and the turn's `final` event (sub-second on- // Codex, a few seconds on Claude Code). Codex delivers whole messages- // BETWEEN work phases and then goes silent — no deltas, no tool events- // — while it reasons toward its next tool call, so an intermediate- // narration message left "Wrapping up" spinning for many minutes and- // read as hung. Once the message goes stale, say what's actually- // happening: the agent is still mid-turn and has been quiet for a while.- if (now - lastEvent.ts > WRAPPING_STALE_MS) {- return {- headline: "Still working",- subtitle: `quiet for ${formatQuietFor(now - lastEvent.ts)} — progress updates from this harness can be sparse`,- phases,- mood: "waiting",- };- }- return {- headline: "Wrapping up",- subtitle: subtitleForLastTool(pendingTools, events),- phases,- mood: "wrapping",- };-}--function formatQuietFor(ms: number): string {- const sec = Math.floor(ms / 1000);- if (sec < 90) return `${sec}s`;- return `${Math.floor(sec / 60)}m`;-}--function subtitleForLastTool(- pendingTools: ToolEntry[],- events: TranscriptEvent[],-): string | null {- const lastDonePending = [...pendingTools].reverse().find((t) => t.done);- if (lastDonePending) {- const verb = humanizeTool(lastDonePending.name, lastDonePending.label).verb;- return `${verb} ${lastDonePending.ok ? "✓" : "failed"}`;- }- const lastDoneCommitted = [...events]- .reverse()- .find((e): e is Extract<TranscriptEvent, { kind: "tool_result" }> =>- e.kind === "tool_result",- );- if (lastDoneCommitted) {- const verb = humanizeTool(lastDoneCommitted.name, null).verb;- return `${verb} ${lastDoneCommitted.ok ? "✓" : "failed"}`;- }- return null;-}--/**- * Build the trajectory pills shown in the indicator. Order:- * 1. Committed tools (in order, deduped by tool_call_id).- * 2. SSE-pending tools not yet in the committed list.- * The last entry is the "active" one. Done entries get a check, the- * active one gets the mood-colored ring + wrench glyph.- */-export function buildPhases(- events: TranscriptEvent[],- pendingTools: ToolEntry[],-): WorkingPhase[] {- const seen = new Set<string>();- const phases: WorkingPhase[] = [];-- // Walk committed events to build phases in order. Capture the `label`- // from the tool_call (where it lives) so the phase chip's intent- // matches what the inline ToolGroup row shows — without it, shell- // commands collapse to "Ran shell command" in the trajectory.- const committedById = new Map<- string,- { name: string; label: string | null; done: boolean; ok: boolean }- >();- for (const e of events) {- if (e.kind === "tool_call") {- committedById.set(e.tool_call_id, {- name: e.name,- label: e.label,- done: false,- ok: true,- });- } else if (e.kind === "tool_result") {- const prev = committedById.get(e.tool_call_id);- if (prev) {- prev.done = true;- prev.ok = e.ok;- } else {- committedById.set(e.tool_call_id, {- name: e.name,- label: null,- done: true,- ok: e.ok,- });- }- }- }- for (const [id, t] of committedById) {- seen.add(id);- phases.push({- id,- label: humanizeTool(t.name, t.label).verb,- state: !t.done ? "active" : t.ok ? "done" : "failed",- });- }-- // Then any SSE-pending tools the committed list doesn't have yet.- for (const t of pendingTools) {- if (seen.has(t.toolCallId)) continue;- const intent = humanizeTool(t.name, t.label);- phases.push({- id: t.toolCallId,- label: intent.verb,- state: !t.done ? "active" : t.ok ? "done" : "failed",- detail: intent.target ?? t.label ?? null,- });- }-- // If multiple phases are flagged "active" (shouldn't happen, but defend),- // demote all but the last so the visual stays clear.- let lastActive = -1;- for (let i = 0; i < phases.length; i++) {- if (phases[i]!.state === "active") lastActive = i;- }- return phases.map((p, i) =>- p.state === "active" && i !== lastActive ? { ...p, state: "done" } : p,- );-}--/**- * Translate a harness stream lifecycle phase into a short- * user-facing label. We don't try to enumerate every possible phase —- * unknown values fall through to a generic "starting up…" so a future- * gateway protocol bump doesn't render a blank status.- */-export function humanLifecyclePhase(phase: string): string {- const p = phase.toLowerCase();- // Capitalized + no trailing ellipsis — these strings are used as the- // indicator's headline alongside "Calling runScript" / "Thinking" /- // "Writing the response".- if (p.includes("warming") || p.includes("warmup")) return "Warming up";- if (p.includes("compact")) return "Compacting context";- if (p === "start" || p.endsWith(".start") || p.includes("run.start"))- return "Calling the model";- if (p.includes("end") || p.includes("complete")) return "Finishing up";- return "Starting up";-}diff --git a/notfair/src/components/client-mount-gate.tsx b/notfair/src/components/client-mount-gate.tsxdeleted file mode 100644index 05031369..00000000--- a/notfair/src/components/client-mount-gate.tsx+++ /dev/null@@ -1,27 +0,0 @@-"use client";--import { useEffect, useState } from "react";--/**- * Render children only AFTER the client has mounted. The server renders an empty- * shell, the client mounts and swaps in real content. Eliminates every class of- * hydration mismatch in the wrapped tree (cookie-state divergence, lazy Radix- * event handlers, browser-extension HTML mutations, etc.) at the cost of an- * extra paint and zero SSR for the wrapped region.- *- * V1 trade-off: the app shell isn't on the SEO/perf critical path; the chat- * itself is what matters, and that's already client-driven. Silencing the- * hydration noise is worth the deferred mount.- */-export function ClientMountGate({- children,- fallback = null,-}: {- children: React.ReactNode;- fallback?: React.ReactNode;-}) {- const [mounted, setMounted] = useState(false);- useEffect(() => setMounted(true), []);- if (!mounted) return <>{fallback}</>;- return <>{children}</>;-}diff --git a/notfair/src/components/codebase-path-card.test.tsx b/notfair/src/components/codebase-path-card.test.tsxdeleted file mode 100644index 6027db68..00000000--- a/notfair/src/components/codebase-path-card.test.tsx+++ /dev/null@@ -1,142 +0,0 @@-// @vitest-environment jsdom-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { fireEvent, render, screen, waitFor } from "@testing-library/react";--import { CodebasePathCard } from "@/components/codebase-path-card";--// Mock at the server-action boundary, per repo test conventions.-const setPath = vi.hoisted(() => vi.fn());-vi.mock("@/server/actions/projects", () => ({- setProjectCodebasePathAction: setPath,-}));--const toastSuccess = vi.hoisted(() => vi.fn());-const toastError = vi.hoisted(() => vi.fn());-vi.mock("sonner", () => ({- toast: { success: toastSuccess, error: toastError },-}));--beforeEach(() => {- vi.clearAllMocks();-});-afterEach(() => {- vi.unstubAllGlobals();-});--function renderCard(currentPath: string | null = null) {- return render(- <CodebasePathCard projectSlug="acme" currentPath={currentPath} />,- );-}--describe("CodebasePathCard", () => {- it("seeds the field from the current path and keeps Save disabled until dirty", () => {- renderCard("/repo/site");- expect(screen.getByLabelText("Local codebase folder")).toHaveValue(- "/repo/site",- );- expect(screen.getByRole("button", { name: "Save" })).toBeDisabled();-- fireEvent.change(screen.getByLabelText("Local codebase folder"), {- target: { value: "/repo/other" },- });- expect(screen.getByRole("button", { name: "Save" })).toBeEnabled();- });-- it("fills the field from the folder picker result", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({- json: async () => ({ ok: true, path: "/picked/dir" }),- }),- );- renderCard();- fireEvent.click(screen.getByRole("button", { name: "Browse for a folder" }));- await waitFor(() =>- expect(screen.getByLabelText("Local codebase folder")).toHaveValue(- "/picked/dir",- ),- );- expect(fetch).toHaveBeenCalledWith("/api/fs/pick-folder", {- method: "POST",- });- });-- it("silently ignores a cancelled folder pick", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({- json: async () => ({ ok: false, kind: "cancelled" }),- }),- );- renderCard();- fireEvent.click(screen.getByRole("button", { name: "Browse for a folder" }));- await waitFor(() => expect(fetch).toHaveBeenCalled());- expect(screen.getByLabelText("Local codebase folder")).toHaveValue("");- expect(toastError).not.toHaveBeenCalled();- });-- it("toasts the picker's message on an unsupported/error result", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockResolvedValue({- json: async () => ({ ok: false, kind: "unsupported", message: "no zenity" }),- }),- );- renderCard();- fireEvent.click(screen.getByRole("button", { name: "Browse for a folder" }));- await waitFor(() => expect(toastError).toHaveBeenCalledWith("no zenity"));- });-- it("toasts a thrown fetch error", async () => {- vi.stubGlobal(- "fetch",- vi.fn().mockRejectedValue(new Error("network down")),- );- renderCard();- fireEvent.click(screen.getByRole("button", { name: "Browse for a folder" }));- await waitFor(() => expect(toastError).toHaveBeenCalledWith("network down"));- });-- it("saves a path and confirms agents can now propose changes", async () => {- setPath.mockResolvedValue({ ok: true, codebase_path: "/repo/site" });- renderCard();- fireEvent.change(screen.getByLabelText("Local codebase folder"), {- target: { value: "/repo/site" },- });- fireEvent.click(screen.getByRole("button", { name: "Save" }));- await waitFor(() => {- expect(setPath).toHaveBeenCalledWith({- project_slug: "acme",- codebase_path: "/repo/site",- });- expect(toastSuccess).toHaveBeenCalledWith(- "Codebase folder saved — agents can now propose code changes via pull requests.",- );- });- });-- it("confirms clearing when the saved path comes back null", async () => {- setPath.mockResolvedValue({ ok: true, codebase_path: null });- renderCard("/repo/site");- fireEvent.change(screen.getByLabelText("Local codebase folder"), {- target: { value: "" },- });- fireEvent.click(screen.getByRole("button", { name: "Save" }));- await waitFor(() =>- expect(toastSuccess).toHaveBeenCalledWith(- "Codebase folder cleared — agents can no longer change code.",- ),- );- });-- it("surfaces a save error as a toast", async () => {- setPath.mockResolvedValue({ ok: false, error: "bad path" });- renderCard();- fireEvent.change(screen.getByLabelText("Local codebase folder"), {- target: { value: "/x" },- });- fireEvent.click(screen.getByRole("button", { name: "Save" }));- await waitFor(() => expect(toastError).toHaveBeenCalledWith("bad path"));- });-});diff --git a/notfair/src/components/codebase-path-card.tsx b/notfair/src/components/codebase-path-card.tsxdeleted file mode 100644index cc8ee7b6..00000000--- a/notfair/src/components/codebase-path-card.tsx+++ /dev/null@@ -1,107 +0,0 @@-"use client";--import { useState, useTransition } from "react";-import { FolderOpen, Loader2 } from "lucide-react";-import { toast } from "sonner";--import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import { setProjectCodebasePathAction } from "@/server/actions/projects";--/**- * Settings card for the workspace's local codebase folder — the sanctioned- * root for agent code changes. Agents can only touch the site's code via- * the branch + PR protocol, and only inside this folder; without it, code- * changes are off the table and agents log recommendations instead.- */-export function CodebasePathCard({- projectSlug,- currentPath,-}: {- projectSlug: string;- currentPath: string | null;-}) {- const [value, setValue] = useState(currentPath ?? "");- const [picking, setPicking] = useState(false);- const [pending, startTransition] = useTransition();-- async function onBrowse() {- setPicking(true);- try {- const res = await fetch("/api/fs/pick-folder", { method: "POST" });- const body = (await res.json()) as- | { ok: true; path: string }- | { ok: false; kind: "cancelled" }- | { ok: false; kind: "unsupported" | "error"; message?: string };- if (body.ok) {- setValue(body.path);- return;- }- if (body.kind === "cancelled") return;- toast.error(body.message ?? "Couldn't open the folder picker.");- } catch (err) {- toast.error(err instanceof Error ? err.message : String(err));- } finally {- setPicking(false);- }- }-- function onSave() {- startTransition(async () => {- const r = await setProjectCodebasePathAction({- project_slug: projectSlug,- codebase_path: value,- });- if (!r.ok) {- toast.error(r.error);- return;- }- toast.success(- r.codebase_path- ? "Codebase folder saved — agents can now propose code changes via pull requests."- : "Codebase folder cleared — agents can no longer change code.",- );- });- }-- const dirty = (currentPath ?? "") !== value.trim();-- return (- <div className="ns-card p-[18px]">- <p className="m-0 mb-1 text-[13px] font-medium">Codebase folder</p>- <p className="m-0 mb-3 text-[12px] leading-relaxed text-[hsl(var(--notfair-ink-4))]">- The local git checkout of your website. Goal agents may change code- only here, only on a branch, and only through a pull request you- review and merge on GitHub. Leave empty to keep code off-limits.- </p>- <div className="flex gap-2">- <Input- value={value}- onChange={(e) => setValue(e.target.value)}- placeholder="/path/to/your/site"- maxLength={500}- disabled={pending || picking}- aria-label="Local codebase folder"- />- <Button- type="button"- variant="outline"- onClick={onBrowse}- disabled={pending || picking}- aria-label="Browse for a folder"- >- {picking ? (- <Loader2 className="mr-1.5 size-4 animate-spin" />- ) : (- <FolderOpen className="mr-1.5 size-4" />- )}- Browse…- </Button>- <Button type="button" onClick={onSave} disabled={pending || !dirty}>- {pending ? <Loader2 className="mr-1.5 size-4 animate-spin" /> : null}- Save- </Button>- </div>- </div>- );-}diff --git a/notfair/src/components/danger-zone.tsx b/notfair/src/components/danger-zone.tsxdeleted file mode 100644index b146121c..00000000--- a/notfair/src/components/danger-zone.tsx+++ /dev/null@@ -1,210 +0,0 @@-"use client";--import { useEffect, useState, useTransition } from "react";-import { useRouter } from "next/navigation";-import { AlertTriangle, Trash2, Loader2 } from "lucide-react";-import { toast } from "sonner";-import { Button } from "@/components/ui/button";-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from "@/components/ui/dialog";-import {- getProjectDeletionSummaryAction,- deleteProjectAction,-} from "@/server/actions/projects";-import type { ProjectDeletionSummary } from "@/server/agents/cascade-delete";--type Props = {- projectSlug: string;- projectName: string;-};--export function DangerZone({ projectSlug, projectName }: Props) {- const router = useRouter();- const [open, setOpen] = useState(false);- const [summary, setSummary] = useState<ProjectDeletionSummary | null>(null);- const [summaryError, setSummaryError] = useState<string | null>(null);- const [loadingSummary, setLoadingSummary] = useState(false);- const [pending, startTransition] = useTransition();-- useEffect(() => {- if (!open) {- setSummary(null);- setSummaryError(null);- return;- }- setLoadingSummary(true);- (async () => {- const r = await getProjectDeletionSummaryAction(projectSlug);- if (r.ok) setSummary(r.data);- else setSummaryError(r.error);- setLoadingSummary(false);- })();- }, [open, projectSlug]);-- const canDelete = !pending && !loadingSummary;-- function onConfirm() {- startTransition(async () => {- const r = await deleteProjectAction(projectSlug, projectSlug);- if (!r.ok) {- toast.error(r.error);- return;- }- const d = r.data;- const partial = d.agentsFailed.length;- if (partial > 0) {- const detail = d.agentsFailed[0]?.error ?? "";- toast.warning(- `Deleted, but ${partial} cleanup step${partial === 1 ? "" : "s"} failed${detail ? `: ${detail}` : "."}`,- );- } else {- toast.success(`Deleted ${projectName}. ${d.agents.length} goals removed.`);- }- setOpen(false);- router.push("/");- router.refresh();- });- }-- return (- <>- <div- className="ns-card"- style={{- boxShadow:- "inset 0 0 0 0.5px hsl(0 72% 51% / 0.25), 0 1px 2px rgba(0,0,0,.04)",- }}- >- <div className="flex items-start gap-4 p-[18px]">- <span- aria-hidden- className="grid size-9 shrink-0 place-items-center rounded-[9px] bg-[hsl(0_92%_96%)] text-[hsl(0_72%_42%)]"- >- <AlertTriangle className="size-4" />- </span>- <div className="min-w-0 flex-1">- <h3 className="text-[14.5px] font-semibold tracking-tight text-[hsl(0_72%_42%)]">- Delete this workspace- </h3>- <p className="mt-1 text-[12.5px] leading-snug text-[hsl(var(--notfair-ink-4))]">- Removes every goal, its agent, and every thread of- chat history. This cannot be undone.- </p>- </div>- <button- type="button"- onClick={() => setOpen(true)}- className="ns-btn ns-btn-danger ns-btn-sm shrink-0"- >- <Trash2 className="size-3.5" />- Delete workspace- </button>- </div>- </div>-- <Dialog open={open} onOpenChange={setOpen}>- <DialogContent className="max-w-md rounded-2xl">- <DialogHeader>- <DialogTitle className="flex items-center gap-2 text-base">- <AlertTriangle className="size-4 text-destructive" />- Delete “{projectName}”?- </DialogTitle>- <DialogDescription>- This will permanently delete the items below from NotFair's- local store. There is no recovery.- </DialogDescription>- </DialogHeader>-- {loadingSummary ? (- <div className="flex items-center gap-2 py-4 text-sm text-muted-foreground">- <Loader2 className="size-3.5 animate-spin" />- Counting what will be removed…- </div>- ) : summaryError ? (- <div className="rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-xs text-destructive">- Could not load deletion summary: {summaryError}- </div>- ) : summary ? (- <div className="space-y-3">- <div className="grid grid-cols-4 divide-x rounded-xl border border-border bg-card">- <Stat label="Agents" value={summary.totals.agents} />- <Stat label="Threads" value={summary.totals.threads} />- <Stat label="MCPs" value={summary.totals.mcps} />- </div>- {summary.agents.some((a) => a.exists) && (- <ul className="space-y-1 text-xs">- {summary.agents- .filter((a) => a.exists)- .map((a) => (- <li- key={a.agentId}- className="flex items-center justify-between gap-2"- >- <span>- {a.display_name}{" "}- <span className="font-mono text-[10px] text-muted-foreground">- {a.agentId}- </span>- </span>- <span className="tabular-nums text-muted-foreground">- {a.threadCount} thread{a.threadCount === 1 ? "" : "s"}- </span>- </li>- ))}- </ul>- )}- </div>- ) : null}-- <DialogFooter className="gap-2 sm:gap-2">- <Button- type="button"- variant="outline"- onClick={() => setOpen(false)}- disabled={pending}- >- Cancel- </Button>- <Button- type="button"- variant="destructive"- onClick={onConfirm}- disabled={!canDelete}- >- {pending ? (- <>- <Loader2 className="mr-1.5 size-3.5 animate-spin" />- Deleting…- </>- ) : (- <>- <Trash2 className="mr-1.5 size-3.5" />- Delete forever- </>- )}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- </>- );-}--function Stat({ label, value }: { label: string; value: number }) {- return (- <div className="px-3 py-2.5 text-center">- <div className="text-[18px] font-semibold tabular-nums tracking-tight">- {value}- </div>- <div className="mt-0.5 text-[10.5px] font-medium uppercase tracking-wide text-muted-foreground">- {label}- </div>- </div>- );-}diff --git a/notfair/src/components/goal-auto-refresh.tsx b/notfair/src/components/goal-auto-refresh.tsxdeleted file mode 100644index dad6d523..00000000--- a/notfair/src/components/goal-auto-refresh.tsx+++ /dev/null@@ -1,18 +0,0 @@-"use client";--import { useRouter } from "next/navigation";-import { useEffect } from "react";--/**- * Poll-refresh for goal states that change server-side without user input- * (intake running, a tick in flight). Server components re-render on- * router.refresh(), so the page stays live without a websocket.- */-export function GoalAutoRefresh({ intervalMs = 5000 }: { intervalMs?: number }) {- const router = useRouter();- useEffect(() => {- const t = setInterval(() => router.refresh(), intervalMs);- return () => clearInterval(t);- }, [router, intervalMs]);- return null;-}diff --git a/notfair/src/components/goal-checks-list.test.tsx b/notfair/src/components/goal-checks-list.test.tsxdeleted file mode 100644index b27ebbf6..00000000--- a/notfair/src/components/goal-checks-list.test.tsx+++ /dev/null@@ -1,219 +0,0 @@-// @vitest-environment jsdom-import { act, fireEvent, render, screen } from "@testing-library/react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--import { GoalChecksList } from "@/components/goal-checks-list";-import type { CheckRow } from "@/server/goals/checks";--// Mock at the server-action boundary, per repo test conventions.-const loadMore = vi.hoisted(() => vi.fn());-vi.mock("@/server/actions/goals", () => ({- loadMoreGoalChecksAction: loadMore,-}));--/** Capture IntersectionObserver callbacks so tests can trip the sentinel. */-let ioCallbacks: IntersectionObserverCallback[];-beforeEach(() => {- ioCallbacks = [];- loadMore.mockReset();- vi.stubGlobal(- "IntersectionObserver",- class {- constructor(cb: IntersectionObserverCallback) {- ioCallbacks.push(cb);- }- observe() {}- disconnect() {}- unobserve() {}- },- );-});-afterEach(() => vi.unstubAllGlobals());--function row(tick_number: number, over: Partial<CheckRow> = {}): CheckRow {- return {- id: `tick-${tick_number}`,- goal_id: "g1",- tick_number,- trigger_kind: "heartbeat",- session_id: null,- metric_value: 10 + tick_number,- metric_error: null,- status: "done",- summary: `summary ${tick_number}`,- started_at: "2026-07-15T00:00:00.000Z",- finished_at: "2026-07-15T00:01:00.000Z",- prs: [],- writes: [],- ...over,- } as CheckRow;-}--const baseProps = {- slug: "proj",- agentSlug: "goal-1",- goalId: "g1",-};--async function tripSentinel() {- await act(async () => {- for (const cb of ioCallbacks) {- cb(- [{ isIntersecting: true } as IntersectionObserverEntry],- {} as IntersectionObserver,- );- }- });-}--describe("GoalChecksList", () => {- it("renders compact trigger icons with full accessible labels and the PR pill", () => {- render(- <GoalChecksList- {...baseProps}- initialRows={[- row(2, { trigger_kind: "manual" }),- row(1, {- prs: [- {- id: "pr1",- url: "https://github.com/acme/site/pull/67",- title: "Fix titles",- state: "merged",- },- ],- }),- ]}- initialHasMore={false}- />,- );- const manualIcon = screen.getByRole("img", { name: "Manually triggered" });- expect(manualIcon).toBeInTheDocument();- expect(screen.getByRole("img", { name: "Heartbeat triggered" })).toBeInTheDocument();- expect(screen.queryByText("manually triggered")).not.toBeInTheDocument();- const pill = screen.getByRole("link", { name: "PR #67 · merged" });- expect(pill).toHaveAttribute("href", "https://github.com/acme/site/pull/67");- // hasMore=false → no sentinel, no observer registered.- expect(ioCallbacks).toHaveLength(0);- });-- it("loads older checks past the cursor when the sentinel appears", async () => {- loadMore.mockResolvedValueOnce({ rows: [row(2), row(1)], hasMore: false });- render(- <GoalChecksList- {...baseProps}- initialRows={[row(4), row(3)]}- initialHasMore={true}- />,- );- await tripSentinel();- expect(loadMore).toHaveBeenCalledWith("g1", 3, undefined); // strictly older than shown- expect(screen.getByText("summary 1")).toBeInTheDocument();- expect(screen.getAllByText(/^Check/)).toHaveLength(4);- });-- it("merges a refreshed first page without dropping loaded history", async () => {- loadMore.mockResolvedValueOnce({ rows: [row(2), row(1)], hasMore: false });- const { rerender } = render(- <GoalChecksList- {...baseProps}- initialRows={[row(4), row(3)]}- initialHasMore={true}- />,- );- await tripSentinel();-- // The page's 5s auto-refresh re-sends a fresh first page — now with a- // new check 5 and check 4 flipped from running to done.- rerender(- <GoalChecksList- {...baseProps}- initialRows={[row(5), row(4, { summary: "updated 4" }), row(3)]}- initialHasMore={true}- />,- );- expect(screen.getAllByText(/^Check/)).toHaveLength(5);- expect(screen.getByText("updated 4")).toBeInTheDocument();- expect(screen.getByText("summary 1")).toBeInTheDocument(); // history kept- });-- it("Action taken hides read-only checks and fetches the filtered page", async () => {- loadMore.mockResolvedValueOnce({- rows: [row(1, { writes: [{ label: "Goal updated", count: 1 }] })],- hasMore: false,- });- render(- <GoalChecksList- {...baseProps}- initialRows={[- row(4),- row(3, { writes: [{ label: "Keyword paused", count: 12 }] }),- row(2, {- prs: [- {- id: "pr1",- url: "https://github.com/acme/site/pull/9",- title: "Add FAQ",- state: "open",- },- ],- }),- ]}- initialHasMore={false}- />,- );-- await act(async () => {- fireEvent.click(screen.getByRole("button", { name: "Action taken" }));- });-- // First toggle fetches the newest filtered page from the server.- expect(loadMore).toHaveBeenCalledWith("g1", undefined, "action");- // Read-only check 4 is hidden; write check 3, PR check 2, and the- // server-fetched check 1 remain.- expect(screen.queryByText("summary 4")).not.toBeInTheDocument();- expect(screen.getByText("summary 3")).toBeInTheDocument();- expect(screen.getByText("summary 2")).toBeInTheDocument();- expect(screen.getByText("summary 1")).toBeInTheDocument();-- // Switching back shows everything again without another fetch.- fireEvent.click(screen.getByRole("button", { name: "All" }));- expect(screen.getByText("summary 4")).toBeInTheDocument();- expect(loadMore).toHaveBeenCalledTimes(1);- });-- it("badges each kind of modification a check made, with counts", () => {- render(- <GoalChecksList- {...baseProps}- initialRows={[- row(2, {- writes: [- { label: "Campaign budget updated", count: 1 },- { label: "Keyword paused", count: 3 },- ],- }),- row(1),- ]}- initialHasMore={false}- />,- );- expect(screen.getByText("Campaign budget updated")).toBeInTheDocument();- expect(screen.getByText("Keyword paused ×3")).toBeInTheDocument();- });-- it("shows an empty message when no check took action", async () => {- loadMore.mockResolvedValueOnce({ rows: [], hasMore: false });- render(- <GoalChecksList- {...baseProps}- initialRows={[row(2), row(1)]}- initialHasMore={false}- />,- );- await act(async () => {- fireEvent.click(screen.getByRole("button", { name: "Action taken" }));- });- expect(screen.getByText("No checks took action yet.")).toBeInTheDocument();- });-});diff --git a/notfair/src/components/goal-checks-list.tsx b/notfair/src/components/goal-checks-list.tsxdeleted file mode 100644index de3bee37..00000000--- a/notfair/src/components/goal-checks-list.tsx+++ /dev/null@@ -1,318 +0,0 @@-"use client";--import Link from "next/link";-import { useEffect, useRef, useState } from "react";-import { HeartPulse, Loader2, Zap } from "lucide-react";-import { loadMoreGoalChecksAction } from "@/server/actions/goals";-import type { CheckFilter, CheckPr, CheckRow, CheckWrite } from "@/server/goals/checks";-import { projectHref } from "@/lib/project-href";-import { formatMetric } from "@/lib/format-metric";-import { timeAgo } from "@/lib/time-ago";-import { cn } from "@/lib/utils";-import { Markdown } from "@/components/markdown";-import {- Tooltip,- TooltipContent,- TooltipProvider,- TooltipTrigger,-} from "@/components/ui/tooltip";--/**- * The goal rail's Checks diary. Server-renders the newest page; older- * checks stream in as the sentinel scrolls into view (cursor-paged by- * tick_number). The page's 5s auto-refresh re-sends the first page, which- * is merged in by id so freshly loaded history is never dropped.- *- * The "Action taken" filter hides read-only checks (nothing modified, no- * PR). Rows are kept in one merged store and filtered at render time,- * so the auto-refresh merge stays filter-agnostic; pagination re-queries- * the server with the filter so skipped checks don't count against pages.- */-export function GoalChecksList({- slug,- agentSlug,- goalId,- initialRows,- initialHasMore,-}: {- slug: string;- agentSlug: string;- goalId: string;- initialRows: CheckRow[];- initialHasMore: boolean;-}) {- const [rows, setRows] = useState<CheckRow[]>(initialRows);- const [filter, setFilter] = useState<CheckFilter>("all");- // hasMore is tracked per filter: only load responses for a given filter- // update it. "action" starts unknown (null) until its first page loads.- const [hasMoreAll, setHasMoreAll] = useState(initialHasMore);- const [hasMoreAction, setHasMoreAction] = useState<boolean | null>(null);- const [loading, setLoading] = useState(false);- const loadingRef = useRef(false);- const sentinelRef = useRef<HTMLDivElement | null>(null);- const visible = filter === "action" ? rows.filter(tookAction) : rows;- // The observer callback outlives renders; read visible rows via a ref.- const visibleRef = useRef(visible);- visibleRef.current = visible;-- useEffect(() => {- setRows((prev) => mergeRows(prev, initialRows));- }, [initialRows]);-- // First switch to "Action taken": the loaded window may hold few or no- // matching rows, so fetch the newest filtered page from the server.- useEffect(() => {- if (filter !== "action" || hasMoreAction !== null) return;- if (loadingRef.current) return;- loadingRef.current = true;- setLoading(true);- loadMoreGoalChecksAction(goalId, undefined, "action")- .then((res) => {- setRows((prev) => mergeRows(prev, res.rows));- setHasMoreAction(res.hasMore);- })- .finally(() => {- loadingRef.current = false;- setLoading(false);- });- }, [filter, hasMoreAction, goalId]);-- const hasMore = filter === "action" ? (hasMoreAction ?? false) : hasMoreAll;-- useEffect(() => {- const el = sentinelRef.current;- if (!el || !hasMore) return;- const io = new IntersectionObserver(async (entries) => {- if (!entries.some((e) => e.isIntersecting)) return;- if (loadingRef.current) return;- loadingRef.current = true;- setLoading(true);- try {- const shown = visibleRef.current;- const oldest =- shown.length > 0 ? Math.min(...shown.map((r) => r.tick_number)) : undefined;- const res = await loadMoreGoalChecksAction(- goalId,- oldest,- filter === "action" ? "action" : undefined,- );- setRows((prev) => mergeRows(prev, res.rows));- if (filter === "action") setHasMoreAction(res.hasMore);- else setHasMoreAll(res.hasMore);- } finally {- loadingRef.current = false;- setLoading(false);- }- });- io.observe(el);- return () => io.disconnect();- }, [goalId, hasMore, filter]);-- if (rows.length === 0) return null;-- return (- <TooltipProvider delayDuration={250}>- <div className="mb-2 flex items-center gap-1" role="group" aria-label="Filter checks">- <FilterButton active={filter === "all"} onClick={() => setFilter("all")}>- All- </FilterButton>- <FilterButton active={filter === "action"} onClick={() => setFilter("action")}>- Action taken- </FilterButton>- </div>- {visible.length === 0 && !loading ? (- <p className="m-0 text-[12px] text-[hsl(var(--notfair-ink-4))]">- No checks took action yet.- </p>- ) : (- <ul className="m-0 flex list-none flex-col divide-y divide-border/40 p-0">- {visible.map((t) => (- <CheckItem key={t.id} slug={slug} agentSlug={agentSlug} tick={t} />- ))}- </ul>- )}- {(hasMore || loading) && (- <div ref={sentinelRef} className="flex justify-center py-2">- {loading && (- <Loader2 className="size-3.5 animate-spin text-[hsl(var(--notfair-ink-4))]" />- )}- </div>- )}- </TooltipProvider>- );-}--/** A check "took action" when it modified something or registered a PR. */-function tookAction(row: CheckRow): boolean {- return row.writes.length > 0 || row.prs.length > 0;-}--function FilterButton({- active,- onClick,- children,-}: {- active: boolean;- onClick: () => void;- children: React.ReactNode;-}) {- return (- <button- type="button"- onClick={onClick}- aria-pressed={active}- className={cn(- "cursor-pointer rounded-md px-2 py-1 text-[11px] font-medium transition-colors",- active- ? "bg-[hsl(var(--notfair-surface-2))] text-[hsl(var(--notfair-ink-2))]"- : "text-[hsl(var(--notfair-ink-4))] hover:text-[hsl(var(--notfair-ink-3))]",- )}- >- {children}- </button>- );-}--/** Upsert incoming rows by id, newest check first. */-function mergeRows(prev: CheckRow[], incoming: CheckRow[]): CheckRow[] {- const byId = new Map(prev.map((r) => [r.id, r]));- for (const r of incoming) byId.set(r.id, r);- return [...byId.values()].sort((a, b) => b.tick_number - a.tick_number);-}--function CheckItem({- slug,- agentSlug,- tick,-}: {- slug: string;- agentSlug: string;- tick: CheckRow;-}) {- const threadLabel = tick.trigger_kind === "intake" ? "main" : `tick-${tick.tick_number}`;- return (- <li className="py-2.5 text-[12px] leading-snug first:pt-0 last:pb-0">- <div className="flex items-baseline justify-between gap-2">- <span className="font-medium">- Check {tick.tick_number}- <CheckTriggerIcon triggerKind={tick.trigger_kind} />- {tick.metric_value !== null && (- <span className="ml-1.5 font-normal tabular-nums text-[hsl(var(--notfair-ink-3))]">- → {formatMetric(tick.metric_value)}- </span>- )}- </span>- <span className="shrink-0 text-[10.5px] tabular-nums text-[hsl(var(--notfair-ink-4))]">- {timeAgo(tick.started_at)}- </span>- </div>- {tick.metric_error && (- <p className="m-0 text-[11.5px] text-[hsl(0_72%_51%)]">{tick.metric_error}</p>- )}- <div className="line-clamp-2 text-[11.5px] text-[hsl(var(--notfair-ink-4))]">- <Markdown className="text-[11.5px] text-[hsl(var(--notfair-ink-4))] [&_p]:m-0 [&_p]:inline [&_p+p]:before:content-['_']">- {tick.status === "running"- ? "running…"- : tick.status === "failed"- ? `failed: ${tick.summary ?? "(no detail)"}`- : (tick.summary ?? "(no summary)")}- </Markdown>- </div>- {/* Running agent checks are watchable live: the session attaches at- turn start and the check page's transcript polls as it streams.- No-op checks never carry a session and stay unlinked. */}- {(tick.session_id ||- tick.status === "running" ||- tick.prs.length > 0 ||- tick.writes.length > 0) && (- <div className="mt-0.5 flex flex-wrap items-center gap-x-2.5 gap-y-1">- {(tick.session_id || tick.status === "running") && (- <Link- href={projectHref(slug, `/goals/${agentSlug}/checks/${threadLabel}`)}- className="ns-link text-[10.5px]"- >- {tick.status === "running" ? "watch live ›" : "details ›"}- </Link>- )}- {tick.writes.map((write) => (- <CheckWriteBadge key={write.label} write={write} />- ))}- {tick.prs.map((pr) => (- <CheckPrButton key={pr.id} pr={pr} />- ))}- </div>- )}- </li>- );-}--/** Quiet trigger provenance: icon at rest, full wording on hover/focus. */-function CheckTriggerIcon({- triggerKind,-}: {- triggerKind: CheckRow["trigger_kind"];-}) {- const manual = triggerKind === "manual";- if (!manual && triggerKind !== "heartbeat") return null;- const label = manual ? "Manually triggered" : "Heartbeat triggered";- const Icon = manual ? Zap : HeartPulse;-- return (- <Tooltip>- <TooltipTrigger asChild>- <span- role="img"- tabIndex={0}- aria-label={label}- className={cn(- "ml-1 inline-flex size-4 translate-y-[2px] items-center justify-center rounded-sm align-baseline outline-none focus-visible:ring-1 focus-visible:ring-ring",- manual- ? "text-[hsl(var(--notfair-warn))]"- : "text-[hsl(var(--notfair-ink-4))]",- )}- >- <Icon className={cn("size-3", manual && "fill-current")} aria-hidden />- </span>- </TooltipTrigger>- <TooltipContent side="top" sideOffset={4}>- {label}- </TooltipContent>- </Tooltip>- );-}--/** Compact accent pill naming one kind of modification the check made- * ("Campaign budget updated", "Keyword paused ×3"). */-function CheckWriteBadge({ write }: { write: CheckWrite }) {- return (- <span className="ns-tag-accent inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-medium">- {write.label}- {write.count > 1 && ` ×${write.count}`}- </span>- );-}--/** Compact colored PR pill on a check row — links straight to GitHub. */-function CheckPrButton({ pr }: { pr: CheckPr }) {- const number = pr.url.match(/\/pull\/(\d+)$/)?.[1];- const tone =- pr.state === "open"- ? "ns-tag-accent"- : pr.state === "merged"- ? "bg-[hsl(217_60%_55%/0.14)] text-[hsl(217_60%_45%)] dark:text-[hsl(217_70%_70%)]"- : "ns-tag-red";- return (- <a- href={pr.url}- target="_blank"- rel="noreferrer"- title={pr.title}- className={cn(- "inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-medium",- tone,- )}- >- PR{number ? ` #${number}` : ""} · {pr.state}- </a>- );-}diff --git a/notfair/src/components/goal-checks-strip.tsx b/notfair/src/components/goal-checks-strip.tsxdeleted file mode 100644index 06556070..00000000--- a/notfair/src/components/goal-checks-strip.tsx+++ /dev/null@@ -1,74 +0,0 @@-import { cn } from "@/lib/utils";-import type { CheckSquare, Streak } from "@/lib/goal-streak";--/**- * Maintain-goal hero: the streak headline plus one square per check —- * held / intervened / failed. Colors are never alone: each square has a- * distinct glyph for the non-held states and a native tooltip, and the- * legend spells the mapping out in text.- */-export function GoalChecksStrip({- squares,- streak,-}: {- squares: CheckSquare[];- streak: Streak | null;-}) {- const recent = squares.slice(-28);- return (- <div>- <p className="m-0 mb-2 text-[13px]">- {streak === null ? (- <span className="text-[hsl(var(--notfair-ink-4))]">No checks yet.</span>- ) : !streak.holding ? (- <span>- <b>Attention needed</b> — the last check drifted or failed.- </span>- ) : streak.days === 0 ? (- <span>- <b>Holding at target</b> — since today’s check.- </span>- ) : (- <span>- Held at target for{" "}- <b className="tabular-nums">- {streak.days} day{streak.days === 1 ? "" : "s"}- </b>- </span>- )}- </p>- {recent.length > 0 && (- <>- <div className="flex flex-wrap gap-1" role="img" aria-label="Check history">- {recent.map((sq) => (- <span- key={sq.tick_number}- title={`Check ${sq.tick_number} — ${- sq.state === "held"- ? "held at target"- : sq.state === "acted"- ? "agent intervened"- : "drifted or failed"- } (${new Date(sq.t).toLocaleDateString()})`}- className={cn(- "flex size-4 items-center justify-center rounded-[3px] text-[9px] font-bold leading-none",- sq.state === "held" &&- "bg-[hsl(var(--notfair-accent))] text-transparent",- sq.state === "acted" &&- "bg-[hsl(217_60%_55%)] text-white",- sq.state === "failed" && "bg-[hsl(0_72%_51%)] text-white",- )}- >- {sq.state === "acted" ? "▼" : sq.state === "failed" ? "✕" : ""}- </span>- ))}- </div>- <p className="m-0 mt-1.5 text-[10.5px] text-[hsl(var(--notfair-ink-4))]">- ■ held · <span className="font-bold">▼</span> intervened ·{" "}- <span className="font-bold">✕</span> drifted/failed- </p>- </>- )}- </div>- );-}diff --git a/notfair/src/components/goal-completion-dialog.test.tsx b/notfair/src/components/goal-completion-dialog.test.tsxdeleted file mode 100644index 2eb1bdcd..00000000--- a/notfair/src/components/goal-completion-dialog.test.tsx+++ /dev/null@@ -1,98 +0,0 @@-// @vitest-environment jsdom-import { fireEvent, render, screen, waitFor } from "@testing-library/react";-import { beforeEach, describe, expect, it, vi } from "vitest";--import { GoalCompletionDialog } from "@/components/goal-completion-dialog";--const archiveGoal = vi.hoisted(() => vi.fn());-const continueGoal = vi.hoisted(() => vi.fn());-vi.mock("@/server/actions/goals", () => ({- archiveCompletedGoalAction: archiveGoal,- continueCompletedGoalAction: continueGoal,-}));--const refresh = vi.hoisted(() => vi.fn());-vi.mock("next/navigation", () => ({- useRouter: () => ({ refresh }),-}));--const PROPS = {- goalId: "goal-1",- label: "Qualified visits → 100",- metricName: "Qualified visits",- currentValue: 112,- targetValue: 100,- metricDirection: "increase" as const,- completionReason: "The verified metric reached 112.",- completedAt: "2026-07-22T18:00:00.000Z",- goalHref: "/acme/goals/goal-1",-};--function renderDialog() {- render(- <GoalCompletionDialog- {...PROPS}- trigger={<button type="button">Completed</button>}- />,- );- fireEvent.click(screen.getByRole("button", { name: "Completed" }));-}--beforeEach(() => {- vi.clearAllMocks();- archiveGoal.mockResolvedValue({ ok: true });- continueGoal.mockResolvedValue({ ok: true });-});--describe("GoalCompletionDialog", () => {- it("celebrates the measured result and keeps every next step explicit", () => {- renderDialog();-- expect(screen.getByRole("heading", { name: "You did it." })).toBeInTheDocument();- expect(screen.getByText("112")).toBeInTheDocument();- expect(screen.getByText("100")).toBeInTheDocument();- expect(screen.getByRole("button", { name: /set a new target/i })).toBeInTheDocument();- expect(screen.getByRole("button", { name: /archive goal/i })).toBeInTheDocument();- expect(screen.getByRole("link", { name: /view the full story/i })).toHaveAttribute(- "href",- "/acme/goals/goal-1",- );- });-- it("continues the same goal with a validated next milestone", async () => {- renderDialog();- fireEvent.click(screen.getByRole("button", { name: /set a new target/i }));- expect(- screen.getByRole("heading", { name: /what’s the next milestone/i }),- ).toBeInTheDocument();-- fireEvent.change(screen.getByLabelText("New target"), {- target: { value: "150" },- });- expect(screen.getByLabelText("Goal name")).toHaveValue(- "Qualified visits → 150",- );- fireEvent.change(screen.getByLabelText(/Deadline/), {- target: { value: "2030-12-31" },- });- fireEvent.click(screen.getByRole("button", { name: /start next milestone/i }));-- await waitFor(() =>- expect(continueGoal).toHaveBeenCalledWith("goal-1", {- target_value: 150,- deadline: "2030-12-31",- label: "Qualified visits → 150",- }),- );- await waitFor(() => expect(refresh).toHaveBeenCalled());- });-- it("archives the achievement without conflating archive with delete", async () => {- renderDialog();- fireEvent.click(screen.getByRole("button", { name: /archive goal/i }));-- await waitFor(() => expect(archiveGoal).toHaveBeenCalledWith("goal-1"));- expect(continueGoal).not.toHaveBeenCalled();- await waitFor(() => expect(refresh).toHaveBeenCalled());- });-});diff --git a/notfair/src/components/goal-completion-dialog.tsx b/notfair/src/components/goal-completion-dialog.tsxdeleted file mode 100644index d18e13fb..00000000--- a/notfair/src/components/goal-completion-dialog.tsx+++ /dev/null@@ -1,404 +0,0 @@-"use client";--import Link from "next/link";-import { useRouter } from "next/navigation";-import {- Archive,- ArrowLeft,- ArrowRight,- Check,- ExternalLink,- Sparkles,- Trophy,-} from "lucide-react";-import {- useMemo,- useState,- useTransition,- type CSSProperties,- type ReactNode,-} from "react";-import { toast } from "sonner";-import { Button } from "@/components/ui/button";-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,- DialogTrigger,-} from "@/components/ui/dialog";-import { Input } from "@/components/ui/input";-import { Label } from "@/components/ui/label";-import {- archiveCompletedGoalAction,- continueCompletedGoalAction,-} from "@/server/actions/goals";-import { formatMetric } from "@/lib/format-metric";--const CONFETTI = Array.from({ length: 20 }, (_, index) => ({- angle: index * 18 + (index % 3) * 4,- delay: (index % 5) * 32,- distance: 90 + (index % 4) * 15,- color: ["#4CAF6E", "#F1B94A", "#8B7CF6", "#54A7E8", "#F26D85"][- index % 5- ],-}));--export type GoalCompletionDialogProps = {- goalId: string;- label: string;- metricName: string | null;- currentValue: number | null;- targetValue: number | null;- metricDirection: "increase" | "decrease" | null;- completionReason: string | null;- completedAt: string;- goalHref?: string;- trigger: ReactNode;-};--/**- * The explicit handoff between "the agent hit the number" and "the user- * decides what happens next." Closing the dialog leaves the achievement in- * the sidebar, so celebration can never accidentally become dismissal.- */-export function GoalCompletionDialog({- goalId,- label,- metricName,- currentValue,- targetValue,- metricDirection,- completionReason,- completedAt,- goalHref,- trigger,-}: GoalCompletionDialogProps) {- const router = useRouter();- const [open, setOpen] = useState(false);- const [step, setStep] = useState<"celebrate" | "continue">("celebrate");- const [target, setTarget] = useState("");- const [nextLabel, setNextLabel] = useState(label);- const [labelEdited, setLabelEdited] = useState(false);- const [deadline, setDeadline] = useState("");- const [pending, startTransition] = useTransition();- const completedLabel = useMemo(- () =>- new Date(completedAt).toLocaleDateString([], {- month: "short",- day: "numeric",- year: "numeric",- }),- [completedAt],- );-- function changeOpen(next: boolean) {- setOpen(next);- if (!next) {- setStep("celebrate");- setTarget("");- setNextLabel(label);- setLabelEdited(false);- setDeadline("");- }- }-- function archive() {- startTransition(async () => {- const result = await archiveCompletedGoalAction(goalId);- if (!result.ok) {- toast.error(result.error ?? "Could not archive this goal.");- return;- }- changeOpen(false);- toast.success("Achievement archived — its full story is saved in All goals.");- router.refresh();- });- }-- function continueGoal() {- const targetValue = Number(target);- if (!target.trim() || !Number.isFinite(targetValue)) {- toast.error("Enter a valid next target.");- return;- }- startTransition(async () => {- const result = await continueCompletedGoalAction(goalId, {- target_value: targetValue,- deadline: deadline || null,- label: nextLabel.trim() || null,- });- if (!result.ok) {- toast.error(result.error ?? "Could not start the next milestone.");- return;- }- changeOpen(false);- toast.success("Next milestone started — your goal is running again.");- router.refresh();- });- }-- const directionWord =- metricDirection === "increase"- ? "above"- : metricDirection === "decrease"- ? "below"- : "beyond";-- function updateTarget(value: string) {- setTarget(value);- if (labelEdited) return;- const numeric = Number(value);- if (!value.trim() || !Number.isFinite(numeric)) {- setNextLabel(label);- return;- }- const nextValue = formatMetric(numeric);- const oldValue = formatMetric(targetValue);- if (targetValue !== null && label.includes(oldValue)) {- setNextLabel(label.replace(oldValue, nextValue));- return;- }- const rawOldValue = targetValue === null ? "" : String(targetValue);- if (rawOldValue && label.includes(rawOldValue)) {- setNextLabel(label.replace(rawOldValue, nextValue));- return;- }- setNextLabel(`${metricName ?? label} → ${nextValue}`);- }-- return (- <Dialog open={open} onOpenChange={changeOpen}>- <DialogTrigger asChild>{trigger}</DialogTrigger>- <DialogContent- className="overflow-hidden p-0 sm:max-w-[540px]"- >- {step === "celebrate" ? (- <>- <div className="ns-celebration-stage">- <div className="ns-celebration-halo" aria-hidden />- <div className="ns-celebration-confetti" aria-hidden>- {CONFETTI.map((piece, index) => (- <span- key={index}- style={- {- "--angle": `${piece.angle}deg`,- "--delay": `${piece.delay}ms`,- "--distance": `-${piece.distance}px`,- "--piece-color": piece.color,- } as CSSProperties- }- />- ))}- </div>- <div className="ns-celebration-medal" aria-hidden>- <Trophy />- <span><Check /></span>- </div>- <div className="relative z-10 px-6 pt-2 text-center">- <div className="mb-2 flex items-center justify-center gap-1.5 text-[11px] font-semibold tracking-[0.14em] text-[hsl(var(--notfair-accent))] uppercase">- <Sparkles className="size-3.5" />- Goal completed- </div>- <DialogHeader className="items-center text-center sm:text-center">- <DialogTitle className="text-[28px] leading-[1.08] tracking-[-0.035em]">- You did it.- </DialogTitle>- <DialogDescription- className="max-w-[42ch] text-[14px] leading-relaxed"- >- <span className="font-medium text-[hsl(var(--notfair-ink-2))]">- {label}- </span>{" "}- crossed the finish line. Every check and smart adjustment- added up to this result.- </DialogDescription>- </DialogHeader>- </div>- </div>-- <div className="px-6 pt-1 pb-6">- <div className="grid grid-cols-2 gap-2 rounded-xl bg-[hsl(var(--notfair-surface-2)/0.62)] p-1.5">- <div className="rounded-[9px] bg-[hsl(var(--card))] px-4 py-3 shadow-[var(--notfair-shadow-sm)]">- <div className="text-[10px] font-medium tracking-[0.08em] text-[hsl(var(--notfair-ink-4))] uppercase">- Result- </div>- <div className="mt-1 text-[22px] leading-none font-semibold tabular-nums tracking-[-0.03em]">- {formatMetric(currentValue)}- </div>- <div className="mt-1 truncate text-[11px] text-[hsl(var(--notfair-ink-4))]">- {metricName ?? "Measured goal"}- </div>- </div>- <div className="px-4 py-3">- <div className="text-[10px] font-medium tracking-[0.08em] text-[hsl(var(--notfair-ink-4))] uppercase">- Target- </div>- <div className="mt-1 text-[22px] leading-none font-semibold tabular-nums tracking-[-0.03em] text-[hsl(var(--notfair-accent))]">- {formatMetric(targetValue)}- </div>- <div className="mt-1 text-[11px] text-[hsl(var(--notfair-ink-4))]">- Completed {completedLabel}- </div>- </div>- </div>-- {completionReason && (- <p className="mt-3 mb-0 line-clamp-2 text-center text-[12px] leading-relaxed text-[hsl(var(--notfair-ink-4))]">- {completionReason}- </p>- )}-- <div className="mt-5">- <p className="mb-2 text-center text-[12px] font-medium text-[hsl(var(--notfair-ink-3))]">- Ready to choose what happens next?- </p>- <div className="grid gap-2 sm:grid-cols-2">- <Button- type="button"- onClick={() => setStep("continue")}- disabled={pending}- >- Set a new target- <ArrowRight />- </Button>- <Button- type="button"- variant="outline"- onClick={archive}- disabled={pending}- >- <Archive />- Archive goal- </Button>- </div>- {goalHref && (- <Button- asChild- variant="ghost"- className="mt-1 w-full text-[12px] text-[hsl(var(--notfair-ink-4))]"- >- <Link href={goalHref} onClick={() => setOpen(false)}>- View the full story- <ExternalLink />- </Link>- </Button>- )}- <p className="mt-2 mb-0 text-center text-[11px] leading-relaxed text-[hsl(var(--notfair-ink-4))]">- Not ready? Close this window. The Completed badge will stay- in your sidebar until you decide.- </p>- </div>- </div>- </>- ) : (- <form- className="p-6"- onSubmit={(event) => {- event.preventDefault();- continueGoal();- }}- >- <DialogHeader>- <button- type="button"- className="mb-3 flex w-fit items-center gap-1 rounded-md text-[12px] text-[hsl(var(--notfair-ink-4))] outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"- onClick={() => setStep("celebrate")}- >- <ArrowLeft className="size-3.5" />- Back to your result- </button>- <DialogTitle className="text-[22px] tracking-[-0.025em]">- What’s the next milestone?- </DialogTitle>- <DialogDescription- className="leading-relaxed"- >- Keep the same metric, history, and agent. Set a target{" "}- {directionWord} your completed result of{" "}- <span className="font-medium tabular-nums text-[hsl(var(--notfair-ink-2))]">- {formatMetric(currentValue)}- </span>- , and the goal will start running again.- </DialogDescription>- </DialogHeader>-- <div className="mt-6 grid gap-5">- <div className="grid gap-2">- <Label htmlFor={`next-target-${goalId}`}>- New target- </Label>- <Input- id={`next-target-${goalId}`}- type="number"- inputMode="decimal"- step="any"- value={target}- onChange={(event) => updateTarget(event.target.value)}- placeholder={`${directionWord[0].toUpperCase()}${directionWord.slice(1)} ${formatMetric(currentValue)}`}- autoFocus- required- />- <p className="m-0 text-[11.5px] text-[hsl(var(--notfair-ink-4))]">- {metricName ?? "The same verified metric"} will stay as the- source of truth.- </p>- </div>- <div className="grid gap-2">- <Label htmlFor={`next-label-${goalId}`}>- Goal name- </Label>- <Input- id={`next-label-${goalId}`}- value={nextLabel}- onChange={(event) => {- setNextLabel(event.target.value);- setLabelEdited(true);- }}- maxLength={120}- required- />- <p className="m-0 text-[11.5px] text-[hsl(var(--notfair-ink-4))]">- This is how the new milestone appears in your sidebar.- </p>- </div>- <div className="grid gap-2">- <Label htmlFor={`next-deadline-${goalId}`}>- Deadline <span className="font-normal text-[hsl(var(--notfair-ink-4))]">(optional)</span>- </Label>- <Input- id={`next-deadline-${goalId}`}- type="date"- min={new Date().toISOString().slice(0, 10)}- value={deadline}- onChange={(event) => setDeadline(event.target.value)}- />- </div>- </div>-- <DialogFooter className="mt-7">- <Button- type="button"- variant="outline"- onClick={() => setStep("celebrate")}- disabled={pending}- >- Cancel- </Button>- <Button- type="submit"- disabled={pending || !target.trim() || !nextLabel.trim()}- >- {pending ? "Starting…" : "Start next milestone"}- <ArrowRight />- </Button>- </DialogFooter>- </form>- )}- </DialogContent>- </Dialog>- );-}diff --git a/notfair/src/components/goal-context-dialog.test.tsx b/notfair/src/components/goal-context-dialog.test.tsxdeleted file mode 100644index 0946741b..00000000--- a/notfair/src/components/goal-context-dialog.test.tsx+++ /dev/null@@ -1,113 +0,0 @@-// @vitest-environment jsdom-import { fireEvent, render, screen } from "@testing-library/react";-import { beforeEach, describe, expect, it, vi } from "vitest";--import { GoalContextDialog } from "@/components/goal-context-dialog";--// Mock at the server-action boundary, per repo test conventions.-const getContext = vi.hoisted(() => vi.fn());-vi.mock("@/server/actions/context", () => ({- getGoalContextAction: getContext,-}));--const props = {- projectSlug: "proj",- agentSlug: "goal-1",- agentId: "agent-1",- threadId: "tick-7",- models: [{ value: "opus", label: "Opus", context_window: 1000 }],-};--function contextOf(totalTokens: number) {- return {- ok: true,- total_tokens: totalTokens,- chunks: [- {- key: "identity",- label: "Agent instructions",- group: "instructions",- chars: totalTokens * 4,- tokens: totalTokens,- content: "You are goal-1.",- format: "markdown",- },- ],- };-}--async function openDialog() {- fireEvent.click(screen.getByRole("button", { name: /context/i }));- await screen.findByText(/agent instructions/i);-}--beforeEach(() => {- getContext.mockReset();- window.localStorage.clear();-});--describe("GoalContextDialog model resolution", () => {- const twoModels = {- ...props,- models: [- { value: "gpt-5.5", label: "GPT-5.5", context_window: 272_000 },- { value: "gpt-5.6-sol", label: "GPT-5.6 sol", context_window: 400_000, is_default: true },- ],- };-- it("uses the harness default model when the composer has no override", async () => {- getContext.mockResolvedValueOnce(contextOf(500));- render(<GoalContextDialog {...twoModels} />);- await openDialog();- expect(screen.getByText(/window of GPT-5\.6 sol · 400k/)).toBeInTheDocument();- });-- it("uses the composer's localStorage model override", async () => {- window.localStorage.setItem("NotFair:model:proj:goal-1", "gpt-5.5");- getContext.mockResolvedValueOnce(contextOf(500));- render(<GoalContextDialog {...twoModels} />);- await openDialog();- expect(screen.getByText(/window of GPT-5\.5 · 272k/)).toBeInTheDocument();- });-- it("ignores a stale override that no longer names a known model", async () => {- window.localStorage.setItem("NotFair:model:proj:goal-1", "retired-model");- getContext.mockResolvedValueOnce(contextOf(500));- render(<GoalContextDialog {...twoModels} />);- await openDialog();- expect(screen.getByText(/window of GPT-5\.6 sol · 400k/)).toBeInTheDocument();- });-- it("offers no model picker — the window follows the chat model", async () => {- getContext.mockResolvedValueOnce(contextOf(500));- render(<GoalContextDialog {...twoModels} />);- await openDialog();- expect(screen.queryByRole("combobox")).toBeNull();- });-});--describe("GoalContextDialog window pressure", () => {- it("stays quiet while the window has comfortable headroom", async () => {- getContext.mockResolvedValueOnce(contextOf(500)); // 50% of 1000- render(<GoalContextDialog {...props} />);- await openDialog();- expect(screen.queryByText(/approaching the window/i)).toBeNull();- expect(screen.getByText(/50\.0% used/)).toBeInTheDocument();- });-- it("explains auto-compaction when usage nears the window", async () => {- getContext.mockResolvedValueOnce(contextOf(850)); // 85% of 1000- render(<GoalContextDialog {...props} />);- await openDialog();- expect(screen.getByText(/approaching the window/i)).toBeInTheDocument();- expect(screen.getByText(/automatically compacts/i)).toBeInTheDocument();- });-- it("reports an outgrown window with an honest >100% figure", async () => {- getContext.mockResolvedValueOnce(contextOf(1250)); // 125% of 1000- render(<GoalContextDialog {...props} />);- await openDialog();- expect(screen.getByText(/outgrown the window/i)).toBeInTheDocument();- expect(screen.getByText(/125\.0% used/)).toBeInTheDocument();- });-});diff --git a/notfair/src/components/goal-context-dialog.tsx b/notfair/src/components/goal-context-dialog.tsxdeleted file mode 100644index 5e2671b9..00000000--- a/notfair/src/components/goal-context-dialog.tsx+++ /dev/null@@ -1,324 +0,0 @@-"use client";--import { useCallback, useMemo, useState } from "react";-import { ChevronRight, Layers, Loader2 } from "lucide-react";-import {- Dialog,- DialogContent,- DialogDescription,- DialogHeader,- DialogTitle,- DialogTrigger,-} from "@/components/ui/dialog";-import {- getGoalContextAction,- type ContextChunk,-} from "@/server/actions/context";-import { cn } from "@/lib/utils";-import { Markdown } from "@/components/markdown";--/**- * /context for a goal: what fills this agent's context window, measured- * against the CURRENT chat model's real window size (read from the- * harness's own model metadata — never hardcoded here). The current model- * is whatever the composer would use: the per-project+agent localStorage- * override when set, else the harness default. Token counts are estimates- * (~4 chars/token); clicking a row reveals the chunk's exact content.- */--export type ContextModelOption = {- value: string;- label: string;- context_window?: number;- is_default?: boolean;-};--const GROUP_META: Record<- ContextChunk["group"],- { label: string; swatch: string }-> = {- instructions: { label: "Instructions", swatch: "bg-[hsl(var(--notfair-accent))]" },- tools: { label: "Tool definitions", swatch: "bg-[hsl(217_60%_55%)]" },- conversation: { label: "Conversation", swatch: "bg-[hsl(38_80%_55%)]" },-};--const FREE_SWATCH = "bg-[hsl(var(--notfair-ink-4)/0.18)]";--/** 36_308 → "36.3k", 272_000 → "272k", 319 → "319". */-function fmtK(n: number): string {- if (n < 1000) return String(n);- const k = n / 1000;- return `${k >= 100 ? Math.round(k) : k.toFixed(1).replace(/\.0$/, "")}k`;-}--type LoadState =- | { phase: "idle" }- | { phase: "loading" }- | { phase: "error"; message: string }- | { phase: "ready"; chunks: ContextChunk[]; total: number };--export function GoalContextDialog({- projectSlug,- agentSlug,- agentId,- threadId,- models,-}: {- projectSlug: string;- /** URL slug — keys the composer's model-override localStorage entry. */- agentSlug: string;- agentId: string;- threadId: string;- models: ContextModelOption[];-}) {- const [open, setOpen] = useState(false);- const [state, setState] = useState<LoadState>({ phase: "idle" });- const [expanded, setExpanded] = useState<string | null>(null);- // The composer's override, read fresh each time the dialog opens (the- // user may have switched models since). "" = no override stored.- const [overrideModel, setOverrideModel] = useState("");-- // Mirror the chat composer's resolution exactly: localStorage override- // when it names a known model, else the harness default.- const selected = useMemo(- () =>- models.find((m) => m.value === overrideModel) ??- models.find((m) => m.is_default) ??- models[0],- [models, overrideModel],- );- const window = selected?.context_window;-- const load = useCallback(async () => {- setState({ phase: "loading" });- const r = await getGoalContextAction({- project_slug: projectSlug,- agent_id: agentId,- thread: threadId,- });- if (r.ok) setState({ phase: "ready", chunks: r.chunks, total: r.total_tokens });- else setState({ phase: "error", message: r.error });- }, [projectSlug, agentId, threadId]);-- function onOpenChange(next: boolean) {- setOpen(next);- if (next) {- // `window` is shadowed by the context-window const above.- setOverrideModel(- globalThis.localStorage?.getItem(`NotFair:model:${projectSlug}:${agentSlug}`) ?? "",- );- if (state.phase === "idle") void load();- }- if (!next) setExpanded(null);- }-- // Denominator: the model's window when known, else the measured total.- const denom =- state.phase === "ready" ? (window && window > state.total ? window : state.total) : 0;- const pct = (tokens: number) => (denom > 0 ? (tokens / denom) * 100 : 0);-- const groupTotals =- state.phase === "ready"- ? (Object.keys(GROUP_META) as ContextChunk["group"][]).map((g) => ({- group: g,- tokens: state.chunks- .filter((c) => c.group === g)- .reduce((a, c) => a + c.tokens, 0),- }))- : [];-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogTrigger asChild>- <button- type="button"- className="ns-chip"- title="What fills this agent's context window"- >- <Layers className="size-3.5" aria-hidden />- Context- </button>- </DialogTrigger>- <DialogContent className="max-h-[82vh] overflow-y-auto sm:max-w-2xl">- <DialogHeader>- <DialogTitle className="flex items-center gap-2 text-[15px]">- <Layers className="size-4" aria-hidden />- Context window- </DialogTitle>- <DialogDescription>- What this goal’s agent works with each turn. Token counts are- estimates (~4 characters per token) — click any row for the exact- content.- </DialogDescription>- </DialogHeader>-- {state.phase === "loading" && (- <div className="flex items-center gap-2 py-6 text-[13px] text-[hsl(var(--notfair-ink-4))]">- <Loader2 className="size-4 animate-spin" aria-hidden />- Measuring instruction files, tool schemas, and the conversation…- </div>- )}- {state.phase === "error" && (- <p className="py-4 text-[13px] text-[hsl(0_72%_51%)]">{state.message}</p>- )}-- {state.phase === "ready" && (- <>- {/* Headline: used-of-window against the model the chat actually- uses — window sizes come from the harness's own model- metadata. */}- <div className="flex flex-wrap items-baseline justify-between gap-2">- <p className="m-0 text-[20px] font-semibold tabular-nums">- ≈{fmtK(state.total)}- {window ? (- <>- <span className="text-[hsl(var(--notfair-ink-4))]"> of </span>- {fmtK(window)}- <span className="ml-2 text-[13px] font-normal text-[hsl(var(--notfair-ink-3))]">- {((state.total / window) * 100).toFixed(1)}% used- </span>- </>- ) : (- <span className="ml-1 text-[13px] font-normal text-[hsl(var(--notfair-ink-4))]">- tokens (window size unknown for this model)- </span>- )}- </p>- {selected && (- <span className="text-[11.5px] text-[hsl(var(--notfair-ink-4))]">- window of {selected.label}- {window ? ` · ${fmtK(window)}` : ""}- </span>- )}- </div>-- {/* Near/over the window: say what actually happens, before the- user has to wonder. The harness compacts on its own; the- goal's operating state never lives in the window. */}- {window !== undefined && state.total >= window * 0.8 && (- <div className="rounded-md bg-[hsl(var(--notfair-warn-soft))] px-3 py-2 text-[12px] leading-relaxed text-[hsl(var(--notfair-warn))]">- <b>- {state.total >= window- ? "This conversation has outgrown the window."- : "Approaching the window."}- </b>{" "}- The harness automatically compacts older turns to keep the- thread going — nothing breaks, but compacted turns are- summarized and lose detail. The goal itself is not at risk:- its metric, actions, and memory live in NotFair’s- database, the agent’s instructions are re-sent every- turn, and every check runs from a fresh, self-contained- brief.- </div>- )}-- {/* Stacked bar of the WHOLE window; the muted tail is free space. */}- <div- className="flex h-4 w-full overflow-hidden rounded-md"- role="img"- aria-label={- window- ? `Estimated ${fmtK(state.total)} of ${fmtK(window)} tokens used`- : `Estimated ${fmtK(state.total)} tokens`- }- >- {state.chunks.map((c) => (- <span- key={c.key}- className={cn(- GROUP_META[c.group].swatch,- "border-r border-[hsl(var(--background))] last:border-r-0",- )}- style={{ width: `${Math.max(0.5, pct(c.tokens))}%` }}- title={`${c.label} — ~${fmtK(c.tokens)} tokens`}- />- ))}- {window && window > state.total && (- <span- className={cn(FREE_SWATCH, "flex-1")}- title={`Free — ~${fmtK(window - state.total)} tokens`}- />- )}- </div>-- {/* Group subtotals as the legend — text carries identity. */}- <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-[11.5px] text-[hsl(var(--notfair-ink-3))]">- {groupTotals.map(({ group, tokens }) => (- <span key={group} className="inline-flex items-center gap-1.5 tabular-nums">- <span className={cn("size-2 rounded-[2px]", GROUP_META[group].swatch)} aria-hidden />- {GROUP_META[group].label} ~{fmtK(tokens)}- </span>- ))}- {window && window > state.total && (- <span className="inline-flex items-center gap-1.5 tabular-nums">- <span className={cn("size-2 rounded-[2px]", FREE_SWATCH)} aria-hidden />- Free ~{fmtK(window - state.total)}- </span>- )}- </div>-- <ul className="m-0 flex list-none flex-col p-0">- {state.chunks.map((c) => {- const isOpen = expanded === c.key;- const share = pct(c.tokens);- return (- <li key={c.key}>- <button- type="button"- onClick={() => setExpanded(isOpen ? null : c.key)}- className="flex w-full items-center gap-2.5 rounded-md px-1.5 py-2.5 text-left text-[13px] transition-colors hover:bg-[hsl(var(--notfair-surface-2))]"- aria-expanded={isOpen}- >- <ChevronRight- className={cn("size-3.5 shrink-0 text-[hsl(var(--notfair-ink-4))] transition-transform", isOpen && "rotate-90")}- aria-hidden- />- <span className={cn("size-2 shrink-0 rounded-[2px]", GROUP_META[c.group].swatch)} aria-hidden />- <span className="min-w-0 flex-1 truncate">{c.label}</span>- {/* per-row share of the window, as a quiet inline bar */}- <span className="hidden h-1.5 w-20 shrink-0 overflow-hidden rounded-full bg-[hsl(var(--notfair-ink-4)/0.12)] sm:block" aria-hidden>- <span- className={cn("block h-full", GROUP_META[c.group].swatch)}- style={{ width: `${Math.min(100, Math.max(1.5, share))}%` }}- />- </span>- <span className="w-16 shrink-0 text-right tabular-nums text-[12px] text-[hsl(var(--notfair-ink-3))]">- ~{fmtK(c.tokens)}- </span>- <span className="w-12 shrink-0 text-right tabular-nums text-[11.5px] text-[hsl(var(--notfair-ink-4))]">- {share < 0.1 ? "<0.1" : share.toFixed(1)}%- </span>- </button>- {isOpen && (- <div className="mb-3 ml-6">- {c.note && (- <p className="m-0 mb-1.5 text-[11.5px] text-[hsl(var(--notfair-ink-4))]">- {c.note}- </p>- )}- {c.format === "json" ? (- <pre className="m-0 max-h-72 overflow-auto rounded-md bg-[hsl(var(--notfair-ink)/0.04)] p-3 text-[11px] leading-relaxed whitespace-pre-wrap break-words text-[hsl(var(--notfair-ink-2))]">- {c.content}- </pre>- ) : (- <div className="max-h-72 overflow-auto rounded-md bg-[hsl(var(--notfair-ink)/0.04)] p-3">- <Markdown className="text-[12px]">{c.content}</Markdown>- </div>- )}- </div>- )}- </li>- );- })}- </ul>- <p className="m-0 text-[11px] leading-snug text-[hsl(var(--notfair-ink-4))]">- Not shown: the harness’s own base prompt and its full- tool-output history — those live inside the runtime and- aren’t visible to NotFair.- </p>- </>- )}- </DialogContent>- </Dialog>- );-}diff --git a/notfair/src/components/goal-controls.tsx b/notfair/src/components/goal-controls.tsxdeleted file mode 100644index b37d0d4d..00000000--- a/notfair/src/components/goal-controls.tsx+++ /dev/null@@ -1,161 +0,0 @@-"use client";--import { useRouter } from "next/navigation";-import { useState, useTransition } from "react";-import { toast } from "sonner";-import { MoreHorizontal, Pause, Play, Square, Zap } from "lucide-react";-import {- killGoalAction,- pauseGoalAction,- resumeGoalAction,- runTickNowAction,-} from "@/server/actions/goals";-import { Button } from "@/components/ui/button";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu";-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from "@/components/ui/dialog";--/**- * Live-goal controls, sized for the chip row. "Run check" stays a- * first-class chip — it's the one control used daily. Pause/resume and- * Close live behind the ⋯ overflow: needed, but rare enough that they- * shouldn't spend header space or invite misclicks next to daily chips.- */-export function GoalControls({- goalId,- status,-}: {- goalId: string;- status: "active" | "paused" | "intake" | "proposed";-}) {- const router = useRouter();- const [pending, startTransition] = useTransition();- const [killOpen, setKillOpen] = useState(false);-- function run(- fn: () => Promise<{ ok: boolean; error?: string }>,- successMsg: string,- ) {- startTransition(async () => {- const r = await fn();- if (!r.ok) {- toast.error(r.error ?? "Action failed.");- return;- }- toast.success(successMsg);- router.refresh();- });- }-- return (- <div className="flex items-center gap-2">- {status === "active" && (- <button- type="button"- className="ns-chip"- aria-label="Run check now"- disabled={pending}- onClick={() => run(() => runTickNowAction(goalId), "Check started — watch the diary.")}- >- <Zap aria-hidden />- <span className="hidden sm:inline">Run check</span>- </button>- )}- {status === "paused" && (- <button- type="button"- className="ns-chip"- aria-label="Resume goal"- disabled={pending}- onClick={() => run(() => resumeGoalAction(goalId), "Goal resumed — heartbeat restarted.")}- >- <Play aria-hidden />- <span className="hidden sm:inline">Resume</span>- </button>- )}-- <DropdownMenu>- <DropdownMenuTrigger asChild>- <button- type="button"- className="ns-chip !px-1.5"- aria-label="More goal actions"- disabled={pending}- >- <MoreHorizontal aria-hidden />- </button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end" className="min-w-44">- {status === "active" && (- <DropdownMenuItem- disabled={pending}- onSelect={() => run(() => pauseGoalAction(goalId), "Goal paused.")}- >- <Pause />- Pause the loop- </DropdownMenuItem>- )}- {status === "paused" && (- <DropdownMenuItem- disabled={pending}- onSelect={() =>- run(() => resumeGoalAction(goalId), "Goal resumed — heartbeat restarted.")- }- >- <Play />- Resume the loop- </DropdownMenuItem>- )}- {(status === "active" || status === "paused") && <DropdownMenuSeparator />}- <DropdownMenuItem- variant="destructive"- disabled={pending}- onSelect={() => setKillOpen(true)}- >- <Square />- Close goal…- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>-- <Dialog open={killOpen} onOpenChange={setKillOpen}>- <DialogContent>- <DialogHeader>- <DialogTitle>Close this goal?</DialogTitle>- <DialogDescription>- The loop stops permanently and the goal moves to history. This- can’t be undone — you’d start a fresh goal instead.- </DialogDescription>- </DialogHeader>- <DialogFooter>- <Button variant="outline" onClick={() => setKillOpen(false)} disabled={pending}>- Keep it- </Button>- <Button- variant="destructive"- disabled={pending}- onClick={() => {- setKillOpen(false);- run(() => killGoalAction(goalId), "Goal closed.");- }}- >- Close goal- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- </div>- );-}diff --git a/notfair/src/components/goal-group-dashboard.test.tsx b/notfair/src/components/goal-group-dashboard.test.tsxdeleted file mode 100644index 3fb00eaa..00000000--- a/notfair/src/components/goal-group-dashboard.test.tsx+++ /dev/null@@ -1,73 +0,0 @@-// @vitest-environment jsdom-import { describe, expect, it } from "vitest";-import { render, screen, within } from "@testing-library/react";-import { GoalGroupDashboard, type GoalGroupDashboardGoal } from "./goal-group-dashboard";--function goal(overrides: Partial<GoalGroupDashboardGoal>): GoalGroupDashboardGoal {- return {- id: "g1",- href: "/project/goals/goal-1",- label: "Google Ads errors <2%",- statement: "Keep errors low",- status: "active",- status_reason: null,- metric_name: "Authenticated tool-call error rate",- current_value: 1.77,- target_value: 2,- metric_direction: "decrease",- cadence_cron: "0 * * * *",- last_tick_at: "2026-07-17T20:00:00.000Z",- next_tick_at: "2026-07-17T22:00:00.000Z",- tick_count: 5,- snapshots: [2.4, 1.9, 1.77],- ...overrides,- };-}--describe("GoalGroupDashboard", () => {- it("shows every member metric with its own target and health", () => {- render(- <GoalGroupDashboard- name="Ads MCP reliability"- description="Keep ads connections healthy."- allGoalsHref="/project/goals"- goals={[- goal({ id: "google" }),- goal({- id: "meta",- href: "/project/goals/goal-2",- label: "Meta MCP errors <5%",- current_value: 29.75,- target_value: 5,- snapshots: [8, 12, 29.75],- }),- ]}- activity={[]}- />,- );-- expect(screen.getByText("1 healthy")).toBeTruthy();- expect(screen.getByText("1 needs attention")).toBeTruthy();- const google = screen.getByRole("link", { name: /Google Ads errors/ });- const meta = screen.getByRole("link", { name: /Meta MCP errors/ });- expect(within(google).getByText("1.77")).toBeTruthy();- expect(within(google).getByText("≤ 2")).toBeTruthy();- expect(within(meta).getByText("29.75")).toBeTruthy();- expect(within(meta).getByText("≤ 5")).toBeTruthy();- });-- it("provides an actionable empty state", () => {- render(- <GoalGroupDashboard- name="Empty"- description=""- allGoalsHref="/project/goals"- goals={[]}- activity={[]}- actions={<button>Manage group</button>}- />,- );- expect(screen.getByText("This group is ready for goals.")).toBeTruthy();- expect(screen.getByRole("button", { name: "Manage group" })).toBeTruthy();- });-});diff --git a/notfair/src/components/goal-group-dashboard.tsx b/notfair/src/components/goal-group-dashboard.tsxdeleted file mode 100644index c034bf2a..00000000--- a/notfair/src/components/goal-group-dashboard.tsx+++ /dev/null@@ -1,271 +0,0 @@-import Link from "next/link";-import { Activity, ArrowLeft, Clock3 } from "lucide-react";-import { GoalSparkline } from "@/components/goal-sparkline";-import { formatMetric } from "@/lib/format-metric";-import { goalGroupHealth, countGoalGroupHealth } from "@/lib/goal-group-health";-import { cadenceLabel } from "@/lib/goal-cadence";-import { timeAgo, timeUntil } from "@/lib/time-ago";-import { cn } from "@/lib/utils";-import { type GoalStatus, type GoalTickStatus, type MetricDirection } from "@/server/db/goals";-import { type ReactNode } from "react";--export type GoalGroupDashboardGoal = {- id: string;- href: string;- label: string;- statement: string;- status: GoalStatus;- status_reason: string | null;- metric_name: string | null;- current_value: number | null;- target_value: number | null;- metric_direction: MetricDirection | null;- cadence_cron: string;- last_tick_at: string | null;- next_tick_at: string | null;- tick_count: number;- snapshots: number[];-};--export type GoalGroupActivity = {- id: string;- goal_id: string;- goal_href: string;- goal_label: string;- tick_number: number;- status: GoalTickStatus;- metric_value: number | null;- metric_error: string | null;- summary: string | null;- started_at: string;-};--const HEALTH_COPY = {- healthy: { label: "healthy", dot: "ns-dot-live", text: "text-[hsl(var(--notfair-accent))]" },- attention: { label: "needs attention", dot: "ns-dot-err", text: "text-[hsl(var(--destructive))]" },- waiting: { label: "waiting for data", dot: "ns-dot-warn", text: "text-[hsl(var(--notfair-warn))]" },- paused: { label: "paused", dot: "ns-dot-mute", text: "text-[hsl(var(--notfair-ink-4))]" },- closed: { label: "closed", dot: "ns-dot-mute", text: "text-[hsl(var(--notfair-ink-4))]" },-} as const;--function latestIso(values: Array<string | null>): string | null {- return values.filter((value): value is string => Boolean(value)).sort().at(-1) ?? null;-}--function earliestIso(values: Array<string | null>): string | null {- return values.filter((value): value is string => Boolean(value)).sort().at(0) ?? null;-}--function plainSummary(value: string): string {- return value- .replace(/\*\*([^*]+)\*\*/g, "$1")- .replace(/`([^`]+)`/g, "$1")- .replace(/\s+/g, " ")- .trim();-}--export function GoalGroupDashboard({- name,- description,- allGoalsHref,- goals,- activity,- actions,-}: {- name: string;- description: string;- allGoalsHref: string;- goals: GoalGroupDashboardGoal[];- activity: GoalGroupActivity[];- actions?: ReactNode;-}) {- const counts = countGoalGroupHealth(goals);- const latestCheck = latestIso(goals.map((goal) => goal.last_tick_at));- const nextCheck = earliestIso(goals.map((goal) => goal.next_tick_at));-- return (- <div className="ns-app-wide">- <Link- href={allGoalsHref}- className="mb-5 inline-flex items-center gap-1.5 text-[12.5px] text-[hsl(var(--notfair-ink-4))] hover:text-[hsl(var(--notfair-ink-2))]"- >- <ArrowLeft className="size-3.5" />- All goals- </Link>- <header className="ns-page-head">- <div className="ns-page-head-stack">- <div className="mb-2 flex flex-wrap items-center gap-2">- <span className="ns-tag-mono">goal group</span>- <span className="text-[11px] tabular-nums text-[hsl(var(--notfair-ink-4))]">- {goals.length} goal{goals.length === 1 ? "" : "s"}- </span>- </div>- <h1 className="ns-page-title">{name}</h1>- <p className="ns-page-sub">{description || "A shared dashboard for related goals."}</p>- </div>- <div className="ns-page-actions">{actions}</div>- </header>-- {goals.length === 0 ? (- <div className="ns-empty">- <p className="ns-empty-title">This group is ready for goals.</p>- <p className="ns-empty-sub">- Use Manage group to add existing goals. Their schedules and history stay unchanged.- </p>- </div>- ) : (- <>- <section- aria-label="Group health summary"- className="mb-7 flex flex-wrap items-center gap-x-5 gap-y-2 rounded-xl bg-[hsl(var(--notfair-surface-2)/0.5)] px-4 py-3 text-[12px]"- >- {counts.healthy > 0 && (- <span className="flex items-center gap-1.5 text-[hsl(var(--notfair-accent))]">- <span className="ns-dot ns-dot-live" aria-hidden />- {counts.healthy} healthy- </span>- )}- {counts.attention > 0 && (- <span className="flex items-center gap-1.5 text-[hsl(var(--destructive))]">- <span className="ns-dot ns-dot-err" aria-hidden />- {counts.attention} need{counts.attention === 1 ? "s" : ""} attention- </span>- )}- {counts.waiting > 0 && <span className="text-[hsl(var(--notfair-ink-4))]">{counts.waiting} waiting for data</span>}- {counts.paused > 0 && <span className="text-[hsl(var(--notfair-ink-4))]">{counts.paused} paused</span>}- <span className="ml-auto flex items-center gap-1.5 font-mono text-[10.5px] text-[hsl(var(--notfair-ink-4))]">- <Clock3 className="size-3" />- {latestCheck ? `last check ${timeAgo(latestCheck)}` : "no checks yet"}- {nextCheck ? ` · next ${timeUntil(nextCheck)}` : ""}- </span>- </section>-- <section aria-labelledby="group-metrics-heading">- <h2 id="group-metrics-heading" className="ns-h2">- <span>Metrics</span>- <span className="ns-h2-meta">Each goal keeps its own threshold</span>- </h2>- <ol className="ns-group">- {goals.map((goal) => {- const health = goalGroupHealth(goal);- const healthCopy = HEALTH_COPY[health];- const comparator = goal.metric_direction === "decrease" ? "≤" : "≥";- return (- <li key={goal.id}>- <Link- href={goal.href}- className="grid min-h-[116px] grid-cols-1 items-center gap-4 px-4 py-4 transition-colors hover:bg-[hsl(var(--notfair-hover))] sm:grid-cols-[minmax(0,1.25fr)_150px_180px_auto]"- >- <span className="min-w-0">- <span className="mb-1 flex items-center gap-2">- <span className={cn("ns-dot", healthCopy.dot)} aria-hidden />- <span className="truncate text-[13.5px] font-medium">{goal.label}</span>- </span>- <span className="block truncate text-[11.5px] text-[hsl(var(--notfair-ink-4))]">- {goal.metric_name ?? "Metric is still being defined"}- </span>- <span className="mt-2 block font-mono text-[10.5px] text-[hsl(var(--notfair-ink-4))]">- {cadenceLabel(goal.cadence_cron)} · {goal.tick_count} check{goal.tick_count === 1 ? "" : "s"}- </span>- </span>-- <span>- <span className="block font-mono text-[10px] uppercase tracking-[0.06em] text-[hsl(var(--notfair-ink-4))]">- current / target- </span>- <span className="mt-1 block text-[20px] font-semibold tabular-nums tracking-[-0.02em]">- {formatMetric(goal.current_value)}- <span className="ml-1.5 text-[12px] font-normal text-[hsl(var(--notfair-ink-4))]">- {goal.target_value === null ? "no target" : `${comparator} ${formatMetric(goal.target_value)}`}- </span>- </span>- </span>-- <span className="hidden sm:block" aria-label={`${goal.label} metric history`}>- {goal.snapshots.length >= 2 ? (- <GoalSparkline- values={goal.snapshots}- target={goal.target_value}- direction={goal.metric_direction}- width={180}- height={44}- />- ) : (- <span className="text-[11px] text-[hsl(var(--notfair-ink-4))]">- History appears after 2 readings- </span>- )}- </span>-- <span className={cn("justify-self-start whitespace-nowrap text-[11.5px] sm:justify-self-end", healthCopy.text)}>- {healthCopy.label} <span className="ml-1 text-[hsl(var(--notfair-ink-4))]">›</span>- </span>- </Link>- </li>- );- })}- </ol>- </section>-- <section aria-labelledby="group-activity-heading">- <h2 id="group-activity-heading" className="ns-h2">- <span>Recent checks</span>- <span className="ns-h2-meta">Across this group</span>- </h2>- {activity.length === 0 ? (- <div className="rounded-xl bg-[hsl(var(--notfair-surface-2)/0.45)] px-4 py-5 text-[12.5px] text-[hsl(var(--notfair-ink-4))]">- No checks yet. Activity appears here when a member goal runs its heartbeat.- </div>- ) : (- <ol className="ns-group">- {activity.map((item) => {- const failed = item.status === "failed" || Boolean(item.metric_error);- const running = item.status === "running";- return (- <li key={item.id}>- <Link href={item.goal_href} className="ns-row-button">- <span className="ns-glyph" aria-hidden>- <Activity className="size-4" />- </span>- <span className="ns-row-body min-w-0">- <span className="ns-row-title-row">- <span className="ns-row-title">{item.goal_label}</span>- <span className="ns-tag-mono">check {item.tick_number}</span>- </span>- <span className="ns-row-desc block truncate">- {plainSummary(item.metric_error || item.summary || (running ? "Check is running…" : "Metric recorded"))}- </span>- </span>- <span className="ml-auto flex shrink-0 items-center gap-3 text-[11px]">- {item.metric_value !== null && (- <span className="font-mono tabular-nums text-[hsl(var(--notfair-ink-3))]">- {formatMetric(item.metric_value)}- </span>- )}- <span- className={cn(- "flex items-center gap-1.5",- failed- ? "text-[hsl(var(--destructive))]"- : running- ? "text-[hsl(var(--notfair-warn))]"- : "text-[hsl(var(--notfair-accent))]",- )}- >- <span className={cn("ns-dot", failed ? "ns-dot-err" : running ? "ns-dot-warn" : "ns-dot-live")} aria-hidden />- {running ? "running" : failed ? "failed" : "done"}- </span>- <span className="font-mono text-[hsl(var(--notfair-ink-4))]">{timeAgo(item.started_at)}</span>- </span>- </Link>- </li>- );- })}- </ol>- )}- </section>- </>- )}- </div>- );-}diff --git a/notfair/src/components/goal-group-editor.tsx b/notfair/src/components/goal-group-editor.tsxdeleted file mode 100644index 9ed4b69e..00000000--- a/notfair/src/components/goal-group-editor.tsx+++ /dev/null@@ -1,244 +0,0 @@-"use client";--import { useState, useTransition } from "react";-import { useRouter } from "next/navigation";-import { FolderPlus, Settings2, Trash2 } from "lucide-react";-import { toast } from "sonner";-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,- DialogTrigger,-} from "@/components/ui/dialog";-import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import {- createGoalGroupAction,- deleteGoalGroupAction,- saveGoalGroupAction,-} from "@/server/actions/goal-groups";-import { projectHref } from "@/lib/project-href";--export type GoalGroupEditorGoal = {- id: string;- label: string;- status: string;- current_group_id: string | null;- current_group_name: string | null;-};--export function GoalGroupEditor({- projectSlug,- goals,- group,- trigger,-}: {- projectSlug: string;- goals: GoalGroupEditorGoal[];- group?: { id: string; name: string; description: string };- /** Custom dialog trigger — defaults to the page-header button. */- trigger?: React.ReactNode;-}) {- const router = useRouter();- const editing = Boolean(group);- const initialSelected = goals- .filter((goal) => goal.current_group_id === group?.id)- .map((goal) => goal.id);- const [open, setOpen] = useState(false);- const [confirmDelete, setConfirmDelete] = useState(false);- const [name, setName] = useState(group?.name ?? "");- const [description, setDescription] = useState(group?.description ?? "");- const [selected, setSelected] = useState<Set<string>>(() => new Set(initialSelected));- const [pending, startTransition] = useTransition();-- function reset() {- setName(group?.name ?? "");- setDescription(group?.description ?? "");- setSelected(new Set(initialSelected));- setConfirmDelete(false);- }-- function toggle(goalId: string) {- setSelected((current) => {- const next = new Set(current);- if (next.has(goalId)) next.delete(goalId);- else next.add(goalId);- return next;- });- }-- function submit() {- startTransition(async () => {- const result = group- ? await saveGoalGroupAction({- group_id: group.id,- name,- description,- goal_ids: [...selected],- })- : await createGoalGroupAction({- project_slug: projectSlug,- name,- description,- goal_ids: [...selected],- });- if (!result.ok || !result.group_id) {- toast.error(result.error ?? "Could not save the group.");- return;- }- toast.success(group ? "Group updated." : "Group created.");- setOpen(false);- router.push(projectHref(projectSlug, `/groups/${result.group_id}`));- router.refresh();- });- }-- function remove() {- if (!group) return;- startTransition(async () => {- const result = await deleteGoalGroupAction(group.id);- if (!result.ok) {- toast.error(result.error ?? "Could not delete the group.");- return;- }- toast.success("Group deleted. Its goals are now ungrouped.");- setOpen(false);- router.push(projectHref(projectSlug, "/goals"));- router.refresh();- });- }-- return (- <Dialog- open={open}- onOpenChange={(next) => {- setOpen(next);- if (next) reset();- }}- >- <DialogTrigger asChild>- {trigger ?? (- <button type="button" className={editing ? "ns-btn ns-btn-ghost" : "ns-btn ns-btn-primary"}>- {editing ? <Settings2 className="size-3.5" /> : <FolderPlus className="size-3.5" />}- {editing ? "Manage group" : "New group"}- </button>- )}- </DialogTrigger>- <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-xl">- <DialogHeader>- <DialogTitle>{editing ? "Manage goal group" : "Create a goal group"}</DialogTitle>- <DialogDescription>- A group is one dashboard for related goals. Moving a goal here removes it from- its previous group, but never changes its heartbeat or history.- </DialogDescription>- </DialogHeader>-- <form- onSubmit={(event) => {- event.preventDefault();- submit();- }}- className="space-y-5"- >- <div className="space-y-2">- <label htmlFor="goal-group-name" className="text-[12.5px] font-medium">- Name- </label>- <Input- id="goal-group-name"- value={name}- onChange={(event) => setName(event.target.value)}- placeholder="Ads MCP reliability"- maxLength={80}- autoFocus- />- </div>- <div className="space-y-2">- <label htmlFor="goal-group-description" className="text-[12.5px] font-medium">- Description <span className="font-normal text-[hsl(var(--notfair-ink-4))]">optional</span>- </label>- <textarea- id="goal-group-description"- value={description}- onChange={(event) => setDescription(event.target.value)}- placeholder="Keep every paid-ads MCP connection reliable."- maxLength={240}- rows={3}- className="w-full resize-none rounded-md border border-transparent bg-[hsl(var(--notfair-surface-2))] px-3 py-2 text-sm outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50"- />- </div>-- <fieldset>- <legend className="mb-2 text-[12.5px] font-medium">- Goals <span className="font-normal tabular-nums text-[hsl(var(--notfair-ink-4))]">{selected.size} selected</span>- </legend>- {goals.length === 0 ? (- <p className="m-0 rounded-xl bg-[hsl(var(--notfair-surface-2)/0.55)] p-4 text-[12.5px] text-[hsl(var(--notfair-ink-4))]">- No goals yet. You can create the empty group now and add goals later.- </p>- ) : (- <div className="flex max-h-72 flex-col gap-2 overflow-y-auto pr-1">- {goals.map((goal) => {- const moving =- selected.has(goal.id) &&- goal.current_group_id !== null &&- goal.current_group_id !== group?.id;- return (- <label- key={goal.id}- className="flex cursor-pointer items-start gap-3 rounded-xl bg-[hsl(var(--notfair-surface-2)/0.55)] px-3 py-2.5 transition-colors hover:bg-[hsl(var(--notfair-surface-2))]"- >- <input- type="checkbox"- checked={selected.has(goal.id)}- onChange={() => toggle(goal.id)}- className="mt-0.5 size-4 accent-[hsl(var(--notfair-ink))]"- />- <span className="min-w-0 flex-1">- <span className="block truncate text-[13px] font-medium">{goal.label}</span>- <span className="block text-[11px] text-[hsl(var(--notfair-ink-4))]">- {moving ? `Moves from ${goal.current_group_name}` : goal.status}- </span>- </span>- </label>- );- })}- </div>- )}- </fieldset>-- <DialogFooter className="items-center sm:justify-between">- {editing ? (- confirmDelete ? (- <div className="flex items-center gap-2">- <span className="text-[11.5px] text-[hsl(var(--notfair-ink-4))]">Goals will become ungrouped.</span>- <Button type="button" size="sm" variant="destructive" onClick={remove} disabled={pending}>- Delete group- </Button>- </div>- ) : (- <Button type="button" size="sm" variant="ghost" onClick={() => setConfirmDelete(true)} disabled={pending}>- <Trash2 className="size-3.5" />- Delete- </Button>- )- ) : (- <span />- )}- <div className="flex gap-2">- <Button type="button" variant="outline" onClick={() => setOpen(false)} disabled={pending}>- Cancel- </Button>- <Button type="submit" disabled={pending || !name.trim()}>- {pending ? "Saving…" : editing ? "Save group" : "Create group"}- </Button>- </div>- </DialogFooter>- </form>- </DialogContent>- </Dialog>- );-}diff --git a/notfair/src/components/goal-memory-dialog.tsx b/notfair/src/components/goal-memory-dialog.tsxdeleted file mode 100644index 072d69c2..00000000--- a/notfair/src/components/goal-memory-dialog.tsx+++ /dev/null@@ -1,91 +0,0 @@-"use client";--import { useState } from "react";-import { Brain } from "lucide-react";-import {- Dialog,- DialogContent,- DialogDescription,- DialogHeader,- DialogTitle,- DialogTrigger,-} from "@/components/ui/dialog";-import { cn } from "@/lib/utils";-import { Markdown } from "@/components/markdown";--export type MemoryEntry = {- id: string;- body: string;- confidence: "low" | "medium" | "high";- created_at: string;-};--const CONFIDENCE_STYLE: Record<MemoryEntry["confidence"], string> = {- high: "text-[hsl(var(--notfair-accent))]",- medium: "text-[hsl(var(--notfair-ink-3))]",- low: "text-[hsl(var(--notfair-ink-4))]",-};--function fmtDate(iso: string): string {- return new Date(iso).toLocaleDateString(undefined, {- month: "short",- day: "numeric",- });-}--/**- * The goal's memory, one click from the header: everything the agent has- * learned about this goal (the `log_learning` ledger), newest first, with- * confidence and date. Lives in the header so it's reachable without- * scrolling the rail, and scales past the handful a rail section could fit.- */-export function GoalMemoryDialog({ entries }: { entries: MemoryEntry[] }) {- const [open, setOpen] = useState(false);- if (entries.length === 0) return null;-- return (- <Dialog open={open} onOpenChange={setOpen}>- <DialogTrigger asChild>- <button- type="button"- className="ns-chip"- title="What the agent has learned about this goal"- >- <Brain className="size-3.5" aria-hidden />- Memory- <span className="tabular-nums text-[hsl(var(--notfair-ink-4))]">- {entries.length}- </span>- </button>- </DialogTrigger>- <DialogContent className="max-h-[70vh] overflow-y-auto sm:max-w-lg">- <DialogHeader>- <DialogTitle className="flex items-center gap-2 text-[15px]">- <Brain className="size-4" aria-hidden />- Memory- </DialogTitle>- <DialogDescription>- What the agent has learned working this goal — it reads these- before every check.- </DialogDescription>- </DialogHeader>- <ul className="m-0 flex list-none flex-col gap-3 p-0">- {entries.map((l) => (- <li- key={l.id}- className="rounded-md bg-[hsl(var(--notfair-surface-2)/0.5)] px-3 py-2.5 text-[13px] leading-snug"- >- <Markdown className="text-[13px] text-[hsl(var(--notfair-ink-2))]">{l.body}</Markdown>- <p className="m-0 mt-1 text-[11px] text-[hsl(var(--notfair-ink-4))]">- <span className={cn("font-medium", CONFIDENCE_STYLE[l.confidence])}>- {l.confidence} confidence- </span>{" "}- · {fmtDate(l.created_at)}- </p>- </li>- ))}- </ul>- </DialogContent>- </Dialog>- );-}diff --git a/notfair/src/components/goal-metric-card.tsx b/notfair/src/components/goal-metric-card.tsxdeleted file mode 100644index 18c9cc01..00000000--- a/notfair/src/components/goal-metric-card.tsx+++ /dev/null@@ -1,126 +0,0 @@-"use client";--import { useState } from "react";-import { GoalProgressChart, type ChartAction, type ChartFailure, type ChartPoint } from "@/components/goal-progress-chart";-import { MetricMethodDialog } from "@/components/metric-method-dialog";-import { formatMetric } from "@/lib/format-metric";-import { cn } from "@/lib/utils";--export type MetricVariant = {- key: string;- /** Switcher label, e.g. "1h", "24h", "7d". */- label: string;- name: string;- current: number | null;- baseline: number | null;- /** Only the goal's own window has a target; context windows pass null. */- target: number | null;- direction: "increase" | "decrease" | null;- sourceKey: string | null;- sourceTool: string | null;- argsJson: string | null;- points: ChartPoint[];-};--/**- * The metric hero with a time-window switcher. One metric, one card:- * the goal's scoring window plus its context windows (24h, 7d) flip in- * place instead of stacking as separate "supporting metrics". The first- * variant is the goal's own — it carries the target line and is what- * checks are scored against; the switcher resets to it per page load.- * Badges, the checks strip, and the cadence footer describe the LOOP,- * not the window, so they render unchanged whichever window shows.- */-export function GoalMetricCard({- variants,- mode,- badges,- strip,- footer,- actions,- failures,- deadline,-}: {- variants: MetricVariant[];- mode: "achieve" | "maintain";- badges?: React.ReactNode;- strip?: React.ReactNode;- footer?: React.ReactNode;- actions: ChartAction[];- failures: ChartFailure[];- deadline: number | null;-}) {- const [key, setKey] = useState(variants[0]!.key);- const active = variants.find((v) => v.key === key) ?? variants[0]!;-- return (- <div className="ns-card p-3.5">- <div className="mb-1 flex items-center justify-between gap-2">- <span className="flex min-w-0 items-center gap-1.5 text-[11px] text-[hsl(var(--notfair-ink-4))]">- <span className="truncate">{active.name}</span>- <MetricMethodDialog- name={active.name}- sourceKey={active.sourceKey}- sourceTool={active.sourceTool}- argsJson={active.argsJson}- direction={active.direction}- />- </span>- <span className="flex shrink-0 items-center gap-2">- {badges}- {variants.length > 1 && (- <span- role="tablist"- aria-label="Metric time window"- className="flex gap-0.5 rounded-md bg-[hsl(var(--notfair-surface-2))] p-0.5"- >- {variants.map((v) => (- <button- key={v.key}- type="button"- role="tab"- aria-selected={v.key === active.key}- className={cn(- "rounded-[5px] px-2 py-0.5 text-[11px] tabular-nums transition-colors",- v.key === active.key- ? "bg-[hsl(var(--card))] font-medium text-[hsl(var(--notfair-ink))] shadow-sm"- : "text-[hsl(var(--notfair-ink-4))] hover:text-[hsl(var(--notfair-ink-2))]",- )}- onClick={() => setKey(v.key)}- >- {v.label}- </button>- ))}- </span>- )}- </span>- </div>-- <div className="flex items-baseline gap-3">- <span className="text-2xl font-semibold tabular-nums">- {formatMetric(active.current)}- </span>- <span className="text-[11.5px] tabular-nums text-[hsl(var(--notfair-ink-4))]">- {active.target !== null &&- `target ${formatMetric(active.target)}${mode === "maintain" ? " (hold)" : ""} · `}- baseline {formatMetric(active.baseline)}- </span>- </div>-- {strip}-- <div className="mt-3">- <GoalProgressChart- points={active.points}- actions={actions}- failures={failures}- target={active.target}- baseline={active.baseline}- deadline={deadline}- />- </div>-- {footer}- </div>- );-}diff --git a/notfair/src/components/goal-moves-dialog.tsx b/notfair/src/components/goal-moves-dialog.tsxdeleted file mode 100644index f86b72c8..00000000--- a/notfair/src/components/goal-moves-dialog.tsx+++ /dev/null@@ -1,61 +0,0 @@-"use client";--import { useState } from "react";-import { Activity } from "lucide-react";-import {- Dialog,- DialogContent,- DialogDescription,- DialogHeader,- DialogTitle,- DialogTrigger,-} from "@/components/ui/dialog";-import { GoalMoves, type MoveRow } from "@/components/goal-moves";--/**- * The goal's moves journal, one click from the header. Everything inside- * is work the agent ALREADY did — the framing exists to kill the- * "is this a to-do list?" misread. Hidden while there are no open moves.- */-export function GoalMovesDialog({- moves,- nextCheckAt,-}: {- moves: MoveRow[];- nextCheckAt: string | null;-}) {- const [open, setOpen] = useState(false);- if (moves.length === 0) return null;-- return (- <Dialog open={open} onOpenChange={setOpen}>- <DialogTrigger asChild>- <button- type="button"- className="ns-chip"- title="Moves the agent has made that aren't scored yet"- >- <Activity className="size-3.5" aria-hidden />- Moves- <span className="tabular-nums text-[hsl(var(--notfair-ink-4))]">- {moves.length}- </span>- </button>- </DialogTrigger>- <DialogContent className="max-h-[75vh] overflow-y-auto sm:max-w-xl">- <DialogHeader>- <DialogTitle className="flex items-center gap-2 text-[15px]">- <Activity className="size-4" aria-hidden />- Moves- </DialogTitle>- <DialogDescription>- Nothing here is a to-do — every move is already done, logged the- moment the agent acted. A move’s effect is observed for a- while, then its outcome gets scored at a later check.- </DialogDescription>- </DialogHeader>- <GoalMoves moves={moves} nextCheckAt={nextCheckAt} />- </DialogContent>- </Dialog>- );-}diff --git a/notfair/src/components/goal-moves.test.tsx b/notfair/src/components/goal-moves.test.tsxdeleted file mode 100644index b58b7a67..00000000--- a/notfair/src/components/goal-moves.test.tsx+++ /dev/null@@ -1,96 +0,0 @@-// @vitest-environment jsdom-import { describe, expect, it, vi } from "vitest";-import { fireEvent, render, screen } from "@testing-library/react";-import { GoalMoves, parseResourceLabel, type MoveRow } from "./goal-moves";--// Mock at the server-action / router boundaries, per repo test conventions.-const releaseLock = vi.hoisted(() => vi.fn(async () => ({ ok: true })));-vi.mock("@/server/actions/goals", () => ({ releaseLockAction: releaseLock }));-vi.mock("next/navigation", () => ({ useRouter: () => ({ refresh: vi.fn() }) }));--function move(overrides: Partial<MoveRow>): MoveRow {- return {- action_id: "a1",- kind: "mutation",- description: "Open one listing PR to acme/awesome-list.",- resources: ["github:acme/awesome-list"],- made_at: new Date(Date.now() - 3600_000).toISOString(),- observe_until: new Date(Date.now() + 3 * 3600_000).toISOString(),- ...overrides,- };-}--describe("parseResourceLabel", () => {- it("splits scope, name, and humanizes the fragment", () => {- expect(parseResourceLabel("local:gh_leads.db#the-nine-blank-pr_url-rows")).toEqual({- scope: "local",- name: "gh_leads.db",- detail: "the nine blank pr_url rows",- href: null,- });- });-- it("links github owner/repo resources", () => {- expect(parseResourceLabel("github:acme/awesome-list").href).toBe(- "https://github.com/acme/awesome-list",- );- });-- it("keeps multi-colon names and unscoped labels intact", () => {- expect(parseResourceLabel("xads:campaign:ol2b7").name).toBe("campaign:ol2b7");- expect(parseResourceLabel("just-a-label").scope).toBeNull();- });-});--describe("GoalMoves", () => {- it("frames an observing move as done, with resources and the window end", () => {- render(<GoalMoves moves={[move({})]} nextCheckAt={null} />);- expect(screen.getByText(/Done — observing the effect/)).toBeInTheDocument();- expect(screen.getByText("✓ done")).toBeInTheDocument();- expect(screen.getByText(/made 1h ago/)).toBeInTheDocument();- expect(- screen.getByRole("link", { name: "acme/awesome-list" }).getAttribute("href"),- ).toBe("https://github.com/acme/awesome-list");- expect(screen.getByText(/observation ends in 3h ·/)).toBeInTheDocument();- expect(screen.getByRole("progressbar")).toBeInTheDocument();- });-- it("queues an expired-window move for the next check", () => {- render(- <GoalMoves- moves={[move({ observe_until: new Date(Date.now() - 60_000).toISOString() })]}- nextCheckAt="2026-07-17T16:00:00.000Z"- />,- );- expect(screen.getByText(/Done — outcome check queued/)).toBeInTheDocument();- expect(- screen.getByText(/records what actually happened at its next check ·/),- ).toBeInTheDocument();- // No unlock button once the window is over.- expect(screen.queryByRole("button", { name: /unlock/i })).toBeNull();- });-- it("shows windowless research as a note, not a done-badge", () => {- render(- <GoalMoves- moves={[move({ kind: "research", observe_until: null, resources: [] })]}- nextCheckAt={null}- />,- );- expect(screen.getByText(/Notes & decisions/)).toBeInTheDocument();- expect(screen.getByText("research")).toBeInTheDocument();- expect(screen.queryByText("✓ done")).toBeNull();- });-- it("shows the full description untruncated", () => {- const long = "A".repeat(400);- render(<GoalMoves moves={[move({ description: long })]} nextCheckAt={null} />);- expect(screen.getByText(long)).toBeInTheDocument();- });-- it("unlocks an observing move via the server action", () => {- render(<GoalMoves moves={[move({ action_id: "a9" })]} nextCheckAt={null} />);- fireEvent.click(screen.getByRole("button", { name: /unlock/i }));- expect(releaseLock).toHaveBeenCalledWith("a9");- });-});diff --git a/notfair/src/components/goal-moves.tsx b/notfair/src/components/goal-moves.tsxdeleted file mode 100644index 8dbc2266..00000000--- a/notfair/src/components/goal-moves.tsx+++ /dev/null@@ -1,293 +0,0 @@-"use client";--import { useTransition } from "react";-import { useRouter } from "next/navigation";-import { toast } from "sonner";-import { LockOpen } from "lucide-react";-import { releaseLockAction } from "@/server/actions/goals";-import { timeAgo, timeUntil } from "@/lib/time-ago";--/**- * The goal's MOVES — work the agent has already done, shown as a journal,- * never as a to-do list. The agent logs each move the moment it acts;- * the move then sits in an observation window while its effect matures- * ("observing"), and once the window ends the outcome gets scored at the- * next check ("outcome check queued"). Research notes and decisions have- * no window at all.- *- * The stage chip leads every card so the agent's imperative descriptions- * ("Open one listing PR to …") read as titles of finished work.- */--export type MoveRow = {- action_id: string;- kind: "mutation" | "research" | "decision";- /** What the agent did — its own words, logged as it acted. */- description: string;- /** Parsed resources_touched_json — locked while observing. */- resources: string[];- /** ISO time the move was made (and logged). */- made_at: string;- /** ISO end of the observation window; null = no window (notes). */- observe_until: string | null;-};--export type MoveStage = "observing" | "outcome-due" | "note";--export function moveStage(move: MoveRow, now = Date.now()): MoveStage {- if (!move.observe_until) return "note";- return Date.parse(move.observe_until) > now ? "observing" : "outcome-due";-}--export type ParsedResource = {- /** Label prefix (`local`, `github`, `xads`, `page`, …); null if none. */- scope: string | null;- /** The thing itself: a file, an `owner/repo`, a campaign id, a path. */- name: string;- /** Humanized `#fragment` — the subset of the resource actually locked. */- detail: string | null;- /** Outbound link when the name is unambiguous (GitHub repos). */- href: string | null;-};--export function parseResourceLabel(raw: string): ParsedResource {- const m = raw.match(/^([a-z][\w-]*):(.+)$/i);- const scope = m ? m[1]! : null;- let name = m ? m[2]! : raw;- let detail: string | null = null;- const hash = name.indexOf("#");- if (hash > 0) {- // Fragments are kebab-case notes ("the-nine-blank-pr_url-rows…") —- // dashes become spaces; underscores stay (they're inside identifiers).- detail = name- .slice(hash + 1)- .replace(/-+/g, " ")- .trim();- name = name.slice(0, hash);- }- const href =- scope === "github" && /^[\w.-]+\/[\w.-]+$/.test(name)- ? `https://github.com/${name}`- : null;- return { scope, name, detail, href };-}--function fmtWhen(iso: string): string {- return new Date(iso).toLocaleString(undefined, {- month: "short",- day: "numeric",- hour: "numeric",- minute: "2-digit",- });-}--/** Elapsed share of the observation window, 0..1. */-function windowProgress(made_at: string, observe_until: string, now = Date.now()): number {- const start = Date.parse(made_at);- const end = Date.parse(observe_until);- if (!(end > start)) return 1;- return Math.min(1, Math.max(0, (now - start) / (end - start)));-}--const SECTION: Record<MoveStage, { title: string; blurb: string }> = {- observing: {- title: "Done — observing the effect",- blurb:- "The move is made; its resources stay untouched until the window ends so the effect can be measured cleanly.",- },- "outcome-due": {- title: "Done — outcome check queued",- blurb: "The window is over; the agent scores what actually happened at its next check.",- },- note: {- title: "Notes & decisions",- blurb: "Research and decisions the agent recorded — no observation window.",- },-};--export function GoalMoves({- moves,- nextCheckAt,-}: {- moves: MoveRow[];- /** ISO time of the next scheduled check, for the outcome-due hint. */- nextCheckAt: string | null;-}) {- const router = useRouter();- const [pending, startTransition] = useTransition();-- function unlock(action_id: string) {- startTransition(async () => {- const r = await releaseLockAction(action_id);- if (!r.ok) {- toast.error(r.error ?? "Could not unlock.");- return;- }- toast.success("Unlocked — the outcome check is now queued for the next check.");- router.refresh();- });- }-- const groups: Array<{ stage: MoveStage; items: MoveRow[] }> = [- {- stage: "observing",- items: moves- .filter((m) => moveStage(m) === "observing")- .sort((a, b) => a.observe_until!.localeCompare(b.observe_until!)),- },- {- stage: "outcome-due",- items: moves- .filter((m) => moveStage(m) === "outcome-due")- .sort((a, b) => a.made_at.localeCompare(b.made_at)),- },- {- stage: "note",- items: moves- .filter((m) => moveStage(m) === "note")- .sort((a, b) => b.made_at.localeCompare(a.made_at)),- },- ];-- return (- <div className="flex flex-col gap-5">- {groups- .filter((g) => g.items.length > 0)- .map((g) => (- <section key={g.stage} aria-label={SECTION[g.stage].title}>- <h3 className="m-0 text-[11px] font-semibold tracking-[0.08em] uppercase text-[hsl(var(--notfair-ink-3))]">- {SECTION[g.stage].title}- <span className="ml-1 font-normal tabular-nums">({g.items.length})</span>- </h3>- <p className="m-0 mt-0.5 mb-2 text-[11.5px] leading-snug text-[hsl(var(--notfair-ink-4))]">- {SECTION[g.stage].blurb}- </p>- <ul className="m-0 flex list-none flex-col gap-2.5 p-0">- {g.items.map((move) => (- <MoveCard- key={move.action_id}- move={move}- nextCheckAt={nextCheckAt}- pending={pending}- onUnlock={unlock}- />- ))}- </ul>- </section>- ))}- </div>- );-}--function MoveCard({- move,- nextCheckAt,- pending,- onUnlock,-}: {- move: MoveRow;- nextCheckAt: string | null;- pending: boolean;- onUnlock: (action_id: string) => void;-}) {- const stage = moveStage(move);- return (- <li className="rounded-xl bg-[hsl(var(--notfair-surface-2)/0.5)] px-4 py-3.5">- <div className="flex items-center justify-between gap-3">- <span className="text-[11px] text-[hsl(var(--notfair-ink-4))]">- {stage === "note" ? (- <span className="ns-tag-mono mr-1.5">{move.kind}</span>- ) : (- <span className="ns-tag mr-1.5">✓ done</span>- )}- made {timeAgo(move.made_at)}- </span>- {stage === "observing" && (- <button- type="button"- disabled={pending}- onClick={() => onUnlock(move.action_id)}- className="ns-btn ns-btn-outline ns-btn-sm shrink-0"- title="End the observation window now — the outcome check moves to the next check"- >- <LockOpen className="size-3" aria-hidden />- Unlock- </button>- )}- </div>-- {/* The move itself — the agent's own record, in full. */}- <p className="m-0 mt-2 text-[12.5px] leading-relaxed text-[hsl(var(--notfair-ink-2))]">- {move.description}- </p>-- {stage === "observing" && (- <>- {move.resources.length > 0 && (- <ul className="m-0 mt-2.5 flex list-none flex-col gap-1 p-0">- {move.resources.map((raw) => {- const r = parseResourceLabel(raw);- return (- <li key={raw} className="text-[12px] leading-relaxed">- <span className="text-[hsl(var(--notfair-ink-4))]">🔒 </span>- {r.scope && (- <span className="ns-tag-mono mr-1.5 align-[1px]">{r.scope}</span>- )}- {r.href ? (- <a- href={r.href}- target="_blank"- rel="noreferrer"- className="ns-link font-medium break-all"- >- {r.name}- </a>- ) : (- <span className="font-medium break-all">{r.name}</span>- )}- {r.detail && (- <span className="text-[11.5px] text-[hsl(var(--notfair-ink-4))]">- {" "}- — only {r.detail}- </span>- )}- </li>- );- })}- </ul>- )}- <div className="mt-2.5">- <div- className="h-1 overflow-hidden rounded-full bg-[hsl(var(--notfair-warn)/0.18)]"- role="progressbar"- aria-label="Observation window elapsed"- aria-valuenow={Math.round(- windowProgress(move.made_at, move.observe_until!) * 100,- )}- aria-valuemin={0}- aria-valuemax={100}- >- <div- className="h-full rounded-full bg-[hsl(var(--notfair-warn))]"- style={{- width: `${Math.max(2, windowProgress(move.made_at, move.observe_until!) * 100)}%`,- }}- />- </div>- <p className="m-0 mt-1.5 text-right text-[11px] tabular-nums text-[hsl(var(--notfair-ink-4))]">- observation ends {timeUntil(move.observe_until!)} ·{" "}- {fmtWhen(move.observe_until!)}- </p>- </div>- </>- )}-- {stage === "outcome-due" && (- <p className="m-0 mt-2 text-[11.5px] text-[hsl(var(--notfair-ink-4))]">- The agent records what actually happened at its next check- {nextCheckAt ? ` · ${fmtWhen(nextCheckAt)}` : ""}.- </p>- )}- </li>- );-}diff --git a/notfair/src/components/goal-needs-you.test.tsx b/notfair/src/components/goal-needs-you.test.tsxdeleted file mode 100644index 2d678112..00000000--- a/notfair/src/components/goal-needs-you.test.tsx+++ /dev/null@@ -1,75 +0,0 @@-// @vitest-environment jsdom-import { fireEvent, render, screen, waitFor } from "@testing-library/react";-import { beforeEach, describe, expect, it, vi } from "vitest";--import { GoalNeedsYouDialog } from "@/components/goal-needs-you";--// Mock at the server-action boundary, per repo test conventions.-const markHandled = vi.hoisted(() => vi.fn());-vi.mock("@/server/actions/goals", () => ({- markUserActionHandledAction: markHandled,-}));--const refresh = vi.hoisted(() => vi.fn());-vi.mock("next/navigation", () => ({- useRouter: () => ({ refresh, push: vi.fn() }),-}));--const ITEMS = [- {- action_id: "a1",- ask: "Replace the production OPENAI_API_KEY with one from an active project.",- tick_number: 43,- raised_at: new Date(Date.now() - 3_600_000).toISOString(),- },- {- action_id: "a2",- ask: "Grant the Meta app image-upload access and re-authorize.",- tick_number: null,- raised_at: new Date().toISOString(),- },-];--beforeEach(() => {- markHandled.mockReset();- refresh.mockReset();-});--describe("GoalNeedsYouDialog", () => {- it("renders no trigger when there are no open asks", () => {- const { container } = render(- <GoalNeedsYouDialog items={[]} projectSlug="acme" agentSlug="meta-errors" />,- );- expect(container).toBeEmptyDOMElement();- });-- it("shows the badge count and lists every ask on open", () => {- render(- <GoalNeedsYouDialog items={ITEMS} projectSlug="acme" agentSlug="meta-errors" />,- );- const trigger = screen.getByRole("button", { name: /needs you\s*2/i });- fireEvent.click(trigger);- expect(screen.getByText(/OPENAI_API_KEY/)).toBeInTheDocument();- expect(screen.getByText(/raised 1h ago · check #43/)).toBeInTheDocument();- expect(screen.getByText(/Meta app image-upload access/)).toBeInTheDocument();- expect(screen.getByRole("link", { name: "Details for check #43" })).toHaveAttribute(- "href",- "/acme/goals/meta-errors/checks/tick-43",- );- expect(screen.getByRole("link", { name: "Details in goal chat" })).toHaveAttribute(- "href",- "/acme/goals/meta-errors",- );- });-- it("marks an ask handled and refreshes", async () => {- markHandled.mockResolvedValue({ ok: true });- render(- <GoalNeedsYouDialog items={ITEMS} projectSlug="acme" agentSlug="meta-errors" />,- );- fireEvent.click(screen.getByRole("button", { name: /needs you\s*2/i }));- fireEvent.click(screen.getAllByRole("button", { name: /mark handled/i })[0]!);- await waitFor(() => expect(markHandled).toHaveBeenCalledWith("a1"));- await waitFor(() => expect(refresh).toHaveBeenCalled());- });-});diff --git a/notfair/src/components/goal-needs-you.tsx b/notfair/src/components/goal-needs-you.tsxdeleted file mode 100644index 042b4554..00000000--- a/notfair/src/components/goal-needs-you.tsx+++ /dev/null@@ -1,144 +0,0 @@-"use client";--import Link from "next/link";-import { useRouter } from "next/navigation";-import { useState, useTransition } from "react";-import { toast } from "sonner";-import { Check, MessageSquareText, TriangleAlert } from "lucide-react";-import {- Dialog,- DialogContent,- DialogDescription,- DialogHeader,- DialogTitle,- DialogTrigger,-} from "@/components/ui/dialog";-import { markUserActionHandledAction } from "@/server/actions/goals";-import { projectHref } from "@/lib/project-href";-import { timeAgo } from "@/lib/time-ago";--export type NeedsYouItem = {- action_id: string;- /** Full escalation text, "USER ACTION REQUIRED" prefix already stripped. */- ask: string;- tick_number: number | null;- raised_at: string;-};--/**- * The escalation surface: open asks only the USER can resolve, one amber- * button in the goal header. Everything else in the loop is the agent's- * job — this dialog is the one place that is explicitly yours. The- * trigger renders nothing when there is nothing to do; when it shows,- * the agent repeats the same asks in every check summary until telemetry- * proves the fix (or you mark one handled here, which the agent later- * verifies — and re-escalates if it is still broken).- */-export function GoalNeedsYouDialog({- items,- projectSlug,- agentSlug,-}: {- items: NeedsYouItem[];- projectSlug: string;- agentSlug: string;-}) {- const router = useRouter();- const [open, setOpen] = useState(false);- const [pending, startTransition] = useTransition();-- if (items.length === 0) return null;-- function markHandled(item: NeedsYouItem) {- startTransition(async () => {- const r = await markUserActionHandledAction(item.action_id);- if (!r.ok) {- toast.error(r.error ?? "Could not mark it handled.");- return;- }- toast.success("Marked handled — the agent verifies it on a later check.");- if (items.length === 1) setOpen(false);- router.refresh();- });- }-- return (- <Dialog open={open} onOpenChange={setOpen}>- <DialogTrigger asChild>- <button- type="button"- className="ns-chip !bg-[hsl(var(--notfair-warn)/0.15)] font-medium !text-[hsl(var(--notfair-warn))] hover:!bg-[hsl(var(--notfair-warn)/0.25)]"- title="Actions only you can take — the agent is blocked on these"- >- <TriangleAlert className="size-3.5" aria-hidden />- Needs you- <span className="inline-flex min-w-4 items-center justify-center rounded-full bg-[hsl(var(--notfair-warn))] px-1 text-[10.5px] font-semibold tabular-nums text-[hsl(var(--card))]">- {items.length}- </span>- </button>- </DialogTrigger>- <DialogContent className="max-h-[75vh] overflow-y-auto sm:max-w-xl">- <DialogHeader>- <DialogTitle className="flex items-center gap-2 text-[15px]">- <TriangleAlert- className="size-4 text-[hsl(var(--notfair-warn))]"- aria-hidden- />- Needs you- </DialogTitle>- <DialogDescription>- The agent hit things only you can fix — credentials, app- permissions, account settings. It repeats each ask in every- check until telemetry proves the fix. Marking one handled- closes the ask; it re-escalates if still broken. Open Details- to ask the agent about it in the conversation that raised it.- </DialogDescription>- </DialogHeader>- <ul className="m-0 flex list-none flex-col gap-3 p-0">- {items.map((item) => (- <li- key={item.action_id}- className="rounded-xl bg-[hsl(var(--notfair-warn)/0.09)] p-3"- >- <p className="m-0 text-[12.5px] leading-relaxed">{item.ask}</p>- <div className="mt-2 flex items-center justify-between gap-2">- <span className="text-[11px] text-[hsl(var(--notfair-ink-4))]">- raised {timeAgo(item.raised_at)}- {item.tick_number !== null && ` · check #${item.tick_number}`}- </span>- <div className="flex shrink-0 items-center gap-1">- <Link- href={projectHref(- projectSlug,- item.tick_number === null- ? `/goals/${agentSlug}`- : `/goals/${agentSlug}/checks/tick-${item.tick_number}`,- )}- className="ns-btn ns-btn-ghost !px-2 !py-0.5 text-[11.5px]"- aria-label={- item.tick_number === null- ? "Details in goal chat"- : `Details for check #${item.tick_number}`- }- >- <MessageSquareText className="size-3" />- Details- </Link>- <button- type="button"- className="ns-btn ns-btn-ghost !px-2 !py-0.5 text-[11.5px]"- disabled={pending}- onClick={() => markHandled(item)}- >- <Check className="size-3" />- Mark handled- </button>- </div>- </div>- </li>- ))}- </ul>- </DialogContent>- </Dialog>- );-}diff --git a/notfair/src/components/goal-progress-chart.test.tsx b/notfair/src/components/goal-progress-chart.test.tsxdeleted file mode 100644index 99e0e492..00000000--- a/notfair/src/components/goal-progress-chart.test.tsx+++ /dev/null@@ -1,95 +0,0 @@-// @vitest-environment jsdom-import { fireEvent, render, screen } from "@testing-library/react";-import { afterEach, beforeEach, expect, it, vi } from "vitest";--import { GoalProgressChart, type ChartAction, type ChartFailure, type ChartPoint } from "./goal-progress-chart";--const now = Date.UTC(2026, 0, 10);-const points: ChartPoint[] = [- { t: now - 3_000, v: 1000, source: "backfill" },- { t: now - 1_000, v: 1250.25, source: "live" },-];-const actions: ChartAction[] = [- { t: now - 2_000, kind: "change", label: "Ship page", expected: "+10%", observed: "+12%", reviewUntil: now + 5_000 },- { t: now - 1_500, kind: "change", label: "Wait", expected: "+5%", observed: null, reviewUntil: now + 2_000 },-];-const failures: ChartFailure[] = [{ t: now - 500, error: "API offline" }];--beforeEach(() => {- vi.useFakeTimers();- vi.setSystemTime(now);-});--afterEach(() => vi.useRealTimers());--it("shows the empty state until there are two readings", () => {- const { rerender } = render(- <GoalProgressChart points={[]} actions={[]} failures={[]} target={null} baseline={null} deadline={null} />,- );- expect(screen.getByText(/chart appears after a couple of readings/)).toBeInTheDocument();- rerender(<GoalProgressChart points={[points[0]!]} actions={[]} failures={[]} target={null} baseline={null} deadline={null} />);- expect(screen.getByText(/chart appears/)).toBeInTheDocument();-});--it("renders metric, references, action windows, failures, and a deadline", () => {- const { container } = render(- <GoalProgressChart- points={points}- actions={actions}- failures={failures}- target={1500}- baseline={1000}- deadline={now - 250}- />,- );- expect(screen.getByRole("img")).toHaveAttribute("aria-label", "Metric over time. Latest 1.3k, target 1.5k.");- expect(screen.getByText("target 1.5k")).toBeInTheDocument();- expect(screen.getByText("⚑ deadline")).toBeInTheDocument();- expect(screen.getByText("✕")).toBeInTheDocument();- expect(container.querySelectorAll("svg rect").length).toBeGreaterThan(2);- expect(container.querySelector("svg path[d^='M']")).toBeInTheDocument();-});--it("handles a flat series by adding vertical padding", () => {- render(- <GoalProgressChart- points={[{ ...points[0]!, v: 7 }, { ...points[1]!, v: 7 }]}- actions={[]}- failures={[]}- target={null}- baseline={null}- deadline={now + 50_000}- />,- );- expect(screen.getByRole("img")).toHaveAttribute("aria-label", "Metric over time. Latest 7.");- expect(screen.queryByText("⚑ deadline")).not.toBeInTheDocument();-});--it("shows nearest point details and clears a distant hover", () => {- render(<GoalProgressChart points={points} actions={[]} failures={[]} target={null} baseline={null} deadline={null} />);- const svg = screen.getByRole("img");- vi.spyOn(svg, "getBoundingClientRect").mockReturnValue({ left: 0, width: 340, top: 0, height: 170 } as DOMRect);- fireEvent.mouseMove(svg, { clientX: 34 });- expect(screen.getAllByText("1.0k")).toHaveLength(2);- expect(screen.getByText(/history/)).toBeInTheDocument();- fireEvent.mouseMove(svg, { clientX: 330 });- fireEvent.mouseLeave(svg);- expect(screen.queryByText(/history/)).not.toBeInTheDocument();-});--it("shows observed, measuring, and failure tooltips", () => {- const { container } = render(- <GoalProgressChart points={points} actions={actions} failures={failures} target={null} baseline={null} deadline={null} />,- );- const hoverGroups = container.querySelectorAll("g.cursor-help");- fireEvent.mouseEnter(hoverGroups[0]!);- expect(screen.getByText(/Ship page/)).toBeInTheDocument();- expect(screen.getByText(/observed: \+12%/)).toBeInTheDocument();- fireEvent.mouseLeave(hoverGroups[0]!);- fireEvent.mouseEnter(hoverGroups[1]!);- expect(screen.getByText(/measuring until/)).toBeInTheDocument();- fireEvent.mouseEnter(hoverGroups[2]!);- expect(screen.getByText("API offline")).toBeInTheDocument();- fireEvent.mouseLeave(hoverGroups[2]!);- expect(screen.queryByText("API offline")).not.toBeInTheDocument();-});diff --git a/notfair/src/components/goal-progress-chart.tsx b/notfair/src/components/goal-progress-chart.tsxdeleted file mode 100644index 336d320f..00000000--- a/notfair/src/components/goal-progress-chart.tsx+++ /dev/null@@ -1,364 +0,0 @@-"use client";--import { useMemo, useRef, useState } from "react";--/**- * The goal's hero chart: the metric over real time, with the target and- * baseline as reference lines, every agent action as a marker on the- * moment it happened, and observation windows shaded — cause and effect- * on one picture.- *- * Dataviz rules applied: single series (no legend — the card title names- * it), 2px line, ≥8px hit targets with a 2px surface ring, recessive- * grid/reference lines in ink tokens, crosshair + tooltip by default,- * text in text tokens never series color, and every colored mark carries- * a shape + tooltip so nothing is color-alone.- */--export type ChartPoint = { t: number; v: number; source: string };-export type ChartAction = {- t: number;- kind: string;- label: string;- expected: string;- observed: string | null;- reviewUntil: number | null;-};-export type ChartFailure = { t: number; error: string };--const W = 340;-const H = 170;-const PAD = { top: 10, right: 10, bottom: 20, left: 34 };--function fmtVal(v: number): string {- if (Math.abs(v) >= 1000) return `${(v / 1000).toFixed(1)}k`;- return Number.isInteger(v) ? String(v) : v.toFixed(2);-}--function fmtDate(t: number): string {- return new Date(t).toLocaleDateString(undefined, { month: "short", day: "numeric" });-}--export function GoalProgressChart({- points,- actions,- failures,- target,- baseline,- deadline,-}: {- points: ChartPoint[];- actions: ChartAction[];- failures: ChartFailure[];- target: number | null;- baseline: number | null;- deadline: number | null;-}) {- const wrapRef = useRef<HTMLDivElement>(null);- const [hover, setHover] = useState<- | { kind: "point"; x: number; y: number; p: ChartPoint }- | { kind: "action"; x: number; y: number; a: ChartAction }- | { kind: "failure"; x: number; y: number; f: ChartFailure }- | null- >(null);-- const model = useMemo(() => {- if (points.length < 2) return null;- const ts = points.map((p) => p.t);- const now = Date.now();- const tMin = Math.min(...ts, ...actions.map((a) => a.t), now - 1);- const tMax = Math.max(...ts, now);- const values = [- ...points.map((p) => p.v),- ...(target !== null ? [target] : []),- ...(baseline !== null ? [baseline] : []),- ];- let vMin = Math.min(...values);- let vMax = Math.max(...values);- if (vMin === vMax) {- vMin -= 1;- vMax += 1;- }- const vPad = (vMax - vMin) * 0.12;- vMin -= vPad;- vMax += vPad;- const x = (t: number) =>- PAD.left + ((t - tMin) / (tMax - tMin)) * (W - PAD.left - PAD.right);- const y = (v: number) =>- PAD.top + (1 - (v - vMin) / (vMax - vMin)) * (H - PAD.top - PAD.bottom);- // 3 recessive horizontal gridlines with value labels.- const gridVals = [vMin + vPad, (vMin + vMax) / 2, vMax - vPad];- // 3 date ticks.- const tickTs = [tMin, (tMin + tMax) / 2, tMax];- return { tMin, tMax, x, y, gridVals, tickTs };- }, [points, actions, target, baseline]);-- if (!model || points.length < 2) {- return (- <div className="flex h-28 items-center justify-center text-[12px] text-[hsl(var(--notfair-ink-4))]">- The chart appears after a couple of readings — history backfills- during setup when the source supports it.- </div>- );- }-- const { x, y, gridVals, tickTs, tMax } = model;- const path = points- .map((p, i) => `${i === 0 ? "M" : "L"}${x(p.t).toFixed(1)},${y(p.v).toFixed(1)}`)- .join(" ");- const last = points[points.length - 1]!;- const deadlineInside = deadline !== null && deadline <= tMax;-- function onMove(e: React.MouseEvent<SVGSVGElement>) {- const rect = e.currentTarget.getBoundingClientRect();- const mx = ((e.clientX - rect.left) / rect.width) * W;- // nearest data point by x- let best: ChartPoint | null = null;- let bestD = Infinity;- for (const p of points) {- const d = Math.abs(x(p.t) - mx);- if (d < bestD) {- bestD = d;- best = p;- }- }- if (best && bestD < 24) {- setHover({ kind: "point", x: x(best.t), y: y(best.v), p: best });- } else {- setHover(null);- }- }-- return (- <div ref={wrapRef} className="relative">- <svg- viewBox={`0 0 ${W} ${H}`}- className="w-full"- role="img"- aria-label={`Metric over time. Latest ${fmtVal(last.v)}${target !== null ? `, target ${fmtVal(target)}` : ""}.`}- onMouseMove={onMove}- onMouseLeave={() => setHover(null)}- >- {/* recessive grid + value labels */}- {gridVals.map((gv, i) => (- <g key={i}>- <line- x1={PAD.left}- x2={W - PAD.right}- y1={y(gv)}- y2={y(gv)}- stroke="hsl(var(--border))"- strokeWidth="1"- />- <text- x={PAD.left - 4}- y={y(gv) + 3}- textAnchor="end"- className="fill-[hsl(var(--notfair-ink-4))] text-[8px] tabular-nums"- >- {fmtVal(gv)}- </text>- </g>- ))}- {/* date ticks */}- {tickTs.map((tt, i) => (- <text- key={i}- x={x(tt)}- y={H - 6}- textAnchor={i === 0 ? "start" : i === tickTs.length - 1 ? "end" : "middle"}- className="fill-[hsl(var(--notfair-ink-4))] text-[8px]"- >- {fmtDate(tt)}- </text>- ))}-- {/* observation windows (shaded) */}- {actions- .filter((a) => a.reviewUntil !== null)- .map((a, i) => (- <rect- key={`w${i}`}- x={x(a.t)}- y={PAD.top}- width={Math.max(0, x(Math.min(a.reviewUntil!, tMax)) - x(a.t))}- height={H - PAD.top - PAD.bottom}- fill="hsl(var(--notfair-accent))"- opacity="0.07"- />- ))}-- {/* reference lines: baseline dotted, target dashed + label */}- {baseline !== null && (- <line- x1={PAD.left}- x2={W - PAD.right}- y1={y(baseline)}- y2={y(baseline)}- stroke="hsl(var(--notfair-ink-4))"- strokeWidth="1"- strokeDasharray="1.5 3"- />- )}- {target !== null && (- <g>- <line- x1={PAD.left}- x2={W - PAD.right}- y1={y(target)}- y2={y(target)}- stroke="hsl(var(--notfair-ink-3))"- strokeWidth="1"- strokeDasharray="5 3"- />- <text- x={W - PAD.right}- y={y(target) - 3}- textAnchor="end"- className="fill-[hsl(var(--notfair-ink-3))] text-[8px]"- >- target {fmtVal(target)}- </text>- </g>- )}-- {/* deadline flag */}- {deadlineInside && (- <g>- <line- x1={x(deadline!)}- x2={x(deadline!)}- y1={PAD.top}- y2={H - PAD.bottom}- stroke="hsl(var(--notfair-ink-4))"- strokeWidth="1"- strokeDasharray="2 3"- />- <text- x={x(deadline!) + 3}- y={PAD.top + 7}- className="fill-[hsl(var(--notfair-ink-4))] text-[8px]"- >- ⚑ deadline- </text>- </g>- )}-- {/* the metric line */}- <path- d={path}- fill="none"- stroke="hsl(var(--notfair-accent))"- strokeWidth="2"- strokeLinejoin="round"- strokeLinecap="round"- />- {/* latest point, ringed */}- <circle cx={x(last.t)} cy={y(last.v)} r="4" fill="hsl(var(--background))" />- <circle cx={x(last.t)} cy={y(last.v)} r="2.5" fill="hsl(var(--notfair-accent))" />-- {/* action markers: ▼ on the time axis of the event */}- {actions.map((a, i) => (- <g- key={`a${i}`}- onMouseEnter={() => setHover({ kind: "action", x: x(a.t), y: PAD.top + 8, a })}- onMouseLeave={() => setHover(null)}- className="cursor-help"- >- {/* generous invisible hit target */}- <rect x={x(a.t) - 8} y={PAD.top} width="16" height="16" fill="transparent" />- <path- d={`M${x(a.t) - 4.5},${PAD.top + 2} L${x(a.t) + 4.5},${PAD.top + 2} L${x(a.t)},${PAD.top + 9} Z`}- fill="hsl(var(--notfair-accent))"- stroke="hsl(var(--background))"- strokeWidth="1.5"- />- </g>- ))}-- {/* failed checks: ✕ */}- {failures.map((f, i) => (- <g- key={`f${i}`}- onMouseEnter={() => setHover({ kind: "failure", x: x(f.t), y: H - PAD.bottom - 8, f })}- onMouseLeave={() => setHover(null)}- className="cursor-help"- >- <rect x={x(f.t) - 8} y={H - PAD.bottom - 16} width="16" height="16" fill="transparent" />- <text- x={x(f.t)}- y={H - PAD.bottom - 5}- textAnchor="middle"- className="fill-[hsl(0_72%_51%)] text-[10px] font-bold"- >- ✕- </text>- </g>- ))}-- {/* crosshair for hovered data point */}- {hover?.kind === "point" && (- <g pointerEvents="none">- <line- x1={hover.x}- x2={hover.x}- y1={PAD.top}- y2={H - PAD.bottom}- stroke="hsl(var(--notfair-ink-4))"- strokeWidth="1"- strokeDasharray="2 2"- />- <circle cx={hover.x} cy={hover.y} r="4" fill="hsl(var(--background))" />- <circle cx={hover.x} cy={hover.y} r="2.5" fill="hsl(var(--notfair-accent))" />- </g>- )}- </svg>-- {/* tooltip */}- {hover && (- <div- className="pointer-events-none absolute z-10 max-w-[240px] rounded-md bg-[hsl(var(--card))] px-2.5 py-1.5 text-[11px] leading-snug shadow-lg"- style={{- left: `${Math.min(92, Math.max(8, (hover.x / W) * 100))}%`,- top: `${(hover.y / H) * 100}%`,- transform: `translate(${hover.x > W * 0.6 ? "-100%" : "8px"}, 10px)`,- }}- >- {hover.kind === "point" && (- <>- <span className="font-medium tabular-nums">{fmtVal(hover.p.v)}</span>{" "}- <span className="text-[hsl(var(--notfair-ink-4))]">- {fmtDate(hover.p.t)}- {hover.p.source === "backfill" ? " · history" : ""}- </span>- </>- )}- {hover.kind === "action" && (- <>- <p className="m-0 font-medium">▼ {hover.a.label}</p>- <p className="m-0 text-[hsl(var(--notfair-ink-4))]">- expected: {hover.a.expected}- </p>- {hover.a.observed && (- <p className="m-0 text-[hsl(var(--notfair-ink-4))]">- observed: {hover.a.observed}- </p>- )}- {!hover.a.observed && hover.a.reviewUntil && (- <p className="m-0 text-[hsl(var(--notfair-ink-4))]">- measuring until {fmtDate(hover.a.reviewUntil)}- </p>- )}- </>- )}- {hover.kind === "failure" && (- <>- <p className="m-0 font-medium text-[hsl(0_72%_51%)]">✕ check failed</p>- <p className="m-0 text-[hsl(var(--notfair-ink-4))]">{hover.f.error}</p>- </>- )}- </div>- )}- </div>- );-}diff --git a/notfair/src/components/goal-prs-dialog.tsx b/notfair/src/components/goal-prs-dialog.tsxdeleted file mode 100644index 2b09544c..00000000--- a/notfair/src/components/goal-prs-dialog.tsx+++ /dev/null@@ -1,117 +0,0 @@-"use client";--import { useState } from "react";-import { GitPullRequest } from "lucide-react";-import {- Dialog,- DialogContent,- DialogDescription,- DialogHeader,- DialogTitle,- DialogTrigger,-} from "@/components/ui/dialog";-import { timeAgo } from "@/lib/time-ago";--/** Plain-JSON PR row for the dialog (subset of the goal_prs table). */-export type PrRow = {- id: string;- url: string;- title: string;- state: "open" | "merged" | "closed";- review_decision: string | null;- comment_count: number;- is_draft: boolean;- branch: string | null;- created_at: string;- sync_error: string | null;-};--/**- * The goal's open pull requests, one click from the header — count on the- * button like Memory, full list with review state in the modal. Merged and- * closed PRs stay reachable from the check that produced them; this is the- * "what's waiting on a human" view. Hidden while nothing is open.- */-export function GoalPrsDialog({ prs }: { prs: PrRow[] }) {- const [open, setOpen] = useState(false);- if (prs.length === 0) return null;-- return (- <Dialog open={open} onOpenChange={setOpen}>- <DialogTrigger asChild>- <button- type="button"- className="ns-chip"- title="Open pull requests this goal's agent is waiting on"- >- <GitPullRequest className="size-3.5" aria-hidden />- PRs- <span className="tabular-nums text-[hsl(var(--notfair-ink-4))]">- {prs.length}- </span>- </button>- </DialogTrigger>- <DialogContent className="max-h-[70vh] overflow-y-auto sm:max-w-lg">- <DialogHeader>- <DialogTitle className="flex items-center gap-2 text-[15px]">- <GitPullRequest className="size-4" aria-hidden />- Open pull requests- </DialogTitle>- <DialogDescription>- Submissions awaiting review — the agent reacts to each PR’s- state on every check.- </DialogDescription>- </DialogHeader>- <ul className="m-0 flex list-none flex-col gap-3 p-0">- {prs.map((pr) => (- <PrItem key={pr.id} pr={pr} />- ))}- </ul>- </DialogContent>- </Dialog>- );-}--function PrItem({ pr }: { pr: PrRow }) {- return (- <li className="rounded-md bg-[hsl(var(--notfair-surface-2)/0.5)] px-3 py-2.5 text-[12.5px] leading-snug">- <div className="flex items-baseline justify-between gap-2">- <a- href={pr.url}- target="_blank"- rel="noreferrer"- className="ns-link min-w-0 truncate font-medium"- >- {pr.title}- </a>- <span className="shrink-0 text-[10.5px] tabular-nums text-[hsl(var(--notfair-ink-4))]">- {timeAgo(pr.created_at)}- </span>- </div>- <p className="m-0 mt-1 flex flex-wrap items-center gap-1.5">- {pr.state === "merged" ? (- <span className="ns-tag">merged</span>- ) : pr.state === "closed" ? (- <span className="ns-tag-red">closed unmerged</span>- ) : pr.is_draft ? (- <span className="ns-tag">draft</span>- ) : pr.review_decision === "CHANGES_REQUESTED" ? (- <span className="ns-tag-amber">changes requested — agent’s turn</span>- ) : (- <span className="ns-tag-accent">needs your review</span>- )}- {pr.comment_count > 0 && (- <span className="text-[11px] text-[hsl(var(--notfair-ink-4))]">- {pr.comment_count} comment{pr.comment_count === 1 ? "" : "s"}- </span>- )}- {pr.branch && <span className="ns-tag-mono">{pr.branch}</span>}- </p>- {pr.sync_error && (- <p className="m-0 mt-0.5 text-[11px] text-[hsl(var(--notfair-warn))]">- sync failed: {pr.sync_error}- </p>- )}- </li>- );-}diff --git a/notfair/src/components/goal-sparkline.tsx b/notfair/src/components/goal-sparkline.tsxdeleted file mode 100644index f722cef6..00000000--- a/notfair/src/components/goal-sparkline.tsx+++ /dev/null@@ -1,77 +0,0 @@-/**- * Hand-rolled inline-SVG sparkline for the goal metric (no chart dep in- * this repo — see cron-calendar for the precedent). Server-renderable:- * pure props → markup, no hooks.- */-export function GoalSparkline({- values,- target,- direction,- width = 560,- height = 96,-}: {- values: number[];- target: number | null;- direction: "increase" | "decrease" | null;- width?: number;- height?: number;-}) {- if (values.length < 2) {- return (- <div- className="flex items-center justify-center text-[12.5px] text-[hsl(var(--notfair-ink-4))]"- style={{ height }}- >- Not enough readings yet — the sparkline appears after a couple of ticks.- </div>- );- }-- const pad = 6;- const all = target !== null ? [...values, target] : values;- const min = Math.min(...all);- const max = Math.max(...all);- const span = max - min || 1;-- const x = (i: number) => pad + (i / (values.length - 1)) * (width - pad * 2);- const y = (v: number) => pad + (1 - (v - min) / span) * (height - pad * 2);-- const points = values.map((v, i) => `${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(" ");- const last = values[values.length - 1]!;- const first = values[0]!;- const improving =- direction === "decrease" ? last <= first : direction === "increase" ? last >= first : true;- const stroke = improving ? "hsl(var(--notfair-accent))" : "hsl(0 72% 51%)";-- return (- <svg- viewBox={`0 0 ${width} ${height}`}- style={{ height }}- className="w-full"- role="img"- aria-label={`Metric trend: ${first} → ${last}${target !== null ? `, target ${target}` : ""}`}- preserveAspectRatio="none"- >- {target !== null && (- <line- x1={pad}- x2={width - pad}- y1={y(target)}- y2={y(target)}- stroke="hsl(var(--notfair-ink-4))"- strokeDasharray="4 4"- strokeWidth="1"- />- )}- <polyline- points={points}- fill="none"- stroke={stroke}- strokeWidth="2"- strokeLinejoin="round"- strokeLinecap="round"- />- <circle cx={x(values.length - 1)} cy={y(last)} r="3" fill={stroke} />- </svg>- );-}diff --git a/notfair/src/components/goal-suggestions.tsx b/notfair/src/components/goal-suggestions.tsxdeleted file mode 100644index 31d34919..00000000--- a/notfair/src/components/goal-suggestions.tsx+++ /dev/null@@ -1,108 +0,0 @@-"use client";--import { useRouter } from "next/navigation";-import { useState, useTransition } from "react";-import { Sparkles, X } from "lucide-react";-import { toast } from "sonner";-import {- acceptSuggestionAction,- dismissSuggestionAction,- refreshSuggestionsAction,-} from "@/server/actions/suggestions";-import type { GoalSuggestion } from "@/server/db/suggestions";-import { projectHref } from "@/lib/project-href";-import { Button } from "@/components/ui/button";--/**- * Suggested-goal cards minted from a mechanical audit of a connected ads- * account. Accepting one runs the normal statement-first flow: a goal- * agent spins up, verifies the metric, and nothing spends until the user- * confirms the plan.- */-export function GoalSuggestionCard({- suggestion,- projectSlug,-}: {- suggestion: GoalSuggestion;- projectSlug: string;-}) {- const router = useRouter();- const [pending, startTransition] = useTransition();- const [dismissed, setDismissed] = useState(false);-- function accept() {- startTransition(async () => {- const r = await acceptSuggestionAction(suggestion.id);- if (!r.ok || !r.agent_slug) {- toast.error(r.error ?? "Could not create the goal.");- return;- }- toast.success("Goal created — your agent is on it.");- router.push(projectHref(projectSlug, `/goals/${r.agent_slug}`));- });- }-- function dismiss() {- setDismissed(true);- startTransition(async () => {- await dismissSuggestionAction(suggestion.id);- router.refresh();- });- }-- if (dismissed) return null;-- return (- <div className="ns-card relative flex flex-col gap-2 p-4">- <button- type="button"- onClick={dismiss}- disabled={pending}- aria-label="Dismiss suggestion"- title="Dismiss — this idea won't come back"- className="absolute right-3 top-3 rounded p-1 text-[hsl(var(--notfair-ink-4))] hover:text-[hsl(var(--notfair-ink-2))]"- >- <X className="size-3.5" />- </button>- <div className="flex items-center gap-2 pr-8">- <Sparkles className="size-3.5 shrink-0 text-[hsl(var(--notfair-accent))]" aria-hidden />- <p className="m-0 text-[13.5px] font-medium">{suggestion.title}</p>- <span className="ns-tag">- {suggestion.mode === "maintain" ? "keep it there" : "reach a target"}- </span>- </div>- <p className="m-0 text-[12.5px] text-[hsl(var(--notfair-ink-3))]">- {suggestion.rationale}- </p>- <div className="mt-1 flex items-center justify-between gap-3">- <p className="m-0 text-[11.5px] text-[hsl(var(--notfair-ink-4))]">- An agent verifies the numbers first — nothing runs until you confirm the plan in chat.- </p>- <Button size="sm" onClick={accept} disabled={pending}>- {pending ? "Creating…" : "Create this goal"}- </Button>- </div>- </div>- );-}--/** Inline retry for a failed account analysis. */-export function RetryAnalysisButton({ projectSlug }: { projectSlug: string }) {- const router = useRouter();- const [pending, startTransition] = useTransition();- return (- <Button- size="xs"- variant="outline"- disabled={pending}- onClick={() =>- startTransition(async () => {- await refreshSuggestionsAction(projectSlug);- router.refresh();- })- }- >- {pending ? "Retrying…" : "Retry"}- </Button>- );-}diff --git a/notfair/src/components/goals-board.test.tsx b/notfair/src/components/goals-board.test.tsxdeleted file mode 100644index c981ffa7..00000000--- a/notfair/src/components/goals-board.test.tsx+++ /dev/null@@ -1,150 +0,0 @@-// @vitest-environment jsdom-import { describe, expect, it } from "vitest";-import { render, screen, within } from "@testing-library/react";-import {- GoalsBoard,- type BoardGoal,- type GoalDashboardSection,-} from "./goals-board";--function goal(overrides: Partial<BoardGoal>): BoardGoal {- return {- id: "g1",- href: "/proj/goals/goal-1",- label: "Goal one",- statement: "Do the thing",- status: "active",- status_reason: null,- metric_name: "Clicks",- current_value: 5,- target_value: 10,- metric_direction: "increase",- mode: "achieve",- tick_count: 3,- pinned: false,- updated_at: "2026-07-10T00:00:00.000Z",- snapshots: [1, 3, 5],- ...overrides,- };-}--function section(overrides: Partial<GoalDashboardSection>): GoalDashboardSection {- return {- id: "group-1",- name: "Acquisition",- description: "Goals that grow qualified demand.",- href: "/proj/groups/group-1",- goals: [],- ...overrides,- };-}--describe("GoalsBoard", () => {- it("renders group sections with every goal's metric history and destination", () => {- render(- <GoalsBoard- sections={[- section({- goals: [- goal({- id: "clicks",- href: "/proj/goals/clicks",- label: "Organic clicks +30%",- current_value: 76,- target_value: 77,- snapshots: [61, 69, 76],- }),- goal({- id: "errors",- href: "/proj/goals/errors",- label: "Errors under 2%",- metric_direction: "decrease",- mode: "maintain",- current_value: 1.82,- target_value: 2,- snapshots: [3.4, 2.5, 1.82],- }),- ],- }),- ]}- />,- );-- const group = screen.getByRole("region", { name: "Acquisition" });- expect(within(group).getByRole("link", { name: "Open group" })).toHaveAttribute(- "href",- "/proj/groups/group-1",- );-- const clicks = within(group).getByRole("link", { name: /^Open Organic clicks \+30%/ });- expect(clicks).toHaveAttribute("href", "/proj/goals/clicks");- expect(within(clicks).getByText("76")).toBeTruthy();- expect(within(clicks).getByText("target ≥ 77")).toBeTruthy();- expect(- within(clicks).getByRole("img", { name: /Metric trend: 61 → 76/ }),- ).toHaveStyle({ height: "76px" });-- const errors = within(group).getByRole("link", { name: /^Open Errors under 2%/ });- expect(within(errors).getByText("hold ≤ 2")).toBeTruthy();- expect(within(errors).getByText("on target")).toBeTruthy();- });-- it("keeps pinned goals first and closed goals behind live goals", () => {- render(- <GoalsBoard- sections={[- section({- href: null,- goals: [- goal({ id: "closed", label: "Closed", status: "killed" }),- goal({ id: "live", label: "Live", updated_at: "2026-07-20T00:00:00.000Z" }),- goal({ id: "pinned", label: "Pinned", pinned: true }),- ],- }),- ]}- />,- );-- const links = within(screen.getByRole("region", { name: "Acquisition" }))- .getAllByRole("link")- .map((link) => link.getAttribute("aria-label")?.split(",")[0]);- expect(links).toEqual(["Open Pinned", "Open Live", "Open Closed"]);- });-- it("shows measured and unmeasured history empty states", () => {- render(- <GoalsBoard- sections={[- section({- goals: [- goal({ id: "one-reading", snapshots: [5] }),- goal({- id: "intake",- label: "New goal",- metric_name: null,- current_value: null,- target_value: null,- snapshots: [],- statement: "Measure signups from the new landing page.",- status: "intake",- }),- ],- }),- ]}- />,- );-- expect(screen.getByText("Trend appears after the next reading")).toBeTruthy();- expect(screen.getByText("Measure signups from the new landing page.")).toBeTruthy();- expect(screen.getByText("Main metric is being defined")).toBeTruthy();- });-- it("keeps empty groups visible and actionable", () => {- render(<GoalsBoard sections={[section({ goals: [] })]} />);- expect(screen.getByText("No goals in this group yet.", { exact: false })).toBeTruthy();- expect(screen.getByRole("link", { name: "Open group" })).toHaveAttribute(- "href",- "/proj/groups/group-1",- );- });-});diff --git a/notfair/src/components/goals-board.tsx b/notfair/src/components/goals-board.tsxdeleted file mode 100644index 764a8258..00000000--- a/notfair/src/components/goals-board.tsx+++ /dev/null@@ -1,266 +0,0 @@-import Link from "next/link";-import { ArrowUpRight, Pin } from "lucide-react";-import { GoalSparkline } from "@/components/goal-sparkline";-import { formatMetric } from "@/lib/format-metric";-import { goalGroupHealth, type GoalGroupHealth } from "@/lib/goal-group-health";-import { timeAgo } from "@/lib/time-ago";-import { cn } from "@/lib/utils";--// Plain JSON is passed from the server route so this dashboard stays cheap to-// render and every card can be a normal link, with no client hydration needed.-type GoalStatus =- | "intake"- | "proposed"- | "active"- | "paused"- | "achieved"- | "failed"- | "killed";--export type BoardGoal = {- id: string;- href: string;- label: string;- statement: string;- status: GoalStatus;- status_reason: string | null;- metric_name: string | null;- current_value: number | null;- target_value: number | null;- metric_direction: "increase" | "decrease" | null;- mode: "achieve" | "maintain";- tick_count: number;- pinned: boolean;- updated_at: string;- snapshots: number[];-};--export type GoalDashboardSection = {- id: string;- name: string;- description: string;- href: string | null;- goals: BoardGoal[];-};--const TERMINAL: GoalStatus[] = ["achieved", "failed", "killed"];--const HEALTH_COPY: Record<- GoalGroupHealth,- { label: string; dot: string; text: string }-> = {- healthy: {- label: "on target",- dot: "ns-dot-live",- text: "text-[hsl(var(--notfair-accent))]",- },- attention: {- label: "needs attention",- dot: "ns-dot-err",- text: "text-[hsl(var(--destructive))]",- },- waiting: {- label: "waiting for data",- dot: "ns-dot-warn",- text: "text-[hsl(var(--notfair-warn))]",- },- paused: {- label: "paused",- dot: "ns-dot-mute",- text: "text-[hsl(var(--notfair-ink-4))]",- },- closed: {- label: "closed",- dot: "ns-dot-mute",- text: "text-[hsl(var(--notfair-ink-4))]",- },-};--/**- * Workspace-level metric dashboard. Groups provide the page structure and- * every raised surface is a real navigation target: clicking any metric card- * opens that goal's full history and chat.- */-export function GoalsBoard({ sections }: { sections: GoalDashboardSection[] }) {- const allGoals = sections.flatMap((section) => section.goals);- const running = allGoals.filter((goal) => goal.status === "active").length;- const paused = allGoals.filter((goal) => goal.status === "paused").length;- const closed = allGoals.filter((goal) => TERMINAL.includes(goal.status)).length;-- return (- <div>- <div- className="mb-9 flex flex-wrap items-center gap-x-5 gap-y-2 text-[12px] text-[hsl(var(--notfair-ink-4))]"- aria-label="Goals summary"- >- <span className="font-mono tabular-nums">- {allGoals.length} goal{allGoals.length === 1 ? "" : "s"}- </span>- {running > 0 && (- <span className="flex items-center gap-1.5 text-[hsl(var(--notfair-accent))]">- <span className="ns-dot ns-dot-live" aria-hidden />- {running} running- </span>- )}- {paused > 0 && (- <span className="flex items-center gap-1.5">- <span className="ns-dot ns-dot-mute" aria-hidden />- {paused} paused- </span>- )}- {closed > 0 && (- <span className="flex items-center gap-1.5">- <span className="ns-dot ns-dot-mute" aria-hidden />- {closed} closed- </span>- )}- </div>-- <div className="flex flex-col gap-12">- {sections.map((section) => {- const goals = [...section.goals].sort((a, b) => {- if (a.pinned !== b.pinned) return a.pinned ? -1 : 1;- if (TERMINAL.includes(a.status) !== TERMINAL.includes(b.status)) {- return TERMINAL.includes(a.status) ? 1 : -1;- }- return b.updated_at.localeCompare(a.updated_at);- });- const headingId = `goal-section-${section.id}`;-- return (- <section key={section.id} aria-labelledby={headingId}>- <header className="mb-4 flex items-end justify-between gap-4">- <div className="min-w-0">- <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">- <h2- id={headingId}- className="m-0 text-[16px] font-semibold tracking-[-0.018em] text-[hsl(var(--notfair-ink-2))]"- >- {section.name}- </h2>- <span className="font-mono text-[10.5px] tabular-nums text-[hsl(var(--notfair-ink-4))]">- {goals.length} goal{goals.length === 1 ? "" : "s"}- </span>- </div>- <p className="m-0 mt-1 max-w-[70ch] text-[12.5px] leading-relaxed text-[hsl(var(--notfair-ink-4))]">- {section.description}- </p>- </div>- {section.href && (- <Link- href={section.href}- className="group/link flex shrink-0 items-center gap-1 text-[11.5px] text-[hsl(var(--notfair-ink-4))] transition-colors hover:text-[hsl(var(--notfair-ink-2))] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- >- Open group- <ArrowUpRight className="size-3 transition-transform group-hover/link:-translate-y-0.5 group-hover/link:translate-x-0.5" />- </Link>- )}- </header>-- {goals.length === 0 ? (- <div className="rounded-xl bg-[hsl(var(--notfair-surface-2)/0.42)] px-5 py-8 text-[12.5px] text-[hsl(var(--notfair-ink-4))]">- No goals in this group yet. Use <span className="text-[hsl(var(--notfair-ink-3))]">Manage group</span> to add one.- </div>- ) : (- <div className="grid grid-cols-1 gap-3 lg:grid-cols-2 2xl:grid-cols-3">- {goals.map((goal) => (- <GoalMetricCard key={goal.id} goal={goal} />- ))}- </div>- )}- </section>- );- })}- </div>- </div>- );-}--function GoalMetricCard({ goal }: { goal: BoardGoal }) {- const health = goalGroupHealth(goal);- const healthCopy = HEALTH_COPY[health];- const comparator = goal.metric_direction === "decrease" ? "≤" : "≥";- const metricReady = goal.metric_name !== null;- const hasChart = goal.snapshots.length >= 2;- const accessibleTarget =- goal.target_value === null- ? ""- : `, ${goal.mode === "maintain" ? "hold" : "target"} ${comparator} ${formatMetric(goal.target_value)}`;-- return (- <Link- href={goal.href}- aria-label={`Open ${goal.label}, current ${formatMetric(goal.current_value)}${accessibleTarget}`}- className="group ns-card flex min-h-[250px] flex-col overflow-hidden p-5 no-underline transition-[transform,box-shadow,background-color] duration-150 hover:-translate-y-0.5 hover:shadow-[var(--notfair-shadow-lg)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- >- <div className="flex items-start justify-between gap-3">- <div className="min-w-0">- <div className="flex items-center gap-2">- <span className={cn("ns-dot", healthCopy.dot)} aria-hidden />- <h3 className="m-0 truncate text-[14px] font-semibold tracking-[-0.012em] text-foreground">- {goal.label}- </h3>- {goal.pinned && (- <Pin- aria-label="Pinned"- className="size-3 shrink-0 text-[hsl(var(--notfair-ink-4))]"- />- )}- </div>- <p className="m-0 mt-1 truncate text-[11.5px] text-[hsl(var(--notfair-ink-4))]">- {goal.metric_name ?? "Main metric is being defined"}- </p>- </div>- <span- className={cn(- "shrink-0 text-[10.5px] font-medium lowercase",- healthCopy.text,- )}- >- {healthCopy.label}- </span>- </div>-- <div className="mt-5 flex items-end gap-2">- <span className="text-[28px] leading-none font-semibold tabular-nums tracking-[-0.035em] text-foreground">- {formatMetric(goal.current_value)}- </span>- {goal.target_value !== null && (- <span className="pb-0.5 font-mono text-[10.5px] tabular-nums text-[hsl(var(--notfair-ink-4))]">- {goal.mode === "maintain" ? "hold " : "target "}- {comparator} {formatMetric(goal.target_value)}- </span>- )}- </div>-- <div className="mt-4 flex min-h-[92px] flex-1 items-center rounded-[10px] bg-[hsl(var(--notfair-surface-2)/0.46)] px-2.5 py-2">- {hasChart ? (- <GoalSparkline- values={goal.snapshots}- target={goal.target_value}- direction={goal.metric_direction}- width={520}- height={76}- />- ) : (- <div className="flex h-[76px] w-full items-center justify-center text-center text-[11.5px] leading-relaxed text-[hsl(var(--notfair-ink-4))]">- {metricReady- ? "Trend appears after the next reading"- : goal.statement}- </div>- )}- </div>-- <div className="mt-4 flex items-center justify-between gap-3 font-mono text-[10.5px] text-[hsl(var(--notfair-ink-4))]">- <span>- {goal.tick_count} check{goal.tick_count === 1 ? "" : "s"} · {timeAgo(goal.updated_at)}- </span>- <ArrowUpRight className="size-3.5 shrink-0 transition-transform group-hover:-translate-y-0.5 group-hover:translate-x-0.5" />- </div>-- {TERMINAL.includes(goal.status) && goal.status_reason && (- <span className="sr-only">{goal.status_reason}</span>- )}- </Link>- );-}diff --git a/notfair/src/components/harness-footer.test.tsx b/notfair/src/components/harness-footer.test.tsxdeleted file mode 100644index d40364ec..00000000--- a/notfair/src/components/harness-footer.test.tsx+++ /dev/null@@ -1,96 +0,0 @@-// @vitest-environment jsdom-import { beforeEach, describe, expect, it, vi } from "vitest";-import { fireEvent, render, screen, waitFor } from "@testing-library/react";--import { HarnessFooter } from "@/components/harness-footer";-import { startCodexLoginAction } from "@/server/actions/harness";--vi.mock("next/navigation", () => ({- useRouter: () => ({ refresh: vi.fn() }),-}));-vi.mock("@/server/actions/harness", () => ({- startCodexLoginAction: vi.fn(),- refreshCodexUsageAction: vi.fn(),-}));--beforeEach(() => {- vi.clearAllMocks();-});--describe("HarnessFooter Codex account state", () => {- it("shows Pro and a single weekly limit for the prolite tier", () => {- render(- <HarnessFooter- adapter="codex-local"- usage={{- kind: "codex",- auth: "chatgpt",- plan: "prolite",- email: "[email protected]",- rateLimits: [- {- label: "Weekly",- used_percent: 8,- limit_window_seconds: 604_800,- reset_at: Math.floor(Date.now() / 1000) + 86_400,- },- ],- }}- />,- );-- expect(screen.getByText("ChatGPT Pro")).toBeInTheDocument();- expect(screen.getByRole("progressbar", { name: "Weekly usage" })).toBeInTheDocument();- expect(screen.queryByText(/Sign in to Codex/)).toBeNull();- });-- it("does not call an authenticated user signed out when usage is unavailable", () => {- render(- <HarnessFooter- adapter="codex-local"- usage={{- kind: "codex",- auth: "chatgpt",- plan: "prolite",- email: "[email protected]",- rateLimits: [],- }}- />,- );-- expect(screen.getByText(/Signed in as [email protected]/)).toBeInTheDocument();- expect(screen.queryByRole("button", { name: "Sign in to Codex" })).toBeNull();- });-- it("offers a working manual sign-in action only when the CLI is actually signed out", async () => {- vi.mocked(startCodexLoginAction).mockResolvedValue({- ok: true,- alreadySignedIn: false,- });- render(- <HarnessFooter- adapter="codex-local"- usage={{- kind: "codex",- auth: "signed-out",- plan: null,- email: null,- rateLimits: [],- }}- />,- );-- expect(screen.getByText("Codex is signed out")).toBeInTheDocument();- expect(- screen.getByRole("button", { name: "Sign in to Codex" }),- ).toBeInTheDocument();-- fireEvent.click(screen.getByRole("button", { name: "Sign in to Codex" }));- await waitFor(() => {- expect(startCodexLoginAction).toHaveBeenCalledOnce();- expect(- screen.getByRole("button", { name: "Waiting for sign-in…" }),- ).toBeDisabled();- });- });-});diff --git a/notfair/src/components/harness-footer.tsx b/notfair/src/components/harness-footer.tsxdeleted file mode 100644index a81a3390..00000000--- a/notfair/src/components/harness-footer.tsx+++ /dev/null@@ -1,401 +0,0 @@-"use client";--import { useEffect, useRef, useState } from "react";-import { useRouter } from "next/navigation";-import { ChevronDown } from "lucide-react";-import type {- CodexUsage,- HarnessUsage,- RateLimitWindow,-} from "@/server/harness-usage";-import {- refreshCodexUsageAction,- startCodexLoginAction,-} from "@/server/actions/harness";--type Props = {- adapter: "claude-code-local" | "codex-local";- usage: HarnessUsage;-};--const HARNESS_LABEL: Record<Props["adapter"], string> = {- "codex-local": "Codex",- "claude-code-local": "Claude Code",-};--// localStorage key — single bool. Default = expanded (we want users to-// see their usage at a glance on first install; collapsing is a-// per-user preference for once they've internalised the pattern).-const COLLAPSE_KEY = "NotFair:harness-footer:collapsed";--/**- * Sidebar footer summary of the active harness. The header row (dot,- * harness name, plan chip, chevron) is always visible and acts as the- * collapse toggle; the detail section below — usage bars for Codex,- * activity counts for Claude Code — hides when the user collapses.- *- * State is persisted in localStorage so the choice survives page- * reloads. Default is expanded.- */-export function HarnessFooter({ adapter, usage }: Props) {- const router = useRouter();- const harnessName = HARNESS_LABEL[adapter];- const [currentUsage, setCurrentUsage] = useState(usage);- const [signingIn, setSigningIn] = useState(false);- const [signInError, setSignInError] = useState<string | null>(null);- const pollingRef = useRef(false);- // Default to expanded; hydrate from localStorage after mount so SSR- // and first paint stay deterministic.- const [collapsed, setCollapsed] = useState(false);- const [hydrated, setHydrated] = useState(false);-- useEffect(() => {- try {- const raw = window.localStorage.getItem(COLLAPSE_KEY);- if (raw === "1") setCollapsed(true);- } catch {- // localStorage unavailable — keep the default.- }- setHydrated(true);- }, []);-- useEffect(() => {- if (!hydrated) return;- try {- if (collapsed) window.localStorage.setItem(COLLAPSE_KEY, "1");- else window.localStorage.removeItem(COLLAPSE_KEY);- } catch {- // Storage write failure is non-fatal.- }- }, [collapsed, hydrated]);-- useEffect(() => setCurrentUsage(usage), [usage]);-- useEffect(() => {- if (!signingIn) return;- let attempts = 0;- const id = window.setInterval(async () => {- if (pollingRef.current) return;- pollingRef.current = true;- try {- const next = await refreshCodexUsageAction();- setCurrentUsage(next);- attempts += 1;- if (- next.kind === "codex" &&- next.auth !== "signed-out" &&- next.auth !== "unknown"- ) {- setSigningIn(false);- setSignInError(null);- router.refresh();- } else if (attempts >= 60) {- setSigningIn(false);- setSignInError("Sign-in was not completed. Try again when ready.");- }- } catch (err) {- attempts += 1;- if (attempts >= 60) {- setSigningIn(false);- setSignInError(- err instanceof Error- ? err.message- : "Couldn’t refresh Codex sign-in status.",- );- }- } finally {- pollingRef.current = false;- }- }, 2_000);- return () => window.clearInterval(id);- }, [router, signingIn]);-- if (currentUsage.kind === "codex") {- const planLabel = formatPlan(currentUsage.plan);- const signedIn =- currentUsage.auth !== "signed-out" && currentUsage.auth !== "unknown";- return (- <FooterShell>- <FooterHeader- harness={harnessName}- chip={codexChip(currentUsage, planLabel)}- chipTone={signedIn ? "accent" : "neutral"}- collapsed={collapsed}- onToggle={() => setCollapsed((v) => !v)}- />- {!collapsed &&- (currentUsage.rateLimits.length > 0 ? (- <div className="mt-2 space-y-2">- {currentUsage.rateLimits.map((window) => (- <UsageBar- key={`${window.label}:${window.limit_window_seconds}`}- label={window.label}- window={window}- />- ))}- </div>- ) : currentUsage.auth === "signed-out" ? (- <div className="mt-1.5 space-y-1.5">- <FooterDetail>Codex is signed out</FooterDetail>- <button- type="button"- disabled={signingIn}- onClick={async () => {- setSignInError(null);- const result = await startCodexLoginAction();- if (!result.ok) {- setSignInError(result.error);- return;- }- setSigningIn(true);- }}- className="ns-btn ns-btn-outline ns-btn-sm w-full justify-center disabled:opacity-60"- >- {signingIn ? "Waiting for sign-in…" : "Sign in to Codex"}- </button>- {signInError && <FooterError>{signInError}</FooterError>}- </div>- ) : (- <FooterDetail>{codexSignedInDetail(currentUsage)}</FooterDetail>- ))}- </FooterShell>- );- }-- if (currentUsage.kind === "claude-code") {- const detail = currentUsage.stale- ? lastSeenLabel(currentUsage.lastComputedDate)- : `${formatCount(currentUsage.messagesToday)} msg · ${formatTokens(- currentUsage.tokensToday,- )} today`;- return (- <FooterShell>- <FooterHeader- harness={harnessName}- chip={currentUsage.stale ? "Idle" : "Active today"}- chipTone={currentUsage.stale ? "neutral" : "accent"}- collapsed={collapsed}- onToggle={() => setCollapsed((v) => !v)}- />- {!collapsed && detail && <FooterDetail>{detail}</FooterDetail>}- </FooterShell>- );- }-- // Unknown harness — nothing collapsible, just a tiny chip.- return (- <FooterShell>- <FooterHeader- harness={harnessName}- chip={null}- collapsed={false}- onToggle={null}- />- </FooterShell>- );-}--function FooterShell({ children }: { children: React.ReactNode }) {- return (- <div className="flex flex-col px-1 py-1.5 leading-tight">{children}</div>- );-}--function FooterHeader({- harness,- chip,- chipTone = "neutral",- collapsed,- onToggle,-}: {- harness: string;- chip: string | null;- chipTone?: "accent" | "neutral";- collapsed: boolean;- onToggle: (() => void) | null;-}) {- const body = (- <>- <span- aria-hidden- className={`ns-dot ${chipTone === "accent" ? "ns-dot-on" : "ns-dot-mute"}`}- />- <span className="text-[12px] font-medium tracking-tight text-[hsl(var(--notfair-ink-2))]">- {harness}- </span>- {chip && (- <span className="ml-auto truncate text-[11px] font-medium text-[hsl(var(--notfair-ink-4))]">- {chip}- </span>- )}- {onToggle && (- <ChevronDown- aria-hidden- className={`size-3 shrink-0 text-[hsl(var(--notfair-ink-4))] transition-transform duration-150 ${- collapsed ? "-rotate-90" : ""- } ${chip ? "ml-1" : "ml-auto"}`}- />- )}- </>- );-- if (!onToggle) {- return <div className="flex items-center gap-1.5">{body}</div>;- }-- return (- <button- type="button"- onClick={onToggle}- aria-expanded={!collapsed}- aria-label={collapsed ? "Show harness usage" : "Hide harness usage"}- className="-mx-1 flex w-[calc(100%+0.5rem)] items-center gap-1.5 rounded-md px-1 py-0.5 transition-colors hover:bg-[hsl(var(--notfair-surface-2))]"- >- {body}- </button>- );-}--function FooterDetail({ children }: { children: React.ReactNode }) {- return (- <p className="m-0 mt-1 truncate text-[11px] tabular-nums text-[hsl(var(--notfair-ink-4))]">- {children}- </p>- );-}--function FooterError({ children }: { children: React.ReactNode }) {- return (- <p className="m-0 text-[10.5px] leading-snug text-destructive">{children}</p>- );-}--function codexChip(usage: CodexUsage, planLabel: string | null): string | null {- if (planLabel) return `ChatGPT ${planLabel}`;- if (usage.auth === "api-key") return "API key";- if (usage.auth === "agent-identity") return "Access token";- if (usage.auth === "chatgpt") return "ChatGPT";- return null;-}--function codexSignedInDetail(usage: CodexUsage): string {- if (usage.auth === "api-key") return "Signed in · usage billed by API";- if (usage.auth === "agent-identity") return "Signed in with access token";- if (usage.auth === "chatgpt") {- return usage.email- ? `Signed in as ${usage.email} · usage unavailable`- : "Signed in · usage limits unavailable";- }- return "Couldn’t check Codex sign-in";-}--/**- * Usage bar — label + remaining percent + thin progress track + reset- * timestamp. Mirrors the ChatGPT settings page bars but compact enough- * to fit a 240px sidebar.- */-function UsageBar({- label,- window,-}: {- label: string;- window: RateLimitWindow;-}) {- const used = clamp(window.used_percent, 0, 100);- const remaining = 100 - used;- // Bar color signals headroom. Brand green when comfortable, amber- // approaching the limit, red when about to hit it.- const tone =- remaining < 5- ? "bg-[hsl(0_72%_51%)]"- : remaining < 20- ? "bg-[hsl(38_92%_50%)]"- : "bg-[hsl(var(--notfair-accent))]";- return (- <div>- <div className="flex items-baseline justify-between gap-2">- <span className="text-[11px] font-medium text-[hsl(var(--notfair-ink-3))]">- {label}- </span>- <span className="text-[11px] tabular-nums text-[hsl(var(--notfair-ink-4))]">- {Math.round(remaining)}% left- </span>- </div>- <div- className="mt-1 h-[3px] w-full overflow-hidden rounded-full bg-[hsl(var(--notfair-surface-2))]"- role="progressbar"- aria-label={`${label} usage`}- aria-valuemin={0}- aria-valuemax={100}- aria-valuenow={Math.round(used)}- >- <div- className={`h-full rounded-full transition-[width] ${tone}`}- style={{ width: `${remaining}%` }}- />- </div>- <p className="m-0 mt-0.5 text-[10.5px] text-[hsl(var(--notfair-ink-4))]">- Resets {formatReset(window.reset_at)}- </p>- </div>- );-}--function formatPlan(slug: string | null): string | null {- if (!slug) return null;- // wham/usage returns lowercase plan slugs like "prolite", "pro",- // "free", "plus". Title-case and tidy a couple of multi-word ones.- const map: Record<string, string> = {- // `prolite` is the provider's internal slug for the lower Pro tier.- // It is still sold and presented to users as ChatGPT Pro.- prolite: "Pro",- pro: "Pro",- free: "Free",- plus: "Plus",- business: "Business",- enterprise: "Enterprise",- edu: "Edu",- };- return map[slug] ?? slug.charAt(0).toUpperCase() + slug.slice(1);-}--function formatReset(unixSeconds: number): string {- const now = Date.now();- const target = unixSeconds * 1000;- const deltaMs = target - now;- if (deltaMs <= 0) return "now";- const minutes = Math.round(deltaMs / 60_000);- if (minutes < 60) return `in ${minutes}m`;- const hours = Math.round(deltaMs / 3_600_000);- if (hours < 24) return `in ${hours}h`;- const date = new Date(target);- return date.toLocaleDateString(undefined, {- month: "short",- day: "numeric",- });-}--function formatCount(n: number): string {- if (n >= 1000) return `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}K`;- return String(n);-}--function formatTokens(n: number): string {- if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;- if (n >= 1000) return `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}K`;- return `${n}`;-}--function lastSeenLabel(iso: string | null): string {- if (!iso) return "No usage logged";- const d = new Date(`${iso}T00:00:00`);- if (Number.isNaN(d.getTime())) return "No usage logged";- return `Last seen ${d.toLocaleDateString(undefined, {- month: "short",- day: "numeric",- })}`;-}--function clamp(n: number, min: number, max: number): number {- return Math.max(min, Math.min(max, n));-}diff --git a/notfair/src/components/live-transcript.test.tsx b/notfair/src/components/live-transcript.test.tsxdeleted file mode 100644index 020a8e8c..00000000--- a/notfair/src/components/live-transcript.test.tsx+++ /dev/null@@ -1,54 +0,0 @@-// @vitest-environment jsdom-import { render, screen } from "@testing-library/react";-import { describe, expect, it, vi } from "vitest";--const stream = vi.hoisted(() => ({- events: [],- sendingChat: true,- remoteTurnActive: false,- openTurn: null,- turnStartedAt: 1_800_000_000_000,- pendingUserMsg: null,- pendingAssistant: "The answer is still streaming.",- pendingTools: [],- pendingError: null,- pendingLifecycle: null,- send: vi.fn(),- stopTurn: vi.fn(),- clearLocal: vi.fn(),-}));--vi.mock("@/components/chat/use-chat-stream", () => ({- useChatStream: () => stream,-}));--import { LiveTranscript } from "@/components/live-transcript";--describe("LiveTranscript streaming layout", () => {- it("keeps the writing status close to the streamed answer", () => {- render(- <LiveTranscript- projectSlug="project"- agentSlug="goal-1"- agentDisplayName="Growth goal"- threadId="main"- initialEvents={[]}- initialCursor={0}- />,- );-- const answerItem = screen- .getByText("The answer is still streaming.")- .closest("li");- const statusItem = screen- .getByRole("status", {- name: "Writing the response",- })- .closest("li");-- expect(answerItem?.nextElementSibling).toBe(statusItem);- expect(statusItem).toHaveAttribute("data-live-working-status");- expect(statusItem).toHaveClass("!mt-2");- expect(statusItem).not.toHaveTextContent("Growth goal");- });-});diff --git a/notfair/src/components/live-transcript.tsx b/notfair/src/components/live-transcript.tsxdeleted file mode 100644index 12f3545c..00000000--- a/notfair/src/components/live-transcript.tsx+++ /dev/null@@ -1,339 +0,0 @@-"use client";--import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";-import { toast } from "sonner";--import { ChatComposer, type ModelOption } from "@/components/chat/composer";-import { LiveWorkingIndicator } from "@/components/chat/live-working-indicator";-import {- AssistantText,- BlockedStatus,- ErrorRow,- RenderItem,- ToolGroup,- TranscriptEmptyState,- UserBubble,-} from "@/components/chat/messages";-import {- collapseEvents,- nextToolGroupKey,-} from "@/components/chat/transcript-model";-import { useChatStream } from "@/components/chat/use-chat-stream";-import type { McpCatalogEntryLite } from "@/components/chat/tool-intent";-import {- executeLocalSlashCommand,- parseSlashMessage,-} from "@/lib/slash-commands";-import type { TranscriptEvent } from "@/server/sessions/transcript-tail";--export type { McpCatalogEntryLite };--type Props = {- projectSlug: string;- agentSlug: string;- agentDisplayName: string;- /** Thread label (the URL half of the (agent, label) session key). */- threadId: string;- /** Server-rendered initial slice of the transcript. */- initialEvents: TranscriptEvent[];- /** Byte offset *after* `initialEvents` — polls start from here. */- initialCursor: number;- /** Keep a static terminal status visible after a completed turn. */- showCompletedStatus?: boolean;- /**- * Set when the agent's task is parked in `blocked` (e.g., waiting on a- * pending approval). Replaces the "thinking…" indicator — that implies- * forward motion, but a blocked task is dormant by design.- */- blockedReason?: string;- /**- * MCP servers known to this project — used to render brand favicons- * next to MCP tool calls. Optional; omitted = generic tool icons.- */- mcpCatalog?: McpCatalogEntryLite[];- /**- * Rendered at the very top of the scrollable log, above the first- * event — scrolling the history to the top reveals it.- */- leadingContent?: React.ReactNode;- /**- * Models the composer's selector offers for this project's harness.- * The option marked `is_default` names the model used when no override- * flag is sent. Omitted/empty = no selector rendered.- */- modelOptions?: ModelOption[];-};--/**- * THE chat surface: committed transcript + live streaming turn + composer.- * This component is a thin orchestrator — the streaming state machine- * lives in `chat/use-chat-stream`, the message rendering in- * `chat/messages`, the composer in `chat/composer`, and every pure- * derivation in `chat/transcript-model` / `chat/tool-intent` /- * `chat/working-view`.- */-export function LiveTranscript({- projectSlug,- agentSlug,- agentDisplayName,- threadId,- initialEvents,- initialCursor,- showCompletedStatus = false,- blockedReason,- mcpCatalog,- leadingContent,- modelOptions = [],-}: Props) {- // Composer model override. "" = harness default (no flag). Persisted- // per project+agent in localStorage; loaded after mount so SSR and the- // first client render agree (no hydration mismatch).- const modelStorageKey = `NotFair:model:${projectSlug}:${agentSlug}`;- const effortStorageKey = `NotFair:effort:${projectSlug}:${agentSlug}`;- const [model, setModel] = useState("");- const [reasoningEffort, setReasoningEffort] = useState("");- useEffect(() => {- const stored = window.localStorage.getItem(modelStorageKey);- const storedOption = modelOptions.find((m) => m.value === stored);- if (storedOption && !storedOption.is_default) {- setModel(storedOption.value);- } else if (storedOption?.is_default) {- window.localStorage.removeItem(modelStorageKey);- }- // modelOptions is a fresh array per render from the server page —- // key its identity by content to avoid effect churn.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [modelStorageKey, JSON.stringify(modelOptions)]);- const defaultModel = modelOptions.find((option) => option.is_default);- const selectedModel =- modelOptions.find((option) => option.value === model) ?? defaultModel;- useEffect(() => {- const stored = window.localStorage.getItem(effortStorageKey);- const supported = selectedModel?.reasoning_efforts ?? [];- if (- stored &&- stored !== selectedModel?.default_reasoning_effort &&- supported.some((option) => option.value === stored)- ) {- setReasoningEffort(stored);- } else {- setReasoningEffort("");- if (stored) window.localStorage.removeItem(effortStorageKey);- }- }, [effortStorageKey, selectedModel]);- function onPickModel(value: string) {- setModel(value);- if (value) window.localStorage.setItem(modelStorageKey, value);- else window.localStorage.removeItem(modelStorageKey);- }- function onPickReasoningEffort(value: string) {- setReasoningEffort(value);- if (value) window.localStorage.setItem(effortStorageKey, value);- else window.localStorage.removeItem(effortStorageKey);- }- const defaultModelLabel =- modelOptions.find((option) => option.is_default)?.label ?? "Default";- const selectedModelLabel =- modelOptions.find((option) => option.value === model)?.label ??- defaultModelLabel;-- const stream = useChatStream({- projectSlug,- agentSlug,- threadId,- initialEvents,- initialCursor,- model,- reasoningEffort,- });- const {- events,- sendingChat,- remoteTurnActive,- openTurn,- turnStartedAt,- pendingUserMsg,- pendingAssistant,- pendingTools,- pendingError,- pendingLifecycle,- } = stream;- const composerBusy = sendingChat || remoteTurnActive;-- // ── Submit routing: local slash commands intercept before the wire. ──- async function onSubmit(text: string) {- const parsed = parseSlashMessage(text);- if (parsed) {- const action = executeLocalSlashCommand(parsed.command, parsed.args);- if (action) {- switch (action.kind) {- case "clear":- stream.clearLocal();- toast.info(- "Local view cleared. Full transcript is still on disk; the next agent reply will repopulate.",- );- return;- case "stop":- stream.stopTurn();- return;- case "set-model": {- const wanted = action.value.toLowerCase();- const names = [- ...(defaultModel ? [] : ["Default"]),- ...modelOptions.map((m) => m.label),- ].join(", ");- if (!wanted) {- toast.message("Model", {- description: `Current: ${selectedModelLabel}. Options: ${names}.`,- });- return;- }- if (wanted === "default") {- onPickModel("");- toast.success(`Model reset to ${defaultModelLabel}.`);- return;- }- const match = modelOptions.find(- (m) =>- m.value.toLowerCase() === wanted ||- m.label.toLowerCase() === wanted,- );- if (!match) {- toast.error(`Unknown model '${action.value}'. Options: ${names}.`);- return;- }- onPickModel(match.value);- toast.success(`Model set to ${match.label}.`);- return;- }- case "help":- toast.message("Slash commands", { description: action.content });- return;- }- }- }- const result = await stream.send(text);- if (result?.error) toast.error(result.error);- }-- // ── Auto-scroll: only when the user is already near the bottom. ─────- const scrollRef = useRef<HTMLDivElement>(null);- const stickyBottomRef = useRef(true);- function onScroll() {- const el = scrollRef.current;- if (!el) return;- const remaining = el.scrollHeight - (el.scrollTop + el.clientHeight);- stickyBottomRef.current = remaining < 96;- }- useLayoutEffect(() => {- if (!stickyBottomRef.current) return;- const el = scrollRef.current;- if (!el) return;- el.scrollTop = el.scrollHeight;- }, [events, sendingChat, pendingAssistant, pendingTools, pendingUserMsg]);-- const rendered = useMemo(() => collapseEvents(events), [events]);- const transcriptEnded = events.some(- (e) => e.kind === "lifecycle" && e.phase === "done",- );- // Keep the indicator at the bottom of the transcript throughout a live- // turn. Completed check conversations retain a static terminal status.- const showThinking =- sendingChat ||- remoteTurnActive ||- Boolean(blockedReason) ||- (showCompletedStatus && transcriptEnded);-- return (- <div className="flex h-full flex-col">- <div- ref={scrollRef}- onScroll={onScroll}- className="min-h-0 flex-1 overflow-y-auto"- role="log"- aria-live="polite"- >- <div className="mx-auto w-full max-w-3xl px-5 py-6 sm:px-6">- {leadingContent}- {rendered.length === 0 &&- !pendingUserMsg &&- !sendingChat &&- !blockedReason ? (- <TranscriptEmptyState agentDisplayName={agentDisplayName} />- ) : (- <ol className="m-0 list-none space-y-6 p-0">- {rendered.map((item) => (- <li key={item.key}>- <RenderItem item={item} mcpCatalog={mcpCatalog} />- </li>- ))}- {pendingUserMsg && (- <li>- <UserBubble body={pendingUserMsg} />- </li>- )}- {pendingTools.length > 0 && (- <li key={nextToolGroupKey(rendered, pendingTools[0]!.toolCallId)}>- <ToolGroup tools={pendingTools} mcpCatalog={mcpCatalog} />- </li>- )}- {pendingAssistant && (- <li>- <AssistantText body={pendingAssistant} />- </li>- )}- {pendingError && (- <li>- <ErrorRow- agentDisplayName={agentDisplayName}- body={pendingError}- />- </li>- )}- {showThinking && (- <li- data-live-working-status- className={pendingAssistant ? "!mt-2" : undefined}- >- {blockedReason ? (- <BlockedStatus reason={blockedReason} />- ) : (- <LiveWorkingIndicator- agentDisplayName={agentDisplayName}- events={events}- turnStartedAt={turnStartedAt ?? openTurn?.startedAt ?? null}- lifecyclePhase={pendingLifecycle}- pendingTools={pendingTools}- hasPendingAssistant={pendingAssistant.length > 0}- />- )}- </li>- )}- </ol>- )}- </div>- </div>-- <div className="bg-gradient-to-t from-background via-background/95 to-transparent pt-2">- <div className="mx-auto w-full max-w-3xl px-5 pb-3 sm:px-6">- <ChatComposer- busy={composerBusy}- sendingChat={sendingChat}- placeholder={- blockedReason- ? "Reply — the agent will see your message"- : "Message this goal's agent… (type / for commands)"- }- modelOptions={modelOptions}- model={model}- reasoningEffort={reasoningEffort}- onPickModel={onPickModel}- onPickReasoningEffort={onPickReasoningEffort}- onSubmit={(text) => void onSubmit(text)}- onStop={stream.stopTurn}- />- </div>- </div>- </div>- );-}diff --git a/notfair/src/components/markdown.test.tsx b/notfair/src/components/markdown.test.tsxdeleted file mode 100644index 437701bd..00000000--- a/notfair/src/components/markdown.test.tsx+++ /dev/null@@ -1,73 +0,0 @@-// @vitest-environment jsdom-import { describe, expect, it } from "vitest";-import { render, screen } from "@testing-library/react";--import { Markdown } from "@/components/markdown";--describe("Markdown", () => {- it("renders headings, lists, and emphasis", () => {- render(- <Markdown>- {"# Title\n## Section\n### Sub\n#### Deep\n\n- one\n- two\n\n1. first\n2. second\n\n**bold** and *italic*"}- </Markdown>,- );- expect(screen.getByRole("heading", { level: 1, name: "Title" })).toBeInTheDocument();- expect(screen.getByRole("heading", { level: 2, name: "Section" })).toBeInTheDocument();- expect(screen.getByRole("heading", { level: 3, name: "Sub" })).toBeInTheDocument();- expect(screen.getByRole("heading", { level: 4, name: "Deep" })).toBeInTheDocument();- expect(screen.getAllByRole("list")).toHaveLength(2);- expect(screen.getAllByRole("listitem")).toHaveLength(4);- expect(screen.getByText("bold").tagName).toBe("STRONG");- expect(screen.getByText("italic").tagName).toBe("EM");- });-- it("opens links in a new tab with safe rel", () => {- render(<Markdown>{"[NotFair](https://notfair.co)"}</Markdown>);- const link = screen.getByRole("link", { name: "NotFair" });- expect(link).toHaveAttribute("href", "https://notfair.co");- expect(link).toHaveAttribute("target", "_blank");- expect(link).toHaveAttribute("rel", "noopener noreferrer");- });-- it("distinguishes inline code from fenced blocks", () => {- const { container } = render(- <Markdown>{"Use `pnpm test` here.\n\n```json\n{\"ok\":true}\n```"}</Markdown>,- );- const inline = screen.getByText("pnpm test");- expect(inline.tagName).toBe("CODE");- expect(inline.className).toContain("bg-muted");-- const pre = container.querySelector("pre");- expect(pre).not.toBeNull();- const fenced = pre!.querySelector("code")!;- expect(fenced.className).toContain("language-json");- expect(fenced.textContent).toContain('{"ok":true}');- });-- it("renders GFM tables inside a horizontal scroll container", () => {- const { container } = render(- <Markdown>{"| Col A | Col B |\n| --- | --- |\n| a1 | b1 |"}</Markdown>,- );- expect(screen.getByRole("table")).toBeInTheDocument();- expect(screen.getByRole("columnheader", { name: "Col A" })).toBeInTheDocument();- expect(screen.getByRole("cell", { name: "b1" })).toBeInTheDocument();- expect(container.querySelector(".overflow-x-auto table")).not.toBeNull();- });-- it("renders blockquotes and horizontal rules", () => {- const { container } = render(- <Markdown>{"> quoted advice\n\n---\n\nafter the rule"}</Markdown>,- );- expect(container.querySelector("blockquote")).toHaveTextContent(- "quoted advice",- );- expect(container.querySelector("hr")).not.toBeNull();- expect(screen.getByText("after the rule")).toBeInTheDocument();- });-- it("does not render raw HTML", () => {- render(<Markdown>{'<script>alert("x")</script> plain text'}</Markdown>);- expect(document.querySelector("script")).toBeNull();- expect(screen.getByText(/plain text/)).toBeInTheDocument();- });-});diff --git a/notfair/src/components/markdown.tsx b/notfair/src/components/markdown.tsxdeleted file mode 100644index fb7171ff..00000000--- a/notfair/src/components/markdown.tsx+++ /dev/null@@ -1,133 +0,0 @@-"use client";--import { memo } from "react";-import ReactMarkdown, { type Components } from "react-markdown";-import remarkGfm from "remark-gfm";-import { cn } from "@/lib/utils";--/**- * Renders an agent message as markdown. Tailored to the streaming chat- * surface: rules favor compact layout, monospace for code/JSON, and- * safe link behavior. Anything react-markdown doesn't know about falls- * back to plain text — we deliberately don't enable raw HTML.- *- * Memoized because the chat re-renders the whole transcript on every- * stream tick; bailing out of re-parsing unchanged messages keeps long- * threads from regressing under heavy streaming.- */--const COMPONENTS: Components = {- p: ({ className, ...props }) => (- <p className={cn("mb-3 last:mb-0 leading-relaxed", className)} {...props} />- ),- ul: ({ className, ...props }) => (- <ul className={cn("mb-3 list-disc space-y-1 pl-5 last:mb-0", className)} {...props} />- ),- ol: ({ className, ...props }) => (- <ol className={cn("mb-3 list-decimal space-y-1 pl-5 last:mb-0", className)} {...props} />- ),- li: ({ className, ...props }) => (- <li className={cn("leading-relaxed", className)} {...props} />- ),- h1: ({ className, ...props }) => (- <h1 className={cn("mb-2 mt-4 text-base font-semibold first:mt-0", className)} {...props} />- ),- h2: ({ className, ...props }) => (- <h2 className={cn("mb-2 mt-4 text-base font-semibold first:mt-0", className)} {...props} />- ),- h3: ({ className, ...props }) => (- <h3 className={cn("mb-2 mt-3 text-sm font-semibold first:mt-0", className)} {...props} />- ),- h4: ({ className, ...props }) => (- <h4 className={cn("mb-1 mt-3 text-sm font-semibold first:mt-0", className)} {...props} />- ),- strong: ({ className, ...props }) => (- <strong className={cn("font-semibold text-foreground", className)} {...props} />- ),- em: ({ className, ...props }) => (- <em className={cn("italic", className)} {...props} />- ),- a: ({ className, href, ...props }) => (- <a- className={cn("font-medium text-foreground underline underline-offset-2 hover:opacity-80", className)}- href={href}- target="_blank"- rel="noopener noreferrer"- {...props}- />- ),- blockquote: ({ className, ...props }) => (- <blockquote- className={cn("mb-3 border-l-2 border-muted-foreground/30 pl-3 text-muted-foreground last:mb-0", className)}- {...props}- />- ),- hr: ({ className, ...props }) => (- <hr className={cn("my-4 border-border", className)} {...props} />- ),- table: ({ className, ...props }) => (- <div className="mb-3 w-full overflow-x-auto last:mb-0">- <table className={cn("min-w-full border-collapse text-xs", className)} {...props} />- </div>- ),- th: ({ className, ...props }) => (- <th- className={cn("bg-[hsl(var(--notfair-surface-2))] px-2 py-1.5 text-left font-medium first:rounded-l-md last:rounded-r-md", className)}- {...props}- />- ),- td: ({ className, ...props }) => (- <td className={cn("px-2 py-1.5 align-top", className)} {...props} />- ),- code: ({ className, children, ...props }) => {- // react-markdown emits both inline and fenced `code`. Inline gets no- // language hint and no surrounding `<pre>`. Fenced gets a language hint- // ("language-json"). We distinguish by checking the language class.- const isFenced = typeof className === "string" && className.startsWith("language-");- if (isFenced) {- // Render as plain inner; <pre> below provides the block container.- return (- <code className={cn("font-mono text-[12px] leading-relaxed", className)} {...props}>- {children}- </code>- );- }- return (- <code- className={cn(- "rounded bg-muted px-1 py-0.5 font-mono text-[0.9em] text-foreground",- className,- )}- {...props}- >- {children}- </code>- );- },- pre: ({ className, ...props }) => (- <pre- className={cn(- "mb-3 max-w-full overflow-x-auto rounded-md bg-muted/60 p-3 last:mb-0",- className,- )}- {...props}- />- ),-};--function MarkdownBase({ children, className }: { children: string; className?: string }) {- return (- <div- className={cn(- "text-sm leading-relaxed text-foreground break-words [&>:first-child]:mt-0",- className,- )}- >- <ReactMarkdown remarkPlugins={[remarkGfm]} components={COMPONENTS}>- {children}- </ReactMarkdown>- </div>- );-}--export const Markdown = memo(MarkdownBase);diff --git a/notfair/src/components/mcp-account-picker-dialog.test.tsx b/notfair/src/components/mcp-account-picker-dialog.test.tsxdeleted file mode 100644index 295e83d1..00000000--- a/notfair/src/components/mcp-account-picker-dialog.test.tsx+++ /dev/null@@ -1,151 +0,0 @@-// @vitest-environment jsdom-import { beforeEach, describe, expect, it, vi } from "vitest";-import { render, screen, waitFor, fireEvent } from "@testing-library/react";--import { McpAccountPickerDialog } from "@/components/mcp-account-picker-dialog";-import {- listGscProperties,- setOnboardingGscPropertyAction,-} from "@/server/onboarding/accounts";--vi.mock("@/server/onboarding/accounts", () => ({- listGoogleAdsAccounts: vi.fn(),- setOnboardingAccountAction: vi.fn(),- listMetaAdsAccounts: vi.fn(),- setOnboardingMetaAdsAccountAction: vi.fn(),- listGscProperties: vi.fn(),- setOnboardingGscPropertyAction: vi.fn(),-}));--const GSC = "notfair-googlesearchconsole";--function renderDialog(- props: Partial<React.ComponentProps<typeof McpAccountPickerDialog>> = {},-) {- const onOpenChange = vi.fn();- const onPicked = vi.fn();- const utils = render(- <McpAccountPickerDialog- projectSlug="proj"- mcpKey={GSC}- selectedId={null}- open- onOpenChange={onOpenChange}- onPicked={onPicked}- {...props}- />,- );- return { ...utils, onOpenChange, onPicked };-}--beforeEach(() => {- vi.clearAllMocks();-});--describe("McpAccountPickerDialog", () => {- it("renders prefetched items without calling the list action", async () => {- renderDialog({- prefetch: {- ok: true,- items: [- { id: "sc-domain:a.com", name: "a.com" },- { id: "sc-domain:b.com", name: "b.com" },- ],- },- });- expect(- await screen.findByRole("button", { name: /Use a\.com/ }),- ).toBeInTheDocument();- expect(screen.queryByText("default")).not.toBeInTheDocument();- expect(listGscProperties).not.toHaveBeenCalled();- });-- it("marks the persisted selection as current", async () => {- renderDialog({- selectedId: "sc-domain:b.com",- prefetch: {- ok: true,- items: [- { id: "sc-domain:a.com", name: "a.com" },- { id: "sc-domain:b.com", name: "b.com" },- ],- },- });- expect(await screen.findByText("current")).toBeInTheDocument();- });-- it("shows a prefetched error with no retry fetch on mount", async () => {- renderDialog({ prefetch: { ok: false, error: "HTTP 502" } });- expect(await screen.findByRole("alert")).toHaveTextContent("HTTP 502");- expect(listGscProperties).not.toHaveBeenCalled();- });-- it("fetches from the MCP when opened without a prefetch (manual open)", async () => {- vi.mocked(listGscProperties).mockResolvedValue({- ok: true,- properties: [{ id: "sc-domain:a.com", name: "a.com" }],- });- renderDialog();- expect(- await screen.findByRole("button", { name: /Use a\.com/ }),- ).toBeInTheDocument();- expect(listGscProperties).toHaveBeenCalledWith("proj");- });-- it("shows the empty state when the bearer reaches nothing", async () => {- vi.mocked(listGscProperties).mockResolvedValue({- ok: true,- properties: [],- });- renderDialog();- expect(- await screen.findByText(/no Search Console property/i),- ).toBeInTheDocument();- });-- it("persists a pick, then notifies and closes", async () => {- vi.mocked(setOnboardingGscPropertyAction).mockResolvedValue({- ok: true,- project: {} as never,- });- const { onOpenChange, onPicked } = renderDialog({- prefetch: {- ok: true,- items: [{ id: "sc-domain:a.com", name: "a.com" }],- },- });- fireEvent.click(await screen.findByRole("button", { name: /Use a\.com/ }));- await waitFor(() => {- expect(setOnboardingGscPropertyAction).toHaveBeenCalledWith(- "proj",- "sc-domain:a.com",- );- expect(onPicked).toHaveBeenCalled();- expect(onOpenChange).toHaveBeenCalledWith(false);- });- });-- it("stays open and does not notify when persisting fails", async () => {- vi.mocked(setOnboardingGscPropertyAction).mockResolvedValue({- ok: false,- error: "not reachable",- });- const { onOpenChange, onPicked } = renderDialog({- prefetch: {- ok: true,- items: [{ id: "sc-domain:a.com", name: "a.com" }],- },- });- fireEvent.click(await screen.findByRole("button", { name: /Use a\.com/ }));- await waitFor(() =>- expect(setOnboardingGscPropertyAction).toHaveBeenCalled(),- );- expect(onPicked).not.toHaveBeenCalled();- expect(onOpenChange).not.toHaveBeenCalledWith(false);- });-- it("renders nothing for MCPs without a picker", () => {- const { container } = renderDialog({ mcpKey: "notfair-xads" });- expect(container).toBeEmptyDOMElement();- });-});\ No newline at end of filediff --git a/notfair/src/components/mcp-account-picker-dialog.tsx b/notfair/src/components/mcp-account-picker-dialog.tsxdeleted file mode 100644index 974d4080..00000000--- a/notfair/src/components/mcp-account-picker-dialog.tsx+++ /dev/null@@ -1,228 +0,0 @@-"use client";--import { useEffect, useRef, useState } from "react";-import { AlertCircle, ChevronRight, Loader2 } from "lucide-react";-import { toast } from "sonner";--import {- Dialog,- DialogContent,- DialogDescription,- DialogHeader,- DialogTitle,-} from "@/components/ui/dialog";-import { cn } from "@/lib/utils";-import {- accountPickerFor,- type AccountPickerItem,-} from "@/lib/mcp-account-pickers";--/**- * Result of the server-side list prefetch the Connections page runs when- * a multi-account MCP just finished OAuth (`?mcp_key=`). Passing data in- * (instead of fetching on mount) matters: a mount-time server-action call- * races the flash banner's URL-cleanup navigation, which can strand the- * action's promise and leave the dialog stuck on "loading".- */-export type AccountPickerPrefetch =- | { ok: true; items: AccountPickerItem[] }- | { ok: false; error: string };--type Phase =- | { phase: "loading" }- | { phase: "error"; message: string }- | { phase: "empty" }- | { phase: "list"; items: AccountPickerItem[] };--/**- * Account/property picker for multi-account MCPs (Google Ads, Meta Ads,- * Search Console) on the Connections page. Opens automatically right- * after OAuth when the bearer offers a real choice (fed by `prefetch`),- * and manually from the card's "Choose …" / "Change …" affordances- * (fetches on open — no navigation in flight then).- *- * Persisting goes through the same validated server actions onboarding- * uses, so the choice lands on the `projects` row goal agents read.- */-export function McpAccountPickerDialog({- projectSlug,- mcpKey,- selectedId,- open,- prefetch,- onOpenChange,- onPicked,-}: {- projectSlug: string;- mcpKey: string;- /** Currently persisted selection on the project row, if any. */- selectedId: string | null;- open: boolean;- /** Server-prefetched list for the post-OAuth auto-open; consumed once. */- prefetch?: AccountPickerPrefetch | null;- onOpenChange: (open: boolean) => void;- /** Fired after a selection was persisted. */- onPicked: () => void;-}) {- const picker = accountPickerFor(mcpKey);- const [state, setState] = useState<Phase>({ phase: "loading" });- const [pickingId, setPickingId] = useState<string | null>(null);- // The prefetch belongs to the auto-open right after OAuth. Later manual- // opens re-fetch so the list (and any transient error) is fresh.- const prefetchConsumedRef = useRef(false);-- useEffect(() => {- if (!open || !picker) return;- setPickingId(null);- if (prefetch && !prefetchConsumedRef.current) {- prefetchConsumedRef.current = true;- setState(- !prefetch.ok- ? { phase: "error", message: prefetch.error }- : prefetch.items.length === 0- ? { phase: "empty" }- : { phase: "list", items: prefetch.items },- );- return;- }- setState({ phase: "loading" });- let cancelled = false;- (async () => {- const r = await picker.list(projectSlug);- if (cancelled) return;- if (!r.ok) {- setState({ phase: "error", message: r.error });- return;- }- setState(- r.items.length === 0- ? { phase: "empty" }- : { phase: "list", items: r.items },- );- })();- return () => {- cancelled = true;- };- // Reload only when the dialog (re)opens or targets a different MCP —- // parent re-renders must not refetch mid-flight.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [open, mcpKey, projectSlug]);-- if (!picker) return null;-- async function onPick(item: AccountPickerItem) {- if (!picker) return;- setPickingId(item.id);- try {- const r = await picker.set(projectSlug, item.id);- if (!r.ok) {- toast.error(r.error);- setPickingId(null);- return;- }- toast.success(`${picker.noun} set: ${item.name}`);- onPicked();- onOpenChange(false);- } catch (err) {- toast.error(err instanceof Error ? err.message : String(err));- setPickingId(null);- }- }-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent className="sm:max-w-md">- <DialogHeader>- <DialogTitle>Which {picker.noun}?</DialogTitle>- <DialogDescription>- This workspace’s goal agents operate on exactly one — pick- it here. You can change it any time from this card.- </DialogDescription>- </DialogHeader>-- {state.phase === "loading" && (- <div className="flex items-center gap-3 py-4 text-sm text-muted-foreground">- <Loader2 className="size-4 animate-spin" aria-hidden />- <span>Loading from the MCP…</span>- </div>- )}-- {state.phase === "error" && (- <div role="alert" className="space-y-2 py-2">- <div className="flex items-center gap-2 text-sm font-medium">- <AlertCircle- className="size-4 text-[hsl(var(--notfair-warn))]"- aria-hidden- />- <span>Couldn’t load the list.</span>- </div>- <p className="text-xs text-muted-foreground">{state.message}</p>- </div>- )}-- {state.phase === "empty" && (- <p className="py-2 text-sm text-muted-foreground">- The connected user has no {picker.noun} the token can reach. Try- reconnecting with a different account.- </p>- )}-- {state.phase === "list" && (- <ul className="max-h-80 space-y-2 overflow-y-auto list-none p-0">- {state.items.map((item) => {- const isSelected = item.id === selectedId;- const isPicking = pickingId === item.id;- const isOtherPicking = pickingId !== null && !isPicking;- return (- <li key={item.id}>- <button- type="button"- onClick={() => onPick(item)}- disabled={pickingId !== null}- aria-label={`Use ${item.name} (${item.id})`}- className={cn(- // Elevation over borders, per the design system: an- // inset surface + soft shadow reads as a card without- // drawing an outline.- "block w-full rounded-[10px] bg-[hsl(var(--notfair-surface-2)/0.5)] p-3 text-left shadow-[var(--notfair-shadow-sm)] transition-colors hover:bg-[hsl(var(--notfair-surface-2))] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-foreground/30 disabled:cursor-not-allowed",- isOtherPicking && "opacity-50",- )}- >- <div className="flex items-center justify-between gap-3">- <div className="min-w-0 flex-1">- <div className="flex items-center gap-2">- <span className="truncate text-sm font-medium">- {item.name}- </span>- {isSelected && (- <span className="ns-tag-accent rounded px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide">- current- </span>- )}- </div>- <p className="truncate text-xs text-muted-foreground tabular-nums">- {picker.id_label} {item.id}- </p>- </div>- {isPicking ? (- <Loader2- className="size-4 shrink-0 animate-spin text-muted-foreground"- aria-hidden- />- ) : (- <ChevronRight- className="size-4 shrink-0 text-muted-foreground"- aria-hidden- />- )}- </div>- </button>- </li>- );- })}- </ul>- )}- </DialogContent>- </Dialog>- );-}diff --git a/notfair/src/components/mcp-card.more.test.tsx b/notfair/src/components/mcp-card.more.test.tsxdeleted file mode 100644index 73db91af..00000000--- a/notfair/src/components/mcp-card.more.test.tsx+++ /dev/null@@ -1,216 +0,0 @@-// @vitest-environment jsdom-import { beforeEach, describe, expect, it, vi } from "vitest";-import { fireEvent, render, screen, waitFor } from "@testing-library/react";--import { McpCard } from "@/components/mcp-card";-import type { McpSpec } from "@/server/mcp-catalog";-import type { McpRuntimeStatus } from "@/server/mcp/state";--// Mock at the server-action boundary, per repo test conventions.-const startConnect = vi.hoisted(() => vi.fn());-const disconnect = vi.hoisted(() => vi.fn());-const listTools = vi.hoisted(() => vi.fn());-const removeServer = vi.hoisted(() => vi.fn());-vi.mock("@/server/actions/mcp", () => ({- startMcpConnect: startConnect,- disconnectMcpAction: disconnect,- listMcpToolsAction: listTools,- removeUserMcpServerAction: removeServer,-}));-vi.mock("@/server/onboarding/accounts", () => ({- listGoogleAdsAccounts: vi.fn(),- setOnboardingAccountAction: vi.fn(),- listMetaAdsAccounts: vi.fn(),- setOnboardingMetaAdsAccountAction: vi.fn(),- listGscProperties: vi.fn(),- setOnboardingGscPropertyAction: vi.fn(),-}));--const refresh = vi.hoisted(() => vi.fn());-vi.mock("next/navigation", () => ({- useRouter: () => ({ refresh, push: vi.fn(), replace: vi.fn() }),-}));--const toastSuccess = vi.hoisted(() => vi.fn());-const toastError = vi.hoisted(() => vi.fn());-vi.mock("sonner", () => ({- toast: { success: toastSuccess, error: toastError },-}));--const xadsSpec: McpSpec = {- key: "notfair-xads",- display_name: "NotFair X Ads",- description: "X Ads campaigns.",- resource_url: "https://notfair.co/api/mcp/notfair",- discovery_url:- "https://notfair.co/.well-known/oauth-protected-resource/api/mcp/notfair",- source: "preset",-};--beforeEach(() => {- vi.clearAllMocks();-});--function openOverflowMenu() {- fireEvent.keyDown(screen.getByRole("button", { name: /More options/ }), {- key: "Enter",- });-}--describe("McpCard status rendering", () => {- it("labels an expired token and offers Reconnect", () => {- render(- <McpCard- spec={xadsSpec}- status={{ state: "stale_token", http_status: 401 } as McpRuntimeStatus}- projectSlug="proj"- />,- );- expect(screen.getByText("token expired")).toBeInTheDocument();- expect(screen.getByText(/token rejected \(HTTP 401\)/)).toBeInTheDocument();- expect(screen.getByRole("button", { name: "Reconnect" })).toBeInTheDocument();- });-- it("labels an unreachable server with its error detail", () => {- render(- <McpCard- spec={xadsSpec}- status={{ state: "unreachable", error: "ECONNREFUSED" } as McpRuntimeStatus}- projectSlug="proj"- />,- );- expect(screen.getByText("unreachable")).toBeInTheDocument();- expect(screen.getByText("ECONNREFUSED")).toBeInTheDocument();- });-- it("labels a configured server that is awaiting its bearer", () => {- render(- <McpCard- spec={xadsSpec}- status={{ state: "configured_no_token" } as McpRuntimeStatus}- projectSlug="proj"- />,- );- expect(screen.getByText("no token")).toBeInTheDocument();- expect(screen.getByText("config saved, awaiting bearer")).toBeInTheDocument();- });-- it("shows just host + connected state once connected", () => {- render(- <McpCard- spec={xadsSpec}- status={{ state: "connected" } as McpRuntimeStatus}- projectSlug="proj"- />,- );- expect(screen.getByRole("status")).toHaveTextContent("connected");- expect(screen.getByText("notfair.co")).toBeInTheDocument();- // No detail after the host for a healthy connection.- expect(screen.queryByText(/·/)).toBeNull();- });-- it("falls back to the raw resource URL when it cannot be parsed", () => {- render(- <McpCard- spec={{ ...xadsSpec, resource_url: "not a url" }}- status={{ state: "not_configured" } as McpRuntimeStatus}- projectSlug="proj"- />,- );- expect(screen.getByText("not a url")).toBeInTheDocument();- expect(screen.getByText("not connected")).toBeInTheDocument();- });-});--describe("McpCard actions", () => {- it("surfaces a Connect failure as a toast and re-enables the button", async () => {- startConnect.mockResolvedValue({ ok: false, error: "no discovery" });- render(- <McpCard- spec={xadsSpec}- status={{ state: "not_configured" } as McpRuntimeStatus}- projectSlug="proj"- />,- );- fireEvent.click(screen.getByRole("button", { name: "Connect" }));- await waitFor(() => {- expect(startConnect).toHaveBeenCalledWith({- mcp_key: "notfair-xads",- return_to: window.location.pathname + window.location.search,- });- expect(toastError).toHaveBeenCalledWith("no discovery");- });- expect(screen.getByRole("button", { name: "Connect" })).toBeEnabled();- });-- it("disconnects from the overflow menu and notifies the host", async () => {- disconnect.mockResolvedValue({ ok: true });- const onMutated = vi.fn();- render(- <McpCard- spec={xadsSpec}- status={{ state: "connected" } as McpRuntimeStatus}- projectSlug="proj"- onMutated={onMutated}- />,- );- openOverflowMenu();- fireEvent.click(screen.getByRole("menuitem", { name: /disconnect/i }));- await waitFor(() => {- expect(disconnect).toHaveBeenCalledWith({ mcp_key: "notfair-xads" });- expect(toastSuccess).toHaveBeenCalledWith("NotFair X Ads disconnected");- expect(refresh).toHaveBeenCalled();- expect(onMutated).toHaveBeenCalled();- });- });-- it("keeps the row when disconnect fails, with an error toast", async () => {- disconnect.mockResolvedValue({ ok: false, error: "still in use" });- render(- <McpCard- spec={xadsSpec}- status={{ state: "connected" } as McpRuntimeStatus}- projectSlug="proj"- />,- );- openOverflowMenu();- fireEvent.click(screen.getByRole("menuitem", { name: /disconnect/i }));- await waitFor(() => expect(toastError).toHaveBeenCalledWith("still in use"));- expect(refresh).not.toHaveBeenCalled();- });-- it("removes the server from the overflow menu", async () => {- removeServer.mockResolvedValue({ ok: true });- render(- <McpCard- spec={xadsSpec}- status={{ state: "not_configured" } as McpRuntimeStatus}- projectSlug="proj"- />,- );- openOverflowMenu();- fireEvent.click(screen.getByRole("menuitem", { name: /remove server/i }));- await waitFor(() => {- expect(removeServer).toHaveBeenCalledWith({ mcp_key: "notfair-xads" });- expect(toastSuccess).toHaveBeenCalledWith("NotFair X Ads removed");- });- });-- it("opens the tools dialog from View tools, fetching via the server action", async () => {- listTools.mockResolvedValue({- ok: true,- tools: [{ name: "createAd", description: "Make an ad.", args: [] }],- });- render(- <McpCard- spec={xadsSpec}- status={{ state: "connected" } as McpRuntimeStatus}- projectSlug="proj"- />,- );- openOverflowMenu();- fireEvent.click(screen.getByRole("menuitem", { name: /view tools/i }));- expect(await screen.findByText("createAd")).toBeInTheDocument();- expect(listTools).toHaveBeenCalledWith({ mcp_key: "notfair-xads" });- });-});diff --git a/notfair/src/components/mcp-card.test.tsx b/notfair/src/components/mcp-card.test.tsxdeleted file mode 100644index 30319d1f..00000000--- a/notfair/src/components/mcp-card.test.tsx+++ /dev/null@@ -1,109 +0,0 @@-// @vitest-environment jsdom-import { beforeEach, describe, expect, it, vi } from "vitest";-import { render, screen } from "@testing-library/react";--import { McpCard } from "@/components/mcp-card";-import type { McpSpec } from "@/server/mcp-catalog";-import type { McpRuntimeStatus } from "@/server/mcp/state";--vi.mock("next/navigation", () => ({- useRouter: () => ({ refresh: vi.fn(), replace: vi.fn(), push: vi.fn() }),-}));-vi.mock("@/server/actions/mcp", () => ({- startMcpConnect: vi.fn(),- disconnectMcpAction: vi.fn(),- listMcpToolsAction: vi.fn(),- removeUserMcpServerAction: vi.fn(),-}));-vi.mock("@/server/onboarding/accounts", () => ({- listGoogleAdsAccounts: vi.fn(),- setOnboardingAccountAction: vi.fn(),- listMetaAdsAccounts: vi.fn(),- setOnboardingMetaAdsAccountAction: vi.fn(),- listGscProperties: vi.fn(),- setOnboardingGscPropertyAction: vi.fn(),-}));--const gscSpec: McpSpec = {- key: "notfair-googlesearchconsole",- display_name: "NotFair Google Search Console",- description: "Organic search performance.",- resource_url: "https://notfair.co/api/mcp/notfair",- discovery_url:- "https://notfair.co/.well-known/oauth-protected-resource/api/mcp/notfair",- source: "preset",-};--const xadsSpec: McpSpec = {- ...gscSpec,- key: "notfair-xads",- display_name: "NotFair X Ads",- resource_url: "https://notfair.co/api/mcp/notfair",-};--const connected: McpRuntimeStatus = { state: "connected" } as McpRuntimeStatus;-const notConfigured: McpRuntimeStatus = {- state: "not_configured",-} as McpRuntimeStatus;--beforeEach(() => {- vi.clearAllMocks();-});--describe("McpCard primary action per setup state", () => {- it("offers Connect when there is no token", () => {- render(- <McpCard spec={gscSpec} status={notConfigured} projectSlug="proj" />,- );- expect(screen.getByRole("button", { name: "Connect" })).toBeInTheDocument();- expect(screen.queryByText(/Choose property/)).not.toBeInTheDocument();- });-- it("offers Choose property when connected with nothing selected", () => {- render(- <McpCard- spec={gscSpec}- status={connected}- projectSlug="proj"- selectedAccountId={null}- />,- );- expect(- screen.getByRole("button", { name: "Choose property" }),- ).toBeInTheDocument();- expect(- screen.queryByRole("button", { name: "Connect" }),- ).not.toBeInTheDocument();- // Disconnect lives in the ⋯ menu now, never on the card face.- expect(- screen.queryByRole("button", { name: "Disconnect" }),- ).not.toBeInTheDocument();- });-- it("offers a quiet Switch property once configured, and shows the selection", () => {- render(- <McpCard- spec={gscSpec}- status={connected}- projectSlug="proj"- selectedAccountId="sc-domain:notfair.co"- />,- );- expect(- screen.getByRole("button", { name: "Switch property" }),- ).toBeInTheDocument();- expect(screen.getByText("sc-domain:notfair.co")).toBeInTheDocument();- expect(- screen.queryByRole("button", { name: "Choose property" }),- ).not.toBeInTheDocument();- });-- it("shows no account action for MCPs without a picker", () => {- render(<McpCard spec={xadsSpec} status={connected} projectSlug="proj" />);- expect(screen.queryByText(/Choose|Switch/)).not.toBeInTheDocument();- // The ⋯ menu is still there for Disconnect / Remove.- expect(- screen.getByRole("button", { name: /More options/ }),- ).toBeInTheDocument();- });-});\ No newline at end of filediff --git a/notfair/src/components/mcp-card.tsx b/notfair/src/components/mcp-card.tsxdeleted file mode 100644index 4bb7d0e5..00000000--- a/notfair/src/components/mcp-card.tsx+++ /dev/null@@ -1,348 +0,0 @@-"use client";--import { useEffect, useRef, useState, useTransition } from "react";-import { useRouter } from "next/navigation";-import {- Loader2,- BookOpenText,- Trash2,- MoreHorizontal,- Unplug,-} from "lucide-react";-import { toast } from "sonner";-import {- startMcpConnect,- disconnectMcpAction,- listMcpToolsAction,- removeUserMcpServerAction,-} from "@/server/actions/mcp";-import type { McpSpec } from "@/server/mcp-catalog";-import type { McpRuntimeStatus } from "@/server/mcp/state";-import { McpToolsDialog } from "@/components/mcp-tools-dialog";-import {- McpAccountPickerDialog,- type AccountPickerPrefetch,-} from "@/components/mcp-account-picker-dialog";-import { McpIcon } from "@/components/mcp-icon";-import { accountPickerFor } from "@/lib/mcp-account-pickers";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu";--type Props = {- spec: McpSpec;- status: McpRuntimeStatus;- /** Needed by the account picker's list/set server actions. */- projectSlug: string;- /**- * Persisted account/property selection for pickable MCPs (Google Ads,- * Meta Ads, Search Console) — null when unset or not pickable.- */- selectedAccountId?: string | null;- /**- * Set when this card's MCP just finished OAuth (`?mcp_key=` matches) and- * the bearer offers a real account/property choice: the page prefetched- * the list server-side, and the card auto-opens the picker with it.- */- pickerPrefetch?: AccountPickerPrefetch | null;- /**- * Fired after any mutation (disconnect, remove, account picked), on top- * of the router.refresh() the card always does. Hosts whose data comes- * from a client-side action (onboarding's connect step) pass their- * reload here; server-rendered hosts (Connections page) omit it.- */- onMutated?: () => void;-};--/**- * One row in the Connections list — Apple-style settings row with brand- * glyph, name + status, and a single primary action that tracks setup- * state: **Connect** when there's no token, **Choose account/property**- * when the token spans multiple accounts and none is picked yet, and a- * quiet **Switch account/property** once configured (the ⋯ menu holds- * Disconnect / Remove).- */-export function McpCard({- spec,- status,- projectSlug,- selectedAccountId = null,- pickerPrefetch = null,- onMutated,-}: Props) {- const [pending, startTransition] = useTransition();- const [busy, setBusy] = useState<"connect" | "disconnect" | "remove" | null>(- null,- );- const [toolsOpen, setToolsOpen] = useState(false);- const [pickerOpen, setPickerOpen] = useState(false);- const autoOpenedRef = useRef(false);- const router = useRouter();-- const picker = accountPickerFor(spec.key);- const isConnected = status.state === "connected";-- // Post-OAuth landing: open the picker exactly once with the prefetched- // list. The flash banner strips ?mcp_key from the URL right after mount,- // so the intent is captured in state before the prop disappears.- useEffect(() => {- if (!pickerPrefetch || !picker || !isConnected) return;- if (autoOpenedRef.current) return;- autoOpenedRef.current = true;- setPickerOpen(true);- }, [pickerPrefetch, picker, isConnected]);-- async function onConnect() {- setBusy("connect");- try {- const return_to = window.location.pathname + window.location.search;- const result = await startMcpConnect({ mcp_key: spec.key, return_to });- if (!result.ok) {- toast.error(result.error);- setBusy(null);- return;- }- window.location.href = result.authorize_url;- } catch (err) {- toast.error(err instanceof Error ? err.message : String(err));- setBusy(null);- }- }-- function onDisconnect() {- setBusy("disconnect");- startTransition(async () => {- const result = await disconnectMcpAction({ mcp_key: spec.key });- if (!result.ok) {- toast.error(result.error);- } else {- toast.success(`${spec.display_name} disconnected`);- router.refresh();- onMutated?.();- }- setBusy(null);- });- }-- function onRemove() {- setBusy("remove");- startTransition(async () => {- const result = await removeUserMcpServerAction({ mcp_key: spec.key });- if (!result.ok) {- toast.error(result.error);- } else {- toast.success(`${spec.display_name} removed`);- router.refresh();- onMutated?.();- }- setBusy(null);- });- }-- const isBusy = busy !== null || pending;-- return (- <>- <article className={`ns-row ${isConnected ? "is-connected" : ""}`}>- <McpIcon- resourceUrl={spec.resource_url}- alt={spec.display_name}- size="lg"- />-- <div className="ns-row-body">- <div className="ns-row-title-row">- <h3 className="ns-row-title">{spec.display_name}</h3>- <StatusLabel status={status} />- </div>- <p className="ns-row-desc line-clamp-1">{spec.description}</p>- <StatusLine status={status} resourceUrl={spec.resource_url} />- {picker && isConnected && selectedAccountId && (- <p className="mt-1.5 flex items-center gap-1.5 text-[11.5px] text-[hsl(var(--notfair-ink-4))]">- <span>{picker.noun}:</span>- <span className="ns-tag-mono">{selectedAccountId}</span>- </p>- )}- </div>-- <div className="ns-row-meta">- {/* One primary action per setup state; a fully configured row- has none — its remaining actions live in the ⋯ menu. */}- {!isConnected ? (- <button- type="button"- className="ns-btn ns-btn-primary ns-btn-sm"- disabled={isBusy}- onClick={onConnect}- >- {busy === "connect" ? (- <Loader2 className="size-3.5 animate-spin" />- ) : null}- {status.state === "stale_token" ? "Reconnect" : "Connect"}- </button>- ) : picker ? (- // Unset gets the loud primary style (setup isn't done);- // switching an already-chosen account is a quiet outline.- <button- type="button"- className={`ns-btn ns-btn-sm ${selectedAccountId ? "ns-btn-outline" : "ns-btn-primary"}`}- disabled={isBusy}- onClick={() => setPickerOpen(true)}- >- {selectedAccountId ? "Switch" : "Choose"} {picker.short_noun}- </button>- ) : null}-- <DropdownMenu>- <DropdownMenuTrigger asChild>- <button- type="button"- className="grid size-7 place-items-center rounded-md text-[hsl(var(--notfair-ink-4))] transition-colors hover:bg-[hsl(var(--notfair-surface-2))] hover:text-[hsl(var(--notfair-ink-2))]"- aria-label={`More options for ${spec.display_name}`}- >- <MoreHorizontal className="size-4" />- </button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end" className="w-44 rounded-xl p-1">- {isConnected && (- <DropdownMenuItem- onSelect={() => setToolsOpen(true)}- className="gap-2 rounded-md px-2 py-1.5 text-[13px]"- >- <BookOpenText className="size-3.5 text-muted-foreground" />- View tools- </DropdownMenuItem>- )}- {isConnected && (- <DropdownMenuItem- onSelect={onDisconnect}- disabled={isBusy}- className="gap-2 rounded-md px-2 py-1.5 text-[13px]"- >- {busy === "disconnect" ? (- <Loader2 className="size-3.5 animate-spin" />- ) : (- <Unplug className="size-3.5 text-muted-foreground" />- )}- Disconnect- </DropdownMenuItem>- )}- <DropdownMenuItem- onSelect={onRemove}- disabled={isBusy}- className="gap-2 rounded-md px-2 py-1.5 text-[13px] text-destructive focus:text-destructive"- >- {busy === "remove" ? (- <Loader2 className="size-3.5 animate-spin" />- ) : (- <Trash2 className="size-3.5" />- )}- Remove server- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </div>- </article>-- <McpToolsDialog- open={toolsOpen}- onOpenChange={setToolsOpen}- mcpName={spec.display_name}- mcpDescription={spec.description}- loadTools={() => listMcpToolsAction({ mcp_key: spec.key })}- />-- {picker && (- <McpAccountPickerDialog- projectSlug={projectSlug}- mcpKey={spec.key}- selectedId={selectedAccountId}- open={pickerOpen}- prefetch={pickerPrefetch}- onOpenChange={setPickerOpen}- onPicked={() => {- router.refresh();- onMutated?.();- }}- />- )}- </>- );-}--function StatusLabel({ status }: { status: McpRuntimeStatus }) {- // Labels are intentionally lowercase + terse — they read as a quiet- // status tag, not a sentence. Mirrors the tokens the tests assert on- // (`connected`, `no token`, `unreachable`, `token expired`).- if (status.state === "connected") {- return (- <span- className="inline-flex items-center gap-1.5 text-[12.5px] font-medium text-[hsl(var(--notfair-accent))]"- role="status"- >- <span aria-hidden className="ns-dot ns-dot-on" />- connected- </span>- );- }- const map: Record<- Exclude<McpRuntimeStatus["state"], "connected">,- { tone: string; label: string }- > = {- stale_token: { tone: "ns-tag-amber", label: "token expired" },- unreachable: { tone: "ns-tag-red", label: "unreachable" },- configured_no_token: { tone: "ns-tag-amber", label: "no token" },- not_configured: { tone: "ns-tag", label: "not connected" },- };- const { tone, label } = map[status.state];- return <span className={tone}>{label}</span>;-}--function StatusLine({- status,- resourceUrl,-}: {- status: McpRuntimeStatus;- resourceUrl: string;-}) {- const host = (() => {- try {- return new URL(resourceUrl).host;- } catch {- return resourceUrl;- }- })();- const detail = describeStatus(status);- return (- <p className="mt-1 truncate font-mono text-[10.5px] text-[hsl(var(--notfair-ink-4))]">- <span>{host}</span>- {detail ? (- <>- <span className="mx-1.5 opacity-50">·</span>- <span>{detail}</span>- </>- ) : null}- </p>- );-}--function describeStatus(status: McpRuntimeStatus): string | null {- switch (status.state) {- case "connected":- // The "connected" indicator next to the title already says- // everything the user needs at a glance. Show just the host on- // this line — no verified timestamp, no live label.- return null;- case "stale_token":- return `token rejected (HTTP ${status.http_status})`;- case "unreachable":- return status.error;- case "configured_no_token":- return "config saved, awaiting bearer";- case "not_configured":- return "one-click OAuth saves the token locally";- }-}diff --git a/notfair/src/components/mcp-flash-banner.tsx b/notfair/src/components/mcp-flash-banner.tsxdeleted file mode 100644index 41fddd4b..00000000--- a/notfair/src/components/mcp-flash-banner.tsx+++ /dev/null@@ -1,51 +0,0 @@-"use client";--import { useEffect, useRef } from "react";-import { useRouter } from "next/navigation";-import { toast } from "sonner";--/**- * One-shot banner driven by the `?mcp_connected` / `?mcp_error` query- * params the OAuth callback redirects with. Fires the toast once on mount- * and strips the params so a refresh doesn't re-toast.- */-export function McpFlashBanner({- connected,- error,- analyzing,- goalsHref,-}: {- connected?: string;- error?: string;- /** Set when the connect kicked off an account analysis for goal ideas. */- analyzing?: boolean;- /** Where the suggestion cards land (the project's goals index). */- goalsHref?: string;-}) {- const router = useRouter();- const fired = useRef(false);-- useEffect(() => {- if (fired.current) return;- if (!connected && !error) return;- fired.current = true;- if (error) toast.error(error);- else if (connected && analyzing) {- toast.success(- `Connected: ${connected} — analyzing the account for goal ideas…`,- goalsHref- ? { action: { label: "See goals", onClick: () => router.push(goalsHref) } }- : undefined,- );- } else if (connected) toast.success(`Connected: ${connected}`);- // Clean the URL so a refresh / back-button doesn't re-fire.- const url = new URL(window.location.href);- url.searchParams.delete("mcp_connected");- url.searchParams.delete("mcp_error");- url.searchParams.delete("mcp_analyzing");- url.searchParams.delete("mcp_key");- router.replace(url.pathname + (url.search ? url.search : ""));- }, [connected, error, analyzing, goalsHref, router]);-- return null;-}diff --git a/notfair/src/components/mcp-icon.tsx b/notfair/src/components/mcp-icon.tsxdeleted file mode 100644index 14f57e93..00000000--- a/notfair/src/components/mcp-icon.tsx+++ /dev/null@@ -1,107 +0,0 @@-"use client";--import { useState } from "react";-import { Plug } from "lucide-react";--/**- * NotFair-hosted platform MCPs all live on `notfair.co`, so the favicon- * heuristic below would render the NotFair mark for every one of them.- * Map each `/api/mcp/<platform>` path to the actual platform's logo- * (bundled under `public/mcp-logos/`) so the row reads as the platform- * the user is connecting, not the host serving it.- */-const PLATFORM_LOGO_BY_MCP_PATH: Record<string, string> = {- google_ads: "/mcp-logos/google-ads-icon.svg",- meta_ads: "/mcp-logos/meta-icon.svg",- google_search_console: "/mcp-logos/search-console-icon.svg",- google_analytics: "/mcp-logos/google-analytics-icon.svg",- x_ads: "/mcp-logos/x-ads-icon.svg",-};--/**- * Local platform-logo path for a NotFair-hosted MCP resource URL, or- * null when the URL isn't a `notfair.co/api/mcp/<platform>` resource- * (user-added servers, third-party connectors → favicon fallback).- */-export function platformLogoForResourceUrl(resourceUrl: string): string | null {- try {- const url = new URL(resourceUrl);- if (brandDomain(url.hostname) !== "notfair.co") return null;- const match = url.pathname.match(/^\/api\/mcp\/([a-z0-9_]+)\/?$/);- if (!match) return null;- return PLATFORM_LOGO_BY_MCP_PATH[match[1]!] ?? null;- } catch {- return null;- }-}--/**- * Brand icon for an MCP server. NotFair-hosted platform MCPs render the- * bundled platform logo (Google Ads, Meta, …); everything else falls- * back to the brand favicon fetched via Google's `faviconV2` service.- * Subdomain-aware: `mcp.stripe.com` resolves to `stripe.com` so we get- * the company brand mark, not the API-subdomain glyph (which usually- * isn't indexed).- *- * Falls back to the `Plug` lucide icon on malformed input or image- * load failure.- */-export function McpIcon({- resourceUrl,- alt,- size = "md",-}: {- resourceUrl: string;- alt: string;- size?: "md" | "lg";-}) {- const [errored, setErrored] = useState(false);- let host: string | null = null;- try {- host = new URL(resourceUrl).hostname;- } catch {- host = null;- }- const platformLogo = platformLogoForResourceUrl(resourceUrl);- const brandHost = host ? brandDomain(host) : null;- const showImg = !!(platformLogo ?? brandHost) && !errored;- const boxClass = size === "lg" ? "size-10" : "size-9";- const imgClass = size === "lg" ? "size-6" : "size-5";- const fallbackClass = size === "lg" ? "size-5" : "size-4";- return (- <div- className={`flex ${boxClass} shrink-0 items-center justify-center overflow-hidden rounded-md bg-muted`}- >- {showImg ? (- // eslint-disable-next-line @next/next/no-img-element- <img- src={- platformLogo ??- `https://t3.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=http://${brandHost}&size=32`- }- alt={alt}- width={32}- height={32}- className={imgClass}- referrerPolicy="no-referrer"- onError={() => setErrored(true)}- />- ) : (- <Plug className={fallbackClass} />- )}- </div>- );-}--/**- * Reduce a hostname to its registrable brand domain- * (`mcp.stripe.com` → `stripe.com`). Simple last-2-labels heuristic;- * wrong for `.co.uk` and friends, but right for ~all consumer SaaS the- * connections page targets, and `faviconV2`'s `fallback_opts` cushions- * the rest.- */-export function brandDomain(host: string): string {- const parts = host.split(".").filter(Boolean);- if (parts.length <= 2) return host;- return parts.slice(-2).join(".");-}diff --git a/notfair/src/components/mcp-tools-dialog.test.tsx b/notfair/src/components/mcp-tools-dialog.test.tsxdeleted file mode 100644index 948f090b..00000000--- a/notfair/src/components/mcp-tools-dialog.test.tsx+++ /dev/null@@ -1,167 +0,0 @@-// @vitest-environment jsdom-import { describe, expect, it, vi } from "vitest";-import { fireEvent, render, screen, waitFor } from "@testing-library/react";--import { McpToolsDialog } from "@/components/mcp-tools-dialog";-import type { ToolSummary } from "@/server/mcp-server/tool-summaries";--const TOOLS: ToolSummary[] = [- {- name: "createCampaign",- description: "Create a Google Ads campaign.",- args: [- {- name: "name",- type: "string",- required: true,- description: "Campaign name.",- },- {- name: "status",- type: "enum: ENABLED | PAUSED",- required: false,- description: "",- },- ],- },- {- name: "listKeywords",- description: "List keywords in an ad group.",- args: [],- },-];--describe("McpToolsDialog with eager tools", () => {- it("renders the tool count, arg grid, and required markers", () => {- render(- <McpToolsDialog- open- onOpenChange={vi.fn()}- mcpName="NotFair Google Ads"- mcpDescription="Campaigns, bids, keywords."- tools={TOOLS}- />,- );- expect(screen.getByText("NotFair Google Ads")).toBeInTheDocument();- expect(screen.getByText("2 tools")).toBeInTheDocument();- expect(screen.getByText("Campaigns, bids, keywords.")).toBeInTheDocument();- expect(screen.getByText("createCampaign")).toBeInTheDocument();- expect(screen.getByText("1/2 required")).toBeInTheDocument();- expect(screen.getByLabelText("required")).toBeInTheDocument();- expect(screen.getByText("enum: ENABLED | PAUSED")).toBeInTheDocument();- // Empty arg description falls back to the italic placeholder.- expect(screen.getByText("no description")).toBeInTheDocument();- });-- it("filters tools by name, description, and arg names", () => {- render(- <McpToolsDialog- open- onOpenChange={vi.fn()}- mcpName="Ads"- tools={TOOLS}- />,- );- const search = screen.getByLabelText("Search tools");-- fireEvent.change(search, { target: { value: "keyword" } });- expect(screen.getByText("listKeywords")).toBeInTheDocument();- expect(screen.queryByText("createCampaign")).toBeNull();-- // Matches createCampaign via its `status` arg name.- fireEvent.change(search, { target: { value: "status" } });- expect(screen.getByText("createCampaign")).toBeInTheDocument();- expect(screen.queryByText("listKeywords")).toBeNull();-- fireEvent.change(search, { target: { value: "zzz-no-match" } });- expect(screen.getByText(/No tools match/)).toBeInTheDocument();- expect(screen.getByText("zzz-no-match")).toBeInTheDocument();- });-- it("says so when the MCP exposes no tools", () => {- render(- <McpToolsDialog open onOpenChange={vi.fn()} mcpName="Empty" tools={[]} />,- );- expect(screen.getByText("This MCP exposes no tools.")).toBeInTheDocument();- expect(screen.getByText("0 tools")).toBeInTheDocument();- });-});--describe("McpToolsDialog lazy loading", () => {- it("loads once on first open and caches the result", async () => {- const loadTools = vi- .fn()- .mockResolvedValue({ ok: true, tools: [TOOLS[1]] });- const { rerender } = render(- <McpToolsDialog- open={false}- onOpenChange={vi.fn()}- mcpName="Ext"- loadTools={loadTools}- />,- );- expect(loadTools).not.toHaveBeenCalled();-- rerender(- <McpToolsDialog- open- onOpenChange={vi.fn()}- mcpName="Ext"- loadTools={loadTools}- />,- );- expect(await screen.findByText("listKeywords")).toBeInTheDocument();- expect(loadTools).toHaveBeenCalledTimes(1);-- // Close and reopen — the cached list is reused, no second fetch.- rerender(- <McpToolsDialog- open={false}- onOpenChange={vi.fn()}- mcpName="Ext"- loadTools={loadTools}- />,- );- rerender(- <McpToolsDialog- open- onOpenChange={vi.fn()}- mcpName="Ext"- loadTools={loadTools}- />,- );- expect(screen.getByText("listKeywords")).toBeInTheDocument();- expect(loadTools).toHaveBeenCalledTimes(1);- });-- it("shows the loader error", async () => {- const loadTools = vi- .fn()- .mockResolvedValue({ ok: false, error: "MCP unreachable" });- render(- <McpToolsDialog- open- onOpenChange={vi.fn()}- mcpName="Ext"- loadTools={loadTools}- />,- );- expect(await screen.findByText("MCP unreachable")).toBeInTheDocument();- });-- it("shows a thrown loader failure as an error message", async () => {- const loadTools = vi.fn().mockRejectedValue(new Error("network down"));- render(- <McpToolsDialog- open- onOpenChange={vi.fn()}- mcpName="Ext"- loadTools={loadTools}- />,- );- expect(await screen.findByText("network down")).toBeInTheDocument();- await waitFor(() =>- expect(screen.queryByText(/Fetching tool list/)).toBeNull(),- );- });-});diff --git a/notfair/src/components/mcp-tools-dialog.tsx b/notfair/src/components/mcp-tools-dialog.tsxdeleted file mode 100644index 05455f0a..00000000--- a/notfair/src/components/mcp-tools-dialog.tsx+++ /dev/null@@ -1,236 +0,0 @@-"use client";--import { useEffect, useMemo, useState } from "react";-import { Loader2, Search } from "lucide-react";--import {- Dialog,- DialogContent,- DialogDescription,- DialogHeader,- DialogTitle,-} from "@/components/ui/dialog";-import { Input } from "@/components/ui/input";-import { Badge } from "@/components/ui/badge";-import { cn } from "@/lib/utils";-import type { ToolSummary } from "@/server/mcp-server/tool-summaries";--/**- * Tools modal for an MCP card.- *- * Two source modes:- * - `tools` prop is supplied (built-in / self-hosted MCP — server-rendered- * summary handed in directly, no network needed)- * - `loadTools` is supplied (external MCP — async server action invoked- * on first open, result cached)- *- * Layout is closer to an API-reference than a JSON dump: each tool gets- * a monospace name, a one-line description, and a small grid of args- * showing name (mono) · type · required-marker · arg description.- * Search filters across tool name + arg names + description text.- */-type Props = {- open: boolean;- onOpenChange: (open: boolean) => void;- mcpName: string;- /** Optional one-liner shown under the title — what the MCP does. */- mcpDescription?: string;- /** Eagerly-supplied tools (built-in MCP). Mutually exclusive with loadTools. */- tools?: ToolSummary[];- /** Lazy loader (external MCP). Called once on first open. */- loadTools?: () => Promise<- { ok: true; tools: ToolSummary[] } | { ok: false; error: string }- >;-};--export function McpToolsDialog({- open,- onOpenChange,- mcpName,- mcpDescription,- tools: eagerTools,- loadTools,-}: Props) {- const [loading, setLoading] = useState(false);- const [error, setError] = useState<string | null>(null);- const [lazyTools, setLazyTools] = useState<ToolSummary[] | null>(null);- const [q, setQ] = useState("");-- // Lazy-load once on first open. Cache forever after — connecting +- // disconnecting wouldn't change a tool list inside one session of the- // modal being mounted, and the dialog unmounts on close anyway.- useEffect(() => {- if (!open) return;- if (eagerTools) return;- if (!loadTools) return;- if (lazyTools !== null) return;- let cancelled = false;- setLoading(true);- setError(null);- void loadTools()- .then((r) => {- if (cancelled) return;- if (r.ok) setLazyTools(r.tools);- else setError(r.error);- })- .catch((err) => {- if (cancelled) return;- setError(err instanceof Error ? err.message : String(err));- })- .finally(() => {- if (!cancelled) setLoading(false);- });- return () => {- cancelled = true;- };- }, [open, eagerTools, loadTools, lazyTools]);-- const tools = eagerTools ?? lazyTools ?? [];-- const filtered = useMemo(() => {- const needle = q.trim().toLowerCase();- if (!needle) return tools;- return tools.filter((t) => {- if (t.name.toLowerCase().includes(needle)) return true;- if (t.description.toLowerCase().includes(needle)) return true;- return t.args.some(- (a) =>- a.name.toLowerCase().includes(needle) ||- a.description.toLowerCase().includes(needle),- );- });- }, [tools, q]);-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent- showCloseButton- className="flex max-h-[85vh] flex-col gap-0 overflow-hidden p-0 sm:max-w-2xl"- >- <DialogHeader className="px-6 pt-5 pb-4">- <DialogTitle className="flex items-baseline gap-2">- <span>{mcpName}</span>- <span className="text-xs font-normal text-muted-foreground">- {tools.length} {tools.length === 1 ? "tool" : "tools"}- </span>- </DialogTitle>- {mcpDescription && (- <DialogDescription className="text-xs">- {mcpDescription}- </DialogDescription>- )}- </DialogHeader>-- {/* Sticky search row — sits between header and scroll area. */}- <div className="bg-[hsl(var(--notfair-surface-2)/0.5)] px-6 py-2.5">- <div className="relative">- <Search- aria-hidden- className="absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2 text-muted-foreground"- />- <Input- autoFocus- value={q}- onChange={(e) => setQ(e.target.value)}- placeholder={`Search ${tools.length} tools…`}- className="h-8 pl-8 text-xs"- disabled={loading}- aria-label="Search tools"- />- </div>- </div>-- {/* Scroll area */}- <div className="min-h-0 flex-1 overflow-y-auto">- {loading && (- <div className="flex items-center justify-center gap-2 py-12 text-xs text-muted-foreground">- <Loader2 className="size-3.5 animate-spin" />- Fetching tool list…- </div>- )}- {!loading && error && (- <div className="px-6 py-12 text-center text-sm text-destructive">- {error}- </div>- )}- {!loading && !error && tools.length === 0 && (- <div className="px-6 py-12 text-center text-sm text-muted-foreground">- This MCP exposes no tools.- </div>- )}- {!loading && !error && tools.length > 0 && filtered.length === 0 && (- <div className="px-6 py-12 text-center text-sm text-muted-foreground">- No tools match{" "}- <span className="font-mono text-foreground">{q}</span>.- </div>- )}- {!loading && !error && filtered.length > 0 && (- <ul className="divide-y">- {filtered.map((t) => (- <ToolRow key={t.name} tool={t} />- ))}- </ul>- )}- </div>- </DialogContent>- </Dialog>- );-}--function ToolRow({ tool }: { tool: ToolSummary }) {- const requiredCount = tool.args.filter((a) => a.required).length;- return (- <li className="px-6 py-4">- <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">- <code className="rounded bg-muted px-1.5 py-0.5 font-mono text-[12px] text-foreground">- {tool.name}- </code>- {tool.args.length > 0 && (- <span className="text-[10px] text-muted-foreground">- {requiredCount}/{tool.args.length} required- </span>- )}- </div>- {tool.description && (- <p className="mt-1.5 text-xs leading-relaxed text-muted-foreground">- {tool.description}- </p>- )}- {tool.args.length > 0 && (- <ul className="mt-3 space-y-1.5">- {tool.args.map((a) => (- <li- key={a.name}- className="grid grid-cols-[minmax(0,8rem)_minmax(0,7rem)_minmax(0,1fr)] items-baseline gap-x-3 text-[11px]"- >- <span className="truncate font-mono text-foreground">- {a.name}- {a.required && (- <span aria-label="required" className="ml-0.5 text-destructive">- *- </span>- )}- </span>- <Badge- variant="outline"- className={cn(- "h-4 truncate px-1 font-mono text-[9px] font-normal",- // enums get a quieter slate-toned outline; primitives stay default- a.type.startsWith("enum:") && "border-dashed",- )}- title={a.type}- >- {a.type}- </Badge>- <span className="truncate text-muted-foreground" title={a.description}>- {a.description || (- <span className="italic opacity-60">no description</span>- )}- </span>- </li>- ))}- </ul>- )}- </li>- );-}diff --git a/notfair/src/components/metric-method-dialog.tsx b/notfair/src/components/metric-method-dialog.tsxdeleted file mode 100644index 0ba9bbd1..00000000--- a/notfair/src/components/metric-method-dialog.tsx+++ /dev/null@@ -1,119 +0,0 @@-"use client";--import { useState } from "react";-import { Info } from "lucide-react";-import {- Dialog,- DialogContent,- DialogDescription,- DialogHeader,- DialogTitle,- DialogTrigger,-} from "@/components/ui/dialog";--/**- * "How is this measured?" — the metric's exact provenance: which- * connection, which tool, and the verbatim query/args the platform runs- * at every check. The value is never self-reported by the agent; this- * dialog is the proof.- */-export function MetricMethodDialog({- name,- sourceKey,- sourceTool,- argsJson,- direction,-}: {- name: string;- sourceKey: string | null;- sourceTool: string | null;- argsJson: string | null;- direction: "increase" | "decrease" | null;-}) {- const [open, setOpen] = useState(false);-- // The common shape is {"query": "<sql>"} — surface the query as code- // and any remaining args as pretty JSON. Fall back to the raw string.- let query: string | null = null;- let otherArgs: string | null = null;- if (argsJson) {- try {- const parsed = JSON.parse(argsJson) as Record<string, unknown>;- if (typeof parsed.query === "string") {- query = parsed.query;- const rest = Object.fromEntries(- Object.entries(parsed).filter(([k]) => k !== "query"),- );- if (Object.keys(rest).length > 0) otherArgs = JSON.stringify(rest, null, 2);- } else {- otherArgs = JSON.stringify(parsed, null, 2);- }- } catch {- otherArgs = argsJson;- }- }-- return (- <Dialog open={open} onOpenChange={setOpen}>- <DialogTrigger asChild>- <button- type="button"- aria-label={`How is “${name}” measured?`}- title="How is this measured?"- className="inline-flex shrink-0 items-center text-[hsl(var(--notfair-ink-4))] transition-colors hover:text-[hsl(var(--notfair-ink-2))]"- >- <Info className="size-3.5" />- </button>- </DialogTrigger>- <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-xl">- <DialogHeader>- <DialogTitle className="text-[14px]">{name}</DialogTitle>- <DialogDescription>- Re-measured by the platform at every check, straight from the- source below — the agent never self-reports this number.- </DialogDescription>- </DialogHeader>- <dl className="m-0 grid grid-cols-[auto_1fr] gap-x-4 gap-y-1.5 text-[12.5px]">- <dt className="text-[hsl(var(--notfair-ink-4))]">Connection</dt>- <dd className="m-0 font-mono text-[12px]">{sourceKey ?? "—"}</dd>- <dt className="text-[hsl(var(--notfair-ink-4))]">Tool</dt>- <dd className="m-0 font-mono text-[12px]">{sourceTool ?? "—"}</dd>- <dt className="text-[hsl(var(--notfair-ink-4))]">Direction</dt>- <dd className="m-0">- {direction === "decrease"- ? "lower is better"- : direction === "increase"- ? "higher is better"- : "—"}- </dd>- </dl>- {query && (- <div>- <p className="m-0 mb-1.5 text-[11px] font-medium uppercase tracking-wide text-[hsl(var(--notfair-ink-4))]">- Query run at every check- </p>- <pre className="m-0 overflow-x-auto rounded-xl bg-[hsl(var(--notfair-surface-2))] p-3 text-[11.5px] leading-relaxed">- <code>{query}</code>- </pre>- </div>- )}- {otherArgs && (- <div>- <p className="m-0 mb-1.5 text-[11px] font-medium uppercase tracking-wide text-[hsl(var(--notfair-ink-4))]">- {query ? "Other arguments" : "Arguments"}- </p>- <pre className="m-0 overflow-x-auto rounded-xl bg-[hsl(var(--notfair-surface-2))] p-3 text-[11.5px] leading-relaxed">- <code>{otherArgs}</code>- </pre>- </div>- )}- {!query && !otherArgs && (- <p className="m-0 text-[12px] text-[hsl(var(--notfair-ink-4))]">- No measurement definition recorded — the metric is still being- set up in chat.- </p>- )}- </DialogContent>- </Dialog>- );-}diff --git a/notfair/src/components/new-goal-form.test.tsx b/notfair/src/components/new-goal-form.test.tsxdeleted file mode 100644index 841238bb..00000000--- a/notfair/src/components/new-goal-form.test.tsx+++ /dev/null@@ -1,113 +0,0 @@-// @vitest-environment jsdom-import { beforeEach, describe, expect, it, vi } from "vitest";-import { fireEvent, render, screen, waitFor } from "@testing-library/react";--import { NewGoalForm } from "@/components/new-goal-form";-import { createGoalAgentAction } from "@/server/actions/goals";--const push = vi.fn();-vi.mock("next/navigation", () => ({- useRouter: () => ({ push, refresh: vi.fn(), replace: vi.fn() }),-}));-vi.mock("@/server/actions/goals", () => ({- createGoalAgentAction: vi.fn(),-}));--beforeEach(() => {- vi.clearAllMocks();-});--describe("NewGoalForm focus chips", () => {- it("shows no focus row when nothing is connected", () => {- render(<NewGoalForm projectSlug="proj" connectedMcpKeys={[]} />);- expect(screen.queryByRole("group", { name: "Goal focus" })).toBeNull();- });-- it("shows one chip per connected platform, plus Other", () => {- render(- <NewGoalForm- projectSlug="proj"- connectedMcpKeys={["notfair-googlesearchconsole", "notfair-xads"]}- />,- );- expect(screen.getByRole("button", { name: "SEO" })).toBeInTheDocument();- expect(screen.getByRole("button", { name: "X Ads" })).toBeInTheDocument();- expect(screen.getByRole("button", { name: "Other" })).toBeInTheDocument();- expect(screen.queryByRole("button", { name: "Google Ads" })).toBeNull();- });-- it("selecting a focus swaps the placeholder and offers tap-to-fill examples", () => {- render(- <NewGoalForm- projectSlug="proj"- connectedMcpKeys={["notfair-googlesearchconsole"]}- />,- );- fireEvent.click(screen.getByRole("button", { name: "SEO" }));- const textarea = screen.getByLabelText<HTMLTextAreaElement>(- "What do you want to achieve?",- );- expect(textarea.placeholder).toMatch(/organic clicks/i);-- fireEvent.click(- screen.getByRole("button", { name: "Grow organic clicks 30% in 90 days" }),- );- expect(textarea.value).toBe("Grow organic clicks 30% in 90 days");- });-- it("passes the chosen focus to goal creation and lands in the agent chat", async () => {- vi.mocked(createGoalAgentAction).mockResolvedValue({- ok: true,- goal_id: "g1",- agent_slug: "goal-1",- });- render(- <NewGoalForm- projectSlug="proj"- connectedMcpKeys={["notfair-googlesearchconsole"]}- />,- );- fireEvent.click(screen.getByRole("button", { name: "SEO" }));- fireEvent.change(screen.getByLabelText("What do you want to achieve?"), {- target: { value: "Grow organic clicks 30% in 90 days" },- });- fireEvent.click(screen.getByRole("button", { name: "Create goal" }));-- await waitFor(() => {- expect(createGoalAgentAction).toHaveBeenCalledWith({- project_slug: "proj",- statement: "Grow organic clicks 30% in 90 days",- focus:- "SEO / organic search — measure via the notfair-googlesearchconsole MCP",- });- expect(push).toHaveBeenCalledWith("/proj/goals/goal-1");- });- });-- it("sends no focus when Other (or nothing) is chosen", async () => {- vi.mocked(createGoalAgentAction).mockResolvedValue({- ok: true,- goal_id: "g1",- agent_slug: "goal-1",- });- render(- <NewGoalForm- projectSlug="proj"- connectedMcpKeys={["notfair-googlesearchconsole"]}- />,- );- fireEvent.click(screen.getByRole("button", { name: "Other" }));- fireEvent.change(screen.getByLabelText("What do you want to achieve?"), {- target: { value: "Double our newsletter signups" },- });- fireEvent.click(screen.getByRole("button", { name: "Create goal" }));-- await waitFor(() => {- expect(createGoalAgentAction).toHaveBeenCalledWith({- project_slug: "proj",- statement: "Double our newsletter signups",- focus: null,- });- });- });-});diff --git a/notfair/src/components/new-goal-form.tsx b/notfair/src/components/new-goal-form.tsxdeleted file mode 100644index 20a99caf..00000000--- a/notfair/src/components/new-goal-form.tsx+++ /dev/null@@ -1,161 +0,0 @@-"use client";--import { useRouter } from "next/navigation";-import { useState, useTransition } from "react";-import { toast } from "sonner";-import { createGoalAgentAction } from "@/server/actions/goals";-import {- goalPlatformsForConnected,- type GoalPlatform,-} from "@/lib/goal-platforms";-import { projectHref } from "@/lib/project-href";-import { cn } from "@/lib/utils";-import { Button } from "@/components/ui/button";--const DEFAULT_PLACEHOLDER =- 'e.g. "Cut our Google Ads CAC to $30" or "Get to 100 signups a month from paid"';--/**- * Statement-first goal creation, shared by the goals index and- * onboarding's first-goal step. When the workspace has connected- * platforms, a focus row appears — one chip per connected platform- * (Google Ads, SEO, …) plus "Other" — with tap-to-fill example- * statements per focus. The chosen focus rides along to the agent's- * intake kickoff so it explores the right platform; the statement- * stays the user's words.- */-export function NewGoalForm({- projectSlug,- connectedMcpKeys = [],-}: {- projectSlug: string;- /** Drives which focus chips show. Omit/empty → no focus row. */- connectedMcpKeys?: string[];-}) {- const router = useRouter();- const [pending, startTransition] = useTransition();- const [statement, setStatement] = useState("");- // null = nothing chosen yet; "other" = explicit free-form choice.- const [selected, setSelected] = useState<GoalPlatform | "other" | null>(null);- const platform = selected && selected !== "other" ? selected : null;-- const platforms = goalPlatformsForConnected(connectedMcpKeys);-- function submit() {- startTransition(async () => {- const r = await createGoalAgentAction({- project_slug: projectSlug,- statement,- focus: platform?.focus ?? null,- });- if (!r.ok || !r.agent_slug) {- toast.error(r.error ?? "Could not create the goal.");- return;- }- toast.success("Your agent is on it — watch it work.");- router.push(projectHref(projectSlug, `/goals/${r.agent_slug}`));- });- }-- return (- <div className="ns-card flex flex-col gap-3 p-4">- <label htmlFor="new-goal-statement" className="text-[13px] font-medium">- What do you want to achieve?- </label>-- {platforms.length > 0 && (- <div- className="flex flex-wrap items-center gap-1.5"- role="group"- aria-label="Goal focus"- >- {platforms.map((p) => (- <FocusChip- key={p.key}- label={p.label}- active={platform?.key === p.key}- disabled={pending}- onClick={() => setSelected(platform?.key === p.key ? null : p)}- />- ))}- <FocusChip- label="Other"- active={selected === "other"}- disabled={pending}- onClick={() => setSelected(selected === "other" ? null : "other")}- />- </div>- )}-- <textarea- id="new-goal-statement"- className="min-h-20 w-full resize-y rounded-lg bg-[hsl(var(--notfair-surface-2))] px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-[hsl(var(--notfair-accent))]"- placeholder={platform?.placeholder ?? DEFAULT_PLACEHOLDER}- value={statement}- onChange={(e) => setStatement(e.target.value)}- onKeyDown={(e) => {- if (e.key === "Enter" && !e.shiftKey && statement.trim() && !pending) {- e.preventDefault();- submit();- }- }}- disabled={pending}- />-- {platform && platform.examples.length > 0 && (- <div className="flex flex-wrap gap-1.5">- {platform.examples.map((example) => (- <button- key={example}- type="button"- disabled={pending}- onClick={() => setStatement(example)}- className="rounded-lg bg-[hsl(var(--notfair-surface-2)/0.6)] px-2.5 py-1 text-[12px] text-[hsl(var(--notfair-ink-3))] shadow-[var(--notfair-shadow-sm)] transition-colors hover:bg-[hsl(var(--notfair-surface-2))] hover:text-[hsl(var(--notfair-ink))]"- >- {example}- </button>- ))}- </div>- )}-- <div className="flex items-center justify-between gap-3">- <p className="m-0 text-[12px] text-[hsl(var(--notfair-ink-4))]">- An agent takes it from here: it turns this into a measured metric,- shows you the baseline, and nothing runs until you confirm the plan.- </p>- <Button onClick={submit} disabled={pending || !statement.trim()}>- {pending ? "Creating…" : "Create goal"}- </Button>- </div>- </div>- );-}--function FocusChip({- label,- active,- disabled,- onClick,-}: {- label: string;- active: boolean;- disabled: boolean;- onClick: () => void;-}) {- return (- <button- type="button"- disabled={disabled}- onClick={onClick}- aria-pressed={active}- className={cn(- "rounded-full px-3 py-1 text-[12.5px] font-medium transition-colors",- active- ? "bg-[hsl(var(--notfair-accent-soft))] text-[hsl(var(--notfair-accent))] shadow-[var(--notfair-shadow-sm)]"- : "bg-[hsl(var(--notfair-surface-2)/0.6)] text-[hsl(var(--notfair-ink-3))] hover:bg-[hsl(var(--notfair-surface-2))]",- )}- >- {label}- </button>- );-}diff --git a/notfair/src/components/onboarding-flow.test.tsx b/notfair/src/components/onboarding-flow.test.tsxdeleted file mode 100644index 07f769dc..00000000--- a/notfair/src/components/onboarding-flow.test.tsx+++ /dev/null@@ -1,191 +0,0 @@-// @vitest-environment jsdom-import { fireEvent, render, screen, waitFor } from "@testing-library/react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- push: vi.fn(),- replace: vi.fn(),- params: new Map<string, string>(),- createProject: vi.fn(),- getCards: vi.fn(),- toastError: vi.fn(),- mcpCardProps: [] as Array<Record<string, unknown>>,- goalFormProps: vi.fn(),- menuProps: vi.fn(),- bannerProps: vi.fn(),-}));--vi.mock("next/navigation", () => ({- useRouter: () => ({ push: mocks.push, replace: mocks.replace }),- useSearchParams: () => ({ get: (key: string) => mocks.params.get(key) ?? null }),-}));-vi.mock("next/link", () => ({- default: ({ href, children, ...props }: React.AnchorHTMLAttributes<HTMLAnchorElement> & { href: string }) => (- <a href={href} {...props}>{children}</a>- ),-}));-vi.mock("sonner", () => ({ toast: { error: mocks.toastError } }));-vi.mock("@/server/actions/projects", () => ({- createProjectForOnboardingAction: mocks.createProject,-}));-vi.mock("@/server/onboarding/accounts", () => ({- getOnboardingConnectCardsAction: mocks.getCards,-}));-vi.mock("@/components/mcp-flash-banner", () => ({- McpFlashBanner: (props: Record<string, unknown>) => {- mocks.bannerProps(props);- return <div data-testid="flash-banner" />;- },-}));-vi.mock("@/components/add-mcp-server-card", () => ({- AddMcpServerMenu: (props: { trigger: React.ReactNode; connectedKeys: string[] }) => {- mocks.menuProps(props);- return <div data-testid="mcp-menu">{props.trigger}</div>;- },-}));-vi.mock("@/components/mcp-card", () => ({- McpCard: (props: Record<string, unknown> & { spec: { key: string }; onMutated: () => void }) => {- mocks.mcpCardProps.push(props);- return <button onClick={props.onMutated}>card:{props.spec.key}</button>;- },-}));-vi.mock("@/components/new-goal-form", () => ({- NewGoalForm: (props: Record<string, unknown>) => {- mocks.goalFormProps(props);- return <div data-testid="new-goal-form" />;- },-}));--import { OnboardingFlow } from "./onboarding-flow";--const cards = [- {- spec: { key: "notfair-googleads", name: "Google Ads" },- status: { state: "connected" },- selected_id: "123",- },- {- spec: { key: "notfair-metaads", name: "Meta Ads" },- status: { state: "not_configured" },- selected_id: null,- },-];--beforeEach(() => {- vi.clearAllMocks();- mocks.params.clear();- mocks.mcpCardProps.length = 0;- mocks.getCards.mockResolvedValue({ ok: true, cards, any_connected: true });- mocks.createProject.mockResolvedValue({ ok: true, data: { slug: "acme", display_name: "Acme" } });- vi.stubGlobal("fetch", vi.fn());-});--afterEach(() => vi.unstubAllGlobals());--describe("workspace step", () => {- it("renders defaults, edits fields, and switches harnesses", () => {- render(<OnboardingFlow />);- expect(screen.getByRole("heading", { name: /set up your workspace/i })).toBeInTheDocument();- fireEvent.change(screen.getByLabelText("Workspace name"), { target: { value: "Acme" } });- fireEvent.change(screen.getByLabelText(/Website URL/), { target: { value: "https://acme.test" } });- expect(screen.getByRole("button", { name: /^Codex/ })).toHaveAttribute("aria-pressed", "true");- fireEvent.click(screen.getByRole("button", { name: /^Claude Code/ }));- expect(screen.getByRole("button", { name: /^Claude Code/ })).toHaveAttribute("aria-pressed", "true");- expect(document.querySelector('input[name="harness_adapter"]')).toHaveValue("claude-code-local");- expect(mocks.bannerProps).toHaveBeenCalledWith(expect.objectContaining({ analyzing: false }));- });-- it("fills a picked codebase folder", async () => {- vi.mocked(fetch).mockResolvedValue({ json: async () => ({ ok: true, path: "/repo/acme" }) } as never);- render(<OnboardingFlow />);- fireEvent.click(screen.getByRole("button", { name: "Browse for a folder" }));- await waitFor(() => expect(screen.getByLabelText("Local codebase folder")).toHaveValue("/repo/acme"));- fireEvent.change(screen.getByLabelText("Local codebase folder"), { target: { value: "/other" } });- expect(screen.getByLabelText("Local codebase folder")).toHaveValue("/other");- });-- it("silently handles cancellation and toasts picker failures", async () => {- vi.mocked(fetch)- .mockResolvedValueOnce({ json: async () => ({ ok: false, kind: "cancelled" }) } as never)- .mockResolvedValueOnce({ json: async () => ({ ok: false, kind: "unsupported" }) } as never)- .mockRejectedValueOnce("network down");- render(<OnboardingFlow />);- const browse = screen.getByRole("button", { name: "Browse for a folder" });- fireEvent.click(browse);- await waitFor(() => expect(fetch).toHaveBeenCalledTimes(1));- expect(mocks.toastError).not.toHaveBeenCalled();- fireEvent.click(browse);- await waitFor(() => expect(mocks.toastError).toHaveBeenCalledWith("Couldn't open the folder picker."));- fireEvent.click(browse);- await waitFor(() => expect(mocks.toastError).toHaveBeenCalledWith("network down"));- });-});--describe("connect step", () => {- beforeEach(() => {- mocks.params.set("step", "connect");- mocks.params.set("slug", "acme co");- mocks.params.set("mcp_connected", "google");- mocks.params.set("mcp_analyzing", "1");- });-- it("shows loading, then cards, passes picker state, and advances", async () => {- let resolve!: (value: unknown) => void;- mocks.getCards.mockReturnValueOnce(new Promise((r) => { resolve = r; }));- render(- <OnboardingFlow- pickerMcpKey="notfair-googleads"- pickerPrefetch={{ ok: true, items: [], selected_id: "123" } as never}- />,- );- expect(screen.getByText(/Loading your connections/)).toBeInTheDocument();- resolve({ ok: true, cards, any_connected: true });- await screen.findByRole("heading", { name: /Connect your data sources/i });- expect(screen.getByText("card:notfair-googleads")).toBeInTheDocument();- expect(mocks.mcpCardProps[0]).toMatchObject({- projectSlug: "acme co",- selectedAccountId: "123",- pickerPrefetch: { ok: true, items: [], selected_id: "123" },- });- expect(mocks.mcpCardProps[1]?.pickerPrefetch).toBeNull();- expect(mocks.menuProps).toHaveBeenCalledWith(expect.objectContaining({ connectedKeys: ["notfair-googleads"] }));- fireEvent.click(screen.getByRole("button", { name: /Next/ }));- expect(mocks.push).toHaveBeenCalledWith("/onboarding?step=goal&slug=acme%20co");- });-- it("reloads card state after a card mutation", async () => {- render(<OnboardingFlow />);- await screen.findByText("card:notfair-googleads");- fireEvent.click(screen.getByText("card:notfair-googleads"));- await waitFor(() => expect(mocks.getCards).toHaveBeenCalledTimes(2));- });-- it("shows load errors", async () => {- mocks.getCards.mockResolvedValue({ ok: false, error: "MCP unavailable" });- render(<OnboardingFlow />);- expect(await screen.findByRole("alert")).toHaveTextContent("MCP unavailable");- expect(screen.getByRole("link", { name: "Start over" })).toHaveAttribute("href", "/onboarding");- });-- it("skips directly into the workspace when nothing is connected", async () => {- mocks.getCards.mockResolvedValue({ ok: true, cards: [], any_connected: false });- render(<OnboardingFlow />);- fireEvent.click(await screen.findByRole("button", { name: "Skip" }));- expect(mocks.replace).toHaveBeenCalledWith("/acme co");- });-});--it("renders the first-goal step and forwards connected keys", () => {- mocks.params.set("step", "goal");- mocks.params.set("slug", "acme");- render(<OnboardingFlow connectedMcpKeys={["google", "meta"]} />);- expect(screen.getByRole("heading", { name: /Create your first goal/ })).toBeInTheDocument();- expect(mocks.goalFormProps).toHaveBeenCalledWith({ projectSlug: "acme", connectedMcpKeys: ["google", "meta"] });- expect(screen.getByRole("link", { name: "Skip for now" })).toHaveAttribute("href", "/acme");-});--it("renders a recovery path when a later step has no slug", () => {- mocks.params.set("step", "goal");- render(<OnboardingFlow />);- expect(screen.getByText(/This step needs a workspace/)).toBeInTheDocument();-});diff --git a/notfair/src/components/onboarding-flow.tsx b/notfair/src/components/onboarding-flow.tsxdeleted file mode 100644index d821f8c1..00000000--- a/notfair/src/components/onboarding-flow.tsx+++ /dev/null@@ -1,657 +0,0 @@-"use client";--import { Suspense, useActionState, useCallback, useEffect, useState } from "react";-import { useRouter, useSearchParams } from "next/navigation";-import Link from "next/link";-import { AlertCircle, FolderOpen, Loader2 } from "lucide-react";-import { toast } from "sonner";--import { Button } from "@/components/ui/button";-import { McpFlashBanner } from "@/components/mcp-flash-banner";-import { Input } from "@/components/ui/input";-import { Label } from "@/components/ui/label";-import { cn } from "@/lib/utils";-import { projectHref } from "@/lib/project-href";-import { createProjectForOnboardingAction } from "@/server/actions/projects";-import {- getOnboardingConnectCardsAction,- type ConnectCard,-} from "@/server/onboarding/accounts";-import { AddMcpServerMenu } from "@/components/add-mcp-server-card";-import { McpCard } from "@/components/mcp-card";-import { NewGoalForm } from "@/components/new-goal-form";-import type { AccountPickerPrefetch } from "@/components/mcp-account-picker-dialog";--type Step = "name" | "connect" | "goal";--/**- * The post-OAuth account/property choice for a multi-account MCP, as- * prefetched by the onboarding server page (`?mcp_key=`). Same shape and- * flow as the Connections page: the matching `McpCard` auto-opens the- * shared picker dialog with this data.- */-type PendingAccountChoice = {- mcp_key: string;- prefetch: AccountPickerPrefetch | null;-};--export function OnboardingFlow({- pickerMcpKey = null,- pickerPrefetch = null,- connectedMcpKeys = [],-}: {- pickerMcpKey?: string | null;- pickerPrefetch?: AccountPickerPrefetch | null;- /** Feeds the first-goal step's focus chips (server-computed). */- connectedMcpKeys?: string[];-}) {- return (- <Suspense fallback={null}>- <OnboardingFlowInner- autoPicker={- pickerMcpKey- ? { mcp_key: pickerMcpKey, prefetch: pickerPrefetch }- : null- }- connectedMcpKeys={connectedMcpKeys}- />- </Suspense>- );-}--function OnboardingFlowInner({- autoPicker,- connectedMcpKeys,-}: {- autoPicker: PendingAccountChoice | null;- connectedMcpKeys: string[];-}) {- const router = useRouter();- const params = useSearchParams();- const stepParam = params.get("step");- const slug = params.get("slug") ?? null;- const mcpConnected = params.get("mcp_connected") ?? undefined;- const mcpError = params.get("mcp_error") ?? undefined;- const mcpAnalyzing = params.get("mcp_analyzing") === "1";- const step: Step =- stepParam === "connect" ? "connect" : stepParam === "goal" ? "goal" : "name";-- return (- <div className="ns-page">- <a- href="#onboarding-main"- className="sr-only focus:not-sr-only focus:absolute focus:top-2 focus:left-2 focus:z-50 focus:rounded-md focus:bg-background focus:px-3 focus:py-2 focus:text-sm focus:shadow"- >- Skip to content- </a>-- {/* Brand row + progress pips. The mark anchors the wizard so the user- always sees where they are; the pips show how far they've gone. */}- <div className="ns-topbar">- {/* eslint-disable-next-line @next/next/no-img-element */}- <img src="/notfair-mark.svg" alt="Notfair" className="dark:hidden" />- {/* eslint-disable-next-line @next/next/no-img-element */}- <img src="/notfair-mark-dark.svg" alt="Notfair" className="hidden dark:block" />- <span className="ns-topbar-label">NotFair</span>- <div className="ml-auto">- <div className="ns-progress">- <Pip n={1} label="Workspace" state={step === "name" ? "active" : "done"} />- <span className="ns-pip-line" />- <Pip- n={2}- label="Connect"- state={- step === "name" ? "pending" : step === "connect" ? "active" : "done"- }- />- <span className="ns-pip-line" />- <Pip- n={3}- label="First goal"- state={step === "goal" ? "active" : "pending"}- />- </div>- </div>- </div>-- <main id="onboarding-main">- <McpFlashBanner- connected={mcpConnected}- error={mcpError}- analyzing={mcpAnalyzing}- goalsHref={slug ? `/${slug}` : undefined}- />- {step === "name" && (- <NameStep- onCreated={(s) =>- router.push(`/onboarding?step=connect&slug=${encodeURIComponent(s)}`)- }- />- )}- {step === "connect" && slug && (- <ConnectStep slug={slug} autoPicker={autoPicker} />- )}- {step === "goal" && slug && (- <FirstGoalStep slug={slug} connectedMcpKeys={connectedMcpKeys} />- )}- {step !== "name" && !slug && <MissingSlug />}- </main>- </div>- );-}--function Pip({- n,- label,- state,-}: {- n: number;- label: string;- state: "pending" | "active" | "done";-}) {- return (- <div- className={`ns-pip ${state === "done" ? "is-done" : ""} ${state === "active" ? "is-active" : ""}`}- >- <span className="ns-pip-dot">{state === "done" ? "✓" : n}</span>- <span className="hidden sm:inline">{label}</span>- </div>- );-}--// ── Codebase folder picker (Step 1 helper) ─────────────────────────-//-// Browsers don't expose absolute paths from `<input type="file"-// webkitdirectory>` or `showDirectoryPicker()` — security. Since this-// server runs on the user's own machine (loopback only), we shell out-// to the OS-native folder dialog via POST /api/fs/pick-folder and let-// the OS handle the picker UI. The field stays editable so users on-// platforms we don't yet support natively (Linux, Windows) can paste.--function CodebasePathPicker({ disabled }: { disabled: boolean }) {- const [value, setValue] = useState("");- const [picking, setPicking] = useState(false);-- async function onBrowse() {- setPicking(true);- try {- const res = await fetch("/api/fs/pick-folder", { method: "POST" });- const body = (await res.json()) as- | { ok: true; path: string }- | { ok: false; kind: "cancelled" }- | { ok: false; kind: "unsupported" | "error"; message?: string };- if (body.ok) {- setValue(body.path);- return;- }- if (body.kind === "cancelled") return; // silent — user closed dialog- toast.error(body.message ?? "Couldn't open the folder picker.");- } catch (err) {- toast.error(err instanceof Error ? err.message : String(err));- } finally {- setPicking(false);- }- }-- return (- <div className="flex gap-2">- <Input- id="codebase_path"- name="codebase_path"- value={value}- onChange={(e) => setValue(e.target.value)}- placeholder="No folder selected"- maxLength={500}- disabled={disabled || picking}- readOnly={picking}- aria-label="Local codebase folder"- />- <Button- type="button"- variant="outline"- onClick={onBrowse}- disabled={disabled || picking}- aria-label="Browse for a folder"- >- {picking ? (- <Loader2 className="mr-1.5 size-4 animate-spin" />- ) : (- <FolderOpen className="mr-1.5 size-4" />- )}- Browse…- </Button>- </div>- );-}--// ── Step 1: Name ───────────────────────────────────────────────────--function NameStep({ onCreated }: { onCreated: (slug: string) => void }) {- const [displayName, setDisplayName] = useState("");- const [websiteUrl, setWebsiteUrl] = useState("");- const [state, formAction, isPending] = useActionState<- | { ok: true; data: { slug: string; display_name: string } }- | { ok: false; error: string }- | null,- FormData- >(async (_prev, formData) => createProjectForOnboardingAction(formData), null);-- useEffect(() => {- if (state && state.ok) onCreated(state.data.slug);- }, [state, onCreated]);-- const errorMessage = state && !state.ok ? state.error : null;-- return (- <>- <header>- <h1 className="ns-hero-title">Let’s set up your workspace.</h1>- <p className="ns-hero-sub">- Name it, point at your site, and pick which local AI runtime does the work.- </p>- </header>-- <form action={formAction} className="mt-5 space-y-3.5">- <div className="space-y-1.5">- <Label htmlFor="display_name" className="text-[13px] font-medium">- Workspace name- </Label>- <Input- id="display_name"- name="display_name"- required- autoFocus- placeholder="Acme Inc"- maxLength={80}- disabled={isPending}- value={displayName}- onChange={(e) => setDisplayName(e.target.value)}- className="h-9 rounded-lg text-[14px]"- />- </div>-- <div className="space-y-1.5">- <Label htmlFor="website_url" className="text-[13px] font-medium">- Website URL{" "}- <span className="text-[12px] font-normal text-muted-foreground">- (optional)- </span>- </Label>- <Input- id="website_url"- name="website_url"- type="url"- placeholder="https://acme.com"- maxLength={500}- disabled={isPending}- value={websiteUrl}- onChange={(e) => setWebsiteUrl(e.target.value)}- className="h-9 rounded-lg text-[14px]"- />- <p className="text-[11.5px] text-muted-foreground leading-tight">- Your agents skim a few pages to learn what you sell.- </p>- </div>-- <div className="space-y-1.5">- <Label htmlFor="codebase_path" className="text-[13px] font-medium">- Local codebase folder{" "}- <span className="text-[12px] font-normal text-muted-foreground">- (optional)- </span>- </Label>- <CodebasePathPicker disabled={isPending} />- <p className="text-[11.5px] text-muted-foreground leading-tight">- Folder your agents can read locally — README, package.json, top-level- files. Skim only.- </p>- </div>-- <HarnessPicker disabled={isPending} />-- {errorMessage && (- <p role="alert" className="text-[13px] text-destructive">- {errorMessage}- </p>- )}-- <button- type="submit"- disabled={isPending}- className="ns-btn ns-btn-primary"- >- {isPending ? <Loader2 className="size-4 animate-spin" /> : null}- Continue- </button>- </form>- </>- );-}--// ── Harness picker ─────────────────────────────────────────────────-//-// Two adapters: Codex (recommended default) and Claude Code. Persisted on-// the project row so different projects can use different harnesses. The-// chosen CLI must be on PATH when chats run — adapter testEnvironment is-// surfaced via the doctor command for diagnostic feedback.--function HarnessPicker({ disabled }: { disabled: boolean }) {- const [value, setValue] = useState<"claude-code-local" | "codex-local">(- "codex-local",- );- const options: Array<{- id: "claude-code-local" | "codex-local";- label: string;- description: string;- recommended: boolean;- }> = [- {- id: "codex-local",- label: "Codex",- description: "Uses your local `codex` CLI. Recommended.",- recommended: true,- },- {- id: "claude-code-local",- label: "Claude Code",- description: "Uses your local `claude` CLI.",- recommended: false,- },- ];- return (- <div className="rounded-md border border-dashed bg-muted/30 p-3 space-y-3">- <div className="space-y-1">- <Label className="text-xs uppercase tracking-wide text-muted-foreground">- AI agent runtime- </Label>- <p className="text-xs text-muted-foreground">- Pick which local CLI runs your agents. You can have different- projects on different harnesses.- </p>- </div>- <input type="hidden" name="harness_adapter" value={value} />- <div className="grid grid-cols-2 gap-2">- {options.map((opt) => (- <button- key={opt.id}- type="button"- disabled={disabled}- onClick={() => setValue(opt.id)}- className={cn(- "flex flex-col items-start gap-1 rounded-lg px-3 py-2 text-left transition-colors",- value === opt.id- ? "bg-[hsl(var(--notfair-surface-2))] shadow-[var(--notfair-shadow-sm)]"- : "bg-background/40 hover:bg-[hsl(var(--notfair-surface-2)/0.6)]",- disabled && "opacity-60",- )}- aria-pressed={value === opt.id}- >- <div className="flex w-full items-center justify-between">- <span className="text-sm font-medium text-foreground">{opt.label}</span>- {opt.recommended && (- <span className="rounded-full bg-[hsl(var(--notfair-accent-soft))] px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-[hsl(var(--notfair-accent))]">- Recommended- </span>- )}- </div>- <span className="text-xs text-muted-foreground">{opt.description}</span>- </button>- ))}- </div>- </div>- );-}--// ── Step 2: Connect ────────────────────────────────────────────────-//-// Renders the exact `McpCard` rows the Connections page uses — one shared-// component, one lifecycle (Connect → Choose account → Switch account),-// zero drift between onboarding and the app. The wizard only curates the-// list (via `getOnboardingConnectCardsAction`): recommended MCPs always-// show; everything else appears once connected and otherwise lives in-// the "More tools" browse menu.--const RECOMMENDED_MCP_KEYS = [- "notfair-googleads",- "notfair-metaads",- "notfair-googlesearchconsole",- "notfair-xads",-];--type ConnectCardsView =- | { phase: "loading" }- | { phase: "loaded"; cards: ConnectCard[]; any_connected: boolean }- | { phase: "error"; message: string };--function ConnectStep({- slug,- autoPicker,-}: {- slug: string;- autoPicker: PendingAccountChoice | null;-}) {- const router = useRouter();- const [view, setView] = useState<ConnectCardsView>({ phase: "loading" });- const [advancing, setAdvancing] = useState(false);-- const loadCards = useCallback(async () => {- const result = await getOnboardingConnectCardsAction(slug);- if (!result.ok) {- setView({ phase: "error", message: result.error });- return;- }- setView({- phase: "loaded",- cards: result.cards,- any_connected: result.any_connected,- });- }, [slug]);-- useEffect(() => {- let cancelled = false;- (async () => {- const result = await getOnboardingConnectCardsAction(slug);- if (cancelled) return;- if (!result.ok) {- setView({ phase: "error", message: result.error });- return;- }- setView({- phase: "loaded",- cards: result.cards,- any_connected: result.any_connected,- });- })();- return () => {- cancelled = true;- };- }, [slug]);-- function onDone() {- setAdvancing(true);- // With sources connected, the wizard's last step mints the first- // goal — focus options derive from what just got connected. With- // nothing connected there's nothing measurable to focus on, so the- // Skip path drops straight into the workspace.- if (view.phase === "loaded" && view.any_connected) {- router.push(`/onboarding?step=goal&slug=${encodeURIComponent(slug)}`);- } else {- router.replace(projectHref(slug, ""));- }- }-- if (view.phase === "loading") {- return (- <div className="flex items-center gap-3 text-sm text-muted-foreground py-8">- <Loader2 className="size-4 animate-spin" aria-hidden />- <span>Loading your connections…</span>- </div>- );- }-- if (view.phase === "error") {- return (- <div role="alert" className="ns-list p-6 space-y-3">- <div className="flex items-center gap-2">- <AlertCircle className="size-4 text-[hsl(var(--notfair-warn))]" aria-hidden />- <span className="font-medium text-sm">- Couldn’t load connection state.- </span>- </div>- <p className="text-xs text-muted-foreground">{view.message}</p>- <Link href="/onboarding" className="ns-btn ns-btn-primary">- Start over- </Link>- </div>- );- }-- const { cards, any_connected } = view;-- return (- <>- <header>- <h1 className="ns-hero-title">Connect your data sources.</h1>- <p className="ns-hero-sub">- Every goal agent shares these — they are what your agents- measure and act on.- </p>- </header>-- <ol className="ns-list">- {cards.map(({ spec, status, selected_id }) => (- <li key={spec.key}>- <McpCard- spec={spec}- status={status}- projectSlug={slug}- selectedAccountId={selected_id}- pickerPrefetch={- autoPicker?.mcp_key === spec.key ? autoPicker.prefetch : null- }- onMutated={loadCards}- />- </li>- ))}- <li>- {/* Reuse the connections-page Add-MCP flow so onboarding gets the- same connector browser and final custom-connector option. The- trigger is tile-shaped so it sits naturally as the last row. */}- <AddMcpServerMenu- // Hide the always-visible recommended MCPs from Browse — they- // each have their own row above already.- hideKeys={RECOMMENDED_MCP_KEYS}- connectedKeys={cards- .filter((c) => c.status.state === "connected")- .map((c) => c.spec.key)}- trigger={- <button- type="button"- aria-label="More tools"- className="ns-tile w-full"- >- <span className="ns-tile-glyph" aria-hidden>- +- </span>- <span className="ns-tile-body">- <span className="ns-tile-name-row">- <span className="ns-tile-name">More tools</span>- </span>- <span className="ns-tile-desc block">- Browse Google Analytics, Stripe, Supabase, PostHog, or- paste a custom MCP URL.- </span>- </span>- <span className="ns-tile-status">- <span className="arrow" aria-hidden>- ›- </span>- </span>- </button>- }- />- </li>- </ol>-- <div className="ns-foot">- <p className="ns-footnote">You can set up MCPs later in the app.</p>- {any_connected ? (- <button- type="button"- onClick={onDone}- disabled={advancing}- className="ns-btn ns-btn-primary"- >- {advancing && <Loader2 className="size-4 animate-spin" />}- Next{" "}- <span aria-hidden style={{ fontWeight: 400 }}>- ›- </span>- </button>- ) : (- <button- type="button"- onClick={onDone}- disabled={advancing}- className="ns-btn ns-btn-ghost"- >- Skip- </button>- )}- </div>- </>- );-}--// ── Step 3: First goal ─────────────────────────────────────────────-//-// The same statement-first creation form the goals index uses — one-// component, one experience. Focus chips derive from the platforms the-// user just connected (SEO for Search Console, Google Ads, …); creating-// drops them straight into the new agent's chat, already working.--function FirstGoalStep({- slug,- connectedMcpKeys,-}: {- slug: string;- connectedMcpKeys: string[];-}) {- return (- <>- <header>- <h1 className="ns-hero-title">Create your first goal.</h1>- <p className="ns-hero-sub">- Pick a focus, state the ambition. An agent measures it, shows you- the baseline, and waits for your go-ahead.- </p>- </header>-- <div className="mt-5">- <NewGoalForm projectSlug={slug} connectedMcpKeys={connectedMcpKeys} />- </div>-- <div className="ns-foot">- <p className="ns-footnote">- Not sure yet? Your workspace has this same form.- </p>- <Link href={projectHref(slug, "")} className="ns-btn ns-btn-ghost">- Skip for now- </Link>- </div>- </>- );-}--function MissingSlug() {- return (- <div className="mt-10 space-y-4">- <p className="text-[15px] text-muted-foreground">- This step needs a workspace. Start from the beginning.- </p>- <Link href="/onboarding" className="ns-btn ns-btn-primary">- Start over- </Link>- </div>- );-}diff --git a/notfair/src/components/project-cookie-sync.tsx b/notfair/src/components/project-cookie-sync.tsxdeleted file mode 100644index 5e92a9cf..00000000--- a/notfair/src/components/project-cookie-sync.tsx+++ /dev/null@@ -1,25 +0,0 @@-"use client";--import { useEffect, useRef } from "react";-import { switchProjectAction } from "@/server/actions/projects";--/**- * Keeps the legacy `notfair_active_project` cookie in lockstep with the URL- * project slug. The cookie is still consulted by the sidebar (mounted higher- * up in the tree than the `[project]` dynamic segment) and the API routes,- * so when a user deep-links into `/<other-slug>/...` we need the cookie to- * flip over to that slug. Fires at most once per slug change per mount.- */-export function ProjectCookieSync({ slug }: { slug: string }) {- const lastSlug = useRef<string | null>(null);-- useEffect(() => {- if (lastSlug.current === slug) return;- lastSlug.current = slug;- // Server action — sets the cookie and revalidates layout cache so the- // sidebar's `activeSlug` matches the URL on next render.- void switchProjectAction(slug);- }, [slug]);-- return null;-}diff --git a/notfair/src/components/project-rename-card.test.tsx b/notfair/src/components/project-rename-card.test.tsxdeleted file mode 100644index f94ad23e..00000000--- a/notfair/src/components/project-rename-card.test.tsx+++ /dev/null@@ -1,175 +0,0 @@-// @vitest-environment jsdom-import { beforeEach, describe, expect, it, vi } from "vitest";-import { fireEvent, render, screen, waitFor } from "@testing-library/react";--import { ProjectRenameCard } from "@/components/project-rename-card";--// Mock at the server-action boundary, per repo test conventions.-const renameFull = vi.hoisted(() => vi.fn());-vi.mock("@/server/actions/projects", () => ({- renameProjectFullAction: renameFull,-}));--const refresh = vi.hoisted(() => vi.fn());-vi.mock("next/navigation", () => ({- useRouter: () => ({ refresh, push: vi.fn() }),-}));--const toastSuccess = vi.hoisted(() => vi.fn());-const toastError = vi.hoisted(() => vi.fn());-vi.mock("sonner", () => ({- toast: { success: toastSuccess, error: toastError },-}));--beforeEach(() => {- vi.clearAllMocks();-});--function renderCard(over: Partial<React.ComponentProps<typeof ProjectRenameCard>> = {}) {- return render(- <ProjectRenameCard- currentSlug="acme"- currentDisplayName="Acme"- {...over}- />,- );-}--describe("ProjectRenameCard", () => {- it("starts with the display name and a disabled save when nothing changed", () => {- renderCard();- expect(screen.getByLabelText("Display name")).toHaveValue("Acme");- expect(- screen.getByText("Same slug — only the display name changes."),- ).toBeInTheDocument();- const btn = screen.getByRole("button", { name: "Save name" });- expect(btn).toBeDisabled();- });-- it("previews a slug change and switches the primary action to rename", () => {- renderCard();- fireEvent.change(screen.getByLabelText("Display name"), {- target: { value: "Acme Rockets" },- });- // Slug-change preview names both the old and derived slug.- expect(screen.getByText(/Slug changes from/)).toBeInTheDocument();- expect(screen.getByText("acme")).toBeInTheDocument();- expect(screen.getByText("acme-rockets")).toBeInTheDocument();- expect(- screen.getByRole("button", { name: "Rename workspace" }),- ).toBeEnabled();- });-- it("flags an unslug-able name and blocks saving", () => {- renderCard();- fireEvent.change(screen.getByLabelText("Display name"), {- target: { value: "!!!" },- });- expect(screen.getByText(/Invalid name:/)).toBeInTheDocument();- expect(screen.getByLabelText("Display name")).toHaveAttribute(- "aria-invalid",- "true",- );- expect(screen.getByRole("button", { name: "Save name" })).toBeDisabled();- });-- it("enables a display-name-only save when the slug is unchanged", () => {- renderCard();- // Same slug ("acme") but different display name.- fireEvent.change(screen.getByLabelText("Display name"), {- target: { value: "ACME" },- });- expect(- screen.getByText("Same slug — only the display name changes."),- ).toBeInTheDocument();- expect(screen.getByRole("button", { name: "Save name" })).toBeEnabled();- });-- it("reports a full rename with relocated agents on success", async () => {- renameFull.mockResolvedValue({- ok: true,- data: {- display_name: "Acme Rockets",- full_rename: true,- agents_relocated: ["a1", "a2"],- agents_failed: [],- },- });- renderCard();- fireEvent.change(screen.getByLabelText("Display name"), {- target: { value: "Acme Rockets" },- });- fireEvent.click(screen.getByRole("button", { name: "Rename workspace" }));- await waitFor(() => {- expect(renameFull).toHaveBeenCalledWith({- current_slug: "acme",- new_display_name: "Acme Rockets",- });- expect(toastSuccess).toHaveBeenCalledWith(- 'Renamed to "Acme Rockets" (2 agents moved)',- );- expect(refresh).toHaveBeenCalled();- });- });-- it("notes failed agent relocations in the success toast", async () => {- renameFull.mockResolvedValue({- ok: true,- data: {- display_name: "Acme Rockets",- full_rename: true,- agents_relocated: ["a1"],- agents_failed: [{ agent_id: "a2", error: "locked" }],- },- });- renderCard();- fireEvent.change(screen.getByLabelText("Display name"), {- target: { value: "Acme Rockets" },- });- fireEvent.click(screen.getByRole("button", { name: "Rename workspace" }));- await waitFor(() =>- expect(toastSuccess).toHaveBeenCalledWith(- 'Renamed to "Acme Rockets" (1 agents moved, 1 failed)',- ),- );- });-- it("uses the plain toast for a display-name-only rename", async () => {- renameFull.mockResolvedValue({- ok: true,- data: {- display_name: "ACME",- full_rename: false,- agents_relocated: [],- agents_failed: [],- },- });- renderCard();- fireEvent.change(screen.getByLabelText("Display name"), {- target: { value: "ACME" },- });- fireEvent.click(screen.getByRole("button", { name: "Save name" }));- await waitFor(() =>- expect(toastSuccess).toHaveBeenCalledWith('Renamed to "ACME"'),- );- });-- it("surfaces a server error and does not refresh", async () => {- renameFull.mockResolvedValue({ ok: false, error: "slug taken" });- renderCard();- fireEvent.change(screen.getByLabelText("Display name"), {- target: { value: "Acme Rockets" },- });- fireEvent.click(screen.getByRole("button", { name: "Rename workspace" }));- await waitFor(() => expect(toastError).toHaveBeenCalledWith("slug taken"));- expect(refresh).not.toHaveBeenCalled();- });-- it("syncs the field when the current display name prop changes", () => {- const { rerender } = renderCard();- rerender(- <ProjectRenameCard currentSlug="acme" currentDisplayName="Renamed Co" />,- );- expect(screen.getByLabelText("Display name")).toHaveValue("Renamed Co");- });-});diff --git a/notfair/src/components/project-rename-card.tsx b/notfair/src/components/project-rename-card.tsxdeleted file mode 100644index 352f4dba..00000000--- a/notfair/src/components/project-rename-card.tsx+++ /dev/null@@ -1,144 +0,0 @@-"use client";--import { useEffect, useState, useTransition } from "react";-import { useRouter } from "next/navigation";-import { Loader2 } from "lucide-react";-import { toast } from "sonner";-import { Label } from "@/components/ui/label";-import { cn } from "@/lib/utils";-import { slugify } from "@/lib/slug";-import { renameProjectFullAction } from "@/server/actions/projects";--type Props = {- currentSlug: string;- currentDisplayName: string;-};--export function ProjectRenameCard({- currentSlug,- currentDisplayName,-}: Props) {- const router = useRouter();- const [name, setName] = useState(currentDisplayName);- const [pending, startTransition] = useTransition();-- useEffect(() => {- setName(currentDisplayName);- }, [currentDisplayName]);-- const trimmed = name.trim();- const slugAttempt = trimmed ? slugify(trimmed) : null;- const derivedSlug = slugAttempt?.ok ? slugAttempt.slug : null;- const slugError = slugAttempt && !slugAttempt.ok ? slugAttempt.reason : null;- const slugChanged = !!derivedSlug && derivedSlug !== currentSlug;- const nameChanged = trimmed !== currentDisplayName;-- function save() {- if (!nameChanged && !slugChanged) return;- startTransition(async () => {- const r = await renameProjectFullAction({- current_slug: currentSlug,- new_display_name: trimmed,- });- if (!r.ok) {- toast.error(r.error);- return;- }- const d = r.data;- if (d.full_rename) {- const failed = d.agents_failed.length;- toast.success(- failed > 0- ? `Renamed to "${d.display_name}" (${d.agents_relocated.length} agents moved, ${failed} failed)`- : `Renamed to "${d.display_name}" (${d.agents_relocated.length} agents moved)`,- );- } else {- toast.success(`Renamed to "${d.display_name}"`);- }- router.refresh();- });- }-- const canSave =- !pending && !slugError && trimmed.length > 0 && (nameChanged || slugChanged);-- return (- <div className="ns-card">- <div className="space-y-3 p-[18px]">- <div>- <h3 className="text-[14.5px] font-semibold tracking-tight text-[hsl(var(--notfair-ink))]">- Rename this workspace- </h3>- <p className="mt-1 text-[12.5px] leading-snug text-[hsl(var(--notfair-ink-4))]">- Changing the slug renames every agent, moves- workspace dirs, and relocates sessions.- </p>- </div>-- <div className="space-y-1.5">- <Label- htmlFor="project-rename-name"- className="text-[12px] font-medium text-[hsl(var(--notfair-ink-3))]"- >- Display name- </Label>- <input- id="project-rename-name"- type="text"- value={name}- onChange={(e) => setName(e.target.value)}- disabled={pending}- className={cn(- "h-9 w-full rounded-lg bg-[hsl(var(--notfair-surface-2))] px-3 text-[13.5px] tracking-tight focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[hsl(var(--notfair-accent-border))]",- slugError && "border-destructive focus-visible:ring-destructive",- pending && "opacity-50",- )}- aria-invalid={!!slugError}- />- {slugError ? (- <p className="text-[11.5px] text-destructive">- Invalid name: {slugError}- </p>- ) : slugChanged ? (- <p className="text-[11.5px] text-[hsl(var(--notfair-ink-4))]">- Slug changes from{" "}- <code className="rounded bg-[hsl(var(--notfair-surface-2))] px-1.5 py-px font-mono text-[11px]">- {currentSlug}- </code>{" "}- to{" "}- <code className="rounded bg-[hsl(var(--notfair-accent-soft))] px-1.5 py-px font-mono text-[11px] text-[hsl(var(--notfair-accent))]">- {derivedSlug}- </code>- . Every agent will be cloned to the new workspace and the old one- removed.- </p>- ) : (- <p className="text-[11.5px] text-[hsl(var(--notfair-ink-4))]">- Same slug — only the display name changes.- </p>- )}- </div>-- <div className="flex justify-end pt-1">- <button- type="button"- onClick={save}- disabled={!canSave}- className="ns-btn ns-btn-primary ns-btn-sm"- >- {pending ? (- <>- <Loader2 className="size-3.5 animate-spin" />- {slugChanged ? "Renaming…" : "Saving…"}- </>- ) : slugChanged ? (- "Rename workspace"- ) : (- "Save name"- )}- </button>- </div>- </div>- </div>- );-}diff --git a/notfair/src/components/project-switcher.tsx b/notfair/src/components/project-switcher.tsxdeleted file mode 100644index 209dbef3..00000000--- a/notfair/src/components/project-switcher.tsx+++ /dev/null@@ -1,123 +0,0 @@-"use client";--import { useTransition } from "react";-import { useRouter, usePathname } from "next/navigation";-import { ChevronsUpDown, Plus, Check } from "lucide-react";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuLabel,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu";-import { SidebarMenuButton } from "@/components/ui/sidebar";-import type { Project } from "@/types";-import { switchProjectAction } from "@/server/actions/projects";-import { projectHref, subPathFromPathname } from "@/lib/project-href";-import { toast } from "sonner";--type Props = {- projects: Project[];- activeSlug: string | null;-};--function initials(name: string): string {- // Apple-style 1-2 character app-icon letterform. Prefer first letters- // of two words; fall back to the first two characters.- const parts = name.trim().split(/\s+/).filter(Boolean);- if (parts.length >= 2) return (parts[0]![0]! + parts[1]![0]!).toUpperCase();- return name.slice(0, 2).toUpperCase();-}--export function ProjectSwitcher({ projects, activeSlug }: Props) {- const router = useRouter();- const pathname = usePathname();- const [pending, start] = useTransition();- const active = projects.find((p) => p.slug === activeSlug) ?? null;-- function pick(slug: string) {- if (slug === activeSlug) return;- const subPath = subPathFromPathname(pathname, activeSlug);- start(async () => {- const result = await switchProjectAction(slug);- if (!result.ok) {- toast.error(result.error);- return;- }- router.push(projectHref(slug, subPath));- });- }-- return (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <SidebarMenuButton- className="h-9 gap-2 px-1.5 data-[state=open]:bg-sidebar-accent"- >- <span- aria-hidden- className="grid size-6 shrink-0 place-items-center rounded-md bg-[hsl(var(--notfair-accent-soft))] text-[10px] font-semibold tracking-tight text-[hsl(var(--notfair-accent))]"- >- {active ? initials(active.display_name) : "—"}- </span>- <span className="min-w-0 flex-1 truncate text-left text-[13px] font-medium tracking-tight">- {active?.display_name ?? "No workspace"}- </span>- <ChevronsUpDown className="size-3.5 shrink-0 opacity-60" />- </SidebarMenuButton>- </DropdownMenuTrigger>- <DropdownMenuContent align="start" sideOffset={6} className="w-64 rounded-xl p-1">- <DropdownMenuLabel className="px-2 pb-1 pt-1.5 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">- Workspaces- </DropdownMenuLabel>- {projects.length === 0 && (- <DropdownMenuItem disabled className="text-xs">- No workspaces yet- </DropdownMenuItem>- )}- {projects.map((p) => {- const isActive = p.slug === activeSlug;- return (- <DropdownMenuItem- key={p.slug}- onSelect={() => pick(p.slug)}- disabled={pending}- className="gap-2 rounded-md px-2 py-1.5"- >- <span- aria-hidden- className={`grid size-6 shrink-0 place-items-center rounded-md text-[10px] font-semibold tracking-tight ${- isActive- ? "bg-[hsl(var(--notfair-accent-soft))] text-[hsl(var(--notfair-accent))]"- : "bg-[hsl(var(--notfair-surface-2))] text-[hsl(var(--notfair-ink-2))]"- }`}- >- {initials(p.display_name)}- </span>- <span className="min-w-0 flex-1 truncate text-[13px] font-medium">- {p.display_name}- </span>- {isActive && (- <Check- className="size-3.5 text-[hsl(var(--notfair-accent))]"- aria-hidden- />- )}- </DropdownMenuItem>- );- })}- <DropdownMenuSeparator />- <DropdownMenuItem asChild className="rounded-md px-2 py-1.5">- <a- href="/onboarding"- className="gap-2 text-[13px] font-medium text-[hsl(var(--notfair-accent))]"- >- <Plus className="size-3.5" />- New workspace- </a>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- );-}diff --git a/notfair/src/components/rail-section.test.tsx b/notfair/src/components/rail-section.test.tsxdeleted file mode 100644index 1b564cd5..00000000--- a/notfair/src/components/rail-section.test.tsx+++ /dev/null@@ -1,58 +0,0 @@-// @vitest-environment jsdom-import { describe, expect, it } from "vitest";-import { fireEvent, render, screen } from "@testing-library/react";--import { RailSection } from "@/components/rail-section";--describe("RailSection", () => {- it("shows the body, title, and count by default", () => {- render(- <RailSection title="Checks" count={12} meta="next check in 42m">- <p>diary rows</p>- </RailSection>,- );- expect(screen.getByRole("button", { name: /checks/i })).toHaveAttribute(- "aria-expanded",- "true",- );- expect(screen.getByText("(12)")).toBeInTheDocument();- expect(screen.getByText("next check in 42m")).toBeInTheDocument();- expect(screen.getByText("diary rows")).toBeVisible();- });-- it("collapses on click without unmounting the body (state survives)", () => {- render(- <RailSection title="Open actions">- <p>action rows</p>- </RailSection>,- );- const toggle = screen.getByRole("button", { name: /open actions/i });- fireEvent.click(toggle);- expect(toggle).toHaveAttribute("aria-expanded", "false");- // Hidden, not removed — client state inside the body must survive.- expect(screen.getByText("action rows")).not.toBeVisible();- fireEvent.click(toggle);- expect(screen.getByText("action rows")).toBeVisible();- });-- it("collapses independently from neighboring sections", () => {- render(- <>- <RailSection title="Goal">- <p>Increase qualified traffic</p>- </RailSection>- <RailSection title="Main metric">- <p>Organic sessions</p>- </RailSection>- </>,- );-- fireEvent.click(screen.getByRole("button", { name: "Goal" }));-- expect(screen.getByText("Increase qualified traffic")).not.toBeVisible();- expect(screen.getByText("Organic sessions")).toBeVisible();- expect(- screen.getByRole("button", { name: "Main metric" }),- ).toHaveAttribute("aria-expanded", "true");- });-});diff --git a/notfair/src/components/rail-section.tsx b/notfair/src/components/rail-section.tsxdeleted file mode 100644index a5bf9da6..00000000--- a/notfair/src/components/rail-section.tsx+++ /dev/null@@ -1,58 +0,0 @@-"use client";--import { useState } from "react";-import { ChevronDown } from "lucide-react";-import { cn } from "@/lib/utils";--/**- * Collapsible goal-rail section: the uppercase heading doubles as the- * toggle. Collapsing hides (not unmounts) the body so client state inside- * — e.g. the checks list's loaded pages — survives the fold.- */-export function RailSection({- title,- count,- meta,- defaultOpen = true,- children,-}: {- title: string;- count?: number;- /** Compact status shown in the section heading, before the chevron. */- meta?: React.ReactNode;- defaultOpen?: boolean;- children: React.ReactNode;-}) {- const [open, setOpen] = useState(defaultOpen);- return (- <section>- <button- type="button"- aria-expanded={open}- onClick={() => setOpen((o) => !o)}- className="mb-2 flex w-full cursor-pointer items-center justify-between gap-2 border-0 bg-transparent p-0 text-left"- >- <span className="text-[10.5px] font-semibold uppercase tracking-[0.08em] text-[hsl(var(--notfair-ink-4))]">- {title}- {count !== undefined && (- <span className="ml-1 font-normal tabular-nums">({count})</span>- )}- </span>- <span className="flex shrink-0 items-center gap-1.5">- {meta && (- <span className="text-[10.5px] font-normal tracking-normal text-[hsl(var(--notfair-ink-4))] normal-case">- {meta}- </span>- )}- <ChevronDown- className={cn(- "size-3.5 shrink-0 text-[hsl(var(--notfair-ink-4))] transition-transform",- !open && "-rotate-90",- )}- />- </span>- </button>- <div hidden={!open}>{children}</div>- </section>- );-}diff --git a/notfair/src/components/remote-control.test.tsx b/notfair/src/components/remote-control.test.tsxdeleted file mode 100644index 0faac388..00000000--- a/notfair/src/components/remote-control.test.tsx+++ /dev/null@@ -1,139 +0,0 @@-// @vitest-environment jsdom-import { fireEvent, render, screen, waitFor } from "@testing-library/react";-import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";--import { RemoteControl } from "@/components/remote-control";-import {- SidebarMenu,- SidebarProvider,-} from "@/components/ui/sidebar";--const toastSuccess = vi.hoisted(() => vi.fn());-const toastError = vi.hoisted(() => vi.fn());--vi.mock("sonner", () => ({- toast: { success: toastSuccess, error: toastError },-}));--const fetchMock = vi.fn();-const writeText = vi.fn();--beforeAll(() => {- window.matchMedia = vi.fn().mockImplementation((query: string) => ({- matches: false,- media: query,- onchange: null,- addEventListener: vi.fn(),- removeEventListener: vi.fn(),- dispatchEvent: vi.fn(),- }));- Object.defineProperty(navigator, "clipboard", {- configurable: true,- value: { writeText },- });-});--beforeEach(() => {- vi.clearAllMocks();- vi.stubGlobal("fetch", fetchMock);-});--function jsonResponse(body: unknown, ok = true) {- return {- ok,- json: vi.fn().mockResolvedValue(body),- };-}--function renderControl() {- return render(- <SidebarProvider>- <SidebarMenu>- <RemoteControl />- </SidebarMenu>- </SidebarProvider>,- );-}--describe("RemoteControl", () => {- it("shows a live session, copies its private link, and stops it", async () => {- const active = {- status: "active",- public_url: "https://phone.trycloudflare.com",- access_url:- "https://phone.trycloudflare.com/#notfair-remote=private-token",- started_at: "2026-07-30T17:00:00.000Z",- };- fetchMock- .mockResolvedValueOnce(jsonResponse(active))- .mockResolvedValueOnce(jsonResponse({ status: "inactive" }));- writeText.mockResolvedValue(undefined);-- renderControl();-- const trigger = (await screen.findByLabelText("Remote control active"))- .closest("button")!;- fireEvent.click(trigger);-- expect(screen.getByText("Remote control is live")).toBeInTheDocument();- expect(screen.getByText(active.public_url)).toBeInTheDocument();- expect(screen.getByRole("link", { name: "Open" })).toHaveAttribute(- "href",- active.access_url,- );-- fireEvent.click(screen.getByRole("button", { name: "Copy private link" }));- await waitFor(() => expect(writeText).toHaveBeenCalledWith(active.access_url));- expect(toastSuccess).toHaveBeenCalledWith("Private remote link copied.");-- fireEvent.click(screen.getByRole("button", { name: "Stop remote control" }));- await waitFor(() => {- expect(fetchMock).toHaveBeenLastCalledWith(- "/api/remote-control",- expect.objectContaining({- method: "POST",- body: JSON.stringify({ action: "stop" }),- }),- );- });- expect(toastSuccess).toHaveBeenCalledWith("Remote control stopped.");- expect(- screen.getByRole("button", { name: "Activate remote control" }),- ).toBeInTheDocument();- });-- it("surfaces an activation failure and allows another attempt", async () => {- fetchMock- .mockResolvedValueOnce(jsonResponse({ status: "inactive" }))- .mockResolvedValueOnce(- jsonResponse({ error: "Cloudflare Tunnel is unavailable." }, false),- );-- renderControl();- await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));- fireEvent.click(- screen.getByRole("button", { name: "Remote control" }),- );- fireEvent.click(- screen.getByRole("button", { name: "Activate remote control" }),- );-- await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));- expect(fetchMock).toHaveBeenLastCalledWith(- "/api/remote-control",- expect.objectContaining({- method: "POST",- body: JSON.stringify({ action: "start" }),- }),- );- expect(- await screen.findByRole("alert"),- ).toHaveTextContent("Cloudflare Tunnel is unavailable.");- expect(toastError).toHaveBeenCalledWith(- "Cloudflare Tunnel is unavailable.",- );- expect(- screen.getByRole("button", { name: "Activate remote control" }),- ).toBeEnabled();- });-});diff --git a/notfair/src/components/remote-control.tsx b/notfair/src/components/remote-control.tsxdeleted file mode 100644index 0129ae45..00000000--- a/notfair/src/components/remote-control.tsx+++ /dev/null@@ -1,209 +0,0 @@-"use client";--import { useEffect, useState } from "react";-import {- Check,- Copy,- ExternalLink,- Loader2,- RadioTower,- ShieldCheck,- Square,-} from "lucide-react";-import { toast } from "sonner";--import { Button } from "@/components/ui/button";-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,- DialogTrigger,-} from "@/components/ui/dialog";-import {- SidebarMenuButton,- SidebarMenuItem,-} from "@/components/ui/sidebar";--type RemoteStatus =- | { status: "inactive" }- | { status: "starting" }- | {- status: "active";- public_url: string;- access_url: string;- started_at: string;- }- | { status: "error"; error: string };--export function RemoteControl() {- const [open, setOpen] = useState(false);- const [status, setStatus] = useState<RemoteStatus>({ status: "inactive" });- const [working, setWorking] = useState(false);- const [copied, setCopied] = useState(false);-- useEffect(() => {- let cancelled = false;- fetch("/api/remote-control", { cache: "no-store" })- .then((response) => response.json() as Promise<RemoteStatus>)- .then((next) => {- if (!cancelled) setStatus(next);- })- .catch(() => {});- return () => {- cancelled = true;- };- }, []);-- async function update(action: "start" | "stop") {- setWorking(true);- if (action === "start") setStatus({ status: "starting" });- try {- const response = await fetch("/api/remote-control", {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify({ action }),- });- const next = (await response.json()) as RemoteStatus | { error: string };- if (!response.ok || !("status" in next)) {- throw new Error(- "error" in next ? next.error : "Could not change remote control.",- );- }- setStatus(next);- if (next.status === "error") toast.error(next.error);- if (action === "stop") toast.success("Remote control stopped.");- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- setStatus({ status: "error", error: message });- toast.error(message);- } finally {- setWorking(false);- }- }-- async function copyLink() {- if (status.status !== "active") return;- await navigator.clipboard.writeText(status.access_url);- setCopied(true);- toast.success("Private remote link copied.");- setTimeout(() => setCopied(false), 2_000);- }-- const active = status.status === "active";- const starting = status.status === "starting" || (working && !active);-- return (- <SidebarMenuItem>- <Dialog open={open} onOpenChange={setOpen}>- <DialogTrigger asChild>- <SidebarMenuButton tooltip="Remote control">- <RadioTower />- <span>Remote control</span>- {active && (- <span- className="ml-auto size-2 rounded-full bg-[hsl(var(--notfair-accent))]"- aria-label="Remote control active"- />- )}- </SidebarMenuButton>- </DialogTrigger>- <DialogContent>- <DialogHeader>- <DialogTitle className="flex items-center gap-2">- <RadioTower className="size-5" />- Remote control- </DialogTitle>- <DialogDescription>- Open this NotFair portal securely from your phone or another- computer while this Mac stays online.- </DialogDescription>- </DialogHeader>-- {active ? (- <div className="space-y-4">- <div className="rounded-xl bg-[hsl(var(--notfair-accent-soft))] p-4">- <div className="flex items-center gap-2 text-sm font-medium text-[hsl(var(--notfair-accent))]">- <span className="size-2 rounded-full bg-current" />- Remote control is live- </div>- <p className="mt-2 break-all text-xs text-[hsl(var(--notfair-ink-3))]">- {status.public_url}- </p>- </div>- <div className="flex items-start gap-3 rounded-xl bg-[hsl(var(--notfair-surface-2))] p-4">- <ShieldCheck className="mt-0.5 size-5 shrink-0 text-[hsl(var(--notfair-accent))]" />- <p className="text-sm leading-5 text-[hsl(var(--notfair-ink-3))]">- The private link signs one browser in. Treat it like a- password: anyone with it can operate your NotFair workspace.- </p>- </div>- <div className="grid grid-cols-2 gap-2">- <Button onClick={copyLink}>- {copied ? <Check /> : <Copy />}- {copied ? "Copied" : "Copy private link"}- </Button>- <Button variant="outline" asChild>- <a- href={status.access_url}- target="_blank"- rel="noreferrer"- >- <ExternalLink />- Open- </a>- </Button>- </div>- </div>- ) : (- <div className="space-y-4">- <div className="flex items-start gap-3 rounded-xl bg-[hsl(var(--notfair-warn-soft))] p-4">- <ShieldCheck className="mt-0.5 size-5 shrink-0 text-[hsl(var(--notfair-warn))]" />- <p className="text-sm leading-5 text-[hsl(var(--notfair-ink-3))]">- Activation creates a temporary Cloudflare tunnel. The- private access token stays in the link fragment and is- exchanged for a secure browser cookie.- </p>- </div>- {status.status === "error" && (- <p- role="alert"- className="rounded-lg bg-destructive/10 px-3 py-2 text-sm text-destructive"- >- {status.error}- </p>- )}- </div>- )}-- <DialogFooter>- {active ? (- <Button- variant="destructive"- onClick={() => void update("stop")}- disabled={working}- >- {working ? <Loader2 className="animate-spin" /> : <Square />}- Stop remote control- </Button>- ) : (- <Button- onClick={() => void update("start")}- disabled={starting}- >- {starting ? (- <Loader2 className="animate-spin" />- ) : (- <RadioTower />- )}- {starting ? "Creating secure link…" : "Activate remote control"}- </Button>- )}- </DialogFooter>- </DialogContent>- </Dialog>- </SidebarMenuItem>- );-}diff --git a/notfair/src/components/reprovision-button.tsx b/notfair/src/components/reprovision-button.tsxdeleted file mode 100644index e1fb203d..00000000--- a/notfair/src/components/reprovision-button.tsx+++ /dev/null@@ -1,46 +0,0 @@-"use client";--import { useTransition } from "react";-import { RotateCw } from "lucide-react";-import { toast } from "sonner";--type ReprovisionResult =- | { ok: true; created: string[]; existed: string[] }- | { ok: false; error: string };--type Props = {- action: () => Promise<ReprovisionResult>;-};--export function ReprovisionButton({ action }: Props) {- const [pending, start] = useTransition();-- function go() {- start(async () => {- const r = await action();- if (!r.ok) {- toast.error(r.error);- return;- }- const created = r.created.length;- const existed = r.existed.length;- toast.success(- created > 0- ? `Provisioned ${created} new agent${created === 1 ? "" : "s"}.`- : `All ${existed} agents already exist.`,- );- });- }-- return (- <button- type="button"- onClick={go}- disabled={pending}- className="ns-btn ns-btn-outline ns-btn-sm"- >- <RotateCw className={`size-3.5 ${pending ? "animate-spin" : ""}`} />- {pending ? "Provisioning…" : "Reprovision agents"}- </button>- );-}diff --git a/notfair/src/components/running-dot.tsx b/notfair/src/components/running-dot.tsxdeleted file mode 100644index e179c749..00000000--- a/notfair/src/components/running-dot.tsx+++ /dev/null@@ -1,38 +0,0 @@-import { cn } from "@/lib/utils";--/**- * Pulsing dot that signals "in flight, watch this." Sky/blue tone is reserved- * for liveness so it doesn't collide with success/destructive badges.- *- * Size: `sm` for inline-with-text, `md` for status rails in lists.- */-export function RunningDot({- size = "sm",- className,- "aria-label": ariaLabel = "Running",-}: {- size?: "sm" | "md";- className?: string;- "aria-label"?: string;-}) {- const px = size === "md" ? "h-2.5 w-2.5" : "h-2 w-2";- return (- <span- role="status"- aria-label={ariaLabel}- className={cn("relative inline-flex", px, className)}- >- <span- aria-hidden- className={cn(- "absolute inset-0 inline-flex rounded-full bg-sky-400 opacity-60",- "motion-safe:animate-ping",- )}- />- <span- aria-hidden- className={cn("relative inline-flex rounded-full bg-sky-500", px)}- />- </span>- );-}diff --git a/notfair/src/components/shared-context-editor.tsx b/notfair/src/components/shared-context-editor.tsxdeleted file mode 100644index 9cddffce..00000000--- a/notfair/src/components/shared-context-editor.tsx+++ /dev/null@@ -1,111 +0,0 @@-"use client";--import { useRouter } from "next/navigation";-import { useState, useTransition } from "react";-import { Pencil } from "lucide-react";-import { toast } from "sonner";-import { saveSharedContextAction } from "@/server/actions/shared-context";-import { Button } from "@/components/ui/button";-import { Markdown } from "@/components/markdown";--/**- * Shared workspace context (PROJECT.md): rendered markdown at rest, raw- * markdown while editing. Saving pushes the new brief into every goal- * agent's identity immediately — same path the agents' own- * `set_shared_context` tool uses.- */-export function SharedContextEditor({- projectSlug,- initialContent,-}: {- projectSlug: string;- initialContent: string;-}) {- const router = useRouter();- const [pending, startTransition] = useTransition();- const [saved, setSaved] = useState(initialContent);- const [content, setContent] = useState(initialContent);- // Nothing written yet → straight into edit mode.- const [editing, setEditing] = useState(initialContent.trim() === "");- const dirty = content.trim() !== saved.trim();-- function save() {- startTransition(async () => {- const r = await saveSharedContextAction({- project_slug: projectSlug,- content,- });- if (!r.ok) {- toast.error(r.error);- return;- }- toast.success(- r.synced_agents > 0- ? `Saved — synced to ${r.synced_agents} goal agent${r.synced_agents === 1 ? "" : "s"}.`- : "Saved.",- );- setSaved(content);- setEditing(false);- router.refresh();- });- }-- if (!editing) {- return (- <div className="flex flex-col gap-3">- <div className="rounded-[14px] bg-[hsl(var(--notfair-surface-2)/0.5)] px-5 py-4">- <Markdown>{saved}</Markdown>- </div>- <div className="flex items-center justify-between gap-3">- <p className="m-0 text-[12px] text-[hsl(var(--notfair-ink-4))]">- Shared with every goal agent — they update it too when they learn- something workspace-wide.- </p>- <Button variant="outline" onClick={() => setEditing(true)}>- <Pencil className="size-3.5" aria-hidden />- Edit- </Button>- </div>- </div>- );- }-- return (- <div className="flex flex-col gap-3">- <textarea- value={content}- onChange={(e) => setContent(e.target.value)}- disabled={pending}- spellCheck={false}- autoFocus- className="min-h-[420px] w-full resize-y rounded-[14px] bg-[hsl(var(--notfair-surface-2))] px-4 py-3.5 font-mono text-[12.5px] leading-relaxed outline-none focus-visible:ring-2 focus-visible:ring-[hsl(var(--notfair-accent))]"- placeholder={- "# Company\nWhat you sell, to whom, and what matters…\n\nAgents usually write this during their first goal's intake — but you know the business best. Anything here reaches every goal agent."- }- />- <div className="flex items-center justify-between gap-3">- <p className="m-0 text-[12px] text-[hsl(var(--notfair-ink-4))]">- Raw markdown — rendered once saved. Keep it a curated brief, not a- dump.- </p>- <div className="flex items-center gap-2">- {saved.trim() !== "" && (- <Button- variant="ghost"- disabled={pending}- onClick={() => {- setContent(saved);- setEditing(false);- }}- >- Cancel- </Button>- )}- <Button onClick={save} disabled={pending || !dirty}>- {pending ? "Saving…" : "Save & sync"}- </Button>- </div>- </div>- </div>- );-}diff --git a/notfair/src/components/sidebar-brand.tsx b/notfair/src/components/sidebar-brand.tsxdeleted file mode 100644index 4f09a389..00000000--- a/notfair/src/components/sidebar-brand.tsx+++ /dev/null@@ -1,66 +0,0 @@-"use client";--import Link from "next/link";-import { PanelLeft } from "lucide-react";-import { useSidebar } from "@/components/ui/sidebar";--type Props = {- /** Where the brand link points when the sidebar is expanded. */- homeHref: string;-};--/**- * Brand mark in the sidebar header. Dual-purpose:- *- * - **Expanded:** a Link to the workspace home, anchoring the rail with- * Notfair identity. A separate SidebarTrigger collapses the rail.- * - **Collapsed:** becomes the expand toggle itself — clicking the mark- * re-opens the sidebar, and the small panel icon overlays on hover to- * signal the action. Saves a row of chrome in the icon rail.- */-export function SidebarBrand({ homeHref }: Props) {- const { state, toggleSidebar } = useSidebar();- const collapsed = state === "collapsed";-- if (collapsed) {- return (- <button- type="button"- onClick={toggleSidebar}- aria-label="Expand sidebar"- title="Expand sidebar"- className="group/brand relative flex h-8 w-full shrink-0 items-center justify-center rounded-md transition-colors hover:bg-[hsl(var(--notfair-surface-2))]"- >- {/* eslint-disable-next-line @next/next/no-img-element */}- <img- src="/notfair-mark.svg"- alt="Notfair"- className="h-[18px] w-auto transition-opacity group-hover/brand:opacity-0 dark:hidden"- />- {/* eslint-disable-next-line @next/next/no-img-element */}- <img- src="/notfair-mark-dark.svg"- alt="Notfair"- className="hidden h-[18px] w-auto transition-opacity group-hover/brand:opacity-0 dark:block"- />- <PanelLeft- aria-hidden- className="absolute size-4 text-[hsl(var(--notfair-ink-3))] opacity-0 transition-opacity group-hover/brand:opacity-100"- />- </button>- );- }-- return (- <Link- href={homeHref}- aria-label="NotFair home"- className="flex h-8 shrink-0 items-center px-2"- >- {/* eslint-disable-next-line @next/next/no-img-element */}- <img src="/notfair-mark.svg" alt="Notfair" className="h-[18px] w-auto dark:hidden" />- {/* eslint-disable-next-line @next/next/no-img-element */}- <img src="/notfair-mark-dark.svg" alt="Notfair" className="hidden h-[18px] w-auto dark:block" />- </Link>- );-}diff --git a/notfair/src/components/sidebar-goal-group.test.tsx b/notfair/src/components/sidebar-goal-group.test.tsxdeleted file mode 100644index 2f7c025b..00000000--- a/notfair/src/components/sidebar-goal-group.test.tsx+++ /dev/null@@ -1,104 +0,0 @@-// @vitest-environment jsdom-import { fireEvent, render, screen, waitFor } from "@testing-library/react";-import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";--import { GOAL_DRAG_TYPE, SidebarGoalGroup } from "@/components/sidebar-goal-group";-import { SidebarMenu, SidebarProvider } from "@/components/ui/sidebar";--// Mock at the server-action boundary, per repo test conventions.-const moveGoal = vi.hoisted(() => vi.fn());-vi.mock("@/server/actions/goal-groups", () => ({- moveGoalToGroupAction: moveGoal,- renameGoalGroupAction: vi.fn(),- deleteGoalGroupAction: vi.fn(),-}));--const refresh = vi.hoisted(() => vi.fn());-vi.mock("next/navigation", () => ({- useRouter: () => ({ refresh, push: vi.fn() }),-}));--beforeAll(() => {- // SidebarProvider's useIsMobile needs matchMedia, which jsdom lacks.- window.matchMedia = vi.fn().mockImplementation((query: string) => ({- matches: false,- media: query,- onchange: null,- addEventListener: vi.fn(),- removeEventListener: vi.fn(),- dispatchEvent: vi.fn(),- }));-});--beforeEach(() => {- moveGoal.mockReset();- refresh.mockReset();- window.localStorage.clear();-});--function renderGroup() {- return render(- <SidebarProvider>- <SidebarMenu>- <SidebarGoalGroup- groupId="g1"- name="Ads MCP reliability"- href="/p/groups/g1"- >- <li>member goal row</li>- </SidebarGoalGroup>- </SidebarMenu>- </SidebarProvider>,- );-}--describe("SidebarGoalGroup", () => {- it("matches goal rows with a trailing disclosure instead of a dot or count", () => {- renderGroup();- const header = screen.getByRole("button", { name: /^ads mcp reliability/i });- const label = screen.getByText("Ads MCP reliability");- const chevron = header.querySelector("[data-group-chevron]");-- expect(header).toHaveAttribute("aria-expanded", "true");- expect(header.querySelector(".ns-dot")).toBeNull();- expect(label.nextElementSibling).toBe(chevron);- expect(chevron).toHaveClass("rotate-90");- expect(screen.queryByText("2")).not.toBeInTheDocument();- expect(screen.getByText("member goal row")).toBeVisible();- });-- it("keeps nested goal actions on the parent row's right edge", () => {- renderGroup();- const sublist = screen.getByText("member goal row").closest("ul");- expect(sublist).toHaveClass("mr-0", "pr-0");- });-- it("collapses on header click without unmounting members, and persists", () => {- renderGroup();- const header = screen.getByRole("button", { name: /^ads mcp reliability/i });- fireEvent.click(header);- expect(header).toHaveAttribute("aria-expanded", "false");- expect(header.querySelector("[data-group-chevron]")).not.toHaveClass("rotate-90");- // Hidden, not removed — member dialog state must survive collapse.- expect(screen.getByText("member goal row")).not.toBeVisible();- expect(window.localStorage.getItem("notfair.rail.group.g1.collapsed")).toBe("1");- fireEvent.click(header);- expect(screen.getByText("member goal row")).toBeVisible();- expect(window.localStorage.getItem("notfair.rail.group.g1.collapsed")).toBeNull();- });-- it("moves a dropped goal into the group", async () => {- moveGoal.mockResolvedValue({ ok: true });- renderGroup();- const item = screen.getByRole("button", { name: /^ads mcp reliability/i })- .closest("li")!;- fireEvent.drop(item, {- dataTransfer: {- types: [GOAL_DRAG_TYPE],- getData: (type: string) => (type === GOAL_DRAG_TYPE ? "goal-9" : ""),- },- });- await waitFor(() => expect(moveGoal).toHaveBeenCalledWith("goal-9", "g1"));- await waitFor(() => expect(refresh).toHaveBeenCalled());- });-});diff --git a/notfair/src/components/sidebar-goal-group.tsx b/notfair/src/components/sidebar-goal-group.tsxdeleted file mode 100644index 97faafb4..00000000--- a/notfair/src/components/sidebar-goal-group.tsx+++ /dev/null@@ -1,277 +0,0 @@-"use client";--import Link from "next/link";-import { useRouter } from "next/navigation";-import { useEffect, useState, useTransition, type DragEvent } from "react";-import { toast } from "sonner";-import {- ChevronRight,- CircleCheck,- LayoutDashboard,- MoreVertical,- Pencil,- Trash2,-} from "lucide-react";-import {- SidebarMenuAction,- SidebarMenuButton,- SidebarMenuItem,- SidebarMenuSub,-} from "@/components/ui/sidebar";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu";-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from "@/components/ui/dialog";-import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import {- deleteGoalGroupAction,- moveGoalToGroupAction,- renameGoalGroupAction,-} from "@/server/actions/goal-groups";-import { cn } from "@/lib/utils";--/** DataTransfer MIME type carrying a goal id during a rail drag. */-export const GOAL_DRAG_TYPE = "application/x-notfair-goal";--/**- * One goal group in the sidebar rail: a goal-style collapsible row with its- * member goals nested beneath, a ⋮ menu (dashboard, rename, delete), and a- * drop target for goal rows dragged from the rail.- */-export function SidebarGoalGroup({- groupId,- name,- href,- completedCount = 0,- children,-}: {- groupId: string;- name: string;- /** Group dashboard route. */- href: string;- /** Unarchived achievements inside a collapsed group remain discoverable. */- completedCount?: number;- children?: React.ReactNode;-}) {- const router = useRouter();- const [pending, startTransition] = useTransition();- const [collapsed, setCollapsed] = useState(false);- const [dragOver, setDragOver] = useState(false);- const [renameOpen, setRenameOpen] = useState(false);- const [deleteOpen, setDeleteOpen] = useState(false);- const [draft, setDraft] = useState(name);-- // Collapse state survives navigation via localStorage; read after mount so- // the server-rendered (expanded) markup hydrates cleanly.- const storageKey = `notfair.rail.group.${groupId}.collapsed`;- useEffect(() => {- setCollapsed(window.localStorage.getItem(storageKey) === "1");- }, [storageKey]);-- function persistCollapsed(next: boolean) {- setCollapsed(next);- if (next) window.localStorage.setItem(storageKey, "1");- else window.localStorage.removeItem(storageKey);- }-- function run(- fn: () => Promise<{ ok: boolean; error?: string }>,- successMsg: string,- after?: () => void,- ) {- startTransition(async () => {- const r = await fn();- if (!r.ok) {- toast.error(r.error ?? "Action failed.");- return;- }- toast.success(successMsg);- after?.();- router.refresh();- });- }-- function onDragOver(e: DragEvent) {- if (!e.dataTransfer.types.includes(GOAL_DRAG_TYPE)) return;- e.preventDefault();- e.dataTransfer.dropEffect = "move";- setDragOver(true);- }-- function onDrop(e: DragEvent) {- setDragOver(false);- const goalId = e.dataTransfer.getData(GOAL_DRAG_TYPE);- if (!goalId) return;- e.preventDefault();- run(- () => moveGoalToGroupAction(goalId, groupId),- `Moved to ${name}.`,- // Expand so the user sees the goal land.- () => persistCollapsed(false),- );- }-- return (- <SidebarMenuItem- onDragOver={onDragOver}- onDragLeave={() => setDragOver(false)}- onDrop={onDrop}- >- <SidebarMenuButton- onClick={() => persistCollapsed(!collapsed)}- aria-expanded={!collapsed}- className={cn(- dragOver && "bg-sidebar-accent ring-2 ring-sidebar-ring",- )}- >- <span className="truncate">{name}</span>- {completedCount > 0 && (- <span- aria-label={`${completedCount} completed goal${completedCount === 1 ? "" : "s"}`}- className="ml-auto flex shrink-0 items-center gap-1 rounded-full bg-[hsl(var(--notfair-accent-soft))] px-1.5 py-0.5 text-[9px] font-semibold tabular-nums text-[hsl(var(--notfair-accent))]"- >- <CircleCheck className="!size-3" />- {completedCount}- </span>- )}- <ChevronRight- data-group-chevron- aria-hidden- className={cn(- "!size-3.5 shrink-0 text-[hsl(var(--notfair-ink-4))] transition-transform",- !collapsed && "rotate-90",- )}- />- </SidebarMenuButton>-- <DropdownMenu>- <DropdownMenuTrigger asChild>- <SidebarMenuAction showOnHover aria-label={`Group actions: ${name}`}>- <MoreVertical />- </SidebarMenuAction>- </DropdownMenuTrigger>- <DropdownMenuContent side="right" align="start" className="min-w-44">- <DropdownMenuItem asChild>- <Link href={href}>- <LayoutDashboard />- Open dashboard- </Link>- </DropdownMenuItem>- <DropdownMenuItem- disabled={pending}- onSelect={() => {- setDraft(name);- setRenameOpen(true);- }}- >- <Pencil />- Rename…- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem- variant="destructive"- disabled={pending}- onSelect={() => setDeleteOpen(true)}- >- <Trash2 />- Delete…- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>-- {/* Members stay mounted while collapsed so their dialog state survives. */}- <SidebarMenuSub className="mr-0 pr-0" hidden={collapsed}>- {children}- </SidebarMenuSub>-- <Dialog open={renameOpen} onOpenChange={setRenameOpen}>- <DialogContent className="max-w-sm">- <DialogHeader>- <DialogTitle>Rename group</DialogTitle>- <DialogDescription>- Changes the display name everywhere — the goals inside are- untouched.- </DialogDescription>- </DialogHeader>- <form- onSubmit={(e) => {- e.preventDefault();- run(- () => renameGoalGroupAction(groupId, draft),- "Group renamed.",- () => setRenameOpen(false),- );- }}- >- <Input- value={draft}- onChange={(e) => setDraft(e.target.value)}- autoFocus- aria-label="Group name"- />- <DialogFooter className="mt-4">- <Button- type="button"- variant="outline"- onClick={() => setRenameOpen(false)}- disabled={pending}- >- Cancel- </Button>- <Button type="submit" disabled={pending || !draft.trim()}>- Rename- </Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>-- <Dialog open={deleteOpen} onOpenChange={setDeleteOpen}>- <DialogContent className="max-w-sm">- <DialogHeader>- <DialogTitle>Delete “{name}”?</DialogTitle>- <DialogDescription>- Removes the group and its dashboard. Its goals become ungrouped —- their heartbeats and history are untouched.- </DialogDescription>- </DialogHeader>- <DialogFooter>- <Button- variant="outline"- onClick={() => setDeleteOpen(false)}- disabled={pending}- >- Cancel- </Button>- <Button- variant="destructive"- disabled={pending}- onClick={() =>- run(- () => deleteGoalGroupAction(groupId),- "Group deleted. Its goals are now ungrouped.",- () => setDeleteOpen(false),- )- }- >- <Trash2 className="size-3.5" />- Delete group- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- </SidebarMenuItem>- );-}diff --git a/notfair/src/components/sidebar-goal-item.tsx b/notfair/src/components/sidebar-goal-item.tsxdeleted file mode 100644index 15c20c32..00000000--- a/notfair/src/components/sidebar-goal-item.tsx+++ /dev/null@@ -1,434 +0,0 @@-"use client";--import Link from "next/link";-import { usePathname, useRouter } from "next/navigation";-import { useState, useTransition } from "react";-import { toast } from "sonner";-import {- Check,- FolderKanban,- FolderMinus,- FolderPlus,- MoreVertical,- Pause,- Pencil,- Pin,- PinOff,- Play,- Sparkles,- Trash2,- TriangleAlert,-} from "lucide-react";-import {- SidebarMenuAction,- SidebarMenuButton,- SidebarMenuItem,-} from "@/components/ui/sidebar";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuPortal,- DropdownMenuSeparator,- DropdownMenuSub,- DropdownMenuSubContent,- DropdownMenuSubTrigger,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu";-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from "@/components/ui/dialog";-import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import {- deleteGoalAction,- pauseGoalAction,- renameGoalAction,- resumeGoalAction,- setGoalPinnedAction,-} from "@/server/actions/goals";-import {- createGoalGroupAction,- moveGoalToGroupAction,-} from "@/server/actions/goal-groups";-import { GOAL_DRAG_TYPE } from "@/components/sidebar-goal-group";-import { GoalCompletionDialog } from "@/components/goal-completion-dialog";-import { cn } from "@/lib/utils";--type SidebarStatus = "intake" | "proposed" | "active" | "paused" | "achieved";--type CompletionSummary = {- metricName: string | null;- currentValue: number | null;- targetValue: number | null;- metricDirection: "increase" | "decrease" | null;- completionReason: string | null;- completedAt: string;-};--/**- * One goal row in the sidebar rail: link to the goal screen plus a ⋮ menu- * (pin, rename, move to group, pause/resume, delete). Rows are draggable onto- * group headers. Server sidebar computes the label color; this component owns- * the interactions.- */-export function SidebarGoalItem({- href,- homeHref,- goalId,- label,- status,- pinned,- labelClass,- projectSlug,- groups,- groupId,- needsAttention = false,- completion,-}: {- href: string;- /** Project home — where the user lands after deleting the open goal. */- homeHref: string;- goalId: string;- label: string;- status: SidebarStatus;- pinned: boolean;- labelClass: string;- projectSlug: string;- /** Every group in the project — targets for "Move to group". */- groups: { id: string; name: string }[];- /** The group this goal currently belongs to, if any. */- groupId: string | null;- /** Open "Needs you" escalations — renders the amber attention mark. */- needsAttention?: boolean;- /** Achievement evidence for the celebration handoff. */- completion?: CompletionSummary;-}) {- const router = useRouter();- const pathname = usePathname();- const [pending, startTransition] = useTransition();- const [renameOpen, setRenameOpen] = useState(false);- const [deleteOpen, setDeleteOpen] = useState(false);- const [newGroupOpen, setNewGroupOpen] = useState(false);- const [draft, setDraft] = useState(label);- const [groupDraft, setGroupDraft] = useState("");-- function run(- fn: () => Promise<{ ok: boolean; error?: string }>,- successMsg?: string,- after?: () => void,- ) {- startTransition(async () => {- const r = await fn();- if (!r.ok) {- toast.error(r.error ?? "Action failed.");- return;- }- if (successMsg) toast.success(successMsg);- after?.();- router.refresh();- });- }-- function onDelete() {- run(- () => deleteGoalAction(goalId),- "Goal deleted.",- () => {- setDeleteOpen(false);- // If the user is anywhere inside the deleted goal's screen, that- // route is now a 404 — send them home.- if (pathname === href || pathname?.startsWith(`${href}/`)) {- router.push(homeHref);- }- },- );- }-- return (- <SidebarMenuItem>- <SidebarMenuButton asChild>- <Link- href={href}- className={cn(status === "achieved" && "pr-[7.4rem]!")}- draggable- onDragStart={(e) => {- e.dataTransfer.setData(GOAL_DRAG_TYPE, goalId);- e.dataTransfer.effectAllowed = "move";- }}- >- <span className={cn("truncate", labelClass)}>{label}</span>- {needsAttention && (- <TriangleAlert- aria-label="Needs your action"- className="!size-3 shrink-0 text-[hsl(var(--notfair-warn))]"- />- )}- {pinned && (- <Pin- aria-label="Pinned"- className="ml-auto !size-3 shrink-0 text-[hsl(var(--notfair-ink-4))]"- />- )}- </Link>- </SidebarMenuButton>-- {status === "achieved" && completion && (- <GoalCompletionDialog- goalId={goalId}- label={label}- metricName={completion.metricName}- currentValue={completion.currentValue}- targetValue={completion.targetValue}- metricDirection={completion.metricDirection}- completionReason={completion.completionReason}- completedAt={completion.completedAt}- goalHref={href}- trigger={- <SidebarMenuAction- data-completion-badge- className="ns-completed-badge right-7 top-1 !h-6 !w-auto gap-1 rounded-full bg-[hsl(var(--notfair-accent-soft))] px-2 text-[10px] font-semibold text-[hsl(var(--notfair-accent))] shadow-[inset_0_0_0_1px_hsl(var(--notfair-accent-border))] hover:bg-[hsl(var(--notfair-accent-soft))] hover:text-[hsl(var(--notfair-accent))]"- aria-label={`Celebrate completed goal: ${label}`}- >- <Sparkles className="!size-3" />- <span>Completed</span>- </SidebarMenuAction>- }- />- )}-- <DropdownMenu>- <DropdownMenuTrigger asChild>- <SidebarMenuAction showOnHover aria-label={`Goal actions: ${label}`}>- <MoreVertical />- </SidebarMenuAction>- </DropdownMenuTrigger>- <DropdownMenuContent side="right" align="start" className="min-w-44">- <DropdownMenuItem- disabled={pending}- onSelect={() =>- run(- () => setGoalPinnedAction(goalId, !pinned),- pinned ? "Unpinned." : "Pinned to top.",- )- }- >- {pinned ? <PinOff /> : <Pin />}- {pinned ? "Unpin" : "Pin to top"}- </DropdownMenuItem>- <DropdownMenuItem- disabled={pending}- onSelect={() => {- setDraft(label);- setRenameOpen(true);- }}- >- <Pencil />- Rename…- </DropdownMenuItem>- <DropdownMenuSub>- <DropdownMenuSubTrigger disabled={pending}>- <FolderKanban />- Move to group- </DropdownMenuSubTrigger>- <DropdownMenuPortal>- <DropdownMenuSubContent className="min-w-44">- {groups.map((group) => (- <DropdownMenuItem- key={group.id}- disabled={pending || group.id === groupId}- onSelect={() =>- run(- () => moveGoalToGroupAction(goalId, group.id),- `Moved to ${group.name}.`,- )- }- >- <span className="truncate">{group.name}</span>- {group.id === groupId && <Check className="ml-auto" />}- </DropdownMenuItem>- ))}- {groups.length > 0 && <DropdownMenuSeparator />}- <DropdownMenuItem- disabled={pending}- onSelect={() => {- setGroupDraft("");- setNewGroupOpen(true);- }}- >- <FolderPlus />- New group…- </DropdownMenuItem>- {groupId && (- <DropdownMenuItem- disabled={pending}- onSelect={() =>- run(- () => moveGoalToGroupAction(goalId, null),- "Removed from group.",- )- }- >- <FolderMinus />- Remove from group- </DropdownMenuItem>- )}- </DropdownMenuSubContent>- </DropdownMenuPortal>- </DropdownMenuSub>- {status === "active" && (- <DropdownMenuItem- disabled={pending}- onSelect={() => run(() => pauseGoalAction(goalId), "Goal paused.")}- >- <Pause />- Pause- </DropdownMenuItem>- )}- {status === "paused" && (- <DropdownMenuItem- disabled={pending}- onSelect={() =>- run(() => resumeGoalAction(goalId), "Goal resumed — heartbeat restarted.")- }- >- <Play />- Resume- </DropdownMenuItem>- )}- <DropdownMenuSeparator />- <DropdownMenuItem- variant="destructive"- disabled={pending}- onSelect={() => setDeleteOpen(true)}- >- <Trash2 />- Delete…- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>-- <Dialog open={renameOpen} onOpenChange={setRenameOpen}>- <DialogContent className="max-w-sm">- <DialogHeader>- <DialogTitle>Rename goal</DialogTitle>- <DialogDescription>- Changes the display name everywhere — the ambition itself stays- as you stated it.- </DialogDescription>- </DialogHeader>- <form- onSubmit={(e) => {- e.preventDefault();- run(- () => renameGoalAction(goalId, draft),- "Goal renamed.",- () => setRenameOpen(false),- );- }}- >- <Input- value={draft}- onChange={(e) => setDraft(e.target.value)}- autoFocus- aria-label="Goal name"- />- <DialogFooter className="mt-4">- <Button- type="button"- variant="outline"- onClick={() => setRenameOpen(false)}- disabled={pending}- >- Cancel- </Button>- <Button type="submit" disabled={pending || !draft.trim()}>- Rename- </Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>-- <Dialog open={deleteOpen} onOpenChange={setDeleteOpen}>- <DialogContent className="max-w-sm">- <DialogHeader>- <DialogTitle>Delete “{label}”?</DialogTitle>- <DialogDescription>- Permanently removes the goal, its agent, its chat history, and- every check. There is no recovery — if you just want the loop to- stop, close the goal from its page instead.- </DialogDescription>- </DialogHeader>- <DialogFooter>- <Button- variant="outline"- onClick={() => setDeleteOpen(false)}- disabled={pending}- >- Cancel- </Button>- <Button variant="destructive" onClick={onDelete} disabled={pending}>- <Trash2 className="size-3.5" />- Delete forever- </Button>- </DialogFooter>- </DialogContent>- </Dialog>-- <Dialog open={newGroupOpen} onOpenChange={setNewGroupOpen}>- <DialogContent className="max-w-sm">- <DialogHeader>- <DialogTitle>New group with “{label}”</DialogTitle>- <DialogDescription>- A group is one dashboard for related goals. This goal becomes its- first member — add more from any goal’s menu or by dragging.- </DialogDescription>- </DialogHeader>- <form- onSubmit={(e) => {- e.preventDefault();- run(- () =>- createGoalGroupAction({- project_slug: projectSlug,- name: groupDraft,- goal_ids: [goalId],- }),- "Group created.",- () => setNewGroupOpen(false),- );- }}- >- <Input- value={groupDraft}- onChange={(e) => setGroupDraft(e.target.value)}- placeholder="Ads MCP reliability"- maxLength={80}- autoFocus- aria-label="Group name"- />- <DialogFooter className="mt-4">- <Button- type="button"- variant="outline"- onClick={() => setNewGroupOpen(false)}- disabled={pending}- >- Cancel- </Button>- <Button type="submit" disabled={pending || !groupDraft.trim()}>- Create group- </Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>- </SidebarMenuItem>- );-}diff --git a/notfair/src/components/sidebar-version.test.tsx b/notfair/src/components/sidebar-version.test.tsxdeleted file mode 100644index a1b6018e..00000000--- a/notfair/src/components/sidebar-version.test.tsx+++ /dev/null@@ -1,132 +0,0 @@-// @vitest-environment jsdom-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { fireEvent, render, screen, waitFor } from "@testing-library/react";--import { SidebarVersion } from "@/components/sidebar-version";--const toastSuccess = vi.hoisted(() => vi.fn());-const toastError = vi.hoisted(() => vi.fn());-vi.mock("sonner", () => ({- toast: { success: toastSuccess, error: toastError },-}));--function jsonResponse(body: unknown, ok = true) {- return { ok, json: async () => body } as Response;-}--describe("SidebarVersion", () => {- const fetchMock = vi.fn();-- beforeEach(() => {- vi.clearAllMocks();- vi.stubGlobal("fetch", fetchMock);- });-- afterEach(() => {- vi.unstubAllGlobals();- });-- it("only downloads an available update before asking the user to apply it", async () => {- fetchMock- .mockResolvedValueOnce(- jsonResponse({ current: "0.9.13", latest: "0.9.14", has_update: true }),- )- .mockResolvedValueOnce(jsonResponse({ ok: true, can_restart: true }));-- render(<SidebarVersion />);-- await waitFor(() => {- expect(fetchMock).toHaveBeenCalledWith("/api/upgrade", {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify({ action: "prepare" }),- });- });- expect(- await screen.findByRole("button", { name: /update to v0\.9\.14/i }),- ).toBeEnabled();- expect(fetchMock).toHaveBeenCalledTimes(2);- expect(toastSuccess).not.toHaveBeenCalled();- expect(screen.queryByRole("button", { name: /restart now/i })).toBeNull();- });-- it("installs and restarts only after the user clicks Update", async () => {- fetchMock- .mockResolvedValueOnce(- jsonResponse({ current: "0.9.13", latest: "0.9.14", has_update: true }),- )- .mockResolvedValueOnce(jsonResponse({ ok: true }))- .mockResolvedValueOnce(jsonResponse({ ok: true, can_restart: true }))- // Keep the restart request pending so the component remains in its- // visible updating state without beginning the version poll.- .mockReturnValueOnce(new Promise<Response>(() => {}));-- render(<SidebarVersion />);- fireEvent.click(- await screen.findByRole("button", { name: /update to v0\.9\.14/i }),- );-- await waitFor(() => {- expect(fetchMock).toHaveBeenCalledWith("/api/upgrade", {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify({ action: "apply" }),- });- expect(fetchMock).toHaveBeenCalledWith("/api/restart", { method: "POST" });- });- expect(screen.queryByRole("button", { name: /restart now/i })).toBeNull();- expect(- screen.getByRole("button", { name: /updating/i }),- ).toBeDisabled();- });-- it("keeps the manual restart fallback for foreground and dev servers", async () => {- fetchMock- .mockResolvedValueOnce(- jsonResponse({ current: "0.9.13", latest: "0.9.14", has_update: true }),- )- .mockResolvedValueOnce(- jsonResponse({ ok: true }),- )- .mockResolvedValueOnce(- jsonResponse({- ok: true,- can_restart: false,- note: "Restart NotFair from your terminal.",- }),- );-- render(<SidebarVersion />);-- fireEvent.click(- await screen.findByRole("button", { name: /update to v0\.9\.14/i }),- );- expect(await screen.findByText("Restart to apply")).toBeInTheDocument();- expect(fetchMock).toHaveBeenCalledTimes(3);- expect(toastSuccess).toHaveBeenCalledWith(- "Restart NotFair from your terminal.",- { duration: 15_000 },- );- });-- it("offers a retry without repeatedly downloading after a failure", async () => {- fetchMock- .mockResolvedValueOnce(- jsonResponse({ current: "0.9.13", latest: "0.9.14", has_update: true }),- )- .mockResolvedValueOnce(- jsonResponse({ ok: false, error: "registry unavailable" }, false),- )- .mockResolvedValueOnce(jsonResponse({ ok: true }));-- render(<SidebarVersion />);- const retry = await screen.findByRole("button", { name: /retry update/i });- expect(fetchMock).toHaveBeenCalledTimes(2);-- fireEvent.click(retry);- expect(- await screen.findByRole("button", { name: /update to v0\.9\.14/i }),- ).toBeEnabled();- expect(fetchMock).toHaveBeenCalledTimes(3);- });-});diff --git a/notfair/src/components/sidebar-version.tsx b/notfair/src/components/sidebar-version.tsxdeleted file mode 100644index 98d84d43..00000000--- a/notfair/src/components/sidebar-version.tsx+++ /dev/null@@ -1,233 +0,0 @@-"use client";--import { useEffect, useRef, useState } from "react";-import { Loader2, Sparkles } from "lucide-react";-import { toast } from "sonner";--import { Button } from "@/components/ui/button";--type VersionInfo = {- current: string;- latest: string | null;- has_update: boolean;-};--type Phase =- | "idle"- | "downloading"- | "ready"- | "updating"- | "manual"- | "failed";--/**- * Sidebar footer: current version + a two-phase update flow. A newer package- * is downloaded in the background without touching the running install. The- * Update button explicitly installs it, restarts an owned background server,- * and reloads on the new version. Foreground/dev runs are told to restart from- * the terminal after the explicit install because the app does not own them.- */-export function SidebarVersion() {- const [info, setInfo] = useState<VersionInfo | null>(null);- const [phase, setPhase] = useState<Phase>("idle");- const autoDownloadVersion = useRef<string | null>(null);-- useEffect(() => {- let cancelled = false;- fetch("/api/version", { cache: "no-store" })- .then((r) => r.json() as Promise<VersionInfo>)- .then((v) => {- if (!cancelled) setInfo(v);- })- .catch(() => {- // Offline / blocked — keep the bar empty rather than spam errors.- });- return () => {- cancelled = true;- };- }, []);-- useEffect(() => {- if (!info?.has_update || !info.latest) return;- if (autoDownloadVersion.current === info.latest) return;- autoDownloadVersion.current = info.latest;- void downloadUpdate(info);- }, [info]);-- async function downloadUpdate(version: VersionInfo) {- if (!version.has_update) return;- setPhase("downloading");- try {- const res = await fetch("/api/upgrade", {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify({ action: "prepare" }),- });- const body = (await res.json()) as- | { ok: true; note?: string }- | { ok: false; error?: string; command?: string; hint?: string };- if (!res.ok || !body.ok) {- const msg = !body.ok- ? body.hint ?? body.error ?? "Upgrade failed"- : "Upgrade failed";- if (!body.ok && body.command) {- await navigator.clipboard.writeText(body.command).catch(() => {});- toast.error(`${msg}\nCommand copied to clipboard.`, { duration: 10_000 });- } else {- toast.error(msg, { duration: 8_000 });- }- setPhase("failed");- return;- }- setPhase("ready");- } catch (err) {- toast.error(err instanceof Error ? err.message : String(err));- setPhase("failed");- }- }-- async function applyAndRestart() {- if (phase !== "ready") return;- setPhase("updating");- try {- const applyResponse = await fetch("/api/upgrade", {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify({ action: "apply" }),- });- const applyBody = (await applyResponse.json()) as- | { ok: true; can_restart: boolean; note?: string }- | { ok: false; error?: string; hint?: string; command?: string };- if (!applyResponse.ok || !applyBody.ok) {- const message = !applyBody.ok- ? applyBody.hint ?? applyBody.error ?? "Could not install the update."- : "Could not install the update.";- if (!applyBody.ok && applyBody.command) {- await navigator.clipboard.writeText(applyBody.command).catch(() => {});- toast.error(`${message}\nCommand copied to clipboard.`, { duration: 10_000 });- } else {- toast.error(message, { duration: 10_000 });- }- setPhase("ready");- return;- }- if (!applyBody.can_restart) {- toast.success(- applyBody.note ?? "Installed. Restart NotFair from your terminal to apply.",- { duration: 15_000 },- );- setPhase("manual");- return;- }-- const restartResponse = await fetch("/api/restart", { method: "POST" });- const restartBody = (await restartResponse.json()) as { ok: boolean; hint?: string };- if (!restartResponse.ok || !restartBody.ok) {- toast.error(restartBody.hint ?? "Could not restart from here — use your terminal.", {- duration: 10_000,- });- setPhase("manual");- return;- }- } catch {- // The server may die mid-response — that's the restart happening.- }- // Poll until the new version answers, then hard-reload so the client- // bundle matches the server again.- const target = info?.latest ?? null;- const deadline = Date.now() + 60_000;- const poll = async () => {- try {- const v = (await (- await fetch("/api/version", { cache: "no-store" })- ).json()) as VersionInfo;- if (!target || v.current === target) {- window.location.reload();- return;- }- } catch {- // Still down — keep waiting.- }- if (Date.now() < deadline) {- setTimeout(poll, 1_500);- } else {- toast.error("The server hasn't come back yet — check `notfair status`.", {- duration: 10_000,- });- setPhase("manual");- }- };- setTimeout(poll, 2_000);- }-- if (!info) {- return (- <div className="px-1 text-[11px] font-mono text-[hsl(var(--notfair-ink-4))]">- NotFair- </div>- );- }-- return (- <div className="flex items-center justify-between gap-2 px-1 text-[11px]">- <span className="font-mono text-[hsl(var(--notfair-ink-4))]">- NotFair v{info.current}- </span>-- {info.has_update && (phase === "idle" || phase === "downloading") && (- <Button- size="sm"- variant="outline"- disabled- title={`Downloading update v${info.latest}`}- className="h-6 gap-1 px-2 text-[10.5px] font-medium"- >- <Loader2 className="h-3 w-3 animate-spin" />- Downloading…- </Button>- )}-- {phase === "failed" && (- <Button- size="sm"- variant="outline"- onClick={() => void downloadUpdate(info)}- title={`Retry update v${info.latest}`}- className="h-6 gap-1 px-2 text-[10.5px] font-medium"- >- <Sparkles className="h-3 w-3" />- Retry update- </Button>- )}-- {(phase === "ready" || phase === "updating") && (- <Button- size="sm"- variant="outline"- disabled={phase === "updating"}- onClick={applyAndRestart}- title={`Install v${info.latest} and restart now`}- className="h-6 gap-1 px-2 text-[10.5px] font-medium"- >- {phase === "updating" ? (- <>- <Loader2 className="h-3 w-3 animate-spin" />- Updating…- </>- ) : (- <>- <Sparkles className="h-3 w-3" />- Update to v{info.latest}- </>- )}- </Button>- )}-- {phase === "manual" && (- <span className="text-[10.5px] text-[hsl(var(--notfair-accent))]">- Restart to apply- </span>- )}- </div>- );-}diff --git a/notfair/src/components/slash-command-popover.tsx b/notfair/src/components/slash-command-popover.tsxdeleted file mode 100644index 7654777b..00000000--- a/notfair/src/components/slash-command-popover.tsx+++ /dev/null@@ -1,108 +0,0 @@-"use client";--import { useEffect, useRef } from "react";-import { cn } from "@/lib/utils";-import type { SlashCommand } from "@/lib/slash-commands";--type Props = {- commands: SlashCommand[];- selectedIndex: number;- onSelect: (command: SlashCommand) => void;- onHover: (index: number) => void;-};--const CATEGORY_LABEL: Record<SlashCommand["category"], string> = {- session: "Session",- model: "Model",- status: "Status",-};--const CATEGORY_ACCENT: Record<SlashCommand["category"], string> = {- session: "text-[hsl(var(--notfair-ink-4))]",- model: "text-[hsl(var(--notfair-ink-4))]",- status: "text-[hsl(var(--notfair-ink-4))]",-};--export function SlashCommandPopover({- commands,- selectedIndex,- onSelect,- onHover,-}: Props) {- const listRef = useRef<HTMLUListElement>(null);-- // Keep the selected row in view as the user arrows through a long list.- useEffect(() => {- const list = listRef.current;- if (!list) return;- const row = list.children[selectedIndex] as HTMLElement | undefined;- if (row) row.scrollIntoView({ block: "nearest" });- }, [selectedIndex]);-- if (commands.length === 0) {- return (- <div- className="absolute bottom-full left-0 right-0 mb-2 rounded-xl border bg-popover p-3 text-xs text-muted-foreground shadow-lg"- role="listbox"- aria-label="Slash commands"- >- No matching slash commands.- </div>- );- }-- return (- <div- className="absolute bottom-full left-0 right-0 mb-2 overflow-hidden rounded-xl border bg-popover shadow-lg"- role="listbox"- aria-label="Slash commands"- >- <ul ref={listRef} className="max-h-72 overflow-y-auto py-1">- {commands.map((c, idx) => {- const isActive = idx === selectedIndex;- return (- <li key={c.name}>- <button- type="button"- onMouseEnter={() => onHover(idx)}- onClick={() => onSelect(c)}- className={cn(- "flex w-full items-center gap-3 px-3 py-2 text-left text-sm transition-colors",- isActive ? "bg-accent" : "hover:bg-accent/50",- )}- role="option"- aria-selected={isActive}- >- <span className="w-28 shrink-0 font-mono text-[13px] text-foreground">- /{c.name}- {c.args && (- <span className="ml-1 text-muted-foreground">{c.args}</span>- )}- </span>- <span className="flex-1 truncate text-xs text-muted-foreground">- {c.description}- </span>- {c.executeLocal && (- <span className="shrink-0 rounded border px-1 text-[9px] uppercase tracking-wide text-muted-foreground">- local- </span>- )}- <span- className={cn(- "shrink-0 text-[10px] uppercase tracking-wide",- CATEGORY_ACCENT[c.category],- )}- >- {CATEGORY_LABEL[c.category]}- </span>- </button>- </li>- );- })}- </ul>- <div className="bg-muted/40 px-3 py-1.5 text-[10px] text-muted-foreground">- ↑↓ navigate · Enter / Tab to select · Enter again to send · Esc to clear- </div>- </div>- );-}diff --git a/notfair/src/components/theme-provider.tsx b/notfair/src/components/theme-provider.tsxdeleted file mode 100644index 3ecfe40c..00000000--- a/notfair/src/components/theme-provider.tsx+++ /dev/null@@ -1,23 +0,0 @@-"use client";--import { ThemeProvider as NextThemesProvider } from "next-themes";--/**- * next-themes wrapper. `attribute="class"` toggles the `.dark` class- * that globals.css keys every token off. Dark is the design's native- * mode (Codex dark-first); "system" is available from the toggle.- * `disableTransitionOnChange` avoids a flash of mistimed CSS- * transitions when every token flips at once.- */-export function ThemeProvider({ children }: { children: React.ReactNode }) {- return (- <NextThemesProvider- attribute="class"- defaultTheme="dark"- enableSystem- disableTransitionOnChange- >- {children}- </NextThemesProvider>- );-}diff --git a/notfair/src/components/theme-toggle.tsx b/notfair/src/components/theme-toggle.tsxdeleted file mode 100644index 5394b36a..00000000--- a/notfair/src/components/theme-toggle.tsx+++ /dev/null@@ -1,31 +0,0 @@-"use client";--import { useEffect, useState } from "react";-import { Moon, Sun } from "lucide-react";-import { useTheme } from "next-themes";--/**- * Light/dark switch for the sidebar footer. Renders after mount only —- * next-themes resolves the stored/system theme on the client, so a- * server-rendered icon would flash the wrong glyph.- */-export function ThemeToggle() {- const { resolvedTheme, setTheme } = useTheme();- const [mounted, setMounted] = useState(false);-- useEffect(() => setMounted(true), []);- if (!mounted) return <span className="size-6" aria-hidden />;-- const isDark = resolvedTheme === "dark";- return (- <button- type="button"- onClick={() => setTheme(isDark ? "light" : "dark")}- aria-label={isDark ? "Switch to light mode" : "Switch to dark mode"}- title={isDark ? "Switch to light mode" : "Switch to dark mode"}- className="grid size-6 place-items-center rounded-md text-[hsl(var(--notfair-ink-4))] transition-colors hover:bg-[hsl(var(--notfair-surface-2))] hover:text-[hsl(var(--notfair-ink-2))]"- >- {isDark ? <Sun className="size-3.5" /> : <Moon className="size-3.5" />}- </button>- );-}diff --git a/notfair/src/components/ui/badge.tsx b/notfair/src/components/ui/badge.tsxdeleted file mode 100644index 7a6a31a6..00000000--- a/notfair/src/components/ui/badge.tsx+++ /dev/null@@ -1,48 +0,0 @@-import * as React from "react"-import { cva, type VariantProps } from "class-variance-authority"-import { Slot } from "radix-ui"--import { cn } from "@/lib/utils"--const badgeVariants = cva(- "inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3",- {- variants: {- variant: {- default: "bg-primary text-primary-foreground [a&]:hover:bg-primary/90",- secondary:- "bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",- destructive:- "bg-destructive text-white focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40 [a&]:hover:bg-destructive/90",- outline:- "bg-[hsl(var(--notfair-surface-2))] text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",- ghost: "[a&]:hover:bg-accent [a&]:hover:text-accent-foreground",- link: "text-primary underline-offset-4 [a&]:hover:underline",- },- },- defaultVariants: {- variant: "default",- },- }-)--function Badge({- className,- variant = "default",- asChild = false,- ...props-}: React.ComponentProps<"span"> &- VariantProps<typeof badgeVariants> & { asChild?: boolean }) {- const Comp = asChild ? Slot.Root : "span"-- return (- <Comp- data-slot="badge"- data-variant={variant}- className={cn(badgeVariants({ variant }), className)}- {...props}- />- )-}--export { Badge, badgeVariants }diff --git a/notfair/src/components/ui/button.tsx b/notfair/src/components/ui/button.tsxdeleted file mode 100644index 27b11c46..00000000--- a/notfair/src/components/ui/button.tsx+++ /dev/null@@ -1,64 +0,0 @@-import * as React from "react"-import { cva, type VariantProps } from "class-variance-authority"-import { Slot } from "radix-ui"--import { cn } from "@/lib/utils"--const buttonVariants = cva(- "inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",- {- variants: {- variant: {- default: "bg-primary text-primary-foreground hover:bg-primary/90",- destructive:- "bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",- outline:- "bg-[hsl(var(--notfair-surface-2))] text-[hsl(var(--notfair-ink-2))] hover:bg-accent hover:text-accent-foreground",- secondary:- "bg-secondary text-secondary-foreground hover:bg-secondary/80",- ghost:- "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",- link: "text-primary underline-offset-4 hover:underline",- },- size: {- default: "h-9 px-4 py-2 has-[>svg]:px-3",- xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",- sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",- lg: "h-10 rounded-md px-6 has-[>svg]:px-4",- icon: "size-9",- "icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",- "icon-sm": "size-8",- "icon-lg": "size-10",- },- },- defaultVariants: {- variant: "default",- size: "default",- },- }-)--function Button({- className,- variant = "default",- size = "default",- asChild = false,- ...props-}: React.ComponentProps<"button"> &- VariantProps<typeof buttonVariants> & {- asChild?: boolean- }) {- const Comp = asChild ? Slot.Root : "button"-- return (- <Comp- data-slot="button"- data-variant={variant}- data-size={size}- className={cn(buttonVariants({ variant, size, className }))}- {...props}- />- )-}--export { Button, buttonVariants }diff --git a/notfair/src/components/ui/card.tsx b/notfair/src/components/ui/card.tsxdeleted file mode 100644index 068b939c..00000000--- a/notfair/src/components/ui/card.tsx+++ /dev/null@@ -1,92 +0,0 @@-import * as React from "react"--import { cn } from "@/lib/utils"--function Card({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="card"- className={cn(- "flex flex-col gap-6 rounded-xl bg-card py-6 text-card-foreground shadow-[var(--notfair-shadow)]",- className- )}- {...props}- />- )-}--function CardHeader({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="card-header"- className={cn(- "@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",- className- )}- {...props}- />- )-}--function CardTitle({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="card-title"- className={cn("leading-none font-semibold", className)}- {...props}- />- )-}--function CardDescription({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="card-description"- className={cn("text-sm text-muted-foreground", className)}- {...props}- />- )-}--function CardAction({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="card-action"- className={cn(- "col-start-2 row-span-2 row-start-1 self-start justify-self-end",- className- )}- {...props}- />- )-}--function CardContent({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="card-content"- className={cn("px-6", className)}- {...props}- />- )-}--function CardFooter({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="card-footer"- className={cn("flex items-center px-6 [.border-t]:pt-6", className)}- {...props}- />- )-}--export {- Card,- CardHeader,- CardFooter,- CardTitle,- CardAction,- CardDescription,- CardContent,-}diff --git a/notfair/src/components/ui/dialog.tsx b/notfair/src/components/ui/dialog.tsxdeleted file mode 100644index 606a0492..00000000--- a/notfair/src/components/ui/dialog.tsx+++ /dev/null@@ -1,158 +0,0 @@-"use client"--import * as React from "react"-import { XIcon } from "lucide-react"-import { Dialog as DialogPrimitive } from "radix-ui"--import { cn } from "@/lib/utils"-import { Button } from "@/components/ui/button"--function Dialog({- ...props-}: React.ComponentProps<typeof DialogPrimitive.Root>) {- return <DialogPrimitive.Root data-slot="dialog" {...props} />-}--function DialogTrigger({- ...props-}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {- return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />-}--function DialogPortal({- ...props-}: React.ComponentProps<typeof DialogPrimitive.Portal>) {- return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />-}--function DialogClose({- ...props-}: React.ComponentProps<typeof DialogPrimitive.Close>) {- return <DialogPrimitive.Close data-slot="dialog-close" {...props} />-}--function DialogOverlay({- className,- ...props-}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {- return (- <DialogPrimitive.Overlay- data-slot="dialog-overlay"- className={cn(- "fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",- className- )}- {...props}- />- )-}--function DialogContent({- className,- children,- showCloseButton = true,- ...props-}: React.ComponentProps<typeof DialogPrimitive.Content> & {- showCloseButton?: boolean-}) {- return (- <DialogPortal data-slot="dialog-portal">- <DialogOverlay />- <DialogPrimitive.Content- data-slot="dialog-content"- className={cn(- "fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-[14px] bg-[hsl(var(--card))] p-6 shadow-[var(--notfair-shadow-lg)] duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",- className- )}- {...props}- >- {children}- {showCloseButton && (- <DialogPrimitive.Close- data-slot="dialog-close"- className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"- >- <XIcon />- <span className="sr-only">Close</span>- </DialogPrimitive.Close>- )}- </DialogPrimitive.Content>- </DialogPortal>- )-}--function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="dialog-header"- className={cn("flex flex-col gap-2 text-center sm:text-left", className)}- {...props}- />- )-}--function DialogFooter({- className,- showCloseButton = false,- children,- ...props-}: React.ComponentProps<"div"> & {- showCloseButton?: boolean-}) {- return (- <div- data-slot="dialog-footer"- className={cn(- "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",- className- )}- {...props}- >- {children}- {showCloseButton && (- <DialogPrimitive.Close asChild>- <Button variant="outline">Close</Button>- </DialogPrimitive.Close>- )}- </div>- )-}--function DialogTitle({- className,- ...props-}: React.ComponentProps<typeof DialogPrimitive.Title>) {- return (- <DialogPrimitive.Title- data-slot="dialog-title"- className={cn("text-lg leading-none font-semibold", className)}- {...props}- />- )-}--function DialogDescription({- className,- ...props-}: React.ComponentProps<typeof DialogPrimitive.Description>) {- return (- <DialogPrimitive.Description- data-slot="dialog-description"- className={cn("text-sm text-muted-foreground", className)}- {...props}- />- )-}--export {- Dialog,- DialogClose,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogOverlay,- DialogPortal,- DialogTitle,- DialogTrigger,-}diff --git a/notfair/src/components/ui/dropdown-menu.tsx b/notfair/src/components/ui/dropdown-menu.tsxdeleted file mode 100644index d6a926f8..00000000--- a/notfair/src/components/ui/dropdown-menu.tsx+++ /dev/null@@ -1,257 +0,0 @@-"use client"--import * as React from "react"-import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"-import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui"--import { cn } from "@/lib/utils"--function DropdownMenu({- ...props-}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {- return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />-}--function DropdownMenuPortal({- ...props-}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {- return (- <DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />- )-}--function DropdownMenuTrigger({- ...props-}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {- return (- <DropdownMenuPrimitive.Trigger- data-slot="dropdown-menu-trigger"- {...props}- />- )-}--function DropdownMenuContent({- className,- sideOffset = 4,- ...props-}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {- return (- <DropdownMenuPrimitive.Portal>- <DropdownMenuPrimitive.Content- data-slot="dropdown-menu-content"- sideOffset={sideOffset}- className={cn(- "z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",- className- )}- {...props}- />- </DropdownMenuPrimitive.Portal>- )-}--function DropdownMenuGroup({- ...props-}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {- return (- <DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />- )-}--function DropdownMenuItem({- className,- inset,- variant = "default",- ...props-}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {- inset?: boolean- variant?: "default" | "destructive"-}) {- return (- <DropdownMenuPrimitive.Item- data-slot="dropdown-menu-item"- data-inset={inset}- data-variant={variant}- className={cn(- "relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",- className- )}- {...props}- />- )-}--function DropdownMenuCheckboxItem({- className,- children,- checked,- ...props-}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {- return (- <DropdownMenuPrimitive.CheckboxItem- data-slot="dropdown-menu-checkbox-item"- className={cn(- "relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",- className- )}- checked={checked}- {...props}- >- <span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">- <DropdownMenuPrimitive.ItemIndicator>- <CheckIcon className="size-4" />- </DropdownMenuPrimitive.ItemIndicator>- </span>- {children}- </DropdownMenuPrimitive.CheckboxItem>- )-}--function DropdownMenuRadioGroup({- ...props-}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {- return (- <DropdownMenuPrimitive.RadioGroup- data-slot="dropdown-menu-radio-group"- {...props}- />- )-}--function DropdownMenuRadioItem({- className,- children,- ...props-}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {- return (- <DropdownMenuPrimitive.RadioItem- data-slot="dropdown-menu-radio-item"- className={cn(- "relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",- className- )}- {...props}- >- <span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">- <DropdownMenuPrimitive.ItemIndicator>- <CircleIcon className="size-2 fill-current" />- </DropdownMenuPrimitive.ItemIndicator>- </span>- {children}- </DropdownMenuPrimitive.RadioItem>- )-}--function DropdownMenuLabel({- className,- inset,- ...props-}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {- inset?: boolean-}) {- return (- <DropdownMenuPrimitive.Label- data-slot="dropdown-menu-label"- data-inset={inset}- className={cn(- "px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",- className- )}- {...props}- />- )-}--function DropdownMenuSeparator({- className,- ...props-}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {- return (- <DropdownMenuPrimitive.Separator- data-slot="dropdown-menu-separator"- className={cn("-mx-1 my-1 h-px bg-border", className)}- {...props}- />- )-}--function DropdownMenuShortcut({- className,- ...props-}: React.ComponentProps<"span">) {- return (- <span- data-slot="dropdown-menu-shortcut"- className={cn(- "ml-auto text-xs tracking-widest text-muted-foreground",- className- )}- {...props}- />- )-}--function DropdownMenuSub({- ...props-}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {- return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />-}--function DropdownMenuSubTrigger({- className,- inset,- children,- ...props-}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {- inset?: boolean-}) {- return (- <DropdownMenuPrimitive.SubTrigger- data-slot="dropdown-menu-sub-trigger"- data-inset={inset}- className={cn(- "flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",- className- )}- {...props}- >- {children}- <ChevronRightIcon className="ml-auto size-4" />- </DropdownMenuPrimitive.SubTrigger>- )-}--function DropdownMenuSubContent({- className,- ...props-}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {- return (- <DropdownMenuPrimitive.SubContent- data-slot="dropdown-menu-sub-content"- className={cn(- "z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-lg bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",- className- )}- {...props}- />- )-}--export {- DropdownMenu,- DropdownMenuPortal,- DropdownMenuTrigger,- DropdownMenuContent,- DropdownMenuGroup,- DropdownMenuLabel,- DropdownMenuItem,- DropdownMenuCheckboxItem,- DropdownMenuRadioGroup,- DropdownMenuRadioItem,- DropdownMenuSeparator,- DropdownMenuShortcut,- DropdownMenuSub,- DropdownMenuSubTrigger,- DropdownMenuSubContent,-}diff --git a/notfair/src/components/ui/input.tsx b/notfair/src/components/ui/input.tsxdeleted file mode 100644index 436e214d..00000000--- a/notfair/src/components/ui/input.tsx+++ /dev/null@@ -1,21 +0,0 @@-import * as React from "react"--import { cn } from "@/lib/utils"--function Input({ className, type, ...props }: React.ComponentProps<"input">) {- return (- <input- type={type}- data-slot="input"- className={cn(- "h-9 w-full min-w-0 rounded-md border border-transparent bg-[hsl(var(--notfair-surface-2))] px-3 py-1 text-base transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30",- "focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",- "aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",- className- )}- {...props}- />- )-}--export { Input }diff --git a/notfair/src/components/ui/label.tsx b/notfair/src/components/ui/label.tsxdeleted file mode 100644index 1ac80f70..00000000--- a/notfair/src/components/ui/label.tsx+++ /dev/null@@ -1,24 +0,0 @@-"use client"--import * as React from "react"-import { Label as LabelPrimitive } from "radix-ui"--import { cn } from "@/lib/utils"--function Label({- className,- ...props-}: React.ComponentProps<typeof LabelPrimitive.Root>) {- return (- <LabelPrimitive.Root- data-slot="label"- className={cn(- "flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",- className- )}- {...props}- />- )-}--export { Label }diff --git a/notfair/src/components/ui/separator.tsx b/notfair/src/components/ui/separator.tsxdeleted file mode 100644index cd873e36..00000000--- a/notfair/src/components/ui/separator.tsx+++ /dev/null@@ -1,28 +0,0 @@-"use client"--import * as React from "react"-import { Separator as SeparatorPrimitive } from "radix-ui"--import { cn } from "@/lib/utils"--function Separator({- className,- orientation = "horizontal",- decorative = true,- ...props-}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {- return (- <SeparatorPrimitive.Root- data-slot="separator"- decorative={decorative}- orientation={orientation}- className={cn(- "shrink-0 bg-border data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",- className- )}- {...props}- />- )-}--export { Separator }diff --git a/notfair/src/components/ui/sheet.tsx b/notfair/src/components/ui/sheet.tsxdeleted file mode 100644index cb53bb28..00000000--- a/notfair/src/components/ui/sheet.tsx+++ /dev/null@@ -1,143 +0,0 @@-"use client"--import * as React from "react"-import { XIcon } from "lucide-react"-import { Dialog as SheetPrimitive } from "radix-ui"--import { cn } from "@/lib/utils"--function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {- return <SheetPrimitive.Root data-slot="sheet" {...props} />-}--function SheetTrigger({- ...props-}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {- return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />-}--function SheetClose({- ...props-}: React.ComponentProps<typeof SheetPrimitive.Close>) {- return <SheetPrimitive.Close data-slot="sheet-close" {...props} />-}--function SheetPortal({- ...props-}: React.ComponentProps<typeof SheetPrimitive.Portal>) {- return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />-}--function SheetOverlay({- className,- ...props-}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {- return (- <SheetPrimitive.Overlay- data-slot="sheet-overlay"- className={cn(- "fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",- className- )}- {...props}- />- )-}--function SheetContent({- className,- children,- side = "right",- showCloseButton = true,- ...props-}: React.ComponentProps<typeof SheetPrimitive.Content> & {- side?: "top" | "right" | "bottom" | "left"- showCloseButton?: boolean-}) {- return (- <SheetPortal>- <SheetOverlay />- <SheetPrimitive.Content- data-slot="sheet-content"- className={cn(- "fixed z-50 flex flex-col gap-4 bg-background shadow-lg transition ease-in-out data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:animate-in data-[state=open]:duration-500",- side === "right" &&- "inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",- side === "left" &&- "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",- side === "top" &&- "inset-x-0 top-0 h-auto border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",- side === "bottom" &&- "inset-x-0 bottom-0 h-auto border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",- className- )}- {...props}- >- {children}- {showCloseButton && (- <SheetPrimitive.Close className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-secondary">- <XIcon className="size-4" />- <span className="sr-only">Close</span>- </SheetPrimitive.Close>- )}- </SheetPrimitive.Content>- </SheetPortal>- )-}--function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="sheet-header"- className={cn("flex flex-col gap-1.5 p-4", className)}- {...props}- />- )-}--function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="sheet-footer"- className={cn("mt-auto flex flex-col gap-2 p-4", className)}- {...props}- />- )-}--function SheetTitle({- className,- ...props-}: React.ComponentProps<typeof SheetPrimitive.Title>) {- return (- <SheetPrimitive.Title- data-slot="sheet-title"- className={cn("font-semibold text-foreground", className)}- {...props}- />- )-}--function SheetDescription({- className,- ...props-}: React.ComponentProps<typeof SheetPrimitive.Description>) {- return (- <SheetPrimitive.Description- data-slot="sheet-description"- className={cn("text-sm text-muted-foreground", className)}- {...props}- />- )-}--export {- Sheet,- SheetTrigger,- SheetClose,- SheetContent,- SheetHeader,- SheetFooter,- SheetTitle,- SheetDescription,-}diff --git a/notfair/src/components/ui/sidebar.tsx b/notfair/src/components/ui/sidebar.tsxdeleted file mode 100644index e37b47b7..00000000--- a/notfair/src/components/ui/sidebar.tsx+++ /dev/null@@ -1,726 +0,0 @@-"use client"--import * as React from "react"-import { cva, type VariantProps } from "class-variance-authority"-import { PanelLeftIcon } from "lucide-react"-import { Slot } from "radix-ui"--import { useIsMobile } from "@/hooks/use-mobile"-import { cn } from "@/lib/utils"-import { Button } from "@/components/ui/button"-import { Input } from "@/components/ui/input"-import { Separator } from "@/components/ui/separator"-import {- Sheet,- SheetContent,- SheetDescription,- SheetHeader,- SheetTitle,-} from "@/components/ui/sheet"-import { Skeleton } from "@/components/ui/skeleton"-import {- Tooltip,- TooltipContent,- TooltipProvider,- TooltipTrigger,-} from "@/components/ui/tooltip"--const SIDEBAR_COOKIE_NAME = "sidebar_state"-const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7-const SIDEBAR_WIDTH = "16rem"-const SIDEBAR_WIDTH_MOBILE = "18rem"-const SIDEBAR_WIDTH_ICON = "3rem"-const SIDEBAR_KEYBOARD_SHORTCUT = "b"--type SidebarContextProps = {- state: "expanded" | "collapsed"- open: boolean- setOpen: (open: boolean) => void- openMobile: boolean- setOpenMobile: (open: boolean) => void- isMobile: boolean- toggleSidebar: () => void-}--const SidebarContext = React.createContext<SidebarContextProps | null>(null)--function useSidebar() {- const context = React.useContext(SidebarContext)- if (!context) {- throw new Error("useSidebar must be used within a SidebarProvider.")- }-- return context-}--function SidebarProvider({- defaultOpen = true,- open: openProp,- onOpenChange: setOpenProp,- className,- style,- children,- ...props-}: React.ComponentProps<"div"> & {- defaultOpen?: boolean- open?: boolean- onOpenChange?: (open: boolean) => void-}) {- const isMobile = useIsMobile()- const [openMobile, setOpenMobile] = React.useState(false)-- // This is the internal state of the sidebar.- // We use openProp and setOpenProp for control from outside the component.- const [_open, _setOpen] = React.useState(defaultOpen)- const open = openProp ?? _open- const setOpen = React.useCallback(- (value: boolean | ((value: boolean) => boolean)) => {- const openState = typeof value === "function" ? value(open) : value- if (setOpenProp) {- setOpenProp(openState)- } else {- _setOpen(openState)- }-- // This sets the cookie to keep the sidebar state.- document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`- },- [setOpenProp, open]- )-- // Helper to toggle the sidebar.- const toggleSidebar = React.useCallback(() => {- return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open)- }, [isMobile, setOpen, setOpenMobile])-- // Adds a keyboard shortcut to toggle the sidebar.- React.useEffect(() => {- const handleKeyDown = (event: KeyboardEvent) => {- if (- event.key === SIDEBAR_KEYBOARD_SHORTCUT &&- (event.metaKey || event.ctrlKey)- ) {- event.preventDefault()- toggleSidebar()- }- }-- window.addEventListener("keydown", handleKeyDown)- return () => window.removeEventListener("keydown", handleKeyDown)- }, [toggleSidebar])-- // We add a state so that we can do data-state="expanded" or "collapsed".- // This makes it easier to style the sidebar with Tailwind classes.- const state = open ? "expanded" : "collapsed"-- const contextValue = React.useMemo<SidebarContextProps>(- () => ({- state,- open,- setOpen,- isMobile,- openMobile,- setOpenMobile,- toggleSidebar,- }),- [state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]- )-- return (- <SidebarContext.Provider value={contextValue}>- <TooltipProvider delayDuration={0}>- <div- data-slot="sidebar-wrapper"- style={- {- "--sidebar-width": SIDEBAR_WIDTH,- "--sidebar-width-icon": SIDEBAR_WIDTH_ICON,- ...style,- } as React.CSSProperties- }- className={cn(- "group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",- className- )}- {...props}- >- {children}- </div>- </TooltipProvider>- </SidebarContext.Provider>- )-}--function Sidebar({- side = "left",- variant = "sidebar",- collapsible = "offcanvas",- className,- children,- ...props-}: React.ComponentProps<"div"> & {- side?: "left" | "right"- variant?: "sidebar" | "floating" | "inset"- collapsible?: "offcanvas" | "icon" | "none"-}) {- const { isMobile, state, openMobile, setOpenMobile } = useSidebar()-- if (collapsible === "none") {- return (- <div- data-slot="sidebar"- className={cn(- "flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground",- className- )}- {...props}- >- {children}- </div>- )- }-- if (isMobile) {- return (- <Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>- <SheetContent- data-sidebar="sidebar"- data-slot="sidebar"- data-mobile="true"- className="w-(--sidebar-width) bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"- style={- {- "--sidebar-width": SIDEBAR_WIDTH_MOBILE,- } as React.CSSProperties- }- side={side}- >- <SheetHeader className="sr-only">- <SheetTitle>Sidebar</SheetTitle>- <SheetDescription>Displays the mobile sidebar.</SheetDescription>- </SheetHeader>- <div className="flex h-full w-full flex-col">{children}</div>- </SheetContent>- </Sheet>- )- }-- return (- <div- className="group peer hidden text-sidebar-foreground md:block"- data-state={state}- data-collapsible={state === "collapsed" ? collapsible : ""}- data-variant={variant}- data-side={side}- data-slot="sidebar"- >- {/* This is what handles the sidebar gap on desktop */}- <div- data-slot="sidebar-gap"- className={cn(- "relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",- "group-data-[collapsible=offcanvas]:w-0",- "group-data-[side=right]:rotate-180",- variant === "floating" || variant === "inset"- ? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"- : "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"- )}- />- <div- data-slot="sidebar-container"- className={cn(- "fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",- side === "left"- ? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"- : "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",- // Adjust the padding for floating and inset variants.- variant === "floating" || variant === "inset"- ? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"- : "group-data-[collapsible=icon]:w-(--sidebar-width-icon)",- className- )}- {...props}- >- <div- data-sidebar="sidebar"- data-slot="sidebar-inner"- className="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow-sm"- >- {children}- </div>- </div>- </div>- )-}--function SidebarTrigger({- className,- onClick,- ...props-}: React.ComponentProps<typeof Button>) {- const { toggleSidebar } = useSidebar()-- return (- <Button- data-sidebar="trigger"- data-slot="sidebar-trigger"- variant="ghost"- size="icon"- className={cn("size-7", className)}- onClick={(event) => {- onClick?.(event)- toggleSidebar()- }}- {...props}- >- <PanelLeftIcon />- <span className="sr-only">Toggle Sidebar</span>- </Button>- )-}--function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {- const { toggleSidebar } = useSidebar()-- return (- <button- data-sidebar="rail"- data-slot="sidebar-rail"- aria-label="Toggle Sidebar"- tabIndex={-1}- onClick={toggleSidebar}- title="Toggle Sidebar"- className={cn(- "absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border sm:flex",- "in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",- "[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",- "group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full hover:group-data-[collapsible=offcanvas]:bg-sidebar",- "[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",- "[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",- className- )}- {...props}- />- )-}--function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {- return (- <main- data-slot="sidebar-inset"- className={cn(- "relative flex min-w-0 w-full flex-1 flex-col bg-background",- "md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",- className- )}- {...props}- />- )-}--function SidebarInput({- className,- ...props-}: React.ComponentProps<typeof Input>) {- return (- <Input- data-slot="sidebar-input"- data-sidebar="input"- className={cn("h-8 w-full bg-background shadow-none", className)}- {...props}- />- )-}--function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="sidebar-header"- data-sidebar="header"- className={cn("flex flex-col gap-2 p-2", className)}- {...props}- />- )-}--function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="sidebar-footer"- data-sidebar="footer"- className={cn("flex flex-col gap-2 p-2", className)}- {...props}- />- )-}--function SidebarSeparator({- className,- ...props-}: React.ComponentProps<typeof Separator>) {- return (- <Separator- data-slot="sidebar-separator"- data-sidebar="separator"- className={cn("mx-2 w-auto bg-sidebar-border", className)}- {...props}- />- )-}--function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="sidebar-content"- data-sidebar="content"- className={cn(- "flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",- className- )}- {...props}- />- )-}--function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="sidebar-group"- data-sidebar="group"- className={cn("relative flex w-full min-w-0 flex-col p-2", className)}- {...props}- />- )-}--function SidebarGroupLabel({- className,- asChild = false,- ...props-}: React.ComponentProps<"div"> & { asChild?: boolean }) {- const Comp = asChild ? Slot.Root : "div"-- return (- <Comp- data-slot="sidebar-group-label"- data-sidebar="group-label"- className={cn(- "flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 ring-sidebar-ring outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",- "group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",- className- )}- {...props}- />- )-}--function SidebarGroupAction({- className,- asChild = false,- ...props-}: React.ComponentProps<"button"> & { asChild?: boolean }) {- const Comp = asChild ? Slot.Root : "button"-- return (- <Comp- data-slot="sidebar-group-action"- data-sidebar="group-action"- className={cn(- "absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground ring-sidebar-ring outline-hidden transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",- // Increases the hit area of the button on mobile.- "after:absolute after:-inset-2 md:after:hidden",- "group-data-[collapsible=icon]:hidden",- className- )}- {...props}- />- )-}--function SidebarGroupContent({- className,- ...props-}: React.ComponentProps<"div">) {- return (- <div- data-slot="sidebar-group-content"- data-sidebar="group-content"- className={cn("w-full text-sm", className)}- {...props}- />- )-}--function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {- return (- <ul- data-slot="sidebar-menu"- data-sidebar="menu"- className={cn("flex w-full min-w-0 flex-col gap-1", className)}- {...props}- />- )-}--function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {- return (- <li- data-slot="sidebar-menu-item"- data-sidebar="menu-item"- className={cn("group/menu-item relative", className)}- {...props}- />- )-}--const sidebarMenuButtonVariants = cva(- "peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm ring-sidebar-ring outline-hidden transition-[width,height,padding] group-has-data-[sidebar=menu-action]/menu-item:pr-8 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",- {- variants: {- variant: {- default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",- outline:- "bg-background shadow-[0_0_0_1px_var(--sidebar-border)] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_var(--sidebar-accent)]",- },- size: {- default: "h-8 text-sm",- sm: "h-7 text-xs",- lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",- },- },- defaultVariants: {- variant: "default",- size: "default",- },- }-)--function SidebarMenuButton({- asChild = false,- isActive = false,- variant = "default",- size = "default",- tooltip,- className,- ...props-}: React.ComponentProps<"button"> & {- asChild?: boolean- isActive?: boolean- tooltip?: string | React.ComponentProps<typeof TooltipContent>-} & VariantProps<typeof sidebarMenuButtonVariants>) {- const Comp = asChild ? Slot.Root : "button"- const { isMobile, state } = useSidebar()-- const button = (- <Comp- data-slot="sidebar-menu-button"- data-sidebar="menu-button"- data-size={size}- data-active={isActive}- className={cn(sidebarMenuButtonVariants({ variant, size }), className)}- {...props}- />- )-- if (!tooltip) {- return button- }-- if (typeof tooltip === "string") {- tooltip = {- children: tooltip,- }- }-- return (- <Tooltip>- <TooltipTrigger asChild>{button}</TooltipTrigger>- <TooltipContent- side="right"- align="center"- hidden={state !== "collapsed" || isMobile}- {...tooltip}- />- </Tooltip>- )-}--function SidebarMenuAction({- className,- asChild = false,- showOnHover = false,- ...props-}: React.ComponentProps<"button"> & {- asChild?: boolean- showOnHover?: boolean-}) {- const Comp = asChild ? Slot.Root : "button"-- return (- <Comp- data-slot="sidebar-menu-action"- data-sidebar="menu-action"- className={cn(- "absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground ring-sidebar-ring outline-hidden transition-transform peer-hover/menu-button:text-sidebar-accent-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",- // Increases the hit area of the button on mobile.- "after:absolute after:-inset-2 md:after:hidden",- "peer-data-[size=sm]/menu-button:top-1",- "peer-data-[size=default]/menu-button:top-1.5",- "peer-data-[size=lg]/menu-button:top-2.5",- "group-data-[collapsible=icon]:hidden",- showOnHover &&- "peer-data-[active=true]/menu-button:text-sidebar-accent-foreground data-[state=open]:opacity-100 md:opacity-0 md:peer-hover/menu-button:opacity-100 md:peer-focus-visible/menu-button:opacity-100 md:hover:opacity-100 md:focus-visible:opacity-100",- className- )}- {...props}- />- )-}--function SidebarMenuBadge({- className,- ...props-}: React.ComponentProps<"div">) {- return (- <div- data-slot="sidebar-menu-badge"- data-sidebar="menu-badge"- className={cn(- "pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium text-sidebar-foreground tabular-nums select-none",- "peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",- "peer-data-[size=sm]/menu-button:top-1",- "peer-data-[size=default]/menu-button:top-1.5",- "peer-data-[size=lg]/menu-button:top-2.5",- "group-data-[collapsible=icon]:hidden",- className- )}- {...props}- />- )-}--function SidebarMenuSkeleton({- className,- showIcon = false,- ...props-}: React.ComponentProps<"div"> & {- showIcon?: boolean-}) {- // Random width between 50 to 90%.- const width = React.useMemo(() => {- return `${Math.floor(Math.random() * 40) + 50}%`- }, [])-- return (- <div- data-slot="sidebar-menu-skeleton"- data-sidebar="menu-skeleton"- className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}- {...props}- >- {showIcon && (- <Skeleton- className="size-4 rounded-md"- data-sidebar="menu-skeleton-icon"- />- )}- <Skeleton- className="h-4 max-w-(--skeleton-width) flex-1"- data-sidebar="menu-skeleton-text"- style={- {- "--skeleton-width": width,- } as React.CSSProperties- }- />- </div>- )-}--function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {- return (- <ul- data-slot="sidebar-menu-sub"- data-sidebar="menu-sub"- className={cn(- "mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5",- "group-data-[collapsible=icon]:hidden",- className- )}- {...props}- />- )-}--function SidebarMenuSubItem({- className,- ...props-}: React.ComponentProps<"li">) {- return (- <li- data-slot="sidebar-menu-sub-item"- data-sidebar="menu-sub-item"- className={cn("group/menu-sub-item relative", className)}- {...props}- />- )-}--function SidebarMenuSubButton({- asChild = false,- size = "md",- isActive = false,- className,- ...props-}: React.ComponentProps<"a"> & {- asChild?: boolean- size?: "sm" | "md"- isActive?: boolean-}) {- const Comp = asChild ? Slot.Root : "a"-- return (- <Comp- data-slot="sidebar-menu-sub-button"- data-sidebar="menu-sub-button"- data-size={size}- data-active={isActive}- className={cn(- "flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground ring-sidebar-ring outline-hidden hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",- "data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",- size === "sm" && "text-xs",- size === "md" && "text-sm",- "group-data-[collapsible=icon]:hidden",- className- )}- {...props}- />- )-}--export {- Sidebar,- SidebarContent,- SidebarFooter,- SidebarGroup,- SidebarGroupAction,- SidebarGroupContent,- SidebarGroupLabel,- SidebarHeader,- SidebarInput,- SidebarInset,- SidebarMenu,- SidebarMenuAction,- SidebarMenuBadge,- SidebarMenuButton,- SidebarMenuItem,- SidebarMenuSkeleton,- SidebarMenuSub,- SidebarMenuSubButton,- SidebarMenuSubItem,- SidebarProvider,- SidebarRail,- SidebarSeparator,- SidebarTrigger,- useSidebar,-}diff --git a/notfair/src/components/ui/skeleton.tsx b/notfair/src/components/ui/skeleton.tsxdeleted file mode 100644index 3ec6be77..00000000--- a/notfair/src/components/ui/skeleton.tsx+++ /dev/null@@ -1,13 +0,0 @@-import { cn } from "@/lib/utils"--function Skeleton({ className, ...props }: React.ComponentProps<"div">) {- return (- <div- data-slot="skeleton"- className={cn("animate-pulse rounded-md bg-accent", className)}- {...props}- />- )-}--export { Skeleton }diff --git a/notfair/src/components/ui/sonner.tsx b/notfair/src/components/ui/sonner.tsxdeleted file mode 100644index 9b20afe2..00000000--- a/notfair/src/components/ui/sonner.tsx+++ /dev/null@@ -1,40 +0,0 @@-"use client"--import {- CircleCheckIcon,- InfoIcon,- Loader2Icon,- OctagonXIcon,- TriangleAlertIcon,-} from "lucide-react"-import { useTheme } from "next-themes"-import { Toaster as Sonner, type ToasterProps } from "sonner"--const Toaster = ({ ...props }: ToasterProps) => {- const { theme = "system" } = useTheme()-- return (- <Sonner- theme={theme as ToasterProps["theme"]}- className="toaster group"- icons={{- success: <CircleCheckIcon className="size-4" />,- info: <InfoIcon className="size-4" />,- warning: <TriangleAlertIcon className="size-4" />,- error: <OctagonXIcon className="size-4" />,- loading: <Loader2Icon className="size-4 animate-spin" />,- }}- style={- {- "--normal-bg": "var(--popover)",- "--normal-text": "var(--popover-foreground)",- "--normal-border": "var(--border)",- "--border-radius": "var(--radius)",- } as React.CSSProperties- }- {...props}- />- )-}--export { Toaster }diff --git a/notfair/src/components/ui/tooltip.tsx b/notfair/src/components/ui/tooltip.tsxdeleted file mode 100644index ec65c1e4..00000000--- a/notfair/src/components/ui/tooltip.tsx+++ /dev/null@@ -1,57 +0,0 @@-"use client"--import * as React from "react"-import { Tooltip as TooltipPrimitive } from "radix-ui"--import { cn } from "@/lib/utils"--function TooltipProvider({- delayDuration = 0,- ...props-}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {- return (- <TooltipPrimitive.Provider- data-slot="tooltip-provider"- delayDuration={delayDuration}- {...props}- />- )-}--function Tooltip({- ...props-}: React.ComponentProps<typeof TooltipPrimitive.Root>) {- return <TooltipPrimitive.Root data-slot="tooltip" {...props} />-}--function TooltipTrigger({- ...props-}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {- return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />-}--function TooltipContent({- className,- sideOffset = 0,- children,- ...props-}: React.ComponentProps<typeof TooltipPrimitive.Content>) {- return (- <TooltipPrimitive.Portal>- <TooltipPrimitive.Content- data-slot="tooltip-content"- sideOffset={sideOffset}- className={cn(- "z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",- className- )}- {...props}- >- {children}- <TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground" />- </TooltipPrimitive.Content>- </TooltipPrimitive.Portal>- )-}--export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }diff --git a/notfair/src/components/working-indicator.more.test.tsx b/notfair/src/components/working-indicator.more.test.tsxdeleted file mode 100644index 10329971..00000000--- a/notfair/src/components/working-indicator.more.test.tsx+++ /dev/null@@ -1,62 +0,0 @@-// @vitest-environment jsdom-import { render, screen } from "@testing-library/react";-import { describe, expect, it } from "vitest";--import { WorkingIndicator, type WorkingPhase } from "@/components/working-indicator";--const phase = (id: string, state: WorkingPhase["state"]): WorkingPhase => ({- id,- label: `phase ${id}`,- state,-});--describe("WorkingIndicator (top-up)", () => {- it("shows only the last three phases with per-state icons", () => {- const { container } = render(- <WorkingIndicator- agentDisplayName="Agent"- headline="Thinking"- subtitle="Ran tests ✓"- phases={[- phase("p1", "done"),- phase("p2", "done"),- phase("p3", "failed"),- phase("p4", "done"),- phase("p5", "active"),- ]}- elapsedMs={5_000}- mood="waiting"- />,- );- // Sliced to the trailing three.- expect(screen.queryByText("phase p1")).toBeNull();- expect(screen.queryByText("phase p2")).toBeNull();- expect(screen.getByText("phase p3")).toBeInTheDocument();- expect(screen.getByText("phase p5")).toBeInTheDocument();- // One list item per visible phase.- expect(container.querySelectorAll("li")).toHaveLength(3);- // Subtitle renders below the headline.- expect(screen.getByText("Ran tests ✓")).toBeInTheDocument();- // Sub-minute elapsed formatting.- expect(screen.getByText("0:05")).toBeInTheDocument();- });-- it("omits the timer when elapsed is null and the phase list when empty", () => {- const { container } = render(- <WorkingIndicator- agentDisplayName="Agent"- headline="Starting"- subtitle={null}- phases={[]}- elapsedMs={null}- mood="waiting"- />,- );- expect(container.querySelector("ol")).toBeNull();- expect(container.querySelector(".tabular-nums")).toBeNull();- expect(screen.getByRole("status", { name: "Agent Starting" })).toHaveAttribute(- "data-run-state",- "running",- );- });-});diff --git a/notfair/src/components/working-indicator.test.tsx b/notfair/src/components/working-indicator.test.tsxdeleted file mode 100644index 1d49dc84..00000000--- a/notfair/src/components/working-indicator.test.tsx+++ /dev/null@@ -1,91 +0,0 @@-// @vitest-environment jsdom-import { describe, expect, it } from "vitest";-import { render, screen } from "@testing-library/react";--import { WorkingIndicator } from "@/components/working-indicator";--describe("WorkingIndicator completed state", () => {- it("shows only animated text while writing the response", () => {- const { container } = render(- <WorkingIndicator- agentDisplayName="Google Ads errors <2%"- headline="Writing the response"- subtitle="Ran query ✓"- phases={[- {- id: "query",- label: "Ran query",- state: "done",- },- ]}- elapsedMs={30_000}- mood="writing"- />,- );-- const status = screen.getByRole("status", {- name: "Writing the response",- });- expect(status).toHaveTextContent(/^Writing the response$/);- expect(status.querySelector(".ns-shimmer-text")).toBeInTheDocument();- expect(status.querySelector("svg")).toBeNull();- expect(status.querySelector("ol")).toBeNull();- expect(screen.queryByText("Google Ads errors <2%")).toBeNull();- expect(screen.queryByText("Ran query ✓")).toBeNull();- expect(screen.queryByText("0:30")).toBeNull();- expect(container.querySelector(".animate-spin")).toBeNull();- });-- it("renders a completed turn without live motion or an increasing timer", () => {- const { container } = render(- <WorkingIndicator- agentDisplayName="Growth agent"- headline="Turn complete"- subtitle={null}- phases={[- {- id: "unfinished-tool",- label: "Inspecting data",- state: "active",- },- ]}- elapsedMs={65_000}- mood="ended"- />,- );-- expect(- screen.getByRole("status", { name: "Growth agent Turn complete" }),- ).toBeInTheDocument();- expect(- screen.getByRole("status", { name: "Growth agent Turn complete" }),- ).toHaveAttribute("data-run-state", "complete");- expect(container.querySelector('[class*="animate-"]')).toBeNull();- expect(screen.queryByText("1:05")).toBeNull();- });-- it("keeps an active tool run visibly running with elapsed time", () => {- render(- <WorkingIndicator- agentDisplayName="Growth agent"- headline="Calling X Ads"- subtitle="summarizeXAccountSetup"- phases={[- {- id: "x-ads-call",- label: "Summarize X account setup",- state: "active",- },- ]}- elapsedMs={65_000}- mood="tool"- />,- );-- expect(- screen.getByRole("status", { name: "Growth agent Calling X Ads" }),- ).toHaveAttribute("data-run-state", "running");- expect(screen.getByText("1:05")).toBeInTheDocument();- expect(screen.getByText("Summarize X account setup")).toBeInTheDocument();- });-});diff --git a/notfair/src/components/working-indicator.tsx b/notfair/src/components/working-indicator.tsxdeleted file mode 100644index 5e995623..00000000--- a/notfair/src/components/working-indicator.tsx+++ /dev/null@@ -1,147 +0,0 @@-"use client";--import { Check, CheckCircle2, Loader2, Wrench, X } from "lucide-react";--import { cn } from "@/lib/utils";--export type WorkingPhase = {- id: string;- label: string;- detail?: string | null;- state: "done" | "active" | "failed";-};--export type WorkingMood = "waiting" | "tool" | "writing" | "wrapping" | "ended";--/**- * A quiet, Codex-style run status that belongs to the conversation flow.- * It deliberately avoids card chrome: one state icon, one honest status,- * and a compact history of the latest tool calls.- */-export function WorkingIndicator({- agentDisplayName,- headline,- subtitle,- phases,- elapsedMs,- mood,-}: {- agentDisplayName: string;- headline: string;- subtitle?: string | null;- phases: WorkingPhase[];- elapsedMs: number | null;- mood: WorkingMood;-}) {- if (mood === "writing") {- return (- <div- role="status"- aria-live="polite"- aria-label={headline}- data-run-state="running"- className="py-1.5 text-xs"- >- <span className="ns-shimmer-text font-medium">{headline}</span>- </div>- );- }-- const ended = mood === "ended";- const visiblePhases = phases.slice(-3);-- return (- <div- role="status"- aria-live="polite"- aria-label={`${agentDisplayName} ${headline}`}- data-run-state={ended ? "complete" : "running"}- className="py-1.5"- >- <div className="flex min-w-0 items-center gap-2 text-xs">- {ended ? (- <CheckCircle2- className="size-3.5 shrink-0 text-emerald-500"- aria-hidden- />- ) : (- <Loader2- className="size-3.5 shrink-0 animate-spin text-[hsl(var(--notfair-accent))]"- aria-hidden- />- )}- <span- className={cn(- "font-medium",- ended ? "text-foreground/90" : "ns-shimmer-text",- )}- >- {headline}- </span>- <span className="text-muted-foreground/45">·</span>- <span className="truncate text-muted-foreground">- {agentDisplayName}- </span>- {!ended && elapsedMs != null && (- <span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground">- {formatElapsed(elapsedMs)}- </span>- )}- </div>-- {subtitle && (- <div className="mt-1 truncate font-mono text-[10.5px] tracking-tight text-muted-foreground/80">- {subtitle}- </div>- )}-- {visiblePhases.length > 0 && (- <ol className="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-1">- {visiblePhases.map((phase) => (- <li- key={phase.id}- className="inline-flex min-w-0 items-center gap-1 text-[10.5px] text-muted-foreground"- >- <PhaseIcon phase={phase} animate={!ended} />- <span className="max-w-44 truncate font-mono">- {phase.label}- </span>- </li>- ))}- </ol>- )}- </div>- );-}--function PhaseIcon({- phase,- animate,-}: {- phase: WorkingPhase;- animate: boolean;-}) {- if (phase.state === "done") {- return <Check className="size-3 shrink-0 text-emerald-500" aria-hidden />;- }- if (phase.state === "failed") {- return <X className="size-3 shrink-0 text-destructive" aria-hidden />;- }- return (- <Wrench- className={cn(- "size-3 shrink-0 text-muted-foreground",- animate && "opacity-80",- )}- aria-hidden- />- );-}--function formatElapsed(ms: number): string {- const totalSec = Math.floor(ms / 1000);- if (totalSec < 60) return `0:${totalSec.toString().padStart(2, "0")}`;- const minutes = Math.floor(totalSec / 60);- const seconds = totalSec % 60;- return `${minutes}:${seconds.toString().padStart(2, "0")}`;-}diff --git a/notfair/src/components/workspace-browser-card.tsx b/notfair/src/components/workspace-browser-card.tsxdeleted file mode 100644index 76c6103c..00000000--- a/notfair/src/components/workspace-browser-card.tsx+++ /dev/null@@ -1,218 +0,0 @@-"use client";--import { useCallback, useEffect, useState } from "react";-import { Loader2 } from "lucide-react";-import { toast } from "sonner";--import { Button } from "@/components/ui/button";--type Status = {- running: boolean;- cdpPort: number;- userDataDir: string;- uptimeMs?: number;- idleMs?: number;- idleTimeoutMs: number;-};--type Tab = { id: string; url: string; title: string };--function formatRunningStatus(status: Status): string {- const parts = [`Running on port ${status.cdpPort}`];- if (status.uptimeMs) parts.push(`${Math.round(status.uptimeMs / 1000)}s uptime`);- if (status.idleMs !== undefined) {- const remainingSec = Math.max(- 0,- Math.round((status.idleTimeoutMs - status.idleMs) / 1000),- );- parts.push(`auto-stops in ${remainingSec}s if idle`);- }- return parts.join(" · ");-}--const SIGNIN_TARGETS: Array<{ label: string; url: string }> = [- { label: "Google", url: "https://accounts.google.com/" },- { label: "Meta / Facebook", url: "https://www.facebook.com/login/" },- { label: "Search Console", url: "https://search.google.com/search-console" },-];--export function WorkspaceBrowserCard({ projectSlug }: { projectSlug: string }) {- const [status, setStatus] = useState<Status | null>(null);- const [tabs, setTabs] = useState<Tab[]>([]);- const [pending, setPending] = useState(false);- const [loading, setLoading] = useState(true);-- const refresh = useCallback(async () => {- try {- const res = await fetch(- `/api/browser/status?project_slug=${encodeURIComponent(projectSlug)}`,- { cache: "no-store" },- );- const body = await res.json();- setStatus(body.status);- setTabs(body.tabs ?? []);- } finally {- setLoading(false);- }- }, [projectSlug]);-- useEffect(() => {- void refresh();- }, [refresh]);-- async function launch(signinUrl?: string) {- setPending(true);- try {- const res = await fetch("/api/browser/launch", {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify({- project_slug: projectSlug,- signin_url: signinUrl,- headless: false,- }),- });- const body = await res.json();- if (!res.ok) throw new Error(body.error ?? "Launch failed");- toast.success(- signinUrl- ? `Opened ${new URL(signinUrl).hostname} — sign in, then come back.`- : "Workspace browser is running.",- );- await refresh();- } catch (err) {- toast.error(err instanceof Error ? err.message : String(err));- } finally {- setPending(false);- }- }-- async function shutdown() {- setPending(true);- try {- const res = await fetch("/api/browser/shutdown", {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify({ project_slug: projectSlug }),- });- const body = await res.json();- if (!res.ok) throw new Error(body.error ?? "Shutdown failed");- toast.success("Workspace browser stopped. Cookies persist for next launch.");- await refresh();- } catch (err) {- toast.error(err instanceof Error ? err.message : String(err));- } finally {- setPending(false);- }- }-- return (- <div className="ns-card">- <div className="space-y-4 p-[18px]">- <div>- <h3 className="text-[14.5px] font-semibold tracking-tight text-[hsl(var(--notfair-ink))]">- Workspace browser- </h3>- <p className="mt-1 text-[12.5px] leading-snug text-[hsl(var(--notfair-ink-4))]">- Agents share a single Chrome instance with persistent cookies.- Sign in once here (Google, Meta, Search Console, …) and every- agent inherits the session. Each agent gets its own labeled tab,- so they don't race.- </p>- </div>-- <div className="flex items-center gap-3">- <span- className={- "inline-flex items-center gap-1.5 text-[12.5px] " +- (status?.running- ? "text-[hsl(var(--notfair-ink-2))]"- : "text-[hsl(var(--notfair-ink-4))]")- }- >- <span- className={- "h-1.5 w-1.5 rounded-full " +- (status?.running ? "bg-[hsl(var(--notfair-accent))]" : "bg-[hsl(var(--notfair-ink-5))]")- }- />- {loading- ? "Checking…"- : status?.running- ? formatRunningStatus(status)- : "Not running"}- </span>-- <div className="ml-auto flex gap-2">- {status?.running ? (- <Button size="sm" variant="ghost" disabled={pending} onClick={shutdown}>- {pending && <Loader2 className="h-3 w-3 animate-spin" />}- Stop- </Button>- ) : (- <Button size="sm" disabled={pending} onClick={() => launch()}>- {pending && <Loader2 className="h-3 w-3 animate-spin" />}- Launch- </Button>- )}- </div>- </div>-- {status?.running && (- <div className="space-y-3">- <div>- <div className="text-[12px] font-medium uppercase tracking-wide text-[hsl(var(--notfair-ink-4))]">- Sign in to a service- </div>- <div className="mt-2 flex flex-wrap gap-2">- {SIGNIN_TARGETS.map((target) => (- <Button- key={target.url}- size="sm"- variant="outline"- disabled={pending}- onClick={() => launch(target.url)}- >- Open {target.label}- </Button>- ))}- </div>- <p className="mt-2 text-[12px] text-[hsl(var(--notfair-ink-4))]">- Clicking opens (or reuses) a tab labelled <code>signin</code>.- Complete the login in the Chrome window — cookies persist- automatically in this workspace's profile directory.- </p>- </div>-- {tabs.length > 0 && (- <div>- <div className="text-[12px] font-medium uppercase tracking-wide text-[hsl(var(--notfair-ink-4))]">- Open tabs ({tabs.length})- </div>- <ul className="mt-2 space-y-1">- {tabs.map((tab) => (- <li- key={tab.id}- className="flex items-center gap-2 text-[12.5px] text-[hsl(var(--notfair-ink-2))]"- >- <span className="ns-tag-mono">{tab.id}</span>- <span className="truncate" title={tab.url}>- {tab.title || tab.url}- </span>- </li>- ))}- </ul>- </div>- )}- </div>- )}-- {status && !status.running && (- <p className="text-[11.5px] text-[hsl(var(--notfair-ink-4))]">- Profile dir: <code className="break-all">{status.userDataDir}</code>- </p>- )}- </div>- </div>- );-}diff --git a/notfair/src/hooks/use-mobile.ts b/notfair/src/hooks/use-mobile.tsdeleted file mode 100644index 2b0fe1df..00000000--- a/notfair/src/hooks/use-mobile.ts+++ /dev/null@@ -1,19 +0,0 @@-import * as React from "react"--const MOBILE_BREAKPOINT = 768--export function useIsMobile() {- const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)-- React.useEffect(() => {- const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)- const onChange = () => {- setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)- }- mql.addEventListener("change", onChange)- setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)- return () => mql.removeEventListener("change", onChange)- }, [])-- return !!isMobile-}diff --git a/notfair/src/instrumentation.ts b/notfair/src/instrumentation.tsdeleted file mode 100644index 3e7048aa..00000000--- a/notfair/src/instrumentation.ts+++ /dev/null@@ -1,8 +0,0 @@-// Next.js boots this once per server process via the instrumentation hook.-// We use it to start the goal-tick loop — without that call, goal-// heartbeats never fire.-export async function register(): Promise<void> {- if (process.env.NEXT_RUNTIME !== "nodejs") return;- const { ensureSchedulerRunning } = await import("@/server/scheduler/tick");- ensureSchedulerRunning();-}diff --git a/notfair/src/lib/agent-colors.ts b/notfair/src/lib/agent-colors.tsdeleted file mode 100644index 54095c7e..00000000--- a/notfair/src/lib/agent-colors.ts+++ /dev/null@@ -1,48 +0,0 @@-/**- * Per-agent color palette used by the cron calendar (and anywhere else a- * per-agent swatch helps scanning). Agent = goal: there are no reserved- * role hues anymore — every agent gets a stable, vivid color by hashing- * its slug. Deliberately vivid: zinc/neutral would read as "disabled"- * against the rest of the UI.- */-export type AgentColor = {- /** Tailwind classes: chip background + text color. Neutral inset fill —- * hue lives in the `dot` / `label` fields only. */- chip: string;- /** Solid dot/legend swatch. */- dot: string;- /** Label color when only the label is shown. */- label: string;-};--const CHIP =- "bg-[hsl(var(--notfair-surface-2))] text-[hsl(var(--notfair-ink-3))] border-transparent";--const PALETTE: AgentColor[] = [- { chip: CHIP, dot: "bg-blue-500", label: "text-blue-700 dark:text-blue-300" },- { chip: CHIP, dot: "bg-violet-500", label: "text-violet-700 dark:text-violet-300" },- { chip: CHIP, dot: "bg-emerald-500", label: "text-emerald-700 dark:text-emerald-300" },- { chip: CHIP, dot: "bg-amber-500", label: "text-amber-700 dark:text-amber-300" },- { chip: CHIP, dot: "bg-rose-500", label: "text-rose-700 dark:text-rose-300" },- { chip: CHIP, dot: "bg-cyan-500", label: "text-cyan-700 dark:text-cyan-300" },- { chip: CHIP, dot: "bg-fuchsia-500", label: "text-fuchsia-700 dark:text-fuchsia-300" },- { chip: CHIP, dot: "bg-teal-500", label: "text-teal-700 dark:text-teal-300" },- { chip: CHIP, dot: "bg-orange-500", label: "text-orange-700 dark:text-orange-300" },- { chip: CHIP, dot: "bg-indigo-500", label: "text-indigo-700 dark:text-indigo-300" },- { chip: CHIP, dot: "bg-pink-500", label: "text-pink-700 dark:text-pink-300" },- { chip: CHIP, dot: "bg-lime-500", label: "text-lime-700 dark:text-lime-300" },-];--/** Fast deterministic hash (djb2) so a slug always maps to the same color. */-function hashSlug(slug: string): number {- let h = 5381;- for (let i = 0; i < slug.length; i++) {- h = ((h << 5) + h + slug.charCodeAt(i)) | 0;- }- return Math.abs(h);-}--/** Stable color for an agent slug (e.g. `goal-alex`). */-export function colorForAgentSlug(slug: string): AgentColor {- return PALETTE[hashSlug(slug) % PALETTE.length]!;-}diff --git a/notfair/src/lib/canonical-mcp.ts b/notfair/src/lib/canonical-mcp.tsdeleted file mode 100644index 913e5a38..00000000--- a/notfair/src/lib/canonical-mcp.ts+++ /dev/null@@ -1,4 +0,0 @@-/** The only NotFair MCP resource new connections should advertise. */-export const CANONICAL_MCP_RESOURCE_URL = "https://notfair.co/api/mcp/notfair";-export const CANONICAL_MCP_DISCOVERY_URL =- "https://notfair.co/.well-known/oauth-protected-resource/api/mcp/notfair";diff --git a/notfair/src/lib/display-helpers.test.ts b/notfair/src/lib/display-helpers.test.tsdeleted file mode 100644index ba78cd80..00000000--- a/notfair/src/lib/display-helpers.test.ts+++ /dev/null@@ -1,72 +0,0 @@-import { describe, expect, it } from "vitest";--import { colorForAgentSlug } from "./agent-colors";-import { cadenceLabel, CADENCE_OPTIONS, DEFAULT_CADENCE } from "./goal-cadence";-import { formatMetric } from "./format-metric";-import { goalLabel } from "./goal-label";-import { buildCheckSquares, currentStreak, heldAtTarget } from "./goal-streak";--describe("display helpers", () => {- it("assigns deterministic, varied agent colors", () => {- expect(colorForAgentSlug("goal-one")).toEqual(colorForAgentSlug("goal-one"));- expect(colorForAgentSlug("goal-one")).not.toEqual(colorForAgentSlug("goal-two"));- expect(colorForAgentSlug("").chip).toContain("surface-2");- });-- it("prefers short labels and trims statement fallbacks at words", () => {- expect(goalLabel({ short_label: " Revenue ", statement: "ignored" })).toBe("Revenue");- expect(goalLabel({ short_label: " ", statement: " Short ambition " })).toBe("Short ambition");- expect(goalLabel({ statement: "This statement is deliberately much longer than forty two characters total" })).toBe(- "This statement is deliberately much…",- );- expect(goalLabel({ statement: "Averylongstatementwithnospacesandmorethanfortytwocharacters" })).toHaveLength(43);- expect(goalLabel({})).toBe("New goal");- });-- it("formats metrics and cadence presets", () => {- expect(formatMetric(null)).toBe("—");- expect(formatMetric(undefined)).toBe("—");- expect(formatMetric(82065.857142)).toBe("82,065.86");- expect(DEFAULT_CADENCE).toBe(CADENCE_OPTIONS[0]!.value);- expect(cadenceLabel(DEFAULT_CADENCE)).toContain("Hourly");- expect(cadenceLabel("custom cron")).toBe("custom cron");- });-});--describe("goal streaks", () => {- it("evaluates increase/decrease targets and null values", () => {- expect(heldAtTarget(null, 1, "increase")).toBe(false);- expect(heldAtTarget(1, null, "decrease")).toBe(false);- expect(heldAtTarget(10, 10, "increase")).toBe(true);- expect(heldAtTarget(9, 10, "increase")).toBe(false);- expect(heldAtTarget(9, 10, "decrease")).toBe(true);- expect(heldAtTarget(11, 10, "decrease")).toBe(false);- });-- it("sorts checks and classifies failed, acted, and held squares", () => {- const squares = buildCheckSquares([- { tick_number: 3, started_at: "2026-01-03T00:00:00Z", metric_value: 12, status: "complete", acted: false },- { tick_number: 1, started_at: "2026-01-01T00:00:00Z", metric_value: 8, status: "complete", acted: false },- { tick_number: 2, started_at: "2026-01-02T00:00:00Z", metric_value: 11, status: "complete", acted: true },- { tick_number: 4, started_at: "2026-01-04T00:00:00Z", metric_value: 20, status: "failed", acted: false },- ], 10, "increase");- expect(squares.map((square) => [square.tick_number, square.state])).toEqual([- [1, "failed"],- [2, "acted"],- [3, "held"],- [4, "failed"],- ]);- });-- it("computes no, broken, and active streaks", () => {- expect(currentStreak([])).toBeNull();- expect(currentStreak([{ tick_number: 1, t: 1, state: "failed" }], 100)).toEqual({ holding: false, days: 0 });- const day = 86_400_000;- expect(currentStreak([- { tick_number: 1, t: day, state: "failed" },- { tick_number: 2, t: 2 * day, state: "acted" },- { tick_number: 3, t: 3 * day, state: "held" },- ], 5 * day)).toEqual({ holding: true, days: 3 });- expect(currentStreak([{ tick_number: 1, t: 10 * day, state: "held" }], 5 * day)).toEqual({ holding: true, days: 0 });- });-});diff --git a/notfair/src/lib/format-metric.ts b/notfair/src/lib/format-metric.tsdeleted file mode 100644index 4f37f7a2..00000000--- a/notfair/src/lib/format-metric.ts+++ /dev/null@@ -1,11 +0,0 @@-/**- * Human formatting for metric values everywhere the UI shows one: floats- * from averaged measurements come in with full precision- * (82065.85714285714) and must never reach the user raw.- */-const FMT = new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 });--export function formatMetric(v: number | null | undefined): string {- if (v === null || v === undefined) return "—";- return FMT.format(v);-}diff --git a/notfair/src/lib/goal-cadence.ts b/notfair/src/lib/goal-cadence.tsdeleted file mode 100644index ce02d338..00000000--- a/notfair/src/lib/goal-cadence.ts+++ /dev/null@@ -1,21 +0,0 @@-/**- * Heartbeat cadence presets for the goal loop. UTC cron under the hood- * (matching the scheduler); labels speak human. 16:00 UTC ≈ 9am Pacific- * (summer) — same convention the goal skill teaches.- */-export type CadenceOption = { value: string; label: string; hint: string };--export const CADENCE_OPTIONS: CadenceOption[] = [- { value: "0 * * * *", label: "Hourly", hint: "every hour" },- { value: "0 16 * * *", label: "Daily", hint: "every day, 9am PT" },- { value: "0 16 * * 1-5", label: "Weekdays", hint: "Mon–Fri, 9am PT" },- { value: "0 */6 * * *", label: "4× daily", hint: "every 6 hours" },- { value: "0 16 * * 1", label: "Weekly", hint: "Mondays, 9am PT" },-];--export const DEFAULT_CADENCE = CADENCE_OPTIONS[0]!.value;--export function cadenceLabel(cron: string): string {- const preset = CADENCE_OPTIONS.find((o) => o.value === cron);- return preset ? `${preset.label} (${preset.hint})` : cron;-}diff --git a/notfair/src/lib/goal-group-health.test.ts b/notfair/src/lib/goal-group-health.test.tsdeleted file mode 100644index b4dd39a6..00000000--- a/notfair/src/lib/goal-group-health.test.ts+++ /dev/null@@ -1,36 +0,0 @@-import { describe, expect, it } from "vitest";-import { countGoalGroupHealth, goalGroupHealth } from "./goal-group-health";--const active = {- status: "active" as const,- target_value: 2,- metric_direction: "decrease" as const,-};--describe("goalGroupHealth", () => {- it("evaluates every goal against its own direction and threshold", () => {- expect(goalGroupHealth({ ...active, current_value: 1.77 })).toBe("healthy");- expect(goalGroupHealth({ ...active, current_value: 29.75, target_value: 5 })).toBe("attention");- expect(- goalGroupHealth({- status: "active",- current_value: 120,- target_value: 100,- metric_direction: "increase",- }),- ).toBe("healthy");- });-- it("does not invent health when data is missing", () => {- expect(goalGroupHealth({ ...active, current_value: null })).toBe("waiting");- });-- it("counts health without averaging unrelated metrics", () => {- expect(- countGoalGroupHealth([- { ...active, current_value: 1.77 },- { ...active, current_value: 29.75, target_value: 5 },- ]),- ).toMatchObject({ healthy: 1, attention: 1 });- });-});diff --git a/notfair/src/lib/goal-group-health.ts b/notfair/src/lib/goal-group-health.tsdeleted file mode 100644index e33cb74b..00000000--- a/notfair/src/lib/goal-group-health.ts+++ /dev/null@@ -1,39 +0,0 @@-import { type GoalStatus, type MetricDirection } from "@/server/db/goals";--export type GoalGroupHealth =- | "healthy"- | "attention"- | "waiting"- | "paused"- | "closed";--export type GoalHealthInput = {- status: GoalStatus;- current_value: number | null;- target_value: number | null;- metric_direction: MetricDirection | null;-};--export function goalGroupHealth(goal: GoalHealthInput): GoalGroupHealth {- if (goal.status === "achieved") return "healthy";- if (goal.status === "failed") return "attention";- if (goal.status === "killed") return "closed";- if (goal.status === "paused") return "paused";- if (goal.status !== "active") return "waiting";- if (goal.current_value === null || goal.target_value === null) return "waiting";- const met =- goal.metric_direction === "decrease"- ? goal.current_value <= goal.target_value- : goal.current_value >= goal.target_value;- return met ? "healthy" : "attention";-}--export function countGoalGroupHealth(goals: GoalHealthInput[]) {- return goals.reduce(- (counts, goal) => {- counts[goalGroupHealth(goal)] += 1;- return counts;- },- { healthy: 0, attention: 0, waiting: 0, paused: 0, closed: 0 },- );-}diff --git a/notfair/src/lib/goal-label.ts b/notfair/src/lib/goal-label.tsdeleted file mode 100644index 06b36146..00000000--- a/notfair/src/lib/goal-label.ts+++ /dev/null@@ -1,28 +0,0 @@-/**- * Display identity for a goal. Goals are the only nameable thing in- * NotFair (agents are plumbing), so every surface labels rows/pages with- * this: the agent-written short_label when it exists, else a trimmed- * statement, else a placeholder for goals whose ambition hasn't landed.- *- * Client-safe: pure string logic, no server imports.- */--const MAX_FALLBACK_CHARS = 42;--export function goalLabel(goal: {- short_label?: string | null;- statement?: string | null;-}): string {- const label = goal.short_label?.trim();- if (label) return label;- const statement = goal.statement?.trim();- if (statement) return trimAtWord(statement, MAX_FALLBACK_CHARS);- return "New goal";-}--function trimAtWord(s: string, max: number): string {- if (s.length <= max) return s;- const cut = s.slice(0, max);- const lastSpace = cut.lastIndexOf(" ");- return `${cut.slice(0, lastSpace > max / 2 ? lastSpace : max)}…`;-}diff --git a/notfair/src/lib/goal-platforms.test.ts b/notfair/src/lib/goal-platforms.test.tsdeleted file mode 100644index 87c211a4..00000000--- a/notfair/src/lib/goal-platforms.test.ts+++ /dev/null@@ -1,51 +0,0 @@-import { describe, expect, it } from "vitest";--import {- GOAL_PLATFORMS,- goalPlatformsForConnected,-} from "@/lib/goal-platforms";--describe("goalPlatformsForConnected", () => {- it("returns nothing when nothing is connected", () => {- expect(goalPlatformsForConnected([])).toEqual([]);- });-- it("unlocks SEO when Search Console is connected", () => {- const platforms = goalPlatformsForConnected([- "notfair-googlesearchconsole",- ]);- expect(platforms.map((p) => p.key)).toEqual(["seo"]);- });-- it("maps each connected MCP to its focus option, in registry order", () => {- const platforms = goalPlatformsForConnected([- "notfair-xads",- "notfair-googleads",- "notfair-googlesearchconsole",- ]);- expect(platforms.map((p) => p.key)).toEqual(["google-ads", "seo", "x-ads"]);- });-- it("ignores MCPs without a goal-platform mapping", () => {- expect(goalPlatformsForConnected(["stripe", "supabase"])).toEqual([]);- });-});--describe("GOAL_PLATFORMS registry", () => {- it("every entry is fully usable by the form and the intake kickoff", () => {- for (const p of GOAL_PLATFORMS) {- expect(p.key, p.mcp_key).toBeTruthy();- expect(p.label).toBeTruthy();- expect(p.focus).toContain(p.mcp_key);- expect(p.placeholder).toBeTruthy();- expect(p.examples.length).toBeGreaterThan(0);- }- });-- it("keys and mcp_keys are unique", () => {- const keys = GOAL_PLATFORMS.map((p) => p.key);- const mcpKeys = GOAL_PLATFORMS.map((p) => p.mcp_key);- expect(new Set(keys).size).toBe(keys.length);- expect(new Set(mcpKeys).size).toBe(mcpKeys.length);- });-});diff --git a/notfair/src/lib/goal-platforms.ts b/notfair/src/lib/goal-platforms.tsdeleted file mode 100644index 0747f0e9..00000000--- a/notfair/src/lib/goal-platforms.ts+++ /dev/null@@ -1,99 +0,0 @@-/**- * Goal-platform registry: which "focus" options the goal-creation form- * offers, derived from the MCPs the workspace has connected. Connecting- * Search Console unlocks an SEO focus, Google Ads a paid-search focus,- * and so on — the form shows only what's actually measurable, plus a- * free-form "Other".- *- * Used by both goal-creation surfaces (the goals index and onboarding's- * first-goal step) so the experience is identical. Pure data — safe to- * import from client and server.- */--export type GoalPlatform = {- /** Stable id for the chip (also what tests key on). */- key: string;- /** MCP catalog key that unlocks this focus. */- mcp_key: string;- /** Chip label the user picks: "SEO", "Google Ads", … */- label: string;- /**- * Focus line threaded into the intake kickoff so the agent explores- * the right platform even when the statement itself is ambiguous.- */- focus: string;- /** Textarea placeholder while this focus is selected. */- placeholder: string;- /** Tap-to-fill starter statements — static, digestible, per platform. */- examples: string[];-};--export const GOAL_PLATFORMS: GoalPlatform[] = [- {- key: "google-ads",- mcp_key: "notfair-googleads",- label: "Google Ads",- focus: "Google Ads (paid search) — measure via the notfair-googleads MCP",- placeholder: 'e.g. "Cut our Google Ads CAC to $30"',- examples: [- "Cut wasted Google Ads spend to $0/week",- "Get Google Ads CAC under $50",- "Grow conversions from Google Ads 25% without raising spend",- ],- },- {- key: "meta-ads",- mcp_key: "notfair-metaads",- label: "Meta Ads",- focus:- "Meta Ads (Facebook + Instagram paid social) — measure via the notfair-metaads MCP",- placeholder: 'e.g. "Get Meta Ads ROAS above 3x"',- examples: [- "Get Meta Ads ROAS above 3x",- "Cut Meta Ads cost per lead under $25",- ],- },- {- key: "seo",- mcp_key: "notfair-googlesearchconsole",- label: "SEO",- focus:- "SEO / organic search — measure via the notfair-googlesearchconsole MCP",- placeholder: 'e.g. "Grow organic clicks 30% in 90 days"',- examples: [- "Grow organic clicks 30% in 90 days",- "Lift CTR on our top 20 queries above 4%",- "Grow impressions for our money keywords 50%",- ],- },- {- key: "x-ads",- mcp_key: "notfair-xads",- label: "X Ads",- focus: "X (Twitter) Ads — measure via the notfair-xads MCP",- placeholder: 'e.g. "Keep X Ads CPM under $8"',- examples: [- "Keep X Ads CPM under $8 while holding impressions steady",- "Grow X Ads engagement rate to 2%",- ],- },- {- key: "analytics",- mcp_key: "notfair-googleanalytics",- label: "Analytics",- focus: "Site analytics (GA4) — measure via the notfair-googleanalytics MCP",- placeholder: 'e.g. "Grow weekly sessions 20%"',- examples: [- "Grow weekly sessions 20%",- "Lift signup conversion rate to 3%",- ],- },-];--/** The focus options a workspace has actually unlocked, in registry order. */-export function goalPlatformsForConnected(- connectedMcpKeys: string[],-): GoalPlatform[] {- const connected = new Set(connectedMcpKeys);- return GOAL_PLATFORMS.filter((p) => connected.has(p.mcp_key));-}diff --git a/notfair/src/lib/goal-streak.ts b/notfair/src/lib/goal-streak.tsdeleted file mode 100644index c14e5e6b..00000000--- a/notfair/src/lib/goal-streak.ts+++ /dev/null@@ -1,69 +0,0 @@-/**- * Streak math for MAINTAIN goals: "held at target for N days" is the- * right hero stat when holding IS the job. Pure — testable without a DB.- */--export type CheckSquare = {- tick_number: number;- t: number;- /** held = measured at/inside target; acted = the agent intervened this- * check; failed = the check errored or the metric drifted. */- state: "held" | "acted" | "failed";-};--export type StreakInput = {- tick_number: number;- started_at: string;- metric_value: number | null;- status: string;- /** true when a mutation action was logged on this check. */- acted: boolean;-};--export function heldAtTarget(- value: number | null,- target: number | null,- direction: "increase" | "decrease" | null,-): boolean {- if (value === null || target === null) return false;- return direction === "decrease" ? value <= target : value >= target;-}--export function buildCheckSquares(- checks: StreakInput[],- target: number | null,- direction: "increase" | "decrease" | null,-): CheckSquare[] {- return checks- .slice()- .sort((a, b) => a.tick_number - b.tick_number)- .map((c) => ({- tick_number: c.tick_number,- t: Date.parse(c.started_at),- state:- c.status === "failed" || !heldAtTarget(c.metric_value, target, direction)- ? ("failed" as const)- : c.acted- ? ("acted" as const)- : ("held" as const),- }));-}--export type Streak = { holding: boolean; days: number };--/**- * The current hold: `holding` is false when the LATEST check drifted or- * failed; otherwise days counts from the first check of the unbroken run- * (0 = held since today). Null when there are no finished checks yet.- */-export function currentStreak(squares: CheckSquare[], now = Date.now()): Streak | null {- if (squares.length === 0) return null;- let runStart: number | null = null;- for (let i = squares.length - 1; i >= 0; i--) {- const sq = squares[i]!;- if (sq.state === "failed") break;- runStart = sq.t;- }- if (runStart === null) return { holding: false, days: 0 };- return { holding: true, days: Math.max(0, Math.floor((now - runStart) / 86_400_000)) };-}diff --git a/notfair/src/lib/mcp-account-pickers.test.ts b/notfair/src/lib/mcp-account-pickers.test.tsdeleted file mode 100644index 963fc59a..00000000--- a/notfair/src/lib/mcp-account-pickers.test.ts+++ /dev/null@@ -1,129 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--import { accountPickerFor } from "@/lib/mcp-account-pickers";-import {- listGoogleAdsAccounts,- listMetaAdsAccounts,- listGscProperties,- setOnboardingAccountAction,- setOnboardingGscPropertyAction,-} from "@/server/onboarding/accounts";-import type { Project } from "@/types";--vi.mock("@/server/onboarding/accounts", () => ({- listGoogleAdsAccounts: vi.fn(),- setOnboardingAccountAction: vi.fn(),- listMetaAdsAccounts: vi.fn(),- setOnboardingMetaAdsAccountAction: vi.fn(),- listGscProperties: vi.fn(),- setOnboardingGscPropertyAction: vi.fn(),-}));--const project = {- google_ads_account_id: "111",- meta_ads_account_id: "act_222",- gsc_property_id: "sc-domain:example.com",-} as Project;--beforeEach(() => {- vi.clearAllMocks();-});--describe("accountPickerFor", () => {- it("returns null for MCPs without an account picker", () => {- expect(accountPickerFor("notfair-xads")).toBeNull();- expect(accountPickerFor("stripe")).toBeNull();- expect(accountPickerFor("")).toBeNull();- });-- it("covers exactly the three multi-account MCPs", () => {- for (const key of [- "notfair-googleads",- "notfair-metaads",- "notfair-googlesearchconsole",- ]) {- expect(accountPickerFor(key), key).not.toBeNull();- }- });-- it("reads the persisted selection off the matching project column", () => {- expect(accountPickerFor("notfair-googleads")!.selectedId(project)).toBe(- "111",- );- expect(accountPickerFor("notfair-metaads")!.selectedId(project)).toBe(- "act_222",- );- expect(- accountPickerFor("notfair-googlesearchconsole")!.selectedId(project),- ).toBe("sc-domain:example.com");- });-});--describe("list normalization", () => {- it("maps Google Ads accounts without a default flag", async () => {- vi.mocked(listGoogleAdsAccounts).mockResolvedValue({- ok: true,- accounts: [- { id: "111", name: "Acme" },- { id: "222", name: "Beta" },- ],- });- const r = await accountPickerFor("notfair-googleads")!.list("proj");- expect(r).toEqual({- ok: true,- items: [- { id: "111", name: "Acme" },- { id: "222", name: "Beta" },- ],- });- expect(listGoogleAdsAccounts).toHaveBeenCalledWith("proj");- });-- it("maps GSC properties through the same shape", async () => {- vi.mocked(listGscProperties).mockResolvedValue({- ok: true,- properties: [- { id: "sc-domain:a.com", name: "a.com", permission: "siteOwner" },- ],- });- const r = await accountPickerFor("notfair-googlesearchconsole")!.list("p");- expect(r).toEqual({- ok: true,- items: [{ id: "sc-domain:a.com", name: "a.com" }],- });- });-- it("passes list failures through untouched", async () => {- vi.mocked(listMetaAdsAccounts).mockResolvedValue({- ok: false,- kind: "rpc",- error: "HTTP 500",- });- const r = await accountPickerFor("notfair-metaads")!.list("p");- expect(r).toEqual({ ok: false, error: "HTTP 500" });- });-});--describe("set normalization", () => {- it("delegates to the platform set action and simplifies the result", async () => {- vi.mocked(setOnboardingAccountAction).mockResolvedValue({- ok: true,- project,- });- const r = await accountPickerFor("notfair-googleads")!.set("proj", "111");- expect(r).toEqual({ ok: true });- expect(setOnboardingAccountAction).toHaveBeenCalledWith("proj", "111");- });-- it("surfaces set failures as { ok: false, error }", async () => {- vi.mocked(setOnboardingGscPropertyAction).mockResolvedValue({- ok: false,- error: "Property X isn't reachable.",- });- const r = await accountPickerFor("notfair-googlesearchconsole")!.set(- "proj",- "X",- );- expect(r).toEqual({ ok: false, error: "Property X isn't reachable." });- });-});diff --git a/notfair/src/lib/mcp-account-pickers.ts b/notfair/src/lib/mcp-account-pickers.tsdeleted file mode 100644index f3e8cf30..00000000--- a/notfair/src/lib/mcp-account-pickers.ts+++ /dev/null@@ -1,123 +0,0 @@-/**- * Registry of MCPs whose bearer can span multiple accounts/properties and- * therefore need a per-project selection (persisted on the `projects` row —- * goal agents read it from their identity's "Workspace facts").- *- * One entry per pickable catalog key, normalizing the per-platform list/set- * server actions from `@/server/onboarding/accounts` into a single shape so- * the Connections-page picker dialog can drive any of them. The onboarding- * wizard keeps its own step-based UI over the same actions.- *- * This module carries no directive on purpose: the server-rendered- * Connections page uses `selectedId` to read the persisted choice off the- * project row, and the client dialog uses `list`/`set` (which resolve to- * server-action stubs on the client).- */--import {- listGoogleAdsAccounts,- setOnboardingAccountAction,- listMetaAdsAccounts,- setOnboardingMetaAdsAccountAction,- listGscProperties,- setOnboardingGscPropertyAction,-} from "@/server/onboarding/accounts";-import type { Project } from "@/types";--export type AccountPickerItem = {- id: string;- name: string;-};--export type AccountPickerListResult =- | { ok: true; items: AccountPickerItem[] }- | { ok: false; error: string };--export type AccountPickerSetResult =- | { ok: true }- | { ok: false; error: string };--export type AccountPickerSpec = {- /** Human noun for the selectable unit, e.g. "Google Ads account". */- noun: string;- /** Bare unit for tight UI slots ("account" / "property") — the card's- * primary button says "Choose account", not the full noun. */- short_noun: string;- /** Label shown before the raw id under each row, e.g. "Customer ID". */- id_label: string;- list: (project_slug: string) => Promise<AccountPickerListResult>;- set: (project_slug: string, id: string) => Promise<AccountPickerSetResult>;- /** Read the persisted selection off the project row. */- selectedId: (project: Project) => string | null;-};--const PICKERS: Record<string, AccountPickerSpec> = {- "notfair-googleads": {- noun: "Google Ads account",- short_noun: "account",- id_label: "Customer ID",- list: async (slug) => {- const r = await listGoogleAdsAccounts(slug);- if (!r.ok) return { ok: false, error: r.error };- return {- ok: true,- items: r.accounts.map((a) => ({- id: a.id,- name: a.name,- })),- };- },- set: async (slug, id) => {- const r = await setOnboardingAccountAction(slug, id);- return r.ok ? { ok: true } : { ok: false, error: r.error };- },- selectedId: (p) => p.google_ads_account_id,- },- "notfair-metaads": {- noun: "Meta ad account",- short_noun: "account",- id_label: "Ad account ID",- list: async (slug) => {- const r = await listMetaAdsAccounts(slug);- if (!r.ok) return { ok: false, error: r.error };- return {- ok: true,- items: r.accounts.map((a) => ({- id: a.id,- name: a.name,- })),- };- },- set: async (slug, id) => {- const r = await setOnboardingMetaAdsAccountAction(slug, id);- return r.ok ? { ok: true } : { ok: false, error: r.error };- },- selectedId: (p) => p.meta_ads_account_id,- },- "notfair-googlesearchconsole": {- noun: "Search Console property",- short_noun: "property",- id_label: "Property",- list: async (slug) => {- const r = await listGscProperties(slug);- if (!r.ok) return { ok: false, error: r.error };- return {- ok: true,- items: r.properties.map((p) => ({- id: p.id,- name: p.name,- })),- };- },- set: async (slug, id) => {- const r = await setOnboardingGscPropertyAction(slug, id);- return r.ok ? { ok: true } : { ok: false, error: r.error };- },- selectedId: (p) => p.gsc_property_id,- },-};--/** Picker spec for a catalog key, or null when the MCP has no account picker. */-export function accountPickerFor(mcp_key: string): AccountPickerSpec | null {- return PICKERS[mcp_key] ?? null;-}diff --git a/notfair/src/lib/pr-poll-policy.test.ts b/notfair/src/lib/pr-poll-policy.test.tsdeleted file mode 100644index cf2be217..00000000--- a/notfair/src/lib/pr-poll-policy.test.ts+++ /dev/null@@ -1,49 +0,0 @@-import { describe, expect, it } from "vitest";--import {- computeNextSyncAt,- nextSyncDelayMs,- SYNC_ERROR_RETRY_MS,-} from "@/lib/pr-poll-policy";--const MIN = 60_000;-const HOUR = 3_600_000;--describe("nextSyncDelayMs", () => {- it("polls fast right after activity, decaying to an hourly cap", () => {- expect(nextSyncDelayMs(0)).toBe(2 * MIN);- expect(nextSyncDelayMs(59 * MIN)).toBe(2 * MIN);- expect(nextSyncDelayMs(2 * HOUR)).toBe(10 * MIN);- expect(nextSyncDelayMs(23 * HOUR)).toBe(10 * MIN);- expect(nextSyncDelayMs(48 * HOUR)).toBe(30 * MIN);- expect(nextSyncDelayMs(100 * HOUR)).toBe(60 * MIN);- expect(nextSyncDelayMs(1000 * HOUR)).toBe(60 * MIN);- });-});--describe("computeNextSyncAt", () => {- it("schedules from now, keyed off quietness", () => {- const now = "2026-07-13T12:00:00.000Z";- // Fresh activity → 2 minutes out.- expect(computeNextSyncAt(now, "2026-07-13T11:59:00.000Z")).toBe(- "2026-07-13T12:02:00.000Z",- );- // Two days quiet → 30 minutes out.- expect(computeNextSyncAt(now, "2026-07-11T12:00:00.000Z")).toBe(- "2026-07-13T12:30:00.000Z",- );- });-- it("treats a garbage activity timestamp as fresh (fast lane)", () => {- const now = "2026-07-13T12:00:00.000Z";- expect(computeNextSyncAt(now, "not-a-date")).toBe(- "2026-07-13T12:02:00.000Z",- );- });-});--describe("SYNC_ERROR_RETRY_MS", () => {- it("retries failures on a short fixed delay", () => {- expect(SYNC_ERROR_RETRY_MS).toBe(5 * MIN);- });-});diff --git a/notfair/src/lib/pr-poll-policy.ts b/notfair/src/lib/pr-poll-policy.tsdeleted file mode 100644index b3d1e098..00000000--- a/notfair/src/lib/pr-poll-policy.ts+++ /dev/null@@ -1,39 +0,0 @@-/**- * Adaptive polling policy for open pull requests — pure functions shared- * by the db layer (which stamps next_sync_at on every write) and tests.- *- * The centralized 30s scheduler sweep syncs a PR when its own- * `next_sync_at` arrives; this policy decides how far out that is. The- * interval keys off time since the PR's last OBSERVED activity (state /- * review decision / comment count change): hot PRs — just opened, just- * reviewed — poll fast; a PR that has sat quiet for days decays toward- * an hourly cap. Any observed change resets the clock to the fast lane.- */--const MINUTE = 60_000;-const HOUR = 3_600_000;--/** How long to wait before the next GitHub check, given quietness. */-export function nextSyncDelayMs(msSinceActivity: number): number {- if (msSinceActivity < 1 * HOUR) return 2 * MINUTE;- if (msSinceActivity < 24 * HOUR) return 10 * MINUTE;- if (msSinceActivity < 72 * HOUR) return 30 * MINUTE;- return 60 * MINUTE;-}--/** Retry delay after a failed sync (gh missing, network, rate limit). */-export const SYNC_ERROR_RETRY_MS = 5 * MINUTE;--/**- * Compute the next_sync_at for an OPEN PR from "now" and its last- * activity timestamp. Terminal PRs never poll — callers store NULL.- */-export function computeNextSyncAt(- nowIso: string,- lastActivityAtIso: string,-): string {- const now = Date.parse(nowIso);- const activity = Date.parse(lastActivityAtIso);- const since = Number.isFinite(activity) ? Math.max(0, now - activity) : 0;- return new Date(now + nextSyncDelayMs(since)).toISOString();-}diff --git a/notfair/src/lib/project-href.test.ts b/notfair/src/lib/project-href.test.tsdeleted file mode 100644index 421505a7..00000000--- a/notfair/src/lib/project-href.test.ts+++ /dev/null@@ -1,42 +0,0 @@-import { describe, expect, it } from "vitest";--import { projectHref, subPathFromPathname } from "./project-href";--describe("projectHref", () => {- it("returns the project root for an empty or slash path", () => {- expect(projectHref("demo")).toBe("/demo");- expect(projectHref("demo", "")).toBe("/demo");- expect(projectHref("demo", "/")).toBe("/demo");- });-- it("prefixes the slug regardless of leading-slash style", () => {- expect(projectHref("demo", "goals/goal-1")).toBe("/demo/goals/goal-1");- expect(projectHref("demo", "/goals/goal-1")).toBe("/demo/goals/goal-1");- });-- it("throws when the slug is missing", () => {- expect(() => projectHref("", "goals")).toThrow("slug is required");- });-});--describe("subPathFromPathname", () => {- it("returns empty for the project home", () => {- expect(subPathFromPathname("/demo", "demo")).toBe("");- });-- it("strips the current slug and keeps the leading slash", () => {- expect(subPathFromPathname("/demo/connections", "demo")).toBe("/connections");- expect(subPathFromPathname("/demo/goals/goal-1", "demo")).toBe("/goals/goal-1");- });-- it("returns empty when the pathname belongs to a different project", () => {- expect(subPathFromPathname("/other/connections", "demo")).toBe("");- // Prefix must be a full segment — "/demofoo" is not project "demo".- expect(subPathFromPathname("/demofoo/x", "demo")).toBe("");- });-- it("returns empty on missing inputs", () => {- expect(subPathFromPathname(null, "demo")).toBe("");- expect(subPathFromPathname("/demo/x", undefined)).toBe("");- });-});diff --git a/notfair/src/lib/project-href.ts b/notfair/src/lib/project-href.tsdeleted file mode 100644index baaffbad..00000000--- a/notfair/src/lib/project-href.ts+++ /dev/null@@ -1,42 +0,0 @@-/**- * Build a project-scoped URL like `/<slug>/goals/goal-1`.- *- * The router treats every URL under `(app)/[project]/...` as project-scoped,- * so every internal link inside the app shell needs the slug prefix. This- * helper keeps that prefixing consistent and centralizes the leading-slash- * normalisation so callers can pass either `goals/goal-1` or `/goals/goal-1`.- *- * Passing an empty `path` returns the project root: `/<slug>`.- */-export function projectHref(slug: string, path = ""): string {- if (!slug) {- throw new Error("projectHref: slug is required");- }- if (!path || path === "/" || path === "") {- return `/${slug}`;- }- const trimmed = path.startsWith("/") ? path.slice(1) : path;- return `/${slug}/${trimmed}`;-}--/**- * Strip the leading `/<currentSlug>` segment from a pathname and return the- * rest (always with a leading slash, or empty when the pathname is the- * project home). Used by the ProjectSwitcher so picking a different project- * preserves the user's current view (`/foo/connections` → `/connections`).- *- * Returns `""` when the pathname doesn't actually start with `/<currentSlug>` —- * the caller should treat that as "send the user to the new project's home."- */-export function subPathFromPathname(- pathname: string | null | undefined,- currentSlug: string | null | undefined,-): string {- if (!pathname || !currentSlug) return "";- if (pathname === `/${currentSlug}`) return "";- const prefix = `/${currentSlug}/`;- if (pathname.startsWith(prefix)) {- return `/${pathname.slice(prefix.length)}`;- }- return "";-}diff --git a/notfair/src/lib/slash-commands.test.ts b/notfair/src/lib/slash-commands.test.tsdeleted file mode 100644index 86e9a48d..00000000--- a/notfair/src/lib/slash-commands.test.ts+++ /dev/null@@ -1,77 +0,0 @@-import { describe, expect, it } from "vitest";--import {- SLASH_COMMANDS,- executeLocalSlashCommand,- filterSlashCommands,- findCommand,- parseSlashMessage,-} from "./slash-commands";--describe("filterSlashCommands", () => {- it("returns the full catalog for an empty or bare-slash query", () => {- expect(filterSlashCommands("")).toEqual(SLASH_COMMANDS);- expect(filterSlashCommands("/")).toEqual(SLASH_COMMANDS);- });-- it("prefix-matches first, with or without the leading slash", () => {- expect(filterSlashCommands("/cl").map((c) => c.name)).toEqual(["clear"]);- expect(filterSlashCommands("mo").map((c) => c.name)).toEqual(["model"]);- });-- it("falls back to substring match when no prefix hits", () => {- // "od" is not a prefix of anything but appears inside "model".- expect(filterSlashCommands("/od").map((c) => c.name)).toEqual(["model"]);- });-- it("returns nothing for a query matching no command", () => {- expect(filterSlashCommands("/zzz")).toEqual([]);- });-});--describe("parseSlashMessage", () => {- it("returns null for plain messages", () => {- expect(parseSlashMessage("hello")).toBeNull();- expect(parseSlashMessage(" not / a command")).toBeNull();- });-- it("splits command and args, trimming both ends", () => {- expect(parseSlashMessage("/stop")).toEqual({ command: "stop", args: "" });- expect(parseSlashMessage(" /model opus fast ")).toEqual({- command: "model",- args: "opus fast",- });- });-});--describe("findCommand", () => {- it("finds catalog commands by name and misses unknowns", () => {- expect(findCommand("help")?.key).toBe("help");- expect(findCommand("nope")).toBeUndefined();- });-});--describe("executeLocalSlashCommand", () => {- it("maps each catalog command to its local action", () => {- expect(executeLocalSlashCommand("clear")).toEqual({ kind: "clear" });- expect(executeLocalSlashCommand("stop")).toEqual({ kind: "stop" });- expect(executeLocalSlashCommand("model", " opus ")).toEqual({- kind: "set-model",- value: "opus",- });- });-- it("renders a help listing that names every command", () => {- const action = executeLocalSlashCommand("help");- expect(action?.kind).toBe("help");- const content = (action as { kind: "help"; content: string }).content;- for (const c of SLASH_COMMANDS) {- expect(content).toContain(`/${c.name}`);- expect(content).toContain(c.description);- }- });-- it("returns null for unknown commands so they pass through to the agent", () => {- expect(executeLocalSlashCommand("compact")).toBeNull();- });-});diff --git a/notfair/src/lib/slash-commands.ts b/notfair/src/lib/slash-commands.tsdeleted file mode 100644index b25bcccd..00000000--- a/notfair/src/lib/slash-commands.ts+++ /dev/null@@ -1,133 +0,0 @@-/**- * Slash command catalog + local executor.- *- * Every command here is handled CLIENT-SIDE by the chat composer.- * Neither `claude -p` nor `codex exec` interprets slash commands in the- * prompt, so the catalog lists only commands NotFair itself executes.- */--export type SlashCommandCategory = "session" | "model" | "status";--export type SlashCommand = {- /** Canonical key. */- key: string;- /** Display name (without the leading slash). */- name: string;- /** Short description shown in the menu. */- description: string;- /** Optional argument hint shown beside the name. */- args?: string;- category: SlashCommandCategory;- /** All current commands run locally; kept for the popover's grouping. */- executeLocal: true;- /** Text inserted into the textarea when the user picks this. Defaults to `/${name} `. */- insert?: string;-};--export const SLASH_COMMANDS: SlashCommand[] = [- {- key: "clear",- name: "clear",- description: "Clear the visible chat buffer (trajectory on disk is kept).",- category: "session",- executeLocal: true,- },- {- key: "stop",- name: "stop",- description: "Stop the in-flight response.",- category: "session",- executeLocal: true,- },- {- key: "model",- name: "model",- description:- "Set the model override for this chat (same as the selector next to Send). No argument shows the options; `default` resets.",- args: "<model>",- category: "model",- executeLocal: true,- insert: "/model ",- },- {- key: "help",- name: "help",- description: "Show available commands.",- category: "status",- executeLocal: true,- },-];--/**- * Filter commands by what the user has typed after the leading `/`.- * Prefix match wins; substring is a fallback so `/od` still finds /model.- */-export function filterSlashCommands(query: string): SlashCommand[] {- const q = query.trim().toLowerCase();- if (!q || q === "/") return SLASH_COMMANDS;- const stripped = q.startsWith("/") ? q.slice(1) : q;- const exact = SLASH_COMMANDS.filter((c) => c.name.toLowerCase().startsWith(stripped));- if (exact.length > 0) return exact;- return SLASH_COMMANDS.filter((c) => c.name.toLowerCase().includes(stripped));-}--/**- * Parse a chat message into { command, args } if it starts with a slash.- * Returns null for plain (non-slash) messages.- */-export function parseSlashMessage(text: string): { command: string; args: string } | null {- const trimmed = text.trim();- if (!trimmed.startsWith("/")) return null;- const space = trimmed.indexOf(" ");- if (space === -1) {- return { command: trimmed.slice(1), args: "" };- }- return { command: trimmed.slice(1, space), args: trimmed.slice(space + 1).trim() };-}--export function findCommand(name: string): SlashCommand | undefined {- return SLASH_COMMANDS.find((c) => c.name === name);-}--// --- Local command actions -----export type LocalSlashAction =- | { kind: "clear" }- | { kind: "stop" }- | { kind: "set-model"; value: string }- | { kind: "help"; content: string };--/**- * Execute a slash command locally if it's in the catalog. Returns null for- * unknown commands — those are sent to the agent verbatim (the user may- * legitimately start a message with "/" for other reasons).- */-export function executeLocalSlashCommand(- command: string,- args = "",-): LocalSlashAction | null {- const def = findCommand(command);- if (!def?.executeLocal) return null;- switch (command) {- case "clear":- return { kind: "clear" };- case "stop":- return { kind: "stop" };- case "model":- return { kind: "set-model", value: args.trim() };- case "help":- return { kind: "help", content: renderHelp() };- default:- // executeLocal=true but no handler? Treat as pass-through.- return null;- }-}--function renderHelp(): string {- const lines = ["**Available commands** (type `/` to open the menu):", ""];- for (const c of SLASH_COMMANDS) {- const args = c.args ? ` ${c.args}` : "";- lines.push(`• \`/${c.name}${args}\` — ${c.description}`);- }- return lines.join("\n");-}diff --git a/notfair/src/lib/slug.test.ts b/notfair/src/lib/slug.test.tsdeleted file mode 100644index 57c3ab8b..00000000--- a/notfair/src/lib/slug.test.ts+++ /dev/null@@ -1,57 +0,0 @@-import { describe, expect, it } from "vitest";--import { isValidSlug, slugify } from "./slug";--describe("slugify", () => {- it("lowercases, hyphenates whitespace, and strips punctuation", () => {- expect(slugify("My Cool Project!")).toEqual({ ok: true, slug: "my-cool-project" });- expect(slugify(" spaced out ")).toEqual({ ok: true, slug: "spaced-out" });- });-- it("normalizes accented characters to ASCII", () => {- expect(slugify("Café Über")).toEqual({ ok: true, slug: "cafe-uber" });- });-- it("collapses runs of separators and trims leading/trailing dashes", () => {- expect(slugify("--a---b--")).toEqual({ ok: true, slug: "a-b" });- });-- it("rejects empty input", () => {- expect(slugify(" ")).toEqual({ ok: false, reason: "input is empty" });- });-- it("rejects input with no usable characters", () => {- expect(slugify("!!! ??? ***")).toEqual({- ok: false,- reason: "no valid characters",- });- });-- it("caps length and strips a dash left dangling by the cut", () => {- const result = slugify("abcde fghij", 6);- // "abcde-fghij" cut at 6 is "abcde-" → trailing dash removed.- expect(result).toEqual({ ok: true, slug: "abcde" });- });-- it("rejects reserved system names with a suggested variation", () => {- const result = slugify("NotFair");- expect(result.ok).toBe(false);- if (!result.ok) {- expect(result.reason).toContain("reserved system name");- expect(result.reason).toContain("notfair-team");- }- });-});--describe("isValidSlug", () => {- it("accepts well-formed non-reserved slugs", () => {- expect(isValidSlug("my-project-2")).toBe(true);- });-- it("rejects malformed and reserved slugs", () => {- expect(isValidSlug("Has Spaces")).toBe(false);- expect(isValidSlug("-leading")).toBe(false);- expect(isValidSlug("api")).toBe(false);- expect(isValidSlug("agents")).toBe(false);- });-});diff --git a/notfair/src/lib/slug.ts b/notfair/src/lib/slug.tsdeleted file mode 100644index 0d67692a..00000000--- a/notfair/src/lib/slug.ts+++ /dev/null@@ -1,58 +0,0 @@-const RESERVED_SLUGS = new Set([- "api",- "app",- "auth",- "admin",- "system",- "settings",- "goals",- "agent",- "agents",- "notfair",-]);--const SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;--export type SlugResult =- | { ok: true; slug: string }- | { ok: false; reason: string };--export function slugify(input: string, maxLen = 40): SlugResult {- const trimmed = input.trim();- if (!trimmed) return { ok: false, reason: "input is empty" };-- const ascii = trimmed- .toLowerCase()- .normalize("NFKD")- .replace(/[̀-ͯ]/g, "")- .replace(/[^a-z0-9\s-]/g, "")- .replace(/\s+/g, "-")- .replace(/-+/g, "-")- .replace(/^-|-$/g, "");-- if (!ascii) return { ok: false, reason: "no valid characters" };-- const capped = ascii.slice(0, maxLen).replace(/-+$/g, "");-- if (!SLUG_PATTERN.test(capped)) {- return { ok: false, reason: "result does not match slug pattern" };- }-- if (RESERVED_SLUGS.has(capped)) {- // Explicitly say "system word" — the previous wording ("'notfair'- // is reserved") read like a row collision and led users to- // delete-and-retry expecting the conflict to clear, when really- // the slug is on a static block-list. Suggest a workaround so the- // user isn't stuck guessing.- return {- ok: false,- reason: `"${capped}" is a reserved system name — try a variation like "${capped}-team" or "${capped}-1".`,- };- }-- return { ok: true, slug: capped };-}--export function isValidSlug(slug: string): boolean {- return SLUG_PATTERN.test(slug) && !RESERVED_SLUGS.has(slug);-}diff --git a/notfair/src/lib/time-ago.test.ts b/notfair/src/lib/time-ago.test.tsdeleted file mode 100644index cc2e0227..00000000--- a/notfair/src/lib/time-ago.test.ts+++ /dev/null@@ -1,23 +0,0 @@-import { describe, expect, it } from "vitest";-import { timeUntil } from "./time-ago";--const NOW = Date.parse("2026-07-17T12:00:00.000Z");--describe("timeUntil", () => {- it("formats each magnitude compactly", () => {- expect(timeUntil("2026-07-17T12:00:30.000Z", NOW)).toBe("in 30s");- expect(timeUntil("2026-07-17T12:45:00.000Z", NOW)).toBe("in 45m");- expect(timeUntil("2026-07-17T15:00:00.000Z", NOW)).toBe("in 3h");- expect(timeUntil("2026-07-19T12:00:00.000Z", NOW)).toBe("in 2d");- });-- it("rounds up so a lock never reads as shorter than it is", () => {- expect(timeUntil("2026-07-17T13:00:01.000Z", NOW)).toBe("in 2h");- expect(timeUntil("2026-07-17T12:00:31.000Z", NOW)).toBe("in 31s");- });-- it("reads 'now' once the moment has passed", () => {- expect(timeUntil("2026-07-17T11:59:00.000Z", NOW)).toBe("now");- expect(timeUntil("2026-07-17T12:00:00.000Z", NOW)).toBe("now");- });-});diff --git a/notfair/src/lib/time-ago.ts b/notfair/src/lib/time-ago.tsdeleted file mode 100644index 43f38013..00000000--- a/notfair/src/lib/time-ago.ts+++ /dev/null@@ -1,20 +0,0 @@-/** Compact relative timestamp: "42s ago", "5m ago", "3h ago", "2d ago". */-export function timeAgo(iso: string): string {- const seconds = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);- if (seconds < 60) return `${Math.floor(seconds)}s ago`;- if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;- if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;- return `${Math.floor(seconds / 86400)}d ago`;-}--/** Compact future counterpart: "in 42s", "in 5m", "in 3h", "in 2d".- * A timestamp already in the past reads "now" — the state flips on the- * next refresh, so don't pretend there's time left. */-export function timeUntil(iso: string, now = Date.now()): string {- const seconds = (new Date(iso).getTime() - now) / 1000;- if (seconds <= 0) return "now";- if (seconds < 60) return `in ${Math.ceil(seconds)}s`;- if (seconds < 3600) return `in ${Math.ceil(seconds / 60)}m`;- if (seconds < 86400) return `in ${Math.ceil(seconds / 3600)}h`;- return `in ${Math.ceil(seconds / 86400)}d`;-}diff --git a/notfair/src/lib/turn-state.test.ts b/notfair/src/lib/turn-state.test.tsdeleted file mode 100644index 65743159..00000000--- a/notfair/src/lib/turn-state.test.ts+++ /dev/null@@ -1,43 +0,0 @@-import { describe, expect, it } from "vitest";--import { findOpenTurn, isOpenTurnLive, OPEN_TURN_STALE_MS } from "./turn-state";--const t0 = 1_800_000_000_000;-const lc = (phase: string, ts: number) => ({ kind: "lifecycle", ts, phase });-const tool = (ts: number) => ({ kind: "tool_call", ts });--describe("findOpenTurn", () => {- it("returns null for an empty log or a completed last turn", () => {- expect(findOpenTurn([])).toBeNull();- expect(findOpenTurn([lc("start", t0), tool(t0 + 1), lc("done", t0 + 2)])).toBeNull();- });-- it("detects a trailing start with no done as an open turn", () => {- const turn = findOpenTurn([lc("start", t0), tool(t0 + 5_000)]);- expect(turn).toEqual({ startedAt: t0, lastEventTs: t0 + 5_000 });- });-- it("is not fooled by earlier completed turns in the same thread", () => {- const events = [- lc("start", t0),- lc("done", t0 + 1),- lc("start", t0 + 10),- tool(t0 + 20),- ];- expect(findOpenTurn(events)).toEqual({ startedAt: t0 + 10, lastEventTs: t0 + 20 });- });-- it("skips non-boundary lifecycle phases (warming etc.)", () => {- const events = [lc("start", t0), lc("warming", t0 + 1), tool(t0 + 2)];- expect(findOpenTurn(events)).toEqual({ startedAt: t0, lastEventTs: t0 + 2 });- });-});--describe("isOpenTurnLive", () => {- const turn = { startedAt: t0, lastEventTs: t0 };- it("is live while events are fresh, stale after the cutoff", () => {- expect(isOpenTurnLive(turn, t0 + 1_000)).toBe(true);- expect(isOpenTurnLive(turn, t0 + OPEN_TURN_STALE_MS + 1)).toBe(false);- expect(isOpenTurnLive(null, t0)).toBe(false);- });-});diff --git a/notfair/src/lib/turn-state.ts b/notfair/src/lib/turn-state.tsdeleted file mode 100644index 59fc0908..00000000--- a/notfair/src/lib/turn-state.ts+++ /dev/null@@ -1,48 +0,0 @@-/**- * Turn-state derivation from committed transcript events.- *- * A turn can be running that the viewing tab didn't start — another tab,- * a page reload mid-turn, or a dropped SSE stream (the backend keeps- * going; disconnect ≠ cancel). The transcript itself is the source of- * truth: the harness writes a lifecycle "start" when a turn begins and- * transcript-tail surfaces its final as lifecycle "done", so a trailing- * "start" with no "done" after it means the agent is still working.- */--type LifecycleLike = { kind: string; ts: number; phase?: string };--export type OpenTurn = {- /** ts of the lifecycle "start" that opened the still-running turn. */- startedAt: number;- /** ts of the newest committed event — the staleness anchor. */- lastEventTs: number;-};--/**- * The still-open turn implied by the event log, or null when the last- * turn completed. Scans backward to the nearest turn boundary so earlier- * completed turns in the same thread can't mask a live one (or fake one).- */-export function findOpenTurn(events: readonly LifecycleLike[]): OpenTurn | null {- for (let i = events.length - 1; i >= 0; i--) {- const e = events[i]!;- if (e.kind !== "lifecycle") continue;- if (e.phase === "done") return null;- if (e.phase === "start") {- return { startedAt: e.ts, lastEventTs: events[events.length - 1]!.ts };- }- }- return null;-}--/**- * No committed event for this long means the run is treated as orphaned- * (server restart mid-turn never writes a final). Live turns emit tool- * and delta events well inside this window, so a healthy turn can't go- * stale; the indicator simply returns when events resume.- */-export const OPEN_TURN_STALE_MS = 10 * 60_000;--export function isOpenTurnLive(turn: OpenTurn | null, now: number): boolean {- return turn !== null && now - turn.lastEventTs < OPEN_TURN_STALE_MS;-}diff --git a/notfair/src/lib/utils.test.ts b/notfair/src/lib/utils.test.tsdeleted file mode 100644index 2e82e903..00000000--- a/notfair/src/lib/utils.test.ts+++ /dev/null@@ -1,13 +0,0 @@-import { describe, expect, it } from "vitest";--import { cn } from "./utils";--describe("cn", () => {- it("joins classes and drops falsy conditionals", () => {- expect(cn("a", false && "b", undefined, "c")).toBe("a c");- });-- it("lets later tailwind utilities win over earlier conflicting ones", () => {- expect(cn("px-2 text-sm", "px-4")).toBe("text-sm px-4");- });-});diff --git a/notfair/src/lib/utils.ts b/notfair/src/lib/utils.tsdeleted file mode 100644index a5ef1935..00000000--- a/notfair/src/lib/utils.ts+++ /dev/null@@ -1,6 +0,0 @@-import { clsx, type ClassValue } from "clsx";-import { twMerge } from "tailwind-merge";--export function cn(...inputs: ClassValue[]) {- return twMerge(clsx(inputs));-}diff --git a/notfair/src/server/actions/agents.test.ts b/notfair/src/server/actions/agents.test.tsdeleted file mode 100644index 7f36c57e..00000000--- a/notfair/src/server/actions/agents.test.ts+++ /dev/null@@ -1,91 +0,0 @@-import { beforeAll, describe, expect, it, vi } from "vitest";-import { existsSync, mkdirSync } from "node:fs";-import { join } from "node:path";--// Real better-sqlite3 against a tmpdir DB, per repo test conventions.-// MUST be hoisted: static imports evaluate before module-level statements,-// and db.ts captures NOTFAIR_DATA_DIR at import time — a plain assignment-// here would silently point the suite at the developer's live ~/.notfair.-const h = vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- const dataDir = mkdtempSync(join(tmpdir(), "notfair-relocate-"));- process.env.NOTFAIR_DATA_DIR = dataDir;- return { dataDir, unregisterMcp: vi.fn(async () => {}) };-});--// Mock the harness boundary: the real adapter would edit the developer's-// actual ~/.codex / ~/.claude config when unregistering MCP servers.-vi.mock("@/server/adapters/registry", () => ({- requireAdapter: () => ({ unregisterMcp: h.unregisterMcp }),-}));-vi.mock("@/server/mcp-catalog", () => ({ getMcpCatalog: () => [] }));-vi.mock("@/server/mcp-server/registration", () => ({- GOALS_MCP_KEY: "notfair-goals",- BROWSER_MCP_KEY: "notfair-browser",-}));--import { getDb } from "@/server/db/db";-import { writeAgentMeta, readAgentMeta } from "@/server/agent-meta";-import { relocateAgent } from "./agents";--const OLD_AGENT = "src-proj-goal-1";-const NEW_AGENT = "dst-proj-goal-1";--beforeAll(async () => {- getDb()- .prepare(- "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('p1', 'src-proj', 'Src', ?, 'codex-local')",- )- .run(new Date().toISOString());- // Old agent: workspace dir + meta sidecar + one chat session.- mkdirSync(join(h.dataDir, "agents", OLD_AGENT), { recursive: true });- await writeAgentMeta({- agent_id: OLD_AGENT,- project_slug: "src-proj",- slug: "goal-1",- name: "Goal 1",- created_at: new Date().toISOString(),- });- getDb()- .prepare(- `INSERT INTO sessions (id, project_slug, agent_id, label, harness_adapter, created_at, updated_at)- VALUES ('s1', 'src-proj', ?, 'main', 'codex-local', ?, ?)`,- )- .run(OLD_AGENT, new Date().toISOString(), new Date().toISOString());-});--describe("relocateAgent", () => {- it("moves the agent and fully cleans up the old one", async () => {- const result = await relocateAgent({- old_agent_id: OLD_AGENT,- source_project_slug: "src-proj",- new_project_slug: "dst-proj",- new_slug: "goal-1",- new_display_name: "Goal 1",- });-- expect(result.new_agent_id).toBe(NEW_AGENT);- // New workspace exists with a sidecar pointing at the new project.- expect(existsSync(join(h.dataDir, "agents", NEW_AGENT))).toBe(true);- expect(readAgentMeta(NEW_AGENT)?.project_slug).toBe("dst-proj");-- // Old artifacts are gone: workspace dir, session rows (this delete used- // to throw on a nonexistent scheduled_jobs table and get swallowed,- // stranding sessions forever), and harness MCP registrations.- expect(existsSync(join(h.dataDir, "agents", OLD_AGENT))).toBe(false);- const sessions = getDb()- .prepare("SELECT COUNT(*) AS n FROM sessions WHERE agent_id = ?")- .get(OLD_AGENT) as { n: number };- expect(sessions.n).toBe(0);- const unregistered = h.unregisterMcp.mock.calls.map(- (c) => (c as unknown as [{ serverName: string; agentId: string }])[0],- );- expect(unregistered.every((u) => u.agentId === OLD_AGENT)).toBe(true);- expect(unregistered.map((u) => u.serverName).sort()).toEqual([- "notfair-browser",- "notfair-goals",- ]);- });-});diff --git a/notfair/src/server/actions/agents.ts b/notfair/src/server/actions/agents.tsdeleted file mode 100644index ca30022f..00000000--- a/notfair/src/server/actions/agents.ts+++ /dev/null@@ -1,61 +0,0 @@-"use server";--import { cloneAgent } from "@/server/agents/clone";-import { cascadeDeleteAgentArtifacts } from "@/server/agents/cascade-delete";-import { writeAgentMeta } from "@/server/agent-meta";--// --- Relocate (used by project rename to move agents to the new slug) -----export type RelocateAgentInput = {- old_agent_id: string;- source_project_slug: string;- new_project_slug: string;- new_slug: string;- new_display_name: string;- preserve_source_agent_id?: string;- preserve_created_at?: string;-};--export type RelocateAgentResult = {- new_agent_id: string;- new_slug: string;-};--export async function relocateAgent(- input: RelocateAgentInput,-): Promise<RelocateAgentResult> {- const cloneResult = await cloneAgent({- source_agent_id: input.old_agent_id,- project_slug: input.new_project_slug,- new_slug: input.new_slug,- display_name: input.new_display_name,- slug_is_canonical: true,- });-- await writeAgentMeta({- agent_id: cloneResult.new_agent_id,- project_slug: input.new_project_slug,- slug: cloneResult.new_slug,- name: input.new_display_name,- ...(input.preserve_source_agent_id- ? { source_agent_id: input.preserve_source_agent_id }- : {}),- created_at: input.preserve_created_at ?? new Date().toISOString(),- });-- // Best-effort: the clone already succeeded, so a cleanup failure must not- // fail the relocation — but it must not be invisible either (a silent- // swallow here previously masked cleanup breaking entirely, stranding the- // old agent's sessions and MCP registrations).- await cascadeDeleteAgentArtifacts(- input.source_project_slug,- input.old_agent_id,- ).catch((err) =>- console.error(`[relocate] cleanup of old agent ${input.old_agent_id} failed:`, err),- );-- return {- new_agent_id: cloneResult.new_agent_id,- new_slug: cloneResult.new_slug,- };-}diff --git a/notfair/src/server/actions/chat-threads.test.ts b/notfair/src/server/actions/chat-threads.test.tsdeleted file mode 100644index 77d830fb..00000000--- a/notfair/src/server/actions/chat-threads.test.ts+++ /dev/null@@ -1,61 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- revalidatePath: vi.fn(),- resolveAgentBySlug: vi.fn(),- getProject: vi.fn(),- deleteSession: vi.fn(),- setSessionPinned: vi.fn(),- setSessionTitle: vi.fn(),- findSession: vi.fn(),-}));--vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));-vi.mock("@/server/agent-meta", () => ({ resolveAgentBySlug: mocks.resolveAgentBySlug }));-vi.mock("@/server/db/projects", () => ({ getProject: mocks.getProject }));-vi.mock("@/server/sessions", () => ({- deleteSession: mocks.deleteSession,- setSessionPinned: mocks.setSessionPinned,- setSessionTitle: mocks.setSessionTitle,-}));-vi.mock("@/server/sessions/view", () => ({ findSessionBySessionId: mocks.findSession }));--import { deleteThreadAction, renameThreadAction, setThreadPinnedAction } from "./chat-threads";--const base = { projectSlug: "acme", agentSlug: "goal-1", threadLabel: "thread-1" };--beforeEach(() => {- vi.clearAllMocks();- mocks.getProject.mockReturnValue({ slug: "acme", archived_at: null });- mocks.resolveAgentBySlug.mockResolvedValue({ agent_id: "agent-1" });- mocks.findSession.mockReturnValue({ sessionKey: "db-session-1" });-});--it("renames, pins, and deletes an owned thread", async () => {- await expect(renameThreadAction({ ...base, title: "New" })).resolves.toEqual({ ok: true });- expect(mocks.setSessionTitle).toHaveBeenCalledWith("db-session-1", "New");- await expect(setThreadPinnedAction({ ...base, pinned: true })).resolves.toEqual({ ok: true });- expect(mocks.setSessionPinned).toHaveBeenCalledWith("db-session-1", true);- await expect(deleteThreadAction(base)).resolves.toEqual({ ok: true });- expect(mocks.deleteSession).toHaveBeenCalledWith("db-session-1");- expect(mocks.revalidatePath).toHaveBeenCalledWith("/", "layout");-});--it.each([null, { slug: "acme", archived_at: "yesterday" }])("rejects missing/archived project %#", async (project) => {- mocks.getProject.mockReturnValue(project);- await expect(renameThreadAction({ ...base, title: "New" })).resolves.toEqual({- ok: false,- error: "Project not found.",- });-});--it("rejects unknown agents and threads", async () => {- mocks.resolveAgentBySlug.mockResolvedValue(null);- await expect(setThreadPinnedAction({ ...base, pinned: false })).resolves.toEqual({- ok: false,- error: "Unknown agent 'goal-1'",- });- mocks.resolveAgentBySlug.mockResolvedValue({ agent_id: "agent-1" });- mocks.findSession.mockReturnValue(null);- await expect(deleteThreadAction(base)).resolves.toEqual({ ok: false, error: "Thread not found." });-});diff --git a/notfair/src/server/actions/chat-threads.ts b/notfair/src/server/actions/chat-threads.tsdeleted file mode 100644index d0ee4679..00000000--- a/notfair/src/server/actions/chat-threads.ts+++ /dev/null@@ -1,95 +0,0 @@-"use server";--import { revalidatePath } from "next/cache";--import { resolveAgentBySlug } from "@/server/agent-meta";-import { getProject } from "@/server/db/projects";-import {- deleteSession,- setSessionPinned,- setSessionTitle,-} from "@/server/sessions";-import { findSessionBySessionId } from "@/server/sessions/view";--export type ThreadActionResult = { ok: true } | { ok: false; error: string };--/**- * Resolve (project, agent slug, thread label) → the sessions row id, with- * ownership checks. The thread label is the UUID in the /chat/<label> URL;- * SessionView.sessionKey carries the DB primary key.- */-async function resolveThread(- projectSlug: string,- agentSlug: string,- threadLabel: string,-): Promise<{ ok: true; sessionId: string } | { ok: false; error: string }> {- const project = getProject(projectSlug);- if (!project || project.archived_at) {- return { ok: false, error: "Project not found." };- }- const agent = await resolveAgentBySlug(project.slug, agentSlug);- if (!agent) return { ok: false, error: `Unknown agent '${agentSlug}'` };- const session = findSessionBySessionId(- project.slug,- agent.agent_id,- threadLabel,- );- if (!session) return { ok: false, error: "Thread not found." };- return { ok: true, sessionId: session.sessionKey };-}--/** Rename a thread (empty title clears back to the derived preview). */-export async function renameThreadAction(input: {- projectSlug: string;- agentSlug: string;- threadLabel: string;- title: string;-}): Promise<ThreadActionResult> {- const resolved = await resolveThread(- input.projectSlug,- input.agentSlug,- input.threadLabel,- );- if (!resolved.ok) return resolved;- setSessionTitle(resolved.sessionId, input.title);- revalidatePath("/", "layout");- return { ok: true };-}--/** Pin or unpin a thread — pinned threads sort to the top of the rail. */-export async function setThreadPinnedAction(input: {- projectSlug: string;- agentSlug: string;- threadLabel: string;- pinned: boolean;-}): Promise<ThreadActionResult> {- const resolved = await resolveThread(- input.projectSlug,- input.agentSlug,- input.threadLabel,- );- if (!resolved.ok) return resolved;- setSessionPinned(resolved.sessionId, input.pinned);- revalidatePath("/", "layout");- return { ok: true };-}--/**- * Permanently delete a thread and its transcript (FK cascade). The rail- * confirms with the user before calling this.- */-export async function deleteThreadAction(input: {- projectSlug: string;- agentSlug: string;- threadLabel: string;-}): Promise<ThreadActionResult> {- const resolved = await resolveThread(- input.projectSlug,- input.agentSlug,- input.threadLabel,- );- if (!resolved.ok) return resolved;- deleteSession(resolved.sessionId);- revalidatePath("/", "layout");- return { ok: true };-}diff --git a/notfair/src/server/actions/context.test.ts b/notfair/src/server/actions/context.test.tsdeleted file mode 100644index 941ac80b..00000000--- a/notfair/src/server/actions/context.test.ts+++ /dev/null@@ -1,144 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- readFile: vi.fn(),- workspaceDirFor: vi.fn((id: string) => `/agents/${id}`),- resolveSessionForThread: vi.fn(),- listTranscriptEvents: vi.fn(),- listProjectMcpTokens: vi.fn(),- mcpRpcAutoRefresh: vi.fn(),- getSecret: vi.fn(() => "loopback-secret"),-}));--vi.mock("node:fs/promises", () => ({ readFile: mocks.readFile }));-vi.mock("@/server/agents/provisioning", () => ({ workspaceDirFor: mocks.workspaceDirFor }));-vi.mock("@/server/sessions/transcript-tail", () => ({- resolveSessionForThread: mocks.resolveSessionForThread,-}));-vi.mock("@/server/sessions/index", () => ({ listTranscriptEvents: mocks.listTranscriptEvents }));-vi.mock("@/server/mcp/tokens", () => ({ listProjectMcpTokens: mocks.listProjectMcpTokens }));-vi.mock("@/server/mcp/rpc", () => ({ mcpRpcAutoRefresh: mocks.mcpRpcAutoRefresh }));-vi.mock("@/server/mcp-server/secret", () => ({- getOrCreateMcpServerSecret: mocks.getSecret,-}));--import { getGoalContextAction } from "./context";--function response(text: string) {- return { text: vi.fn(async () => text) };-}--beforeEach(() => {- vi.clearAllMocks();- delete process.env.NOTFAIR_PORT;- mocks.readFile.mockRejectedValue(new Error("missing"));- mocks.listProjectMcpTokens.mockReturnValue([]);- mocks.resolveSessionForThread.mockReturnValue(null);- vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response("{}")));-});--afterEach(() => {- vi.unstubAllGlobals();-});--describe("getGoalContextAction", () => {- it("splits shared context out of identity and estimates tokens", async () => {- const identity = "# Identity\nintro\n## Shared workspace context\nAcme brief\n## Protocol\nDo work";- mocks.readFile.mockResolvedValue(identity);- const result = await getGoalContextAction({ project_slug: "acme", agent_id: "agent-1", thread: "main" });- expect(result.ok).toBe(true);- if (!result.ok) return;- expect(result.chunks.map((c) => c.key)).toEqual(["identity", "shared-context"]);- expect(result.chunks[0]!.content).toContain("## Protocol");- expect(result.chunks[0]!.content).not.toContain("Acme brief");- expect(result.chunks[1]!.content).toContain("Acme brief");- expect(result.total_tokens).toBe(result.chunks.reduce((sum, c) => sum + c.tokens, 0));- });-- it("handles shared context as the final identity section", async () => {- mocks.readFile.mockResolvedValue("intro\n## Shared workspace context\nlast section");- const result = await getGoalContextAction({ project_slug: "p", agent_id: "a", thread: "t" });- expect(result).toMatchObject({ ok: true });- if (!result.ok) return;- expect(result.chunks).toHaveLength(2);- expect(result.chunks[0]!.content).toBe("intro");- });-- it("keeps an identity without the marker as one chunk", async () => {- mocks.readFile.mockResolvedValue("plain identity");- const result = await getGoalContextAction({ project_slug: "p", agent_id: "a", thread: "t" });- if (!result.ok) throw new Error(result.error);- expect(result.chunks).toMatchObject([{ key: "identity", content: "plain identity" }]);- });-- it("collects loopback tools from JSON and SSE responses", async () => {- process.env.NOTFAIR_PORT = "4444";- vi.mocked(fetch)- .mockResolvedValueOnce(response(JSON.stringify({ result: { tools: [{ name: "goal", description: "d" }] } })) as never)- .mockResolvedValueOnce(response("event: message\ndata:{\"result\":{\"tools\":[{\"name\":\"browser\"}]}}\n\n") as never);- const result = await getGoalContextAction({ project_slug: "p", agent_id: "a", thread: "t" });- if (!result.ok) throw new Error(result.error);- expect(result.chunks.map((c) => c.key)).toEqual(["tools:notfair-goals", "tools:notfair-browser"]);- expect(result.chunks[0]).toMatchObject({ format: "json", group: "tools" });- expect(fetch).toHaveBeenCalledWith(- "http://127.0.0.1:4444/api/mcp/goals",- expect.objectContaining({- method: "POST",- headers: expect.objectContaining({ Authorization: "Bearer loopback-secret" }),- }),- );- });-- it("ignores empty, invalid, and failed internal tool responses", async () => {- vi.mocked(fetch)- .mockResolvedValueOnce(response("event: message\nnot-data") as never)- .mockRejectedValueOnce(new Error("offline"));- const result = await getGoalContextAction({ project_slug: "p", agent_id: "a", thread: "t" });- expect(result).toEqual({ ok: true, chunks: [], total_tokens: 0 });- });-- it("includes successful external MCP schemas and skips failures/empty lists", async () => {- mocks.listProjectMcpTokens.mockReturnValue([- { server_name: "one" },- { server_name: "two" },- { server_name: "three" },- ]);- mocks.mcpRpcAutoRefresh- .mockResolvedValueOnce({ ok: true, result: { tools: [{ name: "search", inputSchema: { type: "object" } }] } })- .mockResolvedValueOnce({ ok: false, kind: "timeout" })- .mockResolvedValueOnce({ ok: true, result: { tools: [] } });- const result = await getGoalContextAction({ project_slug: "p", agent_id: "a", thread: "t" });- if (!result.ok) throw new Error(result.error);- expect(result.chunks.map((c) => c.key)).toEqual(["tools:one"]);- expect(mocks.mcpRpcAutoRefresh).toHaveBeenCalledWith(- "p", "one", "tools/list", {}, { timeoutMs: 10_000 },- );- });-- it("groups transcript events into briefs, user messages, replies, and tools", async () => {- mocks.resolveSessionForThread.mockReturnValue({ id: "session-1" });- mocks.listTranscriptEvents.mockReturnValue([- { kind: "user", payload_json: JSON.stringify({ text: "[TICK] inspect", source: "goal-tick" }) },- { kind: "user", payload_json: JSON.stringify({ text: "hello", source: "human" }) },- { kind: "user", payload_json: "not-json" },- { kind: "final", payload_json: JSON.stringify({ text: "done" }) },- { kind: "final", payload_json: JSON.stringify({ text: 42 }) },- { kind: "tool", payload_json: JSON.stringify({ name: "fetch" }) },- { kind: "meta", payload_json: "{}" },- ]);- const result = await getGoalContextAction({ project_slug: "p", agent_id: "a", thread: "thread-1" });- if (!result.ok) throw new Error(result.error);- expect(result.chunks.map((c) => c.key)).toEqual(["briefs", "user", "replies", "tool-activity"]);- expect(result.chunks.find((c) => c.key === "user")?.content).toBe("hello");- expect(result.chunks.find((c) => c.key === "tool-activity")?.format).toBe("json");- expect(mocks.listTranscriptEvents).toHaveBeenCalledWith("session-1", { limit: 10_000 });- });-- it.each([new Error("database down"), "unexpected"])("returns a safe top-level error for %#", async (failure) => {- mocks.listProjectMcpTokens.mockImplementation(() => { throw failure; });- await expect(getGoalContextAction({ project_slug: "p", agent_id: "a", thread: "t" })).resolves.toEqual({- ok: false,- error: failure instanceof Error ? failure.message : failure,- });- });-});diff --git a/notfair/src/server/actions/context.ts b/notfair/src/server/actions/context.tsdeleted file mode 100644index ac53acb3..00000000--- a/notfair/src/server/actions/context.ts+++ /dev/null@@ -1,186 +0,0 @@-"use server";--import { readFile } from "node:fs/promises";-import { join } from "node:path";-import { workspaceDirFor } from "@/server/agents/provisioning";-import { resolveSessionForThread } from "@/server/sessions/transcript-tail";-import { listTranscriptEvents } from "@/server/sessions/index";-import { listProjectMcpTokens } from "@/server/mcp/tokens";-import { mcpRpcAutoRefresh } from "@/server/mcp/rpc";-import { getOrCreateMcpServerSecret } from "@/server/mcp-server/secret";--/**- * Assemble an estimated breakdown of what sits in a goal agent's context- * window: workspace instruction files, MCP tool schemas, and the thread's- * conversation. Token counts are ESTIMATES (~4 chars/token) — the harness- * doesn't expose its real accounting — and the UI says so.- */--export type ContextChunk = {- key: string;- label: string;- group: "instructions" | "tools" | "conversation";- chars: number;- tokens: number;- content: string;- /** How the UI should display `content`: prose renders as markdown. */- format: "markdown" | "json";- note?: string;-};--export type GoalContextResult =- | { ok: true; chunks: ContextChunk[]; total_tokens: number }- | { ok: false; error: string };--const est = (chars: number) => Math.ceil(chars / 4);--function chunk(- key: string,- label: string,- group: ContextChunk["group"],- content: string,- note?: string,- format: ContextChunk["format"] = "markdown",-): ContextChunk {- return { key, label, group, chars: content.length, tokens: est(content.length), content, format, note };-}--async function readWorkspaceFile(agent_id: string, name: string): Promise<string | null> {- try {- return await readFile(join(workspaceDirFor(agent_id), name), "utf8");- } catch {- return null;- }-}--type ToolsListResult = {- tools?: Array<{ name: string; description?: string; inputSchema?: unknown }>;-};--/** tools/list against one of our internal loopback MCP servers. */-async function internalToolsList(path: string): Promise<ToolsListResult | null> {- const port = process.env.NOTFAIR_PORT?.trim() || "3326";- try {- const res = await fetch(`http://127.0.0.1:${port}/api/mcp/${path}`, {- method: "POST",- headers: {- "Content-Type": "application/json",- Accept: "application/json, text/event-stream",- Authorization: `Bearer ${getOrCreateMcpServerSecret()}`,- },- body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }),- });- const text = await res.text();- // The route may answer as SSE; take the last data: line in that case.- const raw = text.startsWith("event:") || text.includes("\ndata:")- ? text.split("\n").filter((l) => l.startsWith("data:")).pop()?.slice(5)- : text;- if (!raw) return null;- const parsed = JSON.parse(raw) as { result?: ToolsListResult };- return parsed.result ?? null;- } catch {- return null;- }-}--function toolsChunk(key: string, label: string, result: ToolsListResult | null): ContextChunk | null {- if (!result?.tools || result.tools.length === 0) return null;- const content = JSON.stringify(result.tools, null, 2);- return chunk(- `tools:${key}`,- `${label} · ${result.tools.length} tools`,- "tools",- content,- "Tool name + description + input schema, as the harness receives them.",- "json",- );-}--export async function getGoalContextAction(input: {- project_slug: string;- agent_id: string;- thread: string;-}): Promise<GoalContextResult> {- const { project_slug, agent_id, thread } = input;- try {- const chunks: ContextChunk[] = [];-- // ── Instruction files ─────────────────────────────────────────- const identity = await readWorkspaceFile(agent_id, "IDENTITY.md");- if (identity) {- // The shared-context section sits mid-file; carve out exactly that- // section (up to the next `## ` heading) and keep the rest together.- const marker = "\n## Shared workspace context";- const start = identity.indexOf(marker);- const end = start >= 0 ? identity.indexOf("\n## ", start + marker.length) : -1;- if (start >= 0) {- const shared = end >= 0 ? identity.slice(start, end) : identity.slice(start);- const rest = end >= 0- ? identity.slice(0, start) + identity.slice(end)- : identity.slice(0, start);- chunks.push(- chunk("identity", "Agent instructions (identity + goal protocol)", "instructions", rest.trim(),- "Auto-loaded by the harness at every turn (AGENTS.md / CLAUDE.md)."),- chunk("shared-context", "Shared workspace context", "instructions", shared.trim(),- "The PROJECT.md brief, inlined into the identity. Shared by every goal in this workspace."),- );- } else {- chunks.push(- chunk("identity", "Agent instructions (identity + goal protocol)", "instructions", identity,- "Auto-loaded by the harness at every turn (AGENTS.md / CLAUDE.md)."),- );- }- }- // ── MCP tool definitions ──────────────────────────────────────- const goalTools = toolsChunk("notfair-goals", "Goal tools (notfair-goals)", await internalToolsList("goals"));- if (goalTools) chunks.push(goalTools);- const browserTools = toolsChunk("notfair-browser", "Browser tools (notfair-browser)", await internalToolsList("browser"));- if (browserTools) chunks.push(browserTools);-- for (const token of listProjectMcpTokens(project_slug)) {- const rpc = await mcpRpcAutoRefresh<ToolsListResult>(- project_slug, token.server_name, "tools/list", {}, { timeoutMs: 10_000 },- );- const c = toolsChunk(token.server_name, `Connected tools (${token.server_name})`, rpc.ok ? rpc.result : null);- if (c) chunks.push(c);- }-- // ── Conversation (this thread) ────────────────────────────────- const session = resolveSessionForThread(project_slug, agent_id, thread);- if (session) {- const events = listTranscriptEvents(session.id, { limit: 10_000 });- let briefs = "", userMsgs = "", replies = "", toolActivity = "";- for (const e of events) {- let payload: Record<string, unknown> = {};- try { payload = JSON.parse(e.payload_json) as Record<string, unknown>; } catch { /* skip */ }- if (e.kind === "user") {- const text = typeof payload.text === "string" ? payload.text : "";- const source = typeof payload.source === "string" ? payload.source : "";- if (source.startsWith("goal-")) briefs += text + "\n\n";- else userMsgs += text + "\n\n";- } else if (e.kind === "final") {- const text = typeof payload.text === "string" ? payload.text : "";- replies += text + "\n\n";- } else if (e.kind === "tool") {- toolActivity += e.payload_json + "\n";- }- }- if (briefs) {- chunks.push(chunk("briefs", "Platform briefs (intake + checks)", "conversation", briefs.trim(),- "The [INTAKE] and [TICK] messages the platform sends the agent."));- }- if (userMsgs) chunks.push(chunk("user", "Your messages", "conversation", userMsgs.trim()));- if (replies) chunks.push(chunk("replies", "Agent replies", "conversation", replies.trim()));- if (toolActivity) {- chunks.push(chunk("tool-activity", "Tool activity (logged)", "conversation", toolActivity.trim(),- "NotFair logs tool calls + result summaries. The harness keeps FULL tool outputs in its own context, so the real share is larger.",- "json"));- }- }-- const total_tokens = chunks.reduce((a, c) => a + c.tokens, 0);- return { ok: true, chunks, total_tokens };- } catch (err) {- return { ok: false, error: err instanceof Error ? err.message : String(err) };- }-}diff --git a/notfair/src/server/actions/goal-groups.test.ts b/notfair/src/server/actions/goal-groups.test.tsdeleted file mode 100644index 7e289cb8..00000000--- a/notfair/src/server/actions/goal-groups.test.ts+++ /dev/null@@ -1,113 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- revalidatePath: vi.fn(),- create: vi.fn(),- remove: vi.fn(),- get: vi.fn(),- rename: vi.fn(),- save: vi.fn(),- setMembership: vi.fn(),- getGoal: vi.fn(),- getProject: vi.fn(),-}));--vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));-vi.mock("@/server/db/goal-groups", () => ({- createGoalGroup: mocks.create,- deleteGoalGroup: mocks.remove,- getGoalGroup: mocks.get,- renameGoalGroup: mocks.rename,- saveGoalGroup: mocks.save,- setGoalGroupMembership: mocks.setMembership,-}));-vi.mock("@/server/db/goals", () => ({ getGoal: mocks.getGoal }));-vi.mock("@/server/db/projects", () => ({ getProject: mocks.getProject }));--import {- createGoalGroupAction,- deleteGoalGroupAction,- moveGoalToGroupAction,- renameGoalGroupAction,- saveGoalGroupAction,-} from "./goal-groups";--const group = { id: "group-1" };--beforeEach(() => {- vi.clearAllMocks();- mocks.getProject.mockReturnValue({ slug: "acme" });- mocks.get.mockReturnValue(group);- mocks.getGoal.mockReturnValue({ id: "goal-1" });- mocks.create.mockReturnValue(group);- mocks.save.mockReturnValue(group);- mocks.rename.mockReturnValue(group);- mocks.remove.mockReturnValue(true);-});--it("creates a trimmed group with default goal ids", async () => {- await expect(createGoalGroupAction({ project_slug: "acme", name: " Growth ", description: " focus " })).resolves.toEqual({- ok: true,- group_id: "group-1",- });- expect(mocks.create).toHaveBeenCalledWith({- project_slug: "acme",- name: "Growth",- description: "focus",- goal_ids: [],- });-});--it("validates project, name, and description lengths", async () => {- mocks.getProject.mockReturnValue(null);- await expect(createGoalGroupAction({ project_slug: "x", name: "a" })).resolves.toMatchObject({ ok: false });- mocks.getProject.mockReturnValue({});- await expect(createGoalGroupAction({ project_slug: "x", name: " " })).resolves.toMatchObject({ error: expect.stringContaining("empty") });- await expect(createGoalGroupAction({ project_slug: "x", name: "a".repeat(81) })).resolves.toMatchObject({ error: expect.stringContaining("80") });- await expect(createGoalGroupAction({ project_slug: "x", name: "a", description: "d".repeat(241) })).resolves.toMatchObject({ error: expect.stringContaining("240") });-});--it.each([- [new Error("UNIQUE constraint failed: groups.name"), "already exists"],- [new Error("database down"), "database down"],- ["plain failure", "plain failure"],-])("maps create errors %#", async (failure, message) => {- mocks.create.mockImplementation(() => { throw failure; });- await expect(createGoalGroupAction({ project_slug: "acme", name: "Growth" })).resolves.toMatchObject({- ok: false,- error: expect.stringContaining(message),- });-});--it("saves, renames, moves, and deletes groups", async () => {- await expect(saveGoalGroupAction({ group_id: "group-1", name: " New ", goal_ids: ["g1"] })).resolves.toMatchObject({ ok: true });- expect(mocks.save).toHaveBeenCalledWith({ id: "group-1", name: "New", description: "", goal_ids: ["g1"] });- await expect(renameGoalGroupAction("group-1", " Renamed ")).resolves.toMatchObject({ ok: true });- await expect(moveGoalToGroupAction("goal-1", "group-1")).resolves.toEqual({ ok: true, group_id: "group-1" });- await expect(moveGoalToGroupAction("goal-1", null)).resolves.toEqual({ ok: true, group_id: undefined });- await expect(deleteGoalGroupAction("group-1")).resolves.toEqual({ ok: true });- expect(mocks.revalidatePath).toHaveBeenCalledWith("/", "layout");-});--it("returns missing-row outcomes from mutations", async () => {- mocks.get.mockReturnValue(null);- await expect(saveGoalGroupAction({ group_id: "x", name: "A", goal_ids: [] })).resolves.toMatchObject({ ok: false });- mocks.get.mockReturnValue(group);- mocks.save.mockReturnValue(null);- await expect(saveGoalGroupAction({ group_id: "x", name: "A", goal_ids: [] })).resolves.toMatchObject({ ok: false });- mocks.rename.mockReturnValue(null);- await expect(renameGoalGroupAction("x", "A")).resolves.toMatchObject({ ok: false });- mocks.getGoal.mockReturnValue(null);- await expect(moveGoalToGroupAction("x", null)).resolves.toMatchObject({ ok: false });- mocks.remove.mockReturnValue(false);- await expect(deleteGoalGroupAction("x")).resolves.toMatchObject({ ok: false });-});--it("maps save, rename, and membership exceptions", async () => {- mocks.save.mockImplementation(() => { throw new Error("save failed"); });- await expect(saveGoalGroupAction({ group_id: "x", name: "A", goal_ids: [] })).resolves.toMatchObject({ error: "save failed" });- mocks.rename.mockImplementation(() => { throw "rename failed"; });- await expect(renameGoalGroupAction("x", "A")).resolves.toMatchObject({ error: "rename failed" });- mocks.setMembership.mockImplementation(() => { throw new Error("move failed"); });- await expect(moveGoalToGroupAction("goal-1", "x")).resolves.toMatchObject({ error: "move failed" });-});diff --git a/notfair/src/server/actions/goal-groups.ts b/notfair/src/server/actions/goal-groups.tsdeleted file mode 100644index 1e49bdc6..00000000--- a/notfair/src/server/actions/goal-groups.ts+++ /dev/null@@ -1,120 +0,0 @@-"use server";--import { revalidatePath } from "next/cache";-import {- createGoalGroup,- deleteGoalGroup,- getGoalGroup,- renameGoalGroup,- saveGoalGroup,- setGoalGroupMembership,-} from "@/server/db/goal-groups";-import { getGoal } from "@/server/db/goals";-import { getProject } from "@/server/db/projects";--export type GoalGroupActionResult = {- ok: boolean;- error?: string;- group_id?: string;-};--function cleanFields(name: string, description?: string):- | { name: string; description: string }- | { error: string } {- const cleanName = name.trim();- const cleanDescription = description?.trim() ?? "";- if (!cleanName) return { error: "Group name can't be empty." };- if (cleanName.length > 80) return { error: "Group name must be 80 characters or fewer." };- if (cleanDescription.length > 240) {- return { error: "Description must be 240 characters or fewer." };- }- return { name: cleanName, description: cleanDescription };-}--function messageForError(error: unknown): string {- if (error instanceof Error && error.message.includes("UNIQUE constraint failed")) {- return "A group with that name already exists in this project.";- }- return error instanceof Error ? error.message : String(error);-}--export async function createGoalGroupAction(input: {- project_slug: string;- name: string;- description?: string;- goal_ids?: string[];-}): Promise<GoalGroupActionResult> {- if (!getProject(input.project_slug)) return { ok: false, error: "Project not found." };- const fields = cleanFields(input.name, input.description);- if ("error" in fields) return { ok: false, error: fields.error };- try {- const group = createGoalGroup({- project_slug: input.project_slug,- ...fields,- goal_ids: input.goal_ids ?? [],- });- revalidatePath("/", "layout");- return { ok: true, group_id: group.id };- } catch (error) {- return { ok: false, error: messageForError(error) };- }-}--export async function saveGoalGroupAction(input: {- group_id: string;- name: string;- description?: string;- goal_ids: string[];-}): Promise<GoalGroupActionResult> {- if (!getGoalGroup(input.group_id)) return { ok: false, error: "Goal group not found." };- const fields = cleanFields(input.name, input.description);- if ("error" in fields) return { ok: false, error: fields.error };- try {- const group = saveGoalGroup({- id: input.group_id,- ...fields,- goal_ids: input.goal_ids,- });- if (!group) return { ok: false, error: "Goal group not found." };- revalidatePath("/", "layout");- return { ok: true, group_id: group.id };- } catch (error) {- return { ok: false, error: messageForError(error) };- }-}--export async function renameGoalGroupAction(- groupId: string,- name: string,-): Promise<GoalGroupActionResult> {- const fields = cleanFields(name);- if ("error" in fields) return { ok: false, error: fields.error };- try {- const group = renameGoalGroup(groupId, fields.name);- if (!group) return { ok: false, error: "Goal group not found." };- revalidatePath("/", "layout");- return { ok: true, group_id: group.id };- } catch (error) {- return { ok: false, error: messageForError(error) };- }-}--export async function moveGoalToGroupAction(- goalId: string,- groupId: string | null,-): Promise<GoalGroupActionResult> {- if (!getGoal(goalId)) return { ok: false, error: "Goal not found." };- try {- setGoalGroupMembership(goalId, groupId);- revalidatePath("/", "layout");- return { ok: true, group_id: groupId ?? undefined };- } catch (error) {- return { ok: false, error: messageForError(error) };- }-}--export async function deleteGoalGroupAction(groupId: string): Promise<GoalGroupActionResult> {- if (!deleteGoalGroup(groupId)) return { ok: false, error: "Goal group not found." };- revalidatePath("/", "layout");- return { ok: true };-}diff --git a/notfair/src/server/actions/goals.test.ts b/notfair/src/server/actions/goals.test.tsdeleted file mode 100644index d9dba596..00000000--- a/notfair/src/server/actions/goals.test.ts+++ /dev/null@@ -1,292 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- archiveAchievedGoal: vi.fn(),- continueAchievedGoal: vi.fn(),- revalidatePath: vi.fn(),- createGoal: vi.fn(),- deleteGoalsForAgent: vi.fn(),- endActionObservation: vi.fn(),- getGoal: vi.fn(),- getGoalAction: vi.fn(),- getGoalForAgent: vi.fn(),- renameGoal: vi.fn(),- reviewGoalAction: vi.fn(),- setGoalPinned: vi.fn(),- setGoalStatus: vi.fn(),- cascadeDeleteAgentArtifacts: vi.fn(),- getProject: vi.fn(),- provisionGoalAgent: vi.fn(),- syncGoalIdentity: vi.fn(),- agentExistsOnDisk: vi.fn(),- listProjectAgents: vi.fn(),- runGoalIntake: vi.fn(),- runGoalTick: vi.fn(),- listCheckRows: vi.fn(),-}));--vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));-vi.mock("@/server/db/goals", () => ({- archiveAchievedGoal: mocks.archiveAchievedGoal,- continueAchievedGoal: mocks.continueAchievedGoal,- createGoal: mocks.createGoal,- deleteGoalsForAgent: mocks.deleteGoalsForAgent,- endActionObservation: mocks.endActionObservation,- getGoal: mocks.getGoal,- getGoalAction: mocks.getGoalAction,- getGoalForAgent: mocks.getGoalForAgent,- renameGoal: mocks.renameGoal,- reviewGoalAction: mocks.reviewGoalAction,- setGoalPinned: mocks.setGoalPinned,- setGoalStatus: mocks.setGoalStatus,- USER_ACTION_PREFIX: "[USER ACTION] ",-}));-vi.mock("@/server/agents/cascade-delete", () => ({- cascadeDeleteAgentArtifacts: mocks.cascadeDeleteAgentArtifacts,-}));-vi.mock("@/server/db/projects", () => ({ getProject: mocks.getProject }));-vi.mock("@/server/goals/provision", () => ({- goalAgentIdFor: (slug: string, n: number) => `${slug}--goal-${n}`,- goalAgentUrlSlug: (n: number) => `goal-${n}`,- provisionGoalAgent: mocks.provisionGoalAgent,- syncGoalIdentity: mocks.syncGoalIdentity,-}));-vi.mock("@/server/agent-meta", () => ({- agentExistsOnDisk: mocks.agentExistsOnDisk,- listProjectAgents: mocks.listProjectAgents,-}));-vi.mock("@/server/goals/intake", () => ({ runGoalIntake: mocks.runGoalIntake }));-vi.mock("@/server/goals/tick", () => ({ runGoalTick: mocks.runGoalTick }));-vi.mock("@/server/goals/checks", () => ({ listCheckRows: mocks.listCheckRows }));--import {- archiveCompletedGoalAction,- continueCompletedGoalAction,- createGoalAgentAction,- deleteGoalAction,- getAgentGoalAction,- killGoalAction,- loadMoreGoalChecksAction,- markUserActionHandledAction,- pauseGoalAction,- releaseLockAction,- renameGoalAction,- resumeGoalAction,- runTickNowAction,- setGoalPinnedAction,-} from "./goals";--const goal = {- id: "goal-db-1",- project_slug: "acme",- agent_id: "acme--goal-3",- status: "active",- statement: "Grow",-};--beforeEach(() => {- vi.clearAllMocks();- mocks.getProject.mockReturnValue({ slug: "acme" });- mocks.listProjectAgents.mockResolvedValue([]);- mocks.agentExistsOnDisk.mockResolvedValue(false);- mocks.createGoal.mockReturnValue(goal);- mocks.archiveAchievedGoal.mockReturnValue({ ...goal, status: "achieved" });- mocks.continueAchievedGoal.mockReturnValue(goal);- mocks.provisionGoalAgent.mockResolvedValue(undefined);- mocks.syncGoalIdentity.mockResolvedValue(undefined);- mocks.runGoalIntake.mockResolvedValue(undefined);- mocks.runGoalTick.mockResolvedValue(undefined);- mocks.getGoal.mockReturnValue(goal);- mocks.setGoalStatus.mockReturnValue(goal);- mocks.renameGoal.mockReturnValue(goal);-});--describe("createGoalAgentAction", () => {- it("validates the project and non-empty statement", async () => {- mocks.getProject.mockReturnValue(null);- await expect(createGoalAgentAction({ project_slug: "x", statement: "hi" })).resolves.toEqual({- ok: false,- error: "Project not found.",- });- mocks.getProject.mockReturnValue({ slug: "acme" });- await expect(createGoalAgentAction({ project_slug: "acme", statement: " " })).resolves.toEqual({- ok: false,- error: "Say what you want to achieve.",- });- });-- it("allocates after the largest sequential agent and skips orphaned dirs", async () => {- mocks.listProjectAgents.mockResolvedValue([- { slug: "goal-2" },- { slug: "goal-7" },- { slug: "named-agent" },- ]);- mocks.agentExistsOnDisk- .mockResolvedValueOnce(true)- .mockResolvedValueOnce(false);- const result = await createGoalAgentAction({- project_slug: "acme",- statement: " Grow now ",- focus: "SEO",- });- expect(mocks.createGoal).toHaveBeenCalledWith({- project_slug: "acme",- agent_id: "acme--goal-9",- statement: "Grow now",- });- expect(mocks.provisionGoalAgent).toHaveBeenCalledWith({ goal, urlSlug: "goal-9" });- expect(mocks.runGoalIntake).toHaveBeenCalledWith(goal, { focus: "SEO" });- expect(result).toEqual({ ok: true, goal_id: goal.id, agent_slug: "goal-9" });- });-- it.each([new Error("duplicate"), "string failure"])("surfaces create failure %#", async (failure) => {- mocks.createGoal.mockImplementation(() => { throw failure; });- await expect(createGoalAgentAction({ project_slug: "acme", statement: "Grow" })).resolves.toEqual({- ok: false,- error: failure instanceof Error ? failure.message : failure,- });- });-- it.each([new Error("disk full"), "bad provision"])("kills a stranded goal on provision failure %#", async (failure) => {- mocks.provisionGoalAgent.mockRejectedValue(failure);- const result = await createGoalAgentAction({ project_slug: "acme", statement: "Grow" });- expect(mocks.setGoalStatus).toHaveBeenCalledWith(goal.id, "killed", "provisioning failed");- expect(result).toMatchObject({- ok: false,- error: expect.stringContaining(failure instanceof Error ? failure.message : failure),- });- });-});--describe("goal lifecycle actions", () => {- it("pauses, kills, renames, and pins existing goals", async () => {- await expect(pauseGoalAction(goal.id)).resolves.toEqual({ ok: true });- await expect(killGoalAction(goal.id, " done ")).resolves.toEqual({ ok: true });- expect(mocks.setGoalStatus).toHaveBeenCalledWith(goal.id, "killed", "done");- await expect(killGoalAction(goal.id, " ")).resolves.toEqual({ ok: true });- expect(mocks.setGoalStatus).toHaveBeenLastCalledWith(goal.id, "killed", "closed by user");- await expect(renameGoalAction(goal.id, " Better label ")).resolves.toEqual({ ok: true });- expect(mocks.renameGoal).toHaveBeenCalledWith(goal.id, "Better label");- await expect(setGoalPinnedAction(goal.id, true)).resolves.toEqual({ ok: true });- expect(mocks.setGoalPinned).toHaveBeenCalledWith(goal.id, true);- });-- it("returns not-found and validation errors", async () => {- mocks.setGoalStatus.mockReturnValue(null);- await expect(pauseGoalAction("missing")).resolves.toMatchObject({ ok: false });- await expect(killGoalAction("missing")).resolves.toMatchObject({ ok: false });- await expect(renameGoalAction(goal.id, " ")).resolves.toMatchObject({ ok: false });- mocks.renameGoal.mockReturnValue(null);- await expect(renameGoalAction("missing", "Name")).resolves.toMatchObject({ ok: false });- mocks.getGoal.mockReturnValue(null);- await expect(setGoalPinnedAction("missing", true)).resolves.toMatchObject({ ok: false });- });-- it("resumes only paused goals", async () => {- mocks.getGoal.mockReturnValue(null);- await expect(resumeGoalAction("missing")).resolves.toMatchObject({ ok: false });- mocks.getGoal.mockReturnValue({ ...goal, status: "active" });- await expect(resumeGoalAction(goal.id)).resolves.toEqual({- ok: false,- error: "Goal is active, not paused.",- });- mocks.getGoal.mockReturnValue({ ...goal, status: "paused" });- await expect(resumeGoalAction(goal.id)).resolves.toEqual({ ok: true });- expect(mocks.setGoalStatus).toHaveBeenCalledWith(goal.id, "active", "resumed by user");- });-- it("archives an achievement without deleting it", async () => {- await expect(archiveCompletedGoalAction(goal.id)).resolves.toEqual({ ok: true });- expect(mocks.archiveAchievedGoal).toHaveBeenCalledWith(goal.id);- expect(mocks.deleteGoalsForAgent).not.toHaveBeenCalled();-- mocks.archiveAchievedGoal.mockReturnValue(null);- await expect(archiveCompletedGoalAction(goal.id)).resolves.toMatchObject({- ok: false,- });- });-- it("continues an achievement with a new milestone and immediate check", async () => {- const continued = { ...goal, target_value: 150 };- mocks.continueAchievedGoal.mockReturnValue(continued);- await expect(- continueCompletedGoalAction(goal.id, {- target_value: 150,- deadline: "2030-12-31",- label: "Qualified visits → 150",- }),- ).resolves.toEqual({ ok: true });- expect(mocks.continueAchievedGoal).toHaveBeenCalledWith(goal.id, {- target_value: 150,- deadline: "2030-12-31",- short_label: "Qualified visits → 150",- });- expect(mocks.syncGoalIdentity).toHaveBeenCalledWith(continued);- expect(mocks.runGoalTick).toHaveBeenCalledWith(continued, "manual");- });-});--describe("deletion, locks, and escalations", () => {- it("deletes agent artifacts before database rows", async () => {- mocks.cascadeDeleteAgentArtifacts.mockResolvedValue(undefined);- await expect(deleteGoalAction(goal.id)).resolves.toEqual({ ok: true });- expect(mocks.cascadeDeleteAgentArtifacts).toHaveBeenCalledWith("acme", "acme--goal-3");- expect(mocks.deleteGoalsForAgent).toHaveBeenCalledWith("acme--goal-3");- expect(mocks.cascadeDeleteAgentArtifacts.mock.invocationCallOrder[0]).toBeLessThan(- mocks.deleteGoalsForAgent.mock.invocationCallOrder[0]!,- );- mocks.getGoal.mockReturnValue(null);- await expect(deleteGoalAction("missing")).resolves.toMatchObject({ ok: false });- });-- it("releases existing observation locks", async () => {- mocks.endActionObservation.mockReturnValue(false);- await expect(releaseLockAction("x")).resolves.toMatchObject({ ok: false });- mocks.endActionObservation.mockReturnValue({ id: "x" });- await expect(releaseLockAction("x")).resolves.toEqual({ ok: true });- });-- it("only marks open prefixed decision actions handled", async () => {- for (const action of [- null,- { kind: "mutation", description: "[USER ACTION] fix" },- { kind: "decision", description: "ordinary" },- ]) {- mocks.getGoalAction.mockReturnValue(action);- await expect(markUserActionHandledAction("a")).resolves.toMatchObject({ ok: false });- }- mocks.getGoalAction.mockReturnValue({ kind: "decision", description: "[USER ACTION] fix billing" });- mocks.reviewGoalAction.mockReturnValue(null);- await expect(markUserActionHandledAction("a")).resolves.toEqual({ ok: false, error: "Already closed." });- mocks.reviewGoalAction.mockReturnValue({ id: "a" });- await expect(markUserActionHandledAction("a")).resolves.toEqual({ ok: true });- });-});--describe("ticks and read helpers", () => {- it("runs manual ticks only for active goals", async () => {- mocks.getGoal.mockReturnValue(null);- await expect(runTickNowAction("missing")).resolves.toMatchObject({ ok: false });- mocks.getGoal.mockReturnValue({ ...goal, status: "paused" });- await expect(runTickNowAction(goal.id)).resolves.toEqual({- ok: false,- error: "Goal is paused — only active goals tick.",- });- mocks.getGoal.mockReturnValue(goal);- await expect(runTickNowAction(goal.id)).resolves.toEqual({ ok: true });- expect(mocks.runGoalTick).toHaveBeenCalledWith(goal, "manual");- });-- it("returns the agent goal and paginated check rows", async () => {- mocks.getGoalForAgent.mockReturnValue(goal);- await expect(getAgentGoalAction(goal.agent_id)).resolves.toBe(goal);- mocks.listCheckRows.mockReturnValue({ rows: [{ tick_number: 4 }], hasMore: true });- await expect(loadMoreGoalChecksAction(goal.id, 5, "action")).resolves.toEqual({- rows: [{ tick_number: 4 }],- hasMore: true,- });- expect(mocks.listCheckRows).toHaveBeenCalledWith(goal.id, { beforeTick: 5, filter: "action" });- mocks.getGoal.mockReturnValue(null);- await expect(loadMoreGoalChecksAction("missing")).resolves.toEqual({ rows: [], hasMore: false });- });-});diff --git a/notfair/src/server/actions/goals.ts b/notfair/src/server/actions/goals.tsdeleted file mode 100644index 3cda1cf6..00000000--- a/notfair/src/server/actions/goals.ts+++ /dev/null@@ -1,337 +0,0 @@-"use server";--import { revalidatePath } from "next/cache";-import {- archiveAchievedGoal,- continueAchievedGoal,- createGoal,- deleteGoalsForAgent,- endActionObservation,- getGoal,- getGoalAction,- getGoalForAgent,- renameGoal,- reviewGoalAction,- setGoalPinned,- setGoalStatus,- USER_ACTION_PREFIX,-} from "@/server/db/goals";-import { cascadeDeleteAgentArtifacts } from "@/server/agents/cascade-delete";-import { getProject } from "@/server/db/projects";-import {- goalAgentIdFor,- goalAgentUrlSlug,- provisionGoalAgent,-} from "@/server/goals/provision";-import { agentExistsOnDisk, listProjectAgents } from "@/server/agent-meta";-import { runGoalIntake } from "@/server/goals/intake";-import { runGoalTick } from "@/server/goals/tick";-import { syncGoalIdentity } from "@/server/goals/provision";-import { listCheckRows, type CheckFilter, type CheckRow } from "@/server/goals/checks";--export type GoalActionResult = {- ok: boolean;- error?: string;- goal_id?: string;- agent_slug?: string;-};--/** Next free sequential goal number for the project (goal-1, goal-2, …). */-async function nextGoalNumber(project_slug: string): Promise<number> {- const agents = await listProjectAgents(project_slug);- let max = 0;- for (const a of agents) {- const m = a.slug.match(/^goal-(\d+)$/);- if (m) max = Math.max(max, Number(m[1]));- }- let n = max + 1;- // Defensive: skip over any orphaned workspace dirs.- while (await agentExistsOnDisk(goalAgentIdFor(project_slug, n))) n++;- return n;-}--/**- * Mint a new goal from an AMBITION. Goals are the identity — the agent- * behind one is anonymous plumbing with a sequential id. The statement- * seeds the goal row and an intake turn fires immediately, so the user- * lands in a chat where the agent is already working out how to measure- * it.- */-export async function createGoalAgentAction(input: {- project_slug: string;- statement: string;- /**- * Platform focus picked in the creation form (a `GoalPlatform.focus`- * line, e.g. "SEO / organic search — measure via the- * notfair-googlesearchconsole MCP"). Threaded into the intake kickoff- * only — the statement stays the user's words.- */- focus?: string | null;-}): Promise<GoalActionResult> {- const project = getProject(input.project_slug);- if (!project) return { ok: false, error: "Project not found." };-- const statement = input.statement.trim();- if (!statement) return { ok: false, error: "Say what you want to achieve." };-- const n = await nextGoalNumber(project.slug);- const agent_id = goalAgentIdFor(project.slug, n);- const urlSlug = goalAgentUrlSlug(n);-- let goal;- try {- goal = createGoal({ project_slug: project.slug, agent_id, statement });- } catch (err) {- return { ok: false, error: err instanceof Error ? err.message : String(err) };- }-- try {- await provisionGoalAgent({ goal, urlSlug });- } catch (err) {- // Roll back so a broken provision doesn't strand a live goal row.- setGoalStatus(goal.id, "killed", "provisioning failed");- return {- ok: false,- error: `Agent provisioning failed: ${err instanceof Error ? err.message : String(err)}`,- };- }-- // The agent starts working immediately; the goal screen's embedded- // chat streams it live.- void runGoalIntake(goal, { focus: input.focus }).catch((err) =>- console.error("[goal-intake] kickoff failed:", err),- );-- revalidatePath("/", "layout");- return {- ok: true,- goal_id: goal.id,- agent_slug: urlSlug,- };-}--export async function pauseGoalAction(goal_id: string): Promise<GoalActionResult> {- const goal = setGoalStatus(goal_id, "paused", "paused by user");- if (!goal) return { ok: false, error: "Goal not found." };- revalidatePath("/", "layout");- return { ok: true };-}--export async function resumeGoalAction(goal_id: string): Promise<GoalActionResult> {- const goal = getGoal(goal_id);- if (!goal) return { ok: false, error: "Goal not found." };- if (goal.status !== "paused") {- return { ok: false, error: `Goal is ${goal.status}, not paused.` };- }- setGoalStatus(goal_id, "active", "resumed by user");- revalidatePath("/", "layout");- return { ok: true };-}--/**- * Close the goal. The agent stays (its chat history and workspace remain- * browsable); a closed agent simply never ticks again. Deleting the agent- * entirely happens in its Settings danger zone.- */-export async function killGoalAction(- goal_id: string,- reason?: string,-): Promise<GoalActionResult> {- const goal = setGoalStatus(goal_id, "killed", reason?.trim() || "closed by user");- if (!goal) return { ok: false, error: "Goal not found." };- revalidatePath("/", "layout");- return { ok: true };-}--/**- * Remove a completed goal from daily navigation while preserving its- * achievement, agent workspace, conversation, checks, and evidence.- */-export async function archiveCompletedGoalAction(- goal_id: string,-): Promise<GoalActionResult> {- const goal = archiveAchievedGoal(goal_id);- if (!goal) {- return { ok: false, error: "Only a completed goal can be archived." };- }- revalidatePath("/", "layout");- return { ok: true };-}--/**- * Continue an achieved goal with a more ambitious target. The metric and- * history stay intact, the heartbeat restarts, and an immediate check lets- * the same agent re-anchor on the new milestone.- */-export async function continueCompletedGoalAction(- goal_id: string,- input: {- target_value: number;- deadline?: string | null;- label?: string | null;- },-): Promise<GoalActionResult> {- const deadline = input.deadline?.trim() || null;- if (- deadline &&- (!/^\d{4}-\d{2}-\d{2}$/.test(deadline) ||- Number.isNaN(new Date(`${deadline}T23:59:59`).getTime()))- ) {- return { ok: false, error: "Enter a valid deadline." };- }- if (- deadline &&- new Date(`${deadline}T23:59:59`).getTime() < Date.now()- ) {- return { ok: false, error: "Choose today or a future deadline." };- }- const label = input.label?.trim() || null;- if (label && label.length > 120) {- return { ok: false, error: "Keep the goal name to 120 characters." };- }-- let goal;- try {- goal = continueAchievedGoal(goal_id, {- target_value: input.target_value,- deadline,- short_label: label,- });- } catch (err) {- return {- ok: false,- error: err instanceof Error ? err.message : String(err),- };- }- if (!goal) {- return { ok: false, error: "This goal is no longer awaiting a next step." };- }-- void syncGoalIdentity(goal).catch((err) =>- console.warn("[goal-actions] continued-goal identity sync failed:", err),- );- void runGoalTick(goal, "manual").catch((err) =>- console.error("[goal-actions] continued-goal check failed:", err),- );- revalidatePath("/", "layout");- return { ok: true };-}--/** Rename the goal's display label (the sidebar/board handle). */-export async function renameGoalAction(- goal_id: string,- label: string,-): Promise<GoalActionResult> {- const trimmed = label.trim();- if (!trimmed) return { ok: false, error: "Name can't be empty." };- const goal = renameGoal(goal_id, trimmed);- if (!goal) return { ok: false, error: "Goal not found." };- revalidatePath("/", "layout");- return { ok: true };-}--/** Pin/unpin the goal to the top of the sidebar rail. */-export async function setGoalPinnedAction(- goal_id: string,- pinned: boolean,-): Promise<GoalActionResult> {- if (!getGoal(goal_id)) return { ok: false, error: "Goal not found." };- setGoalPinned(goal_id, pinned);- revalidatePath("/", "layout");- return { ok: true };-}--/**- * Delete the goal AND its agent — workspace dir, chat history, MCP- * registrations, every goal row. Unlike closing (killGoalAction), nothing- * survives; this is the "it never happened" path.- */-export async function deleteGoalAction(goal_id: string): Promise<GoalActionResult> {- const goal = getGoal(goal_id);- if (!goal) return { ok: false, error: "Goal not found." };- await cascadeDeleteAgentArtifacts(goal.project_slug, goal.agent_id);- deleteGoalsForAgent(goal.agent_id);- revalidatePath("/", "layout");- return { ok: true };-}--/**- * Manual unlock: end an action's observation window now. The resources- * release immediately; the action becomes due for review, so the agent- * scores its outcome on the next check exactly as it would at expiry.- */-export async function releaseLockAction(action_id: string): Promise<GoalActionResult> {- const released = endActionObservation(action_id);- if (!released) {- return { ok: false, error: "Lock not found — it may already be released." };- }- revalidatePath("/", "layout");- return { ok: true };-}--/**- * "Mark handled" on a Needs-you escalation. The user says they made the- * fix; the action closes so the card stops nagging. If telemetry later- * proves otherwise, the agent's blocked-on-user rule re-escalates with a- * fresh decision action — acknowledgment is cheap, lying to the loop isn't.- */-export async function markUserActionHandledAction(- action_id: string,-): Promise<GoalActionResult> {- const action = getGoalAction(action_id);- if (- !action ||- action.kind !== "decision" ||- !action.description.startsWith(USER_ACTION_PREFIX)- ) {- return { ok: false, error: "Not an open user-action escalation." };- }- const reviewed = reviewGoalAction(- action_id,- "User marked this handled from the goal screen. Verify against telemetry on a later check; re-escalate if it is still broken.",- );- if (!reviewed) return { ok: false, error: "Already closed." };- revalidatePath("/", "layout");- return { ok: true };-}--/**- * Manual "Run tick now". Fire-and-forget for the turn itself, but the- * check row is claimed synchronously inside runGoalTick's pre-await- * prefix, so the Checks list shows the new (running, manual) check the- * moment this action returns.- */-export async function runTickNowAction(goal_id: string): Promise<GoalActionResult> {- const goal = getGoal(goal_id);- if (!goal) return { ok: false, error: "Goal not found." };- if (goal.status !== "active") {- return { ok: false, error: `Goal is ${goal.status} — only active goals tick.` };- }- void runGoalTick(goal, "manual").catch((err) =>- console.error("[goal-tick] manual tick failed:", err),- );- revalidatePath("/", "layout");- return { ok: true };-}--/** The live goal for an agent, if any (server helper for pages). */-export async function getAgentGoalAction(agent_id: string) {- return getGoalForAgent(agent_id);-}--/**- * Diary page for the goal screen's Checks list — checks strictly older- * than `beforeTick` (omit for the newest page), newest first. Cursor- * pagination (not offset) so rows never shift under the reader when a- * new check lands mid-scroll. `filter: "action"` keeps only checks that- * recorded an action or registered a PR.- */-export async function loadMoreGoalChecksAction(- goal_id: string,- beforeTick?: number,- filter?: CheckFilter,-): Promise<{ rows: CheckRow[]; hasMore: boolean }> {- const goal = getGoal(goal_id);- if (!goal) return { rows: [], hasMore: false };- return listCheckRows(goal.id, { beforeTick, filter });-}diff --git a/notfair/src/server/actions/harness.test.ts b/notfair/src/server/actions/harness.test.tsdeleted file mode 100644index 047899d5..00000000--- a/notfair/src/server/actions/harness.test.ts+++ /dev/null@@ -1,66 +0,0 @@-import { EventEmitter } from "node:events";-import { beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- homedir: vi.fn(() => "/home/user"),- spawn: vi.fn(),- refreshUsage: vi.fn(),- resolveCodexBinary: vi.fn(() => "codex"),-}));--vi.mock("node:os", () => ({ default: { homedir: mocks.homedir } }));-vi.mock("node:child_process", () => ({ spawn: mocks.spawn }));-vi.mock("@/server/harness-usage", () => ({ refreshHarnessUsage: mocks.refreshUsage }));-vi.mock("@/server/adapters/codex-local/binary", () => ({- resolveCodexBinary: mocks.resolveCodexBinary,-}));--import { refreshCodexUsageAction, startCodexLoginAction } from "./harness";--function child() {- const proc = new EventEmitter() as EventEmitter & { unref: ReturnType<typeof vi.fn> };- proc.unref = vi.fn();- return proc;-}--beforeEach(() => {- vi.clearAllMocks();- mocks.refreshUsage.mockResolvedValue({ kind: "codex", auth: "signed-out" });-});--it.each(["signed-in", "expired"])("does not spawn when auth is %s", async (auth) => {- mocks.refreshUsage.mockResolvedValue({ kind: "codex", auth });- await expect(startCodexLoginAction()).resolves.toEqual({ ok: true, alreadySignedIn: true });- expect(mocks.spawn).not.toHaveBeenCalled();-});--it.each([{ kind: "claude", auth: "signed-in" }, { kind: "codex", auth: "unknown" }])("starts detached login for %#", async (usage) => {- mocks.refreshUsage.mockResolvedValue(usage);- const proc = child();- mocks.spawn.mockReturnValue(proc);- const promise = startCodexLoginAction();- await vi.waitFor(() => expect(mocks.spawn).toHaveBeenCalled());- proc.emit("spawn");- await expect(promise).resolves.toEqual({ ok: true, alreadySignedIn: false });- expect(mocks.spawn).toHaveBeenCalledWith("codex", ["login"], expect.objectContaining({ cwd: "/home/user", detached: true, stdio: "ignore" }));- expect(proc.unref).toHaveBeenCalled();-});--it("maps spawn errors and synchronous throws", async () => {- let proc = child();- mocks.spawn.mockReturnValue(proc);- let promise = startCodexLoginAction();- await vi.waitFor(() => expect(mocks.spawn).toHaveBeenCalled());- proc.emit("error", new Error("denied"));- await expect(promise).resolves.toEqual({ ok: false, error: "denied" });-- mocks.spawn.mockImplementation(() => { throw "no binary"; });- await expect(startCodexLoginAction()).resolves.toEqual({ ok: false, error: "no binary" });-});--it("refreshes Codex usage", async () => {- const usage = { kind: "codex", auth: "signed-in" };- mocks.refreshUsage.mockResolvedValue(usage);- await expect(refreshCodexUsageAction()).resolves.toBe(usage);- expect(mocks.refreshUsage).toHaveBeenCalledWith("codex-local");-});diff --git a/notfair/src/server/actions/harness.ts b/notfair/src/server/actions/harness.tsdeleted file mode 100644index 01010ae3..00000000--- a/notfair/src/server/actions/harness.ts+++ /dev/null@@ -1,53 +0,0 @@-"use server";--import os from "node:os";-import { spawn } from "node:child_process";-import {- refreshHarnessUsage,- type HarnessUsage,-} from "@/server/harness-usage";-import { resolveCodexBinary } from "@/server/adapters/codex-local/binary";--export type StartCodexLoginResult =- | { ok: true; alreadySignedIn: boolean }- | { ok: false; error: string };--/**- * Start Codex's official browser login without tying the child process to- * the lifetime of this server-action request. The client polls auth status- * and updates itself as soon as the browser callback completes.- */-export async function startCodexLoginAction(): Promise<StartCodexLoginResult> {- const current = await refreshHarnessUsage("codex-local");- if (- current.kind === "codex" &&- current.auth !== "signed-out" &&- current.auth !== "unknown"- ) {- return { ok: true, alreadySignedIn: true };- }-- try {- const child = spawn(resolveCodexBinary(), ["login"], {- cwd: os.homedir(),- detached: true,- stdio: "ignore",- env: process.env,- });- await new Promise<void>((resolve, reject) => {- child.once("spawn", resolve);- child.once("error", reject);- });- child.unref();- return { ok: true, alreadySignedIn: false };- } catch (err) {- return {- ok: false,- error: err instanceof Error ? err.message : String(err),- };- }-}--export async function refreshCodexUsageAction(): Promise<HarnessUsage> {- return refreshHarnessUsage("codex-local");-}diff --git a/notfair/src/server/actions/mcp.test.ts b/notfair/src/server/actions/mcp.test.tsdeleted file mode 100644index 9a187fbf..00000000--- a/notfair/src/server/actions/mcp.test.ts+++ /dev/null@@ -1,575 +0,0 @@-import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";-import { createHash } from "node:crypto";--// Real better-sqlite3 against a tmpdir DB, per repo test conventions.-// MUST be hoisted: static imports evaluate before module-level statements,-// and db.ts captures NOTFAIR_DATA_DIR at import time — a plain assignment-// here would silently point the suite at the developer's live ~/.notfair.-vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-actions-mcp-"));-});--const mocks = vi.hoisted(() => ({- revalidatePath: vi.fn(),- getActiveProject: vi.fn(),- setPending: vi.fn(),- disconnectMcp: vi.fn(async () => {}),- getMcpConfig: vi.fn(),- mcpRpcAutoRefresh: vi.fn(),- listProjectAgents: vi.fn(async () => [] as Array<{ agent_id: string }>),- unregisterMcp: vi.fn(async () => {}),- headerMap: new Map<string, string>(),-}));--vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));-vi.mock("next/headers", () => ({- headers: async () => ({- get: (name: string) => mocks.headerMap.get(name.toLowerCase()) ?? null,- }),-}));-vi.mock("@/server/active-project", () => ({- getActiveProject: mocks.getActiveProject,-}));-vi.mock("@/server/mcp-pending", () => ({ setPending: mocks.setPending }));-vi.mock("@/server/mcp/state", () => ({ disconnectMcp: mocks.disconnectMcp }));-vi.mock("@/server/mcp/rpc", () => ({- getMcpConfig: mocks.getMcpConfig,- mcpRpcAutoRefresh: mocks.mcpRpcAutoRefresh,-}));-vi.mock("@/server/agent-meta", () => ({- listProjectAgents: mocks.listProjectAgents,-}));-vi.mock("@/server/adapters/registry", () => ({- requireAdapter: () => ({ unregisterMcp: mocks.unregisterMcp }),-}));--import { getDb } from "@/server/db/db";-import { getProject } from "@/server/db/projects";-import {- addHiddenMcpPresetKey,- getHiddenMcpPresetKeys,-} from "@/server/db/projects";-import {- findUserMcpServer,- insertUserMcpServer,-} from "@/server/db/user-mcp-servers";-import {- addUserMcpServerAction,- disconnectMcpAction,- listMcpToolsAction,- probeMcpDiscovery,- removeUserMcpServerAction,- startMcpConnect,-} from "./mcp";--const SLUG = "proj";--// ── fetch fixture: a routable fake OAuth ecosystem ───────────────────-const RESOURCE_URL = "https://mcp.acme.dev/sse";-const DISCOVERY_URL =- "https://mcp.acme.dev/.well-known/oauth-protected-resource/sse";-const ISSUER = "https://auth.acme.dev";-const AS_METADATA_URL = `${ISSUER}/.well-known/oauth-authorization-server`;-const REGISTRATION_URL = `${ISSUER}/register`;--type Route = (init?: RequestInit) => Response | Promise<Response>;-let routes: Map<string, Route>;-const fetchCalls: Array<{ url: string; init?: RequestInit }> = [];--function json(body: unknown, status = 200): Response {- return new Response(JSON.stringify(body), {- status,- headers: { "Content-Type": "application/json" },- });-}--function installDefaultRoutes(opts: { authMethods?: string[] } = {}) {- routes = new Map<string, Route>([- [DISCOVERY_URL, () => json({ authorization_servers: [`${ISSUER}/`] })],- [- AS_METADATA_URL,- () =>- json({- issuer: ISSUER,- authorization_endpoint: `${ISSUER}/authorize`,- token_endpoint: `${ISSUER}/token`,- registration_endpoint: REGISTRATION_URL,- token_endpoint_auth_methods_supported: opts.authMethods ?? ["none"],- }),- ],- [REGISTRATION_URL, () => json({ client_id: "cid-1", client_secret: "sec-1" })],- ]);-}--beforeAll(() => {- getDb()- .prepare(- "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('p1', ?, 'Proj', ?, 'claude-code-local')",- )- .run(SLUG, new Date().toISOString());- insertUserMcpServer({- project_slug: SLUG,- key: "acme",- display_name: "Acme MCP",- resource_url: RESOURCE_URL,- discovery_url: DISCOVERY_URL,- });- vi.stubGlobal("fetch", async (input: RequestInfo | URL, init?: RequestInit) => {- const url = String(input);- fetchCalls.push({ url, init });- const route = routes.get(url);- if (!route) return new Response("not found", { status: 404 });- return route(init);- });-});--beforeEach(() => {- vi.clearAllMocks();- fetchCalls.length = 0;- installDefaultRoutes();- mocks.getActiveProject.mockResolvedValue(getProject(SLUG));- mocks.headerMap.clear();- mocks.headerMap.set("host", "localhost:3326");-});--// ── startMcpConnect ──────────────────────────────────────────────────--describe("startMcpConnect", () => {- it("fails without an active project", async () => {- mocks.getActiveProject.mockResolvedValue(null);- const r = await startMcpConnect({ mcp_key: "acme" });- expect(r).toMatchObject({ ok: false });- if (r.ok) return;- expect(r.error).toContain("No active project");- });-- it("fails on an unknown catalog key", async () => {- const r = await startMcpConnect({ mcp_key: "does-not-exist" });- expect(r).toMatchObject({ ok: false, error: "Unknown MCP key: does-not-exist" });- });-- it("surfaces discovery failures", async () => {- routes.delete(DISCOVERY_URL); // 404s now- const r = await startMcpConnect({ mcp_key: "acme" });- expect(r).toMatchObject({ ok: false });- if (r.ok) return;- expect(r.error).toMatch(/^Discovery failed: /);- });-- it("surfaces DCR failures", async () => {- routes.set(REGISTRATION_URL, () => new Response("denied", { status: 400 }));- const r = await startMcpConnect({ mcp_key: "acme" });- expect(r).toMatchObject({ ok: false });- if (r.ok) return;- expect(r.error).toContain("Registration failed: DCR 400");- });-- it("builds the authorize URL and stashes the pending flow", async () => {- const r = await startMcpConnect({ mcp_key: "acme", return_to: "/goals/1" });- expect(r.ok).toBe(true);- if (!r.ok) return;-- const u = new URL(r.authorize_url);- expect(u.origin + u.pathname).toBe(`${ISSUER}/authorize`);- expect(u.searchParams.get("response_type")).toBe("code");- expect(u.searchParams.get("client_id")).toBe("cid-1");- // localhost normalized to the RFC 8252 loopback IP.- expect(u.searchParams.get("redirect_uri")).toBe(- "http://127.0.0.1:3326/api/mcp-oauth/callback",- );- expect(u.searchParams.get("code_challenge_method")).toBe("S256");- expect(u.searchParams.get("resource")).toBe(RESOURCE_URL);-- expect(mocks.setPending).toHaveBeenCalledTimes(1);- const [state, flow] = mocks.setPending.mock.calls[0]! as [- string,- Record<string, unknown>,- ];- expect(state).toBe(u.searchParams.get("state"));- expect(flow).toMatchObject({- catalog_key: "acme",- display_name: "Acme MCP",- resource_url: RESOURCE_URL,- issuer: ISSUER, // trailing slash stripped- token_endpoint: `${ISSUER}/token`,- client_id: "cid-1",- client_secret: "sec-1",- redirect_uri: "http://127.0.0.1:3326/api/mcp-oauth/callback",- project_slug: SLUG,- return_to: "/goals/1",- });- // The challenge in the URL is the S256 hash of the stashed verifier.- const expected = createHash("sha256")- .update(String(flow.code_verifier))- .digest("base64")- .replace(/\+/g, "-")- .replace(/\//g, "_")- .replace(/=+$/, "");- expect(u.searchParams.get("code_challenge")).toBe(expected);-- // DCR registered a public client (AS advertised `none`).- const dcr = fetchCalls.find((c) => c.url === REGISTRATION_URL)!;- const body = JSON.parse(String(dcr.init?.body));- expect(body.token_endpoint_auth_method).toBe("none");- expect(body.grant_types).toEqual(["authorization_code", "refresh_token"]);- });-- it("drops off-site and protocol-relative return_to values", async () => {- for (const bad of ["https://evil.example", "//evil.example/x"]) {- await startMcpConnect({ mcp_key: "acme", return_to: bad });- const flow = mocks.setPending.mock.calls.at(-1)![1] as Record<string, unknown>;- expect(flow.return_to).toBeUndefined();- }- });-- it("falls back to client_secret_post when the AS doesn't allow public clients", async () => {- installDefaultRoutes({ authMethods: ["client_secret_post", "client_secret_basic"] });- const r = await startMcpConnect({ mcp_key: "acme" });- expect(r.ok).toBe(true);- const dcr = fetchCalls.find((c) => c.url === REGISTRATION_URL)!;- expect(JSON.parse(String(dcr.init?.body)).token_endpoint_auth_method).toBe(- "client_secret_post",- );- });-- it("respects forwarded proto/host headers", async () => {- mocks.headerMap.set("x-forwarded-proto", "https");- mocks.headerMap.set("x-forwarded-host", "notfair.example");- const r = await startMcpConnect({ mcp_key: "acme" });- expect(r.ok).toBe(true);- if (!r.ok) return;- expect(new URL(r.authorize_url).searchParams.get("redirect_uri")).toBe(- "https://notfair.example/api/mcp-oauth/callback",- );- });-});--// ── probeMcpDiscovery ────────────────────────────────────────────────--describe("probeMcpDiscovery", () => {- it("rejects non-URL and non-http(s) resource URLs", async () => {- for (const bad of ["not a url", "ftp://mcp.acme.dev"]) {- const r = await probeMcpDiscovery({ resource_url: bad });- expect(r).toMatchObject({ ok: false, kind: "bad_url" });- }- });-- it("classifies a missing discovery doc", async () => {- routes.delete(DISCOVERY_URL);- const r = await probeMcpDiscovery({ resource_url: RESOURCE_URL });- expect(r).toMatchObject({ ok: false, kind: "no_discovery_doc" });- });-- it("classifies a doc without authorization_servers", async () => {- routes.set(DISCOVERY_URL, () => json({ resource: RESOURCE_URL }));- const r = await probeMcpDiscovery({ resource_url: RESOURCE_URL });- expect(r).toMatchObject({ ok: false, kind: "no_authorization_servers" });- routes.set(DISCOVERY_URL, () => json({ authorization_servers: [] }));- expect(await probeMcpDiscovery({ resource_url: RESOURCE_URL })).toMatchObject({- ok: false,- kind: "no_authorization_servers",- });- });-- it("classifies unreachable AS metadata, listing every attempted URL", async () => {- routes.delete(AS_METADATA_URL);- const r = await probeMcpDiscovery({ resource_url: RESOURCE_URL });- expect(r).toMatchObject({ ok: false, kind: "as_metadata_missing_endpoints" });- if (r.ok) return;- expect(r.error).toContain("Couldn't fetch AS metadata");- expect(r.error).toContain(AS_METADATA_URL);- expect(r.error).toContain(`${ISSUER}/.well-known/openid-configuration`);- });-- it("classifies metadata missing endpoints and missing DCR", async () => {- routes.set(AS_METADATA_URL, () => json({ issuer: ISSUER }));- expect(await probeMcpDiscovery({ resource_url: RESOURCE_URL })).toMatchObject({- ok: false,- kind: "as_metadata_missing_endpoints",- });- routes.set(AS_METADATA_URL, () =>- json({- authorization_endpoint: `${ISSUER}/authorize`,- token_endpoint: `${ISSUER}/token`,- }),- );- expect(await probeMcpDiscovery({ resource_url: RESOURCE_URL })).toMatchObject({- ok: false,- kind: "dcr_unsupported",- });- });-- it("resolves happy-path metadata", async () => {- const r = await probeMcpDiscovery({ resource_url: RESOURCE_URL });- expect(r).toEqual({- ok: true,- discovery_url: DISCOVERY_URL,- issuer: ISSUER,- registration_endpoint: REGISTRATION_URL,- });- });-- it("falls back to appended-form metadata URLs for path-bearing issuers", async () => {- const pathIssuer = `${ISSUER}/tenant`;- routes.set(DISCOVERY_URL, () => json({ authorization_servers: [pathIssuer] }));- // Inserted forms 404; only the appended form resolves.- routes.set(`${pathIssuer}/.well-known/oauth-authorization-server`, () =>- json({- authorization_endpoint: `${pathIssuer}/authorize`,- token_endpoint: `${pathIssuer}/token`,- registration_endpoint: `${pathIssuer}/register`,- }),- );- const r = await probeMcpDiscovery({ resource_url: RESOURCE_URL });- expect(r).toMatchObject({ ok: true, issuer: pathIssuer });- const attempted = fetchCalls.map((c) => c.url);- // Spec-correct inserted forms were tried first.- expect(attempted).toContain(- `${ISSUER}/.well-known/oauth-authorization-server/tenant`,- );- expect(attempted).toContain(`${ISSUER}/.well-known/openid-configuration/tenant`);- });-});--// ── disconnectMcpAction ──────────────────────────────────────────────--describe("disconnectMcpAction", () => {- it("fails without an active project", async () => {- mocks.getActiveProject.mockResolvedValue(null);- const r = await disconnectMcpAction({ mcp_key: "acme" });- expect(r).toMatchObject({ ok: false });- });-- it("surfaces disconnect errors (including non-Error throws)", async () => {- mocks.disconnectMcp.mockRejectedValueOnce(new Error("token vault sealed"));- expect(await disconnectMcpAction({ mcp_key: "acme" })).toEqual({- ok: false,- error: "token vault sealed",- });- mocks.disconnectMcp.mockRejectedValueOnce("plain string");- expect(await disconnectMcpAction({ mcp_key: "acme" })).toEqual({- ok: false,- error: "plain string",- });- expect(mocks.revalidatePath).not.toHaveBeenCalled();- });-- it("disconnects and revalidates", async () => {- const r = await disconnectMcpAction({ mcp_key: "acme" });- expect(r).toEqual({ ok: true });- expect(mocks.disconnectMcp).toHaveBeenCalledWith(SLUG, "acme");- expect(mocks.revalidatePath).toHaveBeenCalledWith("/", "layout");- });-});--// ── listMcpToolsAction ───────────────────────────────────────────────--describe("listMcpToolsAction", () => {- it("fails without an active project or config", async () => {- mocks.getActiveProject.mockResolvedValueOnce(null);- expect(await listMcpToolsAction({ mcp_key: "acme" })).toMatchObject({ ok: false });-- mocks.getMcpConfig.mockReturnValueOnce(null);- expect(await listMcpToolsAction({ mcp_key: "acme" })).toEqual({- ok: false,- error: "MCP is not configured for this project.",- });- });-- it.each([- [{ ok: false, kind: "http_error", status: 503 }, "HTTP 503"],- [{ ok: false, kind: "rpc_error", code: -32000, message: "nope" }, "RPC -32000: nope"],- [{ ok: false, kind: "timeout" }, "MCP call timed out"],- [{ ok: false, kind: "aborted" }, "MCP call aborted"],- [{ ok: false, kind: "malformed_response", message: "not json" }, "not json"],- [{ ok: false, kind: "network_error", message: "ECONNREFUSED" }, "ECONNREFUSED"],- ])("maps rpc failure %o to a human message", async (rpcResult, expected) => {- mocks.getMcpConfig.mockReturnValue({ bearer: "b" });- mocks.mcpRpcAutoRefresh.mockResolvedValueOnce(rpcResult);- expect(await listMcpToolsAction({ mcp_key: "acme" })).toEqual({- ok: false,- error: expected,- });- });-- it("normalizes the tools list into ToolSummary shape", async () => {- mocks.getMcpConfig.mockReturnValue({ bearer: "b" });- mocks.mcpRpcAutoRefresh.mockResolvedValueOnce({- ok: true,- result: {- tools: [- {- name: "search",- description: "Search things",- inputSchema: {- type: "object",- properties: { q: { type: "string", description: "query" } },- required: ["q"],- },- },- { name: "bare" }, // no description, no schema- { name: 42 }, // dropped: non-string name- ],- },- });- const r = await listMcpToolsAction({ mcp_key: "acme" });- expect(r).toEqual({- ok: true,- tools: [- {- name: "search",- description: "Search things",- args: [{ name: "q", type: "string", description: "query", required: true }],- },- { name: "bare", description: "", args: [] },- ],- });- });-- it("returns an empty list when the server sends no tools array", async () => {- mocks.getMcpConfig.mockReturnValue({ bearer: "b" });- mocks.mcpRpcAutoRefresh.mockResolvedValueOnce({ ok: true, result: {} });- expect(await listMcpToolsAction({ mcp_key: "acme" })).toEqual({- ok: true,- tools: [],- });- });-});--// ── addUserMcpServerAction ───────────────────────────────────────────--describe("addUserMcpServerAction", () => {- it("fails without an active project", async () => {- mocks.getActiveProject.mockResolvedValue(null);- const r = await addUserMcpServerAction({- display_name: "X",- resource_url: RESOURCE_URL,- });- expect(r).toMatchObject({ ok: false, kind: "no_project" });- });-- it("rejects a name that can't slugify", async () => {- const r = await addUserMcpServerAction({- display_name: "###",- resource_url: RESOURCE_URL,- });- expect(r).toMatchObject({ ok: false, kind: "name_unusable" });- });-- it("un-hides a preset key instead of writing a row", async () => {- addHiddenMcpPresetKey(SLUG, "notfair-googleads");- const r = await addUserMcpServerAction({- display_name: "NotFair Google Ads",- resource_url: "https://notfair.co/api/mcp/notfair",- key: "notfair-googleads",- });- expect(r).toEqual({ ok: true, key: "notfair-googleads" });- expect(getHiddenMcpPresetKeys(SLUG)).toEqual([]);- expect(findUserMcpServer(SLUG, "notfair-googleads")).toBeNull();- expect(fetchCalls).toEqual([]); // no discovery probe- });-- it("is a no-op success when the key already exists", async () => {- const r = await addUserMcpServerAction({- display_name: "Acme MCP",- resource_url: RESOURCE_URL,- key: "acme",- });- expect(r).toEqual({ ok: true, key: "acme" });- expect(fetchCalls).toEqual([]);- });-- it("re-uses the stored key when the same URL exists under another key", async () => {- const r = await addUserMcpServerAction({- display_name: "Acme Renamed",- resource_url: "https://mcp.acme.dev/sse/", // trailing slash: normalized match- });- expect(r).toEqual({ ok: true, key: "acme" });- expect(fetchCalls).toEqual([]);- });-- it("propagates probe failures", async () => {- routes.delete(DISCOVERY_URL);- const r = await addUserMcpServerAction({- display_name: "Broken",- resource_url: RESOURCE_URL.replace("/sse", "/other"),- });- expect(r).toMatchObject({ ok: false, kind: "no_discovery_doc" });- expect(findUserMcpServer(SLUG, "broken")).toBeNull();- });-- it("probes discovery and inserts a trimmed row (ignoring an invalid key override)", async () => {- const resource = "https://mcp.acme.dev/v2";- const discovery =- "https://mcp.acme.dev/.well-known/oauth-protected-resource/v2";- routes.set(discovery, () => json({ authorization_servers: [ISSUER] }));- const r = await addUserMcpServerAction({- display_name: " Acme V2 ",- description: " second gen ",- resource_url: resource,- key: "Not_A_Valid_Key",- });- expect(r).toEqual({ ok: true, key: "acme-v2" });- expect(findUserMcpServer(SLUG, "acme-v2")).toMatchObject({- display_name: "Acme V2",- description: "second gen",- resource_url: resource,- discovery_url: discovery,- });- expect(mocks.revalidatePath).toHaveBeenCalledWith("/", "layout");- });-});--// ── removeUserMcpServerAction ────────────────────────────────────────--describe("removeUserMcpServerAction", () => {- it("fails without an active project or on an unknown user key", async () => {- mocks.getActiveProject.mockResolvedValueOnce(null);- expect(await removeUserMcpServerAction({ mcp_key: "acme" })).toMatchObject({- ok: false,- });- expect(await removeUserMcpServerAction({ mcp_key: "ghost" })).toEqual({- ok: false,- error: "Unknown MCP key: ghost.",- });- });-- it("surfaces disconnect failures", async () => {- mocks.disconnectMcp.mockRejectedValueOnce(new Error("db locked"));- expect(await removeUserMcpServerAction({ mcp_key: "acme" })).toEqual({- ok: false,- error: "db locked",- });- expect(findUserMcpServer(SLUG, "acme")).not.toBeNull();- });-- it("hides a preset and unregisters it from every agent (best-effort)", async () => {- mocks.listProjectAgents.mockResolvedValueOnce([- { agent_id: "proj-goal-1" },- { agent_id: "proj-goal-2" },- ]);- mocks.unregisterMcp.mockRejectedValueOnce(new Error("harness config missing"));- const r = await removeUserMcpServerAction({ mcp_key: "notfair-metaads" });- expect(r).toEqual({ ok: true });- expect(getHiddenMcpPresetKeys(SLUG)).toContain("notfair-metaads");- expect(mocks.disconnectMcp).toHaveBeenCalledWith(SLUG, "notfair-metaads");- expect(- mocks.unregisterMcp.mock.calls.map(- (c) => ((c as unknown[])[0] as { agentId: string }).agentId,- ),- ).toEqual([- "proj-goal-1",- "proj-goal-2",- ]);- });-- it("deletes a user row", async () => {- const r = await removeUserMcpServerAction({ mcp_key: "acme" });- expect(r).toEqual({ ok: true });- expect(findUserMcpServer(SLUG, "acme")).toBeNull();- expect(mocks.revalidatePath).toHaveBeenCalledWith("/", "layout");- });-});diff --git a/notfair/src/server/actions/mcp.ts b/notfair/src/server/actions/mcp.tsdeleted file mode 100644index acab902a..00000000--- a/notfair/src/server/actions/mcp.ts+++ /dev/null@@ -1,643 +0,0 @@-"use server";--import { randomBytes, createHash } from "node:crypto";-import { revalidatePath } from "next/cache";-import { headers } from "next/headers";-import { getActiveProject } from "@/server/active-project";-import { isPresetKey, mcpSpecByKey } from "@/server/mcp-catalog";-import { setPending } from "@/server/mcp-pending";-import { disconnectMcp as runDisconnect } from "@/server/mcp/state";-import {- insertUserMcpServer,- findUserMcpServer,- findUserMcpServerByResourceUrl,- deleteUserMcpServer,-} from "@/server/db/user-mcp-servers";-import { slugify } from "@/lib/slug";-import { deriveDiscoveryUrl } from "@/server/mcp/discovery-url";--export type StartMcpConnectResult =- | { ok: true; authorize_url: string }- | { ok: false; error: string };--/**- * Begin a one-click MCP OAuth flow. Server-side: discovery → DCR →- * PKCE-pair → pending-state stash → caller redirects browser to the- * authorize URL we return. The callback handler in- * `/api/mcp-oauth/callback` finishes the exchange + writes the harness- * mcp config.- */-export async function startMcpConnect(input: {- mcp_key: string;- /**- * Same-origin path to bounce back to after the callback. Anything that- * doesn't look like a local path (no leading `/`, or `//` protocol-relative)- * is dropped — the callback will use the default `/connections` instead.- */- return_to?: string;-}): Promise<StartMcpConnectResult> {- const project = await getActiveProject();- if (!project) {- return { ok: false, error: "No active project. Pick one before connecting an MCP." };- }-- const spec = mcpSpecByKey(project.slug, input.mcp_key);- if (!spec) return { ok: false, error: `Unknown MCP key: ${input.mcp_key}` };-- let resolved: ResolvedAuthServer;- try {- resolved = await resolveAuthServer(spec.discovery_url);- } catch (err) {- return { ok: false, error: `Discovery failed: ${humanError(err)}` };- }-- const origin = await originFromIncomingRequest();- const redirect_uri = `${origin}/api/mcp-oauth/callback`;-- const auth_method = pickClientAuthMethod(- resolved.token_endpoint_auth_methods_supported,- );- let dcr: DcrResponse;- try {- dcr = await dynamicRegister(- resolved.registration_endpoint,- redirect_uri,- auth_method,- );- } catch (err) {- return { ok: false, error: `Registration failed: ${humanError(err)}` };- }-- // PKCE — S256 challenge from a 64-byte verifier.- const code_verifier = base64url(randomBytes(64));- const code_challenge = base64url(- createHash("sha256").update(code_verifier).digest(),- );- const state = base64url(randomBytes(24));-- setPending(state, {- catalog_key: spec.key,- display_name: spec.display_name,- resource_url: spec.resource_url,- issuer: resolved.issuer,- token_endpoint: resolved.token_endpoint,- client_id: dcr.client_id,- client_secret: dcr.client_secret,- code_verifier,- redirect_uri,- project_slug: project.slug,- return_to: sanitizeReturnTo(input.return_to),- created_at: Date.now(),- });-- const u = new URL(resolved.authorization_endpoint);- u.searchParams.set("response_type", "code");- u.searchParams.set("client_id", dcr.client_id);- u.searchParams.set("redirect_uri", redirect_uri);- u.searchParams.set("code_challenge", code_challenge);- u.searchParams.set("code_challenge_method", "S256");- u.searchParams.set("state", state);- u.searchParams.set("resource", spec.resource_url);-- return { ok: true, authorize_url: u.toString() };-}--export async function disconnectMcpAction(input: {- mcp_key: string;-}): Promise<{ ok: true } | { ok: false; error: string }> {- const project = await getActiveProject();- if (!project) {- return { ok: false, error: "No active project to disconnect from." };- }- try {- await runDisconnect(project.slug, input.mcp_key);- } catch (err) {- return { ok: false, error: humanError(err) };- }- revalidatePath("/", "layout");- return { ok: true };-}--/**- * Fetch the tool list for an external (OAuth-connected) MCP. Driven by the- * tools modal on the Connections page — lazy on dialog-open so we don't- * pay the RPC roundtrip when the user is just glancing at the page.- *- * Probes the MCP's tools/list endpoint with the stored bearer, then- * normalizes each entry into the same ToolSummary shape we ship for- * built-in tools — the modal renders both identically.- */-export async function listMcpToolsAction(input: {- mcp_key: string;-}): Promise<- | { ok: true; tools: import("@/server/mcp-server/tool-summaries").ToolSummary[] }- | { ok: false; error: string }-> {- const project = await getActiveProject();- if (!project) {- return { ok: false, error: "No active project." };- }- const { getMcpConfig, mcpRpcAutoRefresh } = await import("@/server/mcp/rpc");- const cfg = getMcpConfig(project.slug, input.mcp_key);- if (!cfg) {- return { ok: false, error: "MCP is not configured for this project." };- }- const r = await mcpRpcAutoRefresh<{- tools?: Array<{ name?: unknown; description?: unknown; inputSchema?: unknown }>;- }>(project.slug, input.mcp_key, "tools/list", {}, { timeoutMs: 5_000 });- if (!r.ok) {- const message =- r.kind === "http_error"- ? `HTTP ${r.status}`- : r.kind === "rpc_error"- ? `RPC ${r.code}: ${r.message}`- : r.kind === "timeout"- ? "MCP call timed out"- : r.kind === "aborted"- ? "MCP call aborted"- : r.kind === "malformed_response"- ? r.message- : r.message;- return { ok: false, error: message };- }- const { argsFromJsonSchema } = await import("@/server/mcp-server/tool-summaries");- const tools = Array.isArray(r.result?.tools)- ? r.result.tools- .filter(- (- t,- ): t is { name: string; description?: string; inputSchema?: Record<string, unknown> } =>- typeof t?.name === "string",- )- .map((t) => ({- name: t.name,- description: typeof t.description === "string" ? t.description : "",- args:- t.inputSchema && typeof t.inputSchema === "object"- ? argsFromJsonSchema(t.inputSchema)- : [],- }))- : [];- return { ok: true, tools };-}--export type ProbeMcpDiscoveryResult =- | {- ok: true;- discovery_url: string;- issuer: string;- registration_endpoint: string;- }- | { ok: false; error: string; kind: ProbeFailureKind };--type ProbeFailureKind =- | "bad_url"- | "no_discovery_doc"- | "no_authorization_servers"- | "as_metadata_missing_endpoints"- | "dcr_unsupported";--/**- * Validate that a candidate MCP resource URL is OAuth-2.0 connectable.- *- * Derives the RFC 9728 discovery URL from the resource URL, fetches it,- * follows the first `authorization_servers` issuer, fetches its RFC 8414- * metadata, and asserts the AS publishes a `registration_endpoint` (DCR).- *- * Returns the resolved discovery URL on success so the caller can stash- * it on the user_mcp_servers row — the connect flow reuses that URL- * verbatim, so we don't re-derive it later.- */-export async function probeMcpDiscovery(input: {- resource_url: string;-}): Promise<ProbeMcpDiscoveryResult> {- const discovery_url = deriveDiscoveryUrl(input.resource_url);- if (!discovery_url) {- return {- ok: false,- kind: "bad_url",- error: "Resource URL must be an https URL.",- };- }- try {- const resolved = await resolveAuthServer(discovery_url);- return {- ok: true,- discovery_url,- issuer: resolved.issuer,- registration_endpoint: resolved.registration_endpoint,- };- } catch (err) {- return classifyProbeError(err);- }-}--export type AddUserMcpServerResult =- | { ok: true; key: string }- | { ok: false; error: string; kind: AddFailureKind };--type AddFailureKind = ProbeFailureKind | "no_project" | "name_unusable";--const KEY_PATTERN = /^[a-z0-9][a-z0-9-]*$/;--/**- * Register an MCP server for the active project — idempotent.- *- * - If `key` matches a preset (e.g. `notfair-googleads`), the action- * only ensures the key is *unhidden* (clears the per-project- * hide-list). No row is written; the preset entry surfaces again via- * `getMcpCatalog`.- * - If a `user_mcp_servers` row for the key already exists, the action- * is a no-op success — used by Browse-connectors so re-clicking a- * tile after a canceled OAuth simply re-runs `startMcpConnect`- * instead of erroring on "already exists".- * - Otherwise probes RFC 9728 discovery + DCR; on success, inserts a- * new `user_mcp_servers` row.- *- * `key` accepts a stable preset/connector identifier to bypass- * slugification (e.g. Browse passes `notfair-googleads` directly so it- * matches the preset key rather than `slugify("NotFair Google Ads")` =- * `notfair-google-ads`). When omitted, the display name is slugified.- */-export async function addUserMcpServerAction(input: {- display_name: string;- description?: string;- resource_url: string;- /** Optional canonical key override (used by Browse connectors). */- key?: string;-}): Promise<AddUserMcpServerResult> {- const project = await getActiveProject();- if (!project) {- return {- ok: false,- kind: "no_project",- error: "No active project. Pick one before adding an MCP server.",- };- }-- let key: string;- if (input.key && KEY_PATTERN.test(input.key)) {- key = input.key;- } else {- const slug = slugify(input.display_name);- if (!slug.ok) {- return {- ok: false,- kind: "name_unusable",- error: `Can't derive a key from this name: ${slug.reason}.`,- };- }- key = slug.slug;- }-- // Preset re-add: just un-hide. No row to write, no discovery probe.- if (isPresetKey(key)) {- const { removeHiddenMcpPresetKey } = await import("@/server/db/projects");- removeHiddenMcpPresetKey(project.slug, key);- revalidatePath("/", "layout");- return { ok: true, key };- }-- // User row already exists for this key — Browse "click again" path.- if (findUserMcpServer(project.slug, key)) {- return { ok: true, key };- }-- // Same MCP server (same URL) is already in this project under a- // different key — e.g. NotFair Meta Ads was added pre-canonical-id and- // saved as `notfair-meta-ads`, while the tile click would use- // `notfair-metaads`. Treat as an idempotent re-pick: return the- // existing key so the connect chain reuses it instead of writing a- // duplicate row.- const existingByUrl = findUserMcpServerByResourceUrl(- project.slug,- input.resource_url,- );- if (existingByUrl) {- return { ok: true, key: existingByUrl.key };- }-- const probe = await probeMcpDiscovery({ resource_url: input.resource_url });- if (!probe.ok) return probe;- insertUserMcpServer({- project_slug: project.slug,- key,- display_name: input.display_name.trim(),- description: input.description?.trim() ?? "",- resource_url: input.resource_url.trim(),- discovery_url: probe.discovery_url,- });- revalidatePath("/", "layout");- return { ok: true, key };-}--/**- * Remove an MCP server from the active project. Works on both presets- * and user rows:- *- * - Preset: appends the key to `projects.hidden_mcp_preset_keys_json`- * so `getMcpCatalog` filters it out from now on. Token + adapter- * cleanup runs the same way.- * - User row: deletes the `user_mcp_servers` row.- *- * Either path also drops the stored bearer and unregisters from every- * agent's harness config.- */-export async function removeUserMcpServerAction(input: {- mcp_key: string;-}): Promise<{ ok: true } | { ok: false; error: string }> {- const project = await getActiveProject();- if (!project) {- return { ok: false, error: "No active project." };- }- const isPreset = isPresetKey(input.mcp_key);- if (!isPreset) {- const row = findUserMcpServer(project.slug, input.mcp_key);- if (!row) {- return { ok: false, error: `Unknown MCP key: ${input.mcp_key}.` };- }- }- try {- await runDisconnect(project.slug, input.mcp_key);- const { listProjectAgents } = await import("@/server/agent-meta");- const { getProject, addHiddenMcpPresetKey } = await import(- "@/server/db/projects"- );- const { requireAdapter } = await import("@/server/adapters/registry");- const proj = getProject(project.slug);- if (proj) {- const adapter = requireAdapter(proj.harness_adapter);- const agents = await listProjectAgents(project.slug);- for (const agent of agents) {- try {- await adapter.unregisterMcp({- serverName: input.mcp_key,- projectSlug: project.slug,- agentId: agent.agent_id,- });- } catch {- // best-effort- }- }- }- if (isPreset) {- addHiddenMcpPresetKey(project.slug, input.mcp_key);- } else {- deleteUserMcpServer(project.slug, input.mcp_key);- }- } catch (err) {- return { ok: false, error: humanError(err) };- }- revalidatePath("/", "layout");- return { ok: true };-}--// ─── helpers ────────────────────────────────────────────────────────--type ResolvedAuthServer = {- issuer: string;- authorization_endpoint: string;- token_endpoint: string;- registration_endpoint: string;- /**- * The AS's advertised auth methods for the token endpoint. Drives DCR- * registration: we prefer the public-PKCE `none` method when the AS- * supports it (MCP spec default), and fall back to `client_secret_post`- * for servers like Supabase that don't accept public clients.- */- token_endpoint_auth_methods_supported: string[];-};--type ClientAuthMethod = "none" | "client_secret_post";--class ProbeError extends Error {- kind: ProbeFailureKind;- constructor(kind: ProbeFailureKind, message: string) {- super(message);- this.kind = kind;- }-}--async function resolveAuthServer(- resourceDiscoveryUrl: string,-): Promise<ResolvedAuthServer> {- // RFC 9728: GET .well-known/oauth-protected-resource → carries the- // `authorization_servers` array. We pick the first and then fetch its- // RFC 8414 AS metadata to learn registration/token/authorize endpoints.- let r1: unknown;- try {- r1 = await fetchJson(resourceDiscoveryUrl, 8000);- } catch (err) {- throw new ProbeError(- "no_discovery_doc",- err instanceof Error ? err.message : String(err),- );- }- const servers = (r1 as { authorization_servers?: unknown }).authorization_servers;- if (!Array.isArray(servers) || servers.length === 0) {- throw new ProbeError(- "no_authorization_servers",- "no authorization_servers in discovery doc",- );- }- const issuer = String(servers[0]).replace(/\/$/, "");- // RFC 8414 §3.1 says the well-known suffix is inserted between the- // issuer's host and path (the "inserted" form). The OIDC Discovery and- // some MCP servers also accept the issuer-suffix variant ("appended"- // form). Try each in order until one returns valid metadata.- const candidates = asMetadataCandidates(issuer);- const attempts: string[] = [];- let meta: Partial<ResolvedAuthServer> | null = null;- for (const url of candidates) {- attempts.push(url);- try {- meta = (await fetchJson(url, 8000)) as Partial<ResolvedAuthServer>;- break;- } catch {- // try the next candidate- }- }- if (!meta) {- throw new ProbeError(- "as_metadata_missing_endpoints",- `Couldn't fetch AS metadata. Tried: ${attempts.join(", ")}`,- );- }- if (!meta.authorization_endpoint || !meta.token_endpoint) {- throw new ProbeError(- "as_metadata_missing_endpoints",- "AS metadata missing authorize/token endpoints",- );- }- if (!meta.registration_endpoint) {- throw new ProbeError(- "dcr_unsupported",- "AS metadata is missing registration_endpoint — dynamic client registration is required.",- );- }- const advertised = (meta as Record<string, unknown>)- .token_endpoint_auth_methods_supported;- return {- issuer,- authorization_endpoint: meta.authorization_endpoint,- token_endpoint: meta.token_endpoint,- registration_endpoint: meta.registration_endpoint,- token_endpoint_auth_methods_supported: Array.isArray(advertised)- ? advertised.filter((s): s is string => typeof s === "string")- : [],- };-}--/**- * Pick a token-endpoint auth method that the AS supports AND we know- * how to drive at the callback. We prefer `none` (PKCE-only, MCP-spec- * default); when the AS doesn't advertise it (Supabase, some OIDC- * providers) we fall back to `client_secret_post`. `client_secret_basic`-- * only servers aren't supported — the callback's token exchange sends- * the secret in the POST body, not the Authorization header.- */-function pickClientAuthMethod(supported: string[]): ClientAuthMethod {- if (supported.length === 0) return "none";- if (supported.includes("none")) return "none";- return "client_secret_post";-}--/**- * Build the AS-metadata URLs to probe, in priority order, for a given- * issuer. The "inserted" variants are spec-correct (RFC 8414 §3.1 / OIDC- * Discovery §4); the "appended" variants are a common deviation a number- * of real-world MCP servers still ship — including, ironically, the- * issuer URL Stripe advertises (`https://access.stripe.com/mcp`), which- * resolves only via the inserted form.- */-function asMetadataCandidates(issuer: string): string[] {- const out: string[] = [];- let u: URL;- try {- u = new URL(issuer);- } catch {- return out;- }- const path = u.pathname === "/" ? "" : u.pathname.replace(/\/+$/, "");- const origin = u.origin;- // RFC 8414: inserted between host and path.- out.push(`${origin}/.well-known/oauth-authorization-server${path}`);- // OIDC Discovery: same insertion shape with a different suffix.- out.push(`${origin}/.well-known/openid-configuration${path}`);- // Appended-form fallbacks for servers that don't follow the insertion- // rule. Only worth trying when the issuer has a non-root path; for a- // root issuer the appended form equals the inserted form.- if (path) {- out.push(`${issuer.replace(/\/$/, "")}/.well-known/oauth-authorization-server`);- out.push(`${issuer.replace(/\/$/, "")}/.well-known/openid-configuration`);- }- return out;-}--function classifyProbeError(err: unknown): ProbeMcpDiscoveryResult {- if (err instanceof ProbeError) {- return { ok: false, kind: err.kind, error: err.message };- }- return {- ok: false,- kind: "no_discovery_doc",- error: err instanceof Error ? err.message : String(err),- };-}--type DcrResponse = {- client_id: string;- client_secret?: string;- token_endpoint_auth_method?: string;-};--async function dynamicRegister(- registration_endpoint: string,- redirect_uri: string,- auth_method: ClientAuthMethod,-): Promise<DcrResponse> {- // PKCE-only `none` is the MCP-spec default for public clients. Some- // OAuth servers (Supabase, certain OIDC providers) reject `none` and- // require a confidential client; for those we register as- // `client_secret_post` — the AS returns a client_secret which the- // callback then sends alongside the code at token exchange.- //- // grant_types includes `refresh_token` per SEP-2207 ("OIDC-Flavored- // Refresh Token Guidance", accepted 2026-02-04). Some Authorization- // Servers (notably Stripe's MCP) only issue refresh tokens to clients- // that explicitly register the capability — without this we still get- // a working access token but the user is forced to reconnect when it- // expires (~1h for Stripe). Servers that don't support refresh_token- // grant either ignore the extra entry or reject it; in the latter case- // we'd fall back to the authorization_code-only registration anyway.- const body = {- client_name: "NotFair",- redirect_uris: [redirect_uri],- grant_types: ["authorization_code", "refresh_token"],- response_types: ["code"],- token_endpoint_auth_method: auth_method,- };- const res = await fetch(registration_endpoint, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(body),- });- if (!res.ok) {- const text = await res.text();- throw new Error(`DCR ${res.status}: ${text.slice(0, 200)}`);- }- const json = (await res.json()) as DcrResponse;- if (!json.client_id) throw new Error("DCR response missing client_id");- return json;-}--async function fetchJson(url: string, timeout_ms: number): Promise<unknown> {- const ctl = new AbortController();- const t = setTimeout(() => ctl.abort(), timeout_ms);- try {- const res = await fetch(url, { signal: ctl.signal });- if (!res.ok) throw new Error(`HTTP ${res.status} from ${url}`);- return await res.json();- } finally {- clearTimeout(t);- }-}--function base64url(b: Buffer): string {- return b.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");-}--async function originFromIncomingRequest(): Promise<string> {- const h = await headers();- // Next surfaces forwarded headers when behind a proxy; fall back to host.- const proto = h.get("x-forwarded-proto") ?? "http";- const rawHost = h.get("x-forwarded-host") ?? h.get("host");- if (!rawHost) {- throw new Error("Could not derive origin from request headers");- }- // RFC 8252 §7.3 says native OAuth clients use the loopback IP (127.0.0.1)- // rather than the `localhost` hostname; some providers (Vercel) enforce- // this and reject `http://localhost` as an "invalid redirect URL".- // Normalize so the registered + exchanged redirect URI is loopback-IP- // regardless of which form the user typed into the address bar.- const host = rawHost.replace(/^localhost(:|$)/, "127.0.0.1$1");- return `${proto}://${host}`;-}--function humanError(err: unknown): string {- if (err instanceof Error) return err.message;- return String(err);-}--/**- * Accept only same-origin, path-only redirect targets. Anything with a scheme- * or a `//` prefix would let a caller redirect the user off-site after OAuth,- * which is an open-redirect class bug. Returns undefined when the input- * isn't a safe local path, so the callback falls back to /connections.- */-function sanitizeReturnTo(raw: string | undefined): string | undefined {- if (!raw) return undefined;- if (!raw.startsWith("/")) return undefined;- if (raw.startsWith("//")) return undefined;- return raw;-}diff --git a/notfair/src/server/actions/projects.test.ts b/notfair/src/server/actions/projects.test.tsdeleted file mode 100644index ba55df0a..00000000--- a/notfair/src/server/actions/projects.test.ts+++ /dev/null@@ -1,412 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";-import { mkdirSync, writeFileSync } from "node:fs";-import { join } from "node:path";--// Real better-sqlite3 against a tmpdir DB, per repo test conventions.-// MUST be hoisted: static imports evaluate before module-level statements,-// and db.ts captures NOTFAIR_DATA_DIR at import time — a plain assignment-// here would silently point the suite at the developer's live ~/.notfair.-const h = vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- const dataDir = mkdtempSync(join(tmpdir(), "notfair-actions-projects-"));- process.env.NOTFAIR_DATA_DIR = dataDir;- return { dataDir };-});--const mocks = vi.hoisted(() => ({- revalidatePath: vi.fn(),- redirect: vi.fn(),- cookieJar: new Map<string, string>(),- listProjectAgents: vi.fn(async () => [] as unknown[]),- readAgentMeta: vi.fn(() => null as unknown),- relocateAgent: vi.fn(async () => ({ new_agent_id: "x", new_slug: "y" })),- cascadeDeleteProjectArtifacts: vi.fn(async () => {}),- getProjectDeletionSummary: vi.fn(async () => ({ agents: [], mcps: [] })),- listProjectMcpTokens: vi.fn(() => [] as unknown[]),- renameProjectBriefDir: vi.fn(async () => {}),- deleteProjectBriefDir: vi.fn(async () => {}),- syncProjectAgents: vi.fn(async () => 0),-}));--vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));-vi.mock("next/navigation", () => ({ redirect: mocks.redirect }));-vi.mock("next/headers", () => ({- cookies: async () => ({- get: (name: string) =>- mocks.cookieJar.has(name) ? { name, value: mocks.cookieJar.get(name)! } : undefined,- set: (name: string, value: string) => void mocks.cookieJar.set(name, value),- delete: (name: string) => void mocks.cookieJar.delete(name),- }),-}));-vi.mock("@/server/agent-meta", () => ({- listProjectAgents: mocks.listProjectAgents,- readAgentMeta: mocks.readAgentMeta,-}));-vi.mock("@/server/actions/agents", () => ({- relocateAgent: mocks.relocateAgent,-}));-vi.mock("@/server/agents/cascade-delete", () => ({- cascadeDeleteProjectArtifacts: mocks.cascadeDeleteProjectArtifacts,- getProjectDeletionSummary: mocks.getProjectDeletionSummary,-}));-vi.mock("@/server/mcp/tokens", () => ({- listProjectMcpTokens: mocks.listProjectMcpTokens,-}));-vi.mock("@/server/onboarding/project-brief", () => ({- renameProjectBriefDir: mocks.renameProjectBriefDir,- deleteProjectBriefDir: mocks.deleteProjectBriefDir,-}));-vi.mock("@/server/goals/provision", () => ({- syncProjectAgents: mocks.syncProjectAgents,-}));--import { getDb } from "@/server/db/db";-import { createProject, getProject } from "@/server/db/projects";-import {- archiveProjectAction,- createProjectAction,- createProjectForOnboardingAction,- deleteProjectAction,- getProjectDeletionSummaryAction,- renameProjectAction,- renameProjectFullAction,- setProjectCodebasePathAction,- switchProjectAction,-} from "./projects";--const COOKIE = "notfair_active_project";--function form(fields: Record<string, string>): FormData {- const fd = new FormData();- for (const [k, v] of Object.entries(fields)) fd.set(k, v);- return fd;-}--beforeEach(() => {- vi.clearAllMocks();- mocks.cookieJar.clear();- mocks.listProjectAgents.mockResolvedValue([]);-});--describe("createProjectAction", () => {- it("throws on a missing name", async () => {- await expect(createProjectAction(form({}))).rejects.toThrow(- "Please enter a workspace name.",- );- });-- it("throws with the createProject reason on failure", async () => {- createProject({ display_name: "Taken" });- await expect(- createProjectAction(form({ display_name: "Taken" })),- ).rejects.toThrow("already exists");- });-- it("creates, activates, and redirects home", async () => {- await createProjectAction(form({ display_name: "Fresh One" }));- expect(getProject("fresh-one")).not.toBeNull();- expect(mocks.cookieJar.get(COOKIE)).toBe("fresh-one");- expect(mocks.revalidatePath).toHaveBeenCalledWith("/", "layout");- expect(mocks.redirect).toHaveBeenCalledWith("/");- });-});--describe("createProjectForOnboardingAction", () => {- it("returns errors instead of throwing", async () => {- expect(await createProjectForOnboardingAction(form({}))).toEqual({- ok: false,- error: "Please enter a workspace name.",- });- const dup = await createProjectForOnboardingAction(- form({ display_name: "Fresh One" }),- );- expect(dup.ok).toBe(false);- });-- it("persists onboarding hints and falls back on an unknown harness", async () => {- const r = await createProjectForOnboardingAction(- form({- display_name: "Onboard Co",- website_url: " https://onboard.co ",- codebase_path: "",- harness_adapter: "not-a-harness",- }),- );- expect(r).toEqual({- ok: true,- data: { slug: "onboard-co", display_name: "Onboard Co" },- });- expect(getProject("onboard-co")).toMatchObject({- website_url: "https://onboard.co",- codebase_path: null,- harness_adapter: "claude-code-local",- });- expect(mocks.cookieJar.get(COOKIE)).toBe("onboard-co");- });-- it("honors a valid harness choice", async () => {- await createProjectForOnboardingAction(- form({ display_name: "Codex Shop", harness_adapter: "codex-local" }),- );- expect(getProject("codex-shop")?.harness_adapter).toBe("codex-local");- });-});--describe("switch / archive / rename actions", () => {- it("switchProjectAction repoints the cookie", async () => {- expect(await switchProjectAction("fresh-one")).toEqual({ ok: true, data: undefined });- expect(mocks.cookieJar.get(COOKIE)).toBe("fresh-one");- });-- it("archiveProjectAction handles missing and existing projects", async () => {- expect(await archiveProjectAction("no-such")).toEqual({- ok: false,- error: "Project not found.",- });- createProject({ display_name: "Archive Target" });- expect(await archiveProjectAction("archive-target")).toEqual({- ok: true,- data: undefined,- });- expect(getProject("archive-target")?.archived_at).toBeTruthy();- });-- it("renameProjectAction handles missing and existing projects", async () => {- expect(await renameProjectAction("no-such", "New")).toEqual({- ok: false,- error: "Project not found or name invalid.",- });- createProject({ display_name: "Rename Target" });- expect(await renameProjectAction("rename-target", "Renamed Target")).toEqual({- ok: true,- data: undefined,- });- expect(getProject("rename-target")?.display_name).toBe("Renamed Target");- });-});--describe("renameProjectFullAction", () => {- it("validates the project, name, and slug", async () => {- expect(- await renameProjectFullAction({ current_slug: "ghost", new_display_name: "X" }),- ).toEqual({ ok: false, error: "Project 'ghost' not found." });-- createProject({ display_name: "Full Rename" });- expect(- await renameProjectFullAction({ current_slug: "full-rename", new_display_name: " " }),- ).toEqual({ ok: false, error: "Name cannot be empty." });- expect(- await renameProjectFullAction({ current_slug: "full-rename", new_display_name: "###" }),- ).toMatchObject({ ok: false });- });-- it("no-ops when nothing changed and takes the cheap path for display-only", async () => {- const same = await renameProjectFullAction({- current_slug: "full-rename",- new_display_name: "Full Rename",- });- expect(same).toEqual({- ok: true,- data: {- slug: "full-rename",- display_name: "Full Rename",- full_rename: false,- agents_relocated: [],- agents_failed: [],- },- });-- const display = await renameProjectFullAction({- current_slug: "full-rename",- new_display_name: "FULL rename", // same slug, new display name- });- expect(display).toMatchObject({- ok: true,- data: { slug: "full-rename", display_name: "FULL rename", full_rename: false },- });- expect(getProject("full-rename")?.display_name).toBe("FULL rename");- expect(mocks.relocateAgent).not.toHaveBeenCalled();- });-- it("refuses to rename onto an existing slug", async () => {- createProject({ display_name: "Slug Squatter" });- expect(- await renameProjectFullAction({- current_slug: "full-rename",- new_display_name: "Slug Squatter",- }),- ).toEqual({ ok: false, error: "A project with slug 'slug-squatter' already exists." });- });-- it("cascades: relocates agents, migrates rows, moves the brief, repoints the cookie", async () => {- mocks.cookieJar.set(COOKIE, "full-rename");- mocks.listProjectAgents.mockResolvedValue([- { agent_id: "full-rename-goal-1", slug: "goal-1", name: "Goal 1" },- { agent_id: "full-rename-goal-2", slug: "goal-2", name: "Goal 2" },- ]);- mocks.readAgentMeta.mockReturnValue({- source_agent_id: "origin-agent",- created_at: "2026-01-01T00:00:00.000Z",- });- mocks.relocateAgent- .mockResolvedValueOnce({ new_agent_id: "renamed-co-goal-1", new_slug: "goal-1" })- .mockRejectedValueOnce(new Error("workspace busy"));-- const r = await renameProjectFullAction({- current_slug: "full-rename",- new_display_name: "Renamed Co",- });- expect(r).toEqual({- ok: true,- data: {- slug: "renamed-co",- display_name: "Renamed Co",- full_rename: true,- agents_relocated: ["full-rename-goal-1"],- agents_failed: [- { agent_id: "full-rename-goal-2", error: "workspace busy" },- ],- },- });- expect(mocks.relocateAgent).toHaveBeenCalledWith({- old_agent_id: "full-rename-goal-1",- source_project_slug: "full-rename",- new_project_slug: "renamed-co",- new_slug: "goal-1",- new_display_name: "Goal 1",- preserve_source_agent_id: "origin-agent",- preserve_created_at: "2026-01-01T00:00:00.000Z",- });- expect(getProject("full-rename")).toBeNull();- expect(getProject("renamed-co")?.display_name).toBe("Renamed Co");- expect(mocks.renameProjectBriefDir).toHaveBeenCalledWith("full-rename", "renamed-co");- expect(mocks.cookieJar.get(COOKIE)).toBe("renamed-co");- });-});--describe("getProjectDeletionSummaryAction", () => {- it("handles missing project, success, and summary failure", async () => {- expect(await getProjectDeletionSummaryAction("ghost")).toEqual({- ok: false,- error: "Project 'ghost' not found.",- });- createProject({ display_name: "Summary Me" });- expect(await getProjectDeletionSummaryAction("summary-me")).toEqual({- ok: true,- data: { agents: [], mcps: [] },- });- mocks.getProjectDeletionSummary.mockRejectedValueOnce(new Error("scan failed"));- expect(await getProjectDeletionSummaryAction("summary-me")).toEqual({- ok: false,- error: "scan failed",- });- });-});--describe("deleteProjectAction", () => {- it("requires a matching confirmation slug and an existing project", async () => {- expect(await deleteProjectAction("a", "b")).toEqual({- ok: false,- error: "Confirmation slug does not match.",- });- expect(await deleteProjectAction("ghost", "ghost")).toEqual({- ok: false,- error: "Project 'ghost' not found.",- });- });-- it("cascades everything and clears the active-project cookie", async () => {- createProject({ display_name: "Doomed" });- const now = new Date().toISOString();- getDb()- .prepare(- `INSERT INTO sessions (id, project_slug, agent_id, label, harness_adapter, created_at, updated_at)- VALUES ('doom-s1', 'doomed', 'doomed-goal-1', 'main', 'claude-code-local', ?, ?)`,- )- .run(now, now);- mocks.cookieJar.set(COOKIE, "doomed");- mocks.listProjectAgents.mockResolvedValue([{ agent_id: "doomed-goal-1" }]);- mocks.listProjectMcpTokens.mockReturnValue([{}, {}]);-- const r = await deleteProjectAction("doomed", "doomed");- expect(r).toEqual({- ok: true,- data: { agents: ["doomed-goal-1"], agentsFailed: [], mcps: 2, mcpsFailed: 0 },- });- expect(mocks.cascadeDeleteProjectArtifacts).toHaveBeenCalledWith("doomed");- expect(mocks.deleteProjectBriefDir).toHaveBeenCalledWith("doomed");- expect(getProject("doomed")).toBeNull();- expect(mocks.cookieJar.has(COOKIE)).toBe(false);- });-- it("records a cascade failure but still deletes the DB rows", async () => {- createProject({ display_name: "Doomed Two" });- mocks.cascadeDeleteProjectArtifacts.mockRejectedValueOnce(new Error("rm failed"));- const err = vi.spyOn(console, "error").mockImplementation(() => {});- try {- const r = await deleteProjectAction("doomed-two", "doomed-two");- expect(r).toMatchObject({- ok: true,- data: { agentsFailed: [{ agentId: "(project)", error: "rm failed" }] },- });- expect(getProject("doomed-two")).toBeNull();- } finally {- err.mockRestore();- }- });-});--describe("setProjectCodebasePathAction", () => {- it("validates slug, path existence, and directory-ness", async () => {- expect(- await setProjectCodebasePathAction({ project_slug: " ", codebase_path: "/x" }),- ).toEqual({ ok: false, error: "Missing project slug." });-- const missing = join(h.dataDir, "does-not-exist");- expect(- await setProjectCodebasePathAction({ project_slug: "s", codebase_path: missing }),- ).toEqual({ ok: false, error: `Folder not found: ${missing}` });-- const file = join(h.dataDir, "a-file.txt");- writeFileSync(file, "hi");- expect(- await setProjectCodebasePathAction({ project_slug: "s", codebase_path: file }),- ).toEqual({ ok: false, error: `Not a folder: ${file}` });- });-- it("fails when the project row is missing", async () => {- const dir = join(h.dataDir, "repo");- mkdirSync(dir, { recursive: true });- expect(- await setProjectCodebasePathAction({ project_slug: "ghost", codebase_path: dir }),- ).toEqual({ ok: false, error: "Project not found." });- });-- it("persists the folder and re-syncs agent identities", async () => {- createProject({ display_name: "Codebase Co" });- const dir = join(h.dataDir, "repo");- const r = await setProjectCodebasePathAction({- project_slug: "codebase-co",- codebase_path: ` ${dir} `,- });- expect(r).toEqual({ ok: true, codebase_path: dir });- expect(mocks.syncProjectAgents).toHaveBeenCalledWith("codebase-co");- expect(getProject("codebase-co")?.codebase_path).toBe(dir);- });-- it("clears the path and tolerates a failing identity sync", async () => {- mocks.syncProjectAgents.mockRejectedValueOnce(new Error("render broke"));- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});- try {- const r = await setProjectCodebasePathAction({- project_slug: "codebase-co",- codebase_path: " ",- });- expect(r).toEqual({ ok: true, codebase_path: null });- } finally {- warn.mockRestore();- }- });-});diff --git a/notfair/src/server/actions/projects.ts b/notfair/src/server/actions/projects.tsdeleted file mode 100644index 50fcf08e..00000000--- a/notfair/src/server/actions/projects.ts+++ /dev/null@@ -1,395 +0,0 @@-"use server";--import { revalidatePath } from "next/cache";-import { redirect } from "next/navigation";-import { cookies } from "next/headers";-import {- archiveProject,- changeProjectSlug,- createProject,- deleteProjectRow,- getProject,- renameProject,-} from "@/server/db/projects";-import { slugify } from "@/lib/slug";-import {- clearActiveProject,- setActiveProject,-} from "@/server/active-project";-import { listProjectAgents, readAgentMeta } from "@/server/agent-meta";-import { relocateAgent } from "@/server/actions/agents";-import {- cascadeDeleteProjectArtifacts,- getProjectDeletionSummary,- type ProjectDeletionSummary,-} from "@/server/agents/cascade-delete";--export type ActionResult<T = void> =- | { ok: true; data: T }- | { ok: false; error: string };--// Throws on validation failure so form action signature is `(formData) => Promise<void>`.-// Pages can render `error.tsx` for fallback; for inline UI feedback, wire `useActionState`-// in a client wrapper later if needed.-export async function createProjectAction(formData: FormData): Promise<void> {- const display_name = String(formData.get("display_name") ?? "").trim();- if (!display_name) throw new Error("Please enter a workspace name.");-- const result = createProject({ display_name });- if (!result.ok) throw new Error(result.reason);-- await setActiveProject(result.project.slug);- revalidatePath("/", "layout");- redirect("/");-}--/**- * Onboarding-flow variant of createProjectAction. Same create + async- * provision (D6) but returns the slug to the caller instead of redirecting- * to /. The client navigates to ?step=connect&slug=... after success.- */-export async function createProjectForOnboardingAction(- formData: FormData,-): Promise<ActionResult<{ slug: string; display_name: string }>> {- const display_name = String(formData.get("display_name") ?? "").trim();- if (!display_name) return { ok: false, error: "Please enter a workspace name." };-- const website_url = String(formData.get("website_url") ?? "").trim() || null;- const codebase_path = String(formData.get("codebase_path") ?? "").trim() || null;- const harness_raw = String(formData.get("harness_adapter") ?? "").trim();- const { isHarnessAdapterId, DEFAULT_HARNESS_ADAPTER } = await import(- "@/server/adapters/registry"- );- const harness_adapter = isHarnessAdapterId(harness_raw)- ? harness_raw- : DEFAULT_HARNESS_ADAPTER;-- const result = createProject({- display_name,- website_url,- codebase_path,- harness_adapter,- });- if (!result.ok) return { ok: false, error: result.reason };-- await setActiveProject(result.project.slug);- revalidatePath("/", "layout");- return {- ok: true,- data: {- slug: result.project.slug,- display_name: result.project.display_name,- },- };-}--export async function switchProjectAction(slug: string): Promise<ActionResult> {- await setActiveProject(slug);- revalidatePath("/", "layout");- return { ok: true, data: undefined };-}--export async function archiveProjectAction(- slug: string,-): Promise<ActionResult> {- const project = archiveProject(slug);- if (!project) return { ok: false, error: "Project not found." };- revalidatePath("/", "layout");- return { ok: true, data: undefined };-}--export async function renameProjectAction(slug: string, display_name: string): Promise<ActionResult> {- const updated = renameProject(slug, display_name);- if (!updated) return { ok: false, error: "Project not found or name invalid." };- revalidatePath("/", "layout");- return { ok: true, data: undefined };-}--export type RenameProjectFullInput = {- current_slug: string;- new_display_name: string;-};--export type RenameProjectFullData = {- slug: string;- display_name: string;- /** True when the slug actually changed (a full cascade ran). */- full_rename: boolean;- /** Per-agent outcomes for the rename pass. */- agents_relocated: string[];- agents_failed: Array<{ agent_id: string; error: string }>;-};--/**- * Rename a project — display name and (when the slugified name differs) URL- * slug too. Display-name-only changes hit just the DB. Slug changes cascade:- * relocate every agent in the project to the new slug (re-uses- * `relocateAgent`, which itself is the shared helper that powers per-agent- * rename), then migrate every DB row keyed off project_slug.- *- * After a full rename: agent_ids change from `<old>-<slug>` to `<new>-<slug>`,- * workspace dirs move, session rows- * relocate, and the active-project cookie repoints at the new slug.- */-export async function renameProjectFullAction(- input: RenameProjectFullInput,-): Promise<ActionResult<RenameProjectFullData>> {- const current = getProject(input.current_slug);- if (!current) return { ok: false, error: `Project '${input.current_slug}' not found.` };-- const newName = input.new_display_name.trim();- if (!newName) return { ok: false, error: "Name cannot be empty." };-- const newSlugResult = slugify(newName);- if (!newSlugResult.ok) {- return { ok: false, error: `Invalid name: ${newSlugResult.reason}` };- }- const newSlug = newSlugResult.slug;- const sameSlug = newSlug === current.slug;-- // Display-name-only change — cheap path.- if (sameSlug) {- if (newName === current.display_name) {- return {- ok: true,- data: {- slug: current.slug,- display_name: current.display_name,- full_rename: false,- agents_relocated: [],- agents_failed: [],- },- };- }- renameProject(current.slug, newName);- revalidatePath("/", "layout");- return {- ok: true,- data: {- slug: current.slug,- display_name: newName,- full_rename: false,- agents_relocated: [],- agents_failed: [],- },- };- }-- if (getProject(newSlug)) {- return { ok: false, error: `A project with slug '${newSlug}' already exists.` };- }-- // 1) Relocate every agent into the new project slug (keeping each agent's- // own slug + display name + clone provenance intact).- const agents = await listProjectAgents(current.slug);- const agentsRelocated: string[] = [];- const agentsFailed: Array<{ agent_id: string; error: string }> = [];- for (const a of agents) {- try {- const meta = readAgentMeta(a.agent_id);- await relocateAgent({- old_agent_id: a.agent_id,- source_project_slug: current.slug,- new_project_slug: newSlug,- new_slug: a.slug,- new_display_name: a.name,- preserve_source_agent_id: meta?.source_agent_id,- preserve_created_at: meta?.created_at,- });- agentsRelocated.push(a.agent_id);- } catch (err) {- agentsFailed.push({- agent_id: a.agent_id,- error: err instanceof Error ? err.message : String(err),- });- }- }-- // 2) Migrate DB rows. If a child-table update fails the rename is partial;- // surface a clear error but leave the moved agents in place (they're- // addressable under the new slug already).- try {- changeProjectSlug(current.slug, newSlug, newName);- } catch (err) {- return {- ok: false,- error: `DB migration failed after agent move: ${- err instanceof Error ? err.message : String(err)- }. Agents already moved; cleanup needed.`,- };- }-- // 2.5) Move the canonical PROJECT.md directory from old slug → new slug- // so the brief survives the rename. The per-agent sidecar copies- // get rewritten on the next identity sync; the canonical file is- // the source of truth they read from, so moving this is what- // matters.- try {- const { renameProjectBriefDir } = await import(- "@/server/onboarding/project-brief"- );- await renameProjectBriefDir(current.slug, newSlug);- } catch (err) {- console.warn(- `[rename-project] failed to move PROJECT.md dir from ${current.slug} to ${newSlug}:`,- err,- );- }-- // 3) Repoint the active-project cookie if it was this one.- const c = await cookies();- if (c.get("notfair_active_project")?.value === current.slug) {- await setActiveProject(newSlug);- }-- revalidatePath("/", "layout");-- return {- ok: true,- data: {- slug: newSlug,- display_name: newName,- full_rename: true,- agents_relocated: agentsRelocated,- agents_failed: agentsFailed,- },- };-}--export async function getProjectDeletionSummaryAction(- slug: string,-): Promise<ActionResult<ProjectDeletionSummary>> {- const project = getProject(slug);- if (!project) return { ok: false, error: `Project '${slug}' not found.` };- try {- const summary = await getProjectDeletionSummary(slug);- return { ok: true, data: summary };- } catch (err) {- return { ok: false, error: err instanceof Error ? err.message : String(err) };- }-}--export type DeleteProjectData = {- agents: string[];- agentsFailed: Array<{ agentId: string; error: string }>;- mcps: number;- mcpsFailed: number;-};--export async function deleteProjectAction(- slug: string,- confirmedSlug: string,-): Promise<ActionResult<DeleteProjectData>> {- if (slug !== confirmedSlug) {- return { ok: false, error: "Confirmation slug does not match." };- }- const project = getProject(slug);- if (!project) return { ok: false, error: `Project '${slug}' not found.` };-- const projectAgentEntries = await listProjectAgents(slug);- const deletedAgents: string[] = projectAgentEntries.map((a) => a.agent_id);- const agentsFailed: Array<{ agentId: string; error: string }> = [];- // MCP token rows are wiped by the cascade below; count upfront for the- // result summary.- const { listProjectMcpTokens } = await import("@/server/mcp/tokens");- const mcpsRevoked = listProjectMcpTokens(slug).length;- const mcpsFailed = 0;--- // Single shot — drops every artifact tied to this project: agent workspace- // dirs, sessions + transcripts, mcp_tokens. Adapter MCP entries get- // unregistered too.- try {- await cascadeDeleteProjectArtifacts(slug);- } catch (err) {- console.error("[delete-project] cascade failed:", err);- agentsFailed.push({- agentId: "(project)",- error: err instanceof Error ? err.message : String(err),- });- }-- // 5) Canonical PROJECT.md directory at ~/.notfair/projects/<slug>/.- // The per-agent sidecar copies inside each workspace were already wiped- // by the cascade's `rm -rf` on the workspace dirs; this is the- // last surface that holds the project brief on disk. Without this,- // recreating a project with the same slug later would silently inherit- // the prior tenant's PROJECT.md (writeIdentityFile inlines it if it- // exists). Best-effort — a missing dir is a no-op.- try {- const { deleteProjectBriefDir } = await import(- "@/server/onboarding/project-brief"- );- await deleteProjectBriefDir(slug);- } catch (err) {- console.warn(- `[delete-project] failed to remove PROJECT.md dir for ${slug}:`,- err,- );- }-- // 6) Local DB rows.- deleteProjectRow(slug);-- // 7) Clear active-project cookie if it pointed at this one.- const c = await cookies();- if (c.get("notfair_active_project")?.value === slug) {- await clearActiveProject();- }-- revalidatePath("/", "layout");-- return {- ok: true,- data: {- agents: deletedAgents,- agentsFailed,- mcps: mcpsRevoked,- mcpsFailed,- },- };-}--/**- * Set (or clear) the workspace's local codebase folder — the sanctioned- * root for agent code changes (branch + PR protocol). Validates the path- * is an existing directory, persists it, and re-renders every goal- * agent's identity so the "Codebase" workspace fact updates immediately.- */-export async function setProjectCodebasePathAction(input: {- project_slug: string;- codebase_path: string;-}): Promise<{ ok: true; codebase_path: string | null } | { ok: false; error: string }> {- const slug = input.project_slug.trim();- if (!slug) return { ok: false, error: "Missing project slug." };- const raw = input.codebase_path.trim();-- let normalized: string | null = null;- if (raw) {- const { stat } = await import("node:fs/promises");- try {- const s = await stat(raw);- if (!s.isDirectory()) {- return { ok: false, error: `Not a folder: ${raw}` };- }- } catch {- return { ok: false, error: `Folder not found: ${raw}` };- }- normalized = raw;- }-- const { setProjectCodebasePath } = await import("@/server/db/projects");- const updated = setProjectCodebasePath(slug, normalized);- if (!updated) return { ok: false, error: "Project not found." };-- // Agents carry the codebase path in their identity's workspace facts.- try {- const { syncProjectAgents } = await import("@/server/goals/provision");- await syncProjectAgents(slug);- } catch (err) {- console.warn("[settings] identity re-render after codebase change failed:", err);- }-- revalidatePath("/", "layout");- return { ok: true, codebase_path: updated.codebase_path };-}diff --git a/notfair/src/server/actions/shared-context.test.ts b/notfair/src/server/actions/shared-context.test.tsdeleted file mode 100644index edbbd60b..00000000--- a/notfair/src/server/actions/shared-context.test.ts+++ /dev/null@@ -1,51 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- revalidatePath: vi.fn(),- getProject: vi.fn(),- writeBrief: vi.fn(),- syncAgents: vi.fn(),-}));--vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));-vi.mock("@/server/db/projects", () => ({ getProject: mocks.getProject }));-vi.mock("@/server/onboarding/project-brief", () => ({- writeProjectBrief: mocks.writeBrief,- PROJECT_BRIEF_MAX_BYTES: 16,-}));-vi.mock("@/server/goals/provision", () => ({ syncProjectAgents: mocks.syncAgents }));--import { saveSharedContextAction } from "./shared-context";--beforeEach(() => {- vi.clearAllMocks();- mocks.getProject.mockReturnValue({ slug: "acme" });- mocks.writeBrief.mockResolvedValue(undefined);- mocks.syncAgents.mockResolvedValue(3);-});--it("validates project, content, and UTF-8 byte length", async () => {- mocks.getProject.mockReturnValue(null);- await expect(saveSharedContextAction({ project_slug: "x", content: "brief" })).resolves.toMatchObject({ ok: false });- mocks.getProject.mockReturnValue({});- await expect(saveSharedContextAction({ project_slug: "x", content: " " })).resolves.toMatchObject({ error: expect.stringContaining("empty") });- await expect(saveSharedContextAction({ project_slug: "x", content: "🌍🌍🌍🌍🌍" })).resolves.toMatchObject({ error: expect.stringContaining("Too long") });-});--it("writes trimmed content, syncs agents, and revalidates", async () => {- await expect(saveSharedContextAction({ project_slug: "acme", content: " company brief " })).resolves.toEqual({- ok: true,- synced_agents: 3,- });- expect(mocks.writeBrief).toHaveBeenCalledWith("acme", "company brief");- expect(mocks.syncAgents).toHaveBeenCalledWith("acme");- expect(mocks.revalidatePath).toHaveBeenCalledWith("/", "layout");-});--it.each([new Error("disk full"), "sync failed"])("maps write failure %#", async (failure) => {- mocks.writeBrief.mockRejectedValue(failure);- await expect(saveSharedContextAction({ project_slug: "acme", content: "brief" })).resolves.toEqual({- ok: false,- error: failure instanceof Error ? failure.message : failure,- });-});diff --git a/notfair/src/server/actions/shared-context.ts b/notfair/src/server/actions/shared-context.tsdeleted file mode 100644index 4ecfb81a..00000000--- a/notfair/src/server/actions/shared-context.ts+++ /dev/null@@ -1,45 +0,0 @@-"use server";--import { revalidatePath } from "next/cache";-import { getProject } from "@/server/db/projects";-import {- writeProjectBrief,- PROJECT_BRIEF_MAX_BYTES,-} from "@/server/onboarding/project-brief";-import { syncProjectAgents } from "@/server/goals/provision";--/**- * User-side editing of the shared workspace context (PROJECT.md). Same- * write + sync path the agents' `set_shared_context` tool uses, so a save- * here lands in every goal agent's identity immediately.- */-export async function saveSharedContextAction(input: {- project_slug: string;- content: string;-}): Promise<- | { ok: true; synced_agents: number }- | { ok: false; error: string }-> {- const project = getProject(input.project_slug);- if (!project) return { ok: false, error: "Workspace not found." };-- const content = input.content.trim();- if (!content) {- return { ok: false, error: "Shared context can't be empty — describe the company instead." };- }- if (Buffer.byteLength(content, "utf8") > PROJECT_BRIEF_MAX_BYTES) {- return {- ok: false,- error: `Too long — keep it under ${Math.round(PROJECT_BRIEF_MAX_BYTES / 1024)}KB. This is a curated brief, not a dump.`,- };- }-- try {- await writeProjectBrief(input.project_slug, content);- const synced_agents = await syncProjectAgents(input.project_slug);- revalidatePath("/", "layout");- return { ok: true, synced_agents };- } catch (err) {- return { ok: false, error: err instanceof Error ? err.message : String(err) };- }-}diff --git a/notfair/src/server/actions/suggestions.test.ts b/notfair/src/server/actions/suggestions.test.tsdeleted file mode 100644index 1cbf0e40..00000000--- a/notfair/src/server/actions/suggestions.test.ts+++ /dev/null@@ -1,66 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- revalidatePath: vi.fn(),- getSuggestion: vi.fn(),- markAccepted: vi.fn(),- markDismissed: vi.fn(),- analyzableSources: vi.fn(),- generate: vi.fn(),- createGoal: vi.fn(),-}));--vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));-vi.mock("@/server/db/suggestions", () => ({- getSuggestion: mocks.getSuggestion,- markSuggestionAccepted: mocks.markAccepted,- markSuggestionDismissed: mocks.markDismissed,-}));-vi.mock("@/server/suggestions/engine", () => ({- analyzableSources: mocks.analyzableSources,- generateSuggestionsForSource: mocks.generate,-}));-vi.mock("@/server/actions/goals", () => ({ createGoalAgentAction: mocks.createGoal }));--import { acceptSuggestionAction, dismissSuggestionAction, refreshSuggestionsAction } from "./suggestions";--const suggestion = { id: "s1", status: "open", project_slug: "acme", statement: "Grow" };--beforeEach(() => {- vi.clearAllMocks();- mocks.getSuggestion.mockReturnValue(suggestion);- mocks.createGoal.mockResolvedValue({ ok: true, goal_id: "g1" });- mocks.analyzableSources.mockReturnValue(["google", "meta"]);-});--it("accepts an open suggestion after creating its goal", async () => {- await expect(acceptSuggestionAction("s1")).resolves.toEqual({ ok: true, goal_id: "g1" });- expect(mocks.createGoal).toHaveBeenCalledWith({ project_slug: "acme", statement: "Grow" });- expect(mocks.markAccepted).toHaveBeenCalledWith("s1", "g1");-});--it("rejects missing/handled suggestions and leaves failed goal creation open", async () => {- mocks.getSuggestion.mockReturnValue(null);- await expect(acceptSuggestionAction("x")).resolves.toMatchObject({ ok: false });- mocks.getSuggestion.mockReturnValue({ ...suggestion, status: "dismissed" });- await expect(acceptSuggestionAction("s1")).resolves.toMatchObject({ ok: false });- mocks.getSuggestion.mockReturnValue(suggestion);- mocks.createGoal.mockResolvedValue({ ok: false, error: "no" });- await expect(acceptSuggestionAction("s1")).resolves.toMatchObject({ ok: false });- expect(mocks.markAccepted).not.toHaveBeenCalled();-});--it("dismisses only open suggestions", async () => {- await expect(dismissSuggestionAction("s1")).resolves.toEqual({ ok: true });- expect(mocks.markDismissed).toHaveBeenCalledWith("s1");- mocks.getSuggestion.mockReturnValue({ ...suggestion, status: "accepted" });- await expect(dismissSuggestionAction("s1")).resolves.toEqual({ ok: false });- mocks.getSuggestion.mockReturnValue(null);- await expect(dismissSuggestionAction("x")).resolves.toEqual({ ok: false });-});--it("fires suggestion generation for each analyzable source", async () => {- await expect(refreshSuggestionsAction("acme")).resolves.toEqual({ ok: true, sources: 2 });- expect(mocks.generate).toHaveBeenCalledWith("acme", "google");- expect(mocks.generate).toHaveBeenCalledWith("acme", "meta");-});diff --git a/notfair/src/server/actions/suggestions.ts b/notfair/src/server/actions/suggestions.tsdeleted file mode 100644index a8edfa7a..00000000--- a/notfair/src/server/actions/suggestions.ts+++ /dev/null@@ -1,56 +0,0 @@-"use server";--import { revalidatePath } from "next/cache";-import {- getSuggestion,- markSuggestionAccepted,- markSuggestionDismissed,-} from "@/server/db/suggestions";-import {- analyzableSources,- generateSuggestionsForSource,-} from "@/server/suggestions/engine";-import { createGoalAgentAction, type GoalActionResult } from "@/server/actions/goals";--/**- * Accept a suggestion: mint the goal from its statement (the normal- * statement-first flow — the agent still verifies the metric and the- * user still confirms the plan in chat) and retire the card.- */-export async function acceptSuggestionAction(id: string): Promise<GoalActionResult> {- const suggestion = getSuggestion(id);- if (!suggestion) return { ok: false, error: "Suggestion not found." };- if (suggestion.status !== "open") {- return { ok: false, error: "This suggestion was already handled." };- }-- const result = await createGoalAgentAction({- project_slug: suggestion.project_slug,- statement: suggestion.statement,- });- if (result.ok && result.goal_id) {- markSuggestionAccepted(id, result.goal_id);- revalidatePath("/", "layout");- }- return result;-}--export async function dismissSuggestionAction(id: string): Promise<{ ok: boolean }> {- const suggestion = getSuggestion(id);- if (!suggestion || suggestion.status !== "open") return { ok: false };- markSuggestionDismissed(id);- revalidatePath("/", "layout");- return { ok: true };-}--/** Re-run analysis across every connected source that supports it. */-export async function refreshSuggestionsAction(- project_slug: string,-): Promise<{ ok: boolean; sources: number }> {- const sources = analyzableSources(project_slug);- for (const key of sources) {- void generateSuggestionsForSource(project_slug, key);- }- revalidatePath("/", "layout");- return { ok: true, sources: sources.length };-}diff --git a/notfair/src/server/active-project.test.ts b/notfair/src/server/active-project.test.tsdeleted file mode 100644index 9bb12820..00000000--- a/notfair/src/server/active-project.test.ts+++ /dev/null@@ -1,111 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";-import type { Project } from "@/types";--// Mock at the framework / db-module boundary per repo conventions: this-// module is pure cookie orchestration around the projects db module.-const mocks = vi.hoisted(() => ({- cookieGet: vi.fn<(name: string) => { value: string } | undefined>(),- cookieSet: vi.fn(),- cookieDelete: vi.fn(),- getProject: vi.fn<(slug: string) => Project | null>(),- listProjects: vi.fn<() => Project[]>(),-}));--vi.mock("next/headers", () => ({- cookies: async () => ({- get: mocks.cookieGet,- set: mocks.cookieSet,- delete: mocks.cookieDelete,- }),-}));-vi.mock("./db/projects", () => ({- getProject: mocks.getProject,- listProjects: mocks.listProjects,-}));--import {- clearActiveProject,- getActiveProject,- setActiveProject,-} from "./active-project";--function project(slug: string, archived_at: string | null = null): Project {- return {- id: `id-${slug}`,- slug,- display_name: slug,- created_at: "2026-01-01T00:00:00.000Z",- archived_at,- google_ads_account_id: null,- meta_ads_account_id: null,- gsc_property_id: null,- website_url: null,- codebase_path: null,- harness_adapter: "claude-code-local",- };-}--beforeEach(() => {- vi.clearAllMocks();-});--describe("getActiveProject", () => {- it("returns the cookie's project when it exists and isn't archived", async () => {- mocks.cookieGet.mockReturnValue({ value: "acme" });- mocks.getProject.mockReturnValue(project("acme"));-- await expect(getActiveProject()).resolves.toMatchObject({ slug: "acme" });- expect(mocks.getProject).toHaveBeenCalledWith("acme");- expect(mocks.listProjects).not.toHaveBeenCalled();- });-- it("falls back to the first listed project when the cookie project is archived", async () => {- mocks.cookieGet.mockReturnValue({ value: "old" });- mocks.getProject.mockReturnValue(project("old", "2026-01-02T00:00:00.000Z"));- mocks.listProjects.mockReturnValue([project("fresh")]);-- await expect(getActiveProject()).resolves.toMatchObject({ slug: "fresh" });- });-- it("falls back when the cookie names a deleted project", async () => {- mocks.cookieGet.mockReturnValue({ value: "ghost" });- mocks.getProject.mockReturnValue(null);- mocks.listProjects.mockReturnValue([project("fresh")]);-- await expect(getActiveProject()).resolves.toMatchObject({ slug: "fresh" });- });-- it("falls back to the first project when no cookie is set", async () => {- mocks.cookieGet.mockReturnValue(undefined);- mocks.listProjects.mockReturnValue([project("a"), project("b")]);-- await expect(getActiveProject()).resolves.toMatchObject({ slug: "a" });- expect(mocks.getProject).not.toHaveBeenCalled();- });-- it("returns null when there are no projects at all", async () => {- mocks.cookieGet.mockReturnValue(undefined);- mocks.listProjects.mockReturnValue([]);-- await expect(getActiveProject()).resolves.toBeNull();- });-});--describe("setActiveProject", () => {- it("writes a year-long httpOnly cookie", async () => {- await setActiveProject("acme");- expect(mocks.cookieSet).toHaveBeenCalledWith("notfair_active_project", "acme", {- httpOnly: true,- sameSite: "lax",- path: "/",- maxAge: 60 * 60 * 24 * 365,- });- });-});--describe("clearActiveProject", () => {- it("deletes the cookie", async () => {- await clearActiveProject();- expect(mocks.cookieDelete).toHaveBeenCalledWith("notfair_active_project");- });-});diff --git a/notfair/src/server/active-project.ts b/notfair/src/server/active-project.tsdeleted file mode 100644index 6aab8c0b..00000000--- a/notfair/src/server/active-project.ts+++ /dev/null@@ -1,32 +0,0 @@-import { cookies } from "next/headers";-import { getProject, listProjects } from "./db/projects";-import type { Project } from "@/types";--const COOKIE_NAME = "notfair_active_project";--export async function getActiveProject(): Promise<Project | null> {- const c = await cookies();- const slug = c.get(COOKIE_NAME)?.value;- if (slug) {- const p = getProject(slug);- if (p && !p.archived_at) return p;- }- // Fall back to the first non-archived project, if any.- const all = listProjects();- return all[0] ?? null;-}--export async function setActiveProject(slug: string): Promise<void> {- const c = await cookies();- c.set(COOKIE_NAME, slug, {- httpOnly: true,- sameSite: "lax",- path: "/",- maxAge: 60 * 60 * 24 * 365,- });-}--export async function clearActiveProject(): Promise<void> {- const c = await cookies();- c.delete(COOKIE_NAME);-}diff --git a/notfair/src/server/adapters/claude-code-local/execute.test.ts b/notfair/src/server/adapters/claude-code-local/execute.test.tsdeleted file mode 100644index 6094629e..00000000--- a/notfair/src/server/adapters/claude-code-local/execute.test.ts+++ /dev/null@@ -1,202 +0,0 @@-import { EventEmitter } from "node:events";-import { mkdtemp, writeFile } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { PassThrough } from "node:stream";-import { beforeEach, describe, expect, it, vi } from "vitest";--import type { HarnessEvent, HarnessExecuteContext } from "../types";--const mocks = vi.hoisted(() => ({ spawn: vi.fn() }));-vi.mock("node:child_process", () => ({ spawn: mocks.spawn }));--import { executeClaudeCodeLocal } from "./execute";--class FakeChild extends EventEmitter {- stdin = { write: vi.fn(), end: vi.fn() };- stdout = new PassThrough();- stderr = new PassThrough();- kill = vi.fn();-}--interface Script {- stdout?: string;- stderr?: string;- exitCode?: number;- spawnError?: Error;-}--/** Mock spawn to return a scripted child; returns the child for inspection. */-function scriptSpawn(script: Script): FakeChild {- const child = new FakeChild();- mocks.spawn.mockImplementationOnce(() => {- setImmediate(async () => {- if (script.spawnError) {- child.emit("error", script.spawnError);- return;- }- if (script.stdout) child.stdout.write(script.stdout);- if (script.stderr) child.stderr.write(script.stderr);- // Let PassThrough flush data events before the close lands.- await new Promise((r) => setTimeout(r, 15));- child.emit("close", script.exitCode ?? 0);- });- return child;- });- return child;-}--async function collect(ctx: HarnessExecuteContext): Promise<HarnessEvent[]> {- const events: HarnessEvent[] = [];- for await (const evt of executeClaudeCodeLocal(ctx)) events.push(evt);- return events;-}--let workspaceDir: string;--function ctx(overrides: Partial<HarnessExecuteContext> = {}): HarnessExecuteContext {- return {- projectSlug: "proj",- agentId: "agent-1",- workspaceDir,- message: "hi there",- threadId: "thread-1",- ...overrides,- };-}--beforeEach(async () => {- mocks.spawn.mockReset();- workspaceDir = await mkdtemp(join(tmpdir(), "notfair-claude-exec-"));-});--describe("executeClaudeCodeLocal — argv wiring", () => {- it("spawns claude in stream-json mode and pipes the message on stdin", async () => {- const child = scriptSpawn({ stdout: `${JSON.stringify({ type: "result", result: "ok" })}\n` });- const events = await collect(ctx());-- expect(mocks.spawn).toHaveBeenCalledTimes(1);- const [bin, args, opts] = mocks.spawn.mock.calls[0]!;- expect(bin).toBe("claude");- expect(args).toEqual([- "--print",- "--output-format",- "stream-json",- "--input-format",- "text",- "--verbose",- ]);- expect(opts).toMatchObject({- cwd: workspaceDir,- env: expect.objectContaining({- NOTFAIR_PROJECT_SLUG: "proj",- NOTFAIR_AGENT_ID: "agent-1",- }),- });- expect(child.stdin.write).toHaveBeenCalledWith("hi there");- expect(child.stdin.end).toHaveBeenCalled();- expect(events).toEqual([- { kind: "delta", text: "ok" },- { kind: "final", text: "ok" },- ]);- });-- it("appends IDENTITY.md as the system prompt when present", async () => {- await writeFile(join(workspaceDir, "IDENTITY.md"), "# You are Greg\n", "utf8");- scriptSpawn({ stdout: `${JSON.stringify({ type: "result", result: "ok" })}\n` });- await collect(ctx());-- const args = mocks.spawn.mock.calls[0]![1] as string[];- const idx = args.indexOf("--append-system-prompt");- expect(idx).toBeGreaterThan(-1);- expect(args[idx + 1]).toBe("# You are Greg\n");- });-- it("passes the model override and resumes real claude session ids", async () => {- scriptSpawn({ stdout: `${JSON.stringify({ type: "result", result: "ok" })}\n` });- const uuid = "123e4567-e89b-42d3-a456-426614174000";- await collect(ctx({ model: "opus", harnessSessionId: uuid }));-- const args = mocks.spawn.mock.calls[0]![1] as string[];- expect(args).toContain("--model");- expect(args[args.indexOf("--model") + 1]).toBe("opus");- expect(args[args.indexOf("--resume") + 1]).toBe(uuid);- });-- it("never passes a non-UUID session id to --resume", async () => {- scriptSpawn({ stdout: `${JSON.stringify({ type: "result", result: "ok" })}\n` });- await collect(ctx({ harnessSessionId: "not-a-claude-session" }));-- expect(mocks.spawn.mock.calls[0]![1]).not.toContain("--resume");- });-});--describe("executeClaudeCodeLocal — stream handling", () => {- it("forwards parsed events across chunk boundaries and flushes the tail line", async () => {- const l1 = JSON.stringify({- type: "system",- subtype: "init",- session_id: "123e4567-e89b-42d3-a456-426614174000",- });- const l2 = JSON.stringify({- type: "assistant",- message: { content: [{ type: "text", text: "hello" }] },- });- // Final line has no trailing newline — must be flushed on close.- const l3 = JSON.stringify({ type: "result", result: "hello" });- scriptSpawn({ stdout: `${l1}\n${l2}\n${l3}` });-- const events = await collect(ctx());- expect(events).toEqual([- { kind: "lifecycle", phase: "init" },- { kind: "session", harnessSessionId: "123e4567-e89b-42d3-a456-426614174000" },- { kind: "delta", text: "hello" },- { kind: "final", text: "hello" },- ]);- });-- it("emits an error with the stderr tail on a non-zero exit without a final", async () => {- scriptSpawn({ exitCode: 1, stderr: "line1\nauth expired\n" });- const events = await collect(ctx());- expect(events).toEqual([- { kind: "error", message: "claude exited with code 1: line1\nauth expired" },- ]);- });-- it("suppresses the exit-code error when the turn already finalized", async () => {- scriptSpawn({- stdout: `${JSON.stringify({ type: "result", result: "done" })}\n`,- exitCode: 1,- });- const events = await collect(ctx());- expect(events).toEqual([- { kind: "delta", text: "done" },- { kind: "final", text: "done" },- ]);- });-- it("yields a terminal error when the binary fails to spawn", async () => {- scriptSpawn({ spawnError: new Error("spawn claude ENOENT") });- const events = await collect(ctx());- expect(events).toEqual([{ kind: "error", message: "spawn claude ENOENT" }]);- });-- it("kills the subprocess when the abort signal fires", async () => {- const controller = new AbortController();- const child = new FakeChild();- child.kill = vi.fn(() => {- child.emit("close", 143);- return true;- });- mocks.spawn.mockImplementationOnce(() => {- setImmediate(() => controller.abort());- return child;- });-- const events = await collect(ctx({ signal: controller.signal }));- expect(child.kill).toHaveBeenCalledWith("SIGTERM");- expect(events).toEqual([- { kind: "error", message: "claude exited with code 143" },- ]);- });-});diff --git a/notfair/src/server/adapters/claude-code-local/execute.ts b/notfair/src/server/adapters/claude-code-local/execute.tsdeleted file mode 100644index 2c55c5f0..00000000--- a/notfair/src/server/adapters/claude-code-local/execute.ts+++ /dev/null@@ -1,167 +0,0 @@-import { spawn } from "node:child_process";-import { readFile } from "node:fs/promises";-import { join } from "node:path";-import type { HarnessEvent, HarnessExecuteContext } from "../types";-import { makeClaudeStreamState, parseClaudeLine } from "./parse";--const CLAUDE_BIN = process.env.NOTFAIR_CLAUDE_BIN?.trim() || "claude";--/**- * Stream one chat turn through the Claude Code CLI.- *- * Wire shape:- * - We spawn `claude --print --output-format stream-json --input-format text`- * with the user message piped in on stdin.- * - The agent's IDENTITY.md is passed as the system prompt via- * `--append-system-prompt`. Claude Code already auto-loads workspace- * CLAUDE.md if present; the IDENTITY.md content takes priority either way.- * - We resume threads via `--resume <session-id>` when NotFair's threadId- * maps onto an existing Claude session. First turn for a thread is fresh.- * - Each stdout line is a JSON event; we forward as HarnessEvents.- */-export async function* executeClaudeCodeLocal(- ctx: HarnessExecuteContext,-): AsyncGenerator<HarnessEvent, void, void> {- let identityMd = "";- try {- identityMd = await readFile(join(ctx.workspaceDir, "IDENTITY.md"), "utf8");- } catch {- // Missing IDENTITY.md isn't fatal — the workspace dir may still have a- // CLAUDE.md Claude Code will auto-load. We pass a brief default below.- }-- const args: string[] = [- "--print",- "--output-format",- "stream-json",- "--input-format",- "text",- "--verbose",- ];- // Composer model override — whitelisted by the chat route.- if (ctx.model) {- args.push("--model", ctx.model);- }- if (identityMd.trim().length > 0) {- args.push("--append-system-prompt", identityMd);- }-- // Resume a Claude session only when we've actually seen one for this- // thread before. NotFair's `sessions.id` UUID is meaningless to- // Claude — passing it to --resume would fail immediately with- // "no session found". The first turn of a thread always runs fresh.- if (ctx.harnessSessionId && isUuid(ctx.harnessSessionId)) {- args.push("--resume", ctx.harnessSessionId);- }-- const child = spawn(CLAUDE_BIN, args, {- cwd: ctx.workspaceDir,- env: { ...process.env, NOTFAIR_PROJECT_SLUG: ctx.projectSlug, NOTFAIR_AGENT_ID: ctx.agentId },- stdio: ["pipe", "pipe", "pipe"],- });-- const abortHandler = () => {- try {- child.kill("SIGTERM");- } catch {- // already dead- }- };- ctx.signal?.addEventListener("abort", abortHandler, { once: true });-- child.stdin.write(ctx.message);- child.stdin.end();-- const state = makeClaudeStreamState();- let stdoutBuf = "";- const events: HarnessEvent[] = [];- let exited = false;- let exitErr: string | null = null;- let resolveWait: (() => void) | null = null;- const wake = () => {- const r = resolveWait;- resolveWait = null;- if (r) r();- };-- child.stdout.setEncoding("utf8");- child.stdout.on("data", (chunk: string) => {- stdoutBuf += chunk;- let idx: number;- while ((idx = stdoutBuf.indexOf("\n")) >= 0) {- const line = stdoutBuf.slice(0, idx);- stdoutBuf = stdoutBuf.slice(idx + 1);- const out = parseClaudeLine(line, state);- for (const evt of out) events.push(evt);- if (out.length > 0) wake();- }- });-- let stderrBuf = "";- child.stderr.setEncoding("utf8");- child.stderr.on("data", (chunk: string) => {- stderrBuf += chunk;- // Stream stderr lines as warnings — Claude Code uses stderr for status- // messages too, so we don't treat presence of stderr as an error.- });-- child.on("error", (err) => {- exited = true;- exitErr = err instanceof Error ? err.message : String(err);- wake();- });- child.on("close", (code) => {- // Flush any tail bytes (no trailing newline case).- if (stdoutBuf.trim().length > 0) {- const out = parseClaudeLine(stdoutBuf, state);- for (const evt of out) events.push(evt);- stdoutBuf = "";- }- if (code !== 0 && !state.finalized) {- const tail = stderrBuf.trim().split("\n").slice(-5).join("\n");- events.push({- kind: "error",- message: `claude exited with code ${code}${tail ? `: ${tail}` : ""}`,- });- }- exited = true;- wake();- });-- try {- while (!exited || events.length > 0) {- while (events.length > 0) {- const evt = events.shift()!;- yield evt;- }- if (exited) break;- await new Promise<void>((resolve) => {- resolveWait = resolve;- // Safety: never hang forever. Long tool calls can pause the stream;- // 5 min is generous for a single turn.- setTimeout(() => {- if (resolveWait === resolve) {- resolveWait = null;- resolve();- }- }, 300_000);- });- }- if (exitErr) {- yield { kind: "error", message: exitErr };- }- } finally {- ctx.signal?.removeEventListener("abort", abortHandler);- if (!exited) {- try {- child.kill("SIGTERM");- } catch {- // ignore- }- }- }-}--function isUuid(s: string): boolean {- return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s);-}diff --git a/notfair/src/server/adapters/claude-code-local/index.test.ts b/notfair/src/server/adapters/claude-code-local/index.test.tsdeleted file mode 100644index 963cd3a8..00000000--- a/notfair/src/server/adapters/claude-code-local/index.test.ts+++ /dev/null@@ -1,77 +0,0 @@-import { join } from "node:path";-import { describe, expect, it, vi } from "vitest";--// dataDir() reads NOTFAIR_DATA_DIR at call time, but hoist anyway so no code-// path in the import graph can ever resolve to the developer's live ~/.notfair.-const tmpDataDir = vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- const dir = mkdtempSync(join(tmpdir(), "notfair-claude-index-"));- process.env.NOTFAIR_DATA_DIR = dir;- return dir;-});--const mocks = vi.hoisted(() => ({- executeClaudeCodeLocal: vi.fn(),- listClaudeCodeModels: vi.fn(async () => []),- provisionClaudeCodeAgent: vi.fn(async () => {}),- testClaudeCodeLocalEnvironment: vi.fn(async () => ({ ok: true })),- registerClaudeCodeMcp: vi.fn(async () => {}),- unregisterClaudeCodeMcp: vi.fn(async () => {}),-}));--vi.mock("./execute", () => ({ executeClaudeCodeLocal: mocks.executeClaudeCodeLocal }));-vi.mock("./models", () => ({ listClaudeCodeModels: mocks.listClaudeCodeModels }));-vi.mock("./provision", () => ({ provisionClaudeCodeAgent: mocks.provisionClaudeCodeAgent }));-vi.mock("./test", () => ({ testClaudeCodeLocalEnvironment: mocks.testClaudeCodeLocalEnvironment }));-vi.mock("./mcp", () => ({- registerClaudeCodeMcp: mocks.registerClaudeCodeMcp,- unregisterClaudeCodeMcp: mocks.unregisterClaudeCodeMcp,-}));--import { claudeCodeLocalAdapter } from "./index";--describe("claudeCodeLocalAdapter", () => {- it("exposes the claude-code-local id and delegates to the submodules", async () => {- expect(claudeCodeLocalAdapter.id).toBe("claude-code-local");- expect(claudeCodeLocalAdapter.testEnvironment).toBe(- mocks.testClaudeCodeLocalEnvironment,- );- expect(claudeCodeLocalAdapter.listModels).toBe(mocks.listClaudeCodeModels);-- const ctx = { agentId: "a" } as never;- const gen = (async function* () {})();- mocks.executeClaudeCodeLocal.mockReturnValueOnce(gen);- expect(claudeCodeLocalAdapter.execute(ctx)).toBe(gen);- expect(mocks.executeClaudeCodeLocal).toHaveBeenCalledWith(ctx);-- const provisionSpec = { agentId: "a" } as never;- await claudeCodeLocalAdapter.provisionAgent(provisionSpec);- expect(mocks.provisionClaudeCodeAgent).toHaveBeenCalledWith(provisionSpec);- });-- it("registers MCP into the agent's workspace under the data dir", async () => {- const spec = {- serverName: "notfair-goals",- agentId: "agent-9",- projectSlug: "proj",- transport: { type: "http" as const, url: "http://x" },- };- await claudeCodeLocalAdapter.registerMcp(spec);- expect(mocks.registerClaudeCodeMcp).toHaveBeenCalledWith(- join(tmpDataDir, "agents", "agent-9"),- spec,- );-- await claudeCodeLocalAdapter.unregisterMcp({- serverName: "notfair-goals",- projectSlug: "proj",- agentId: "agent-9",- });- expect(mocks.unregisterClaudeCodeMcp).toHaveBeenCalledWith(- join(tmpDataDir, "agents", "agent-9"),- "notfair-goals",- );- });-});diff --git a/notfair/src/server/adapters/claude-code-local/index.ts b/notfair/src/server/adapters/claude-code-local/index.tsdeleted file mode 100644index a581feda..00000000--- a/notfair/src/server/adapters/claude-code-local/index.ts+++ /dev/null@@ -1,41 +0,0 @@-import { homedir } from "node:os";-import { join } from "node:path";-import type {- HarnessAdapter,- HarnessExecuteContext,- HarnessEvent,- AgentProvisionSpec,- McpRegistrationSpec,- McpUnregistrationSpec,-} from "../types";-import { executeClaudeCodeLocal } from "./execute";-import { listClaudeCodeModels } from "./models";-import { provisionClaudeCodeAgent } from "./provision";-import { testClaudeCodeLocalEnvironment } from "./test";-import { registerClaudeCodeMcp, unregisterClaudeCodeMcp } from "./mcp";--function dataDir(): string {- return process.env.NOTFAIR_DATA_DIR ?? join(homedir(), ".notfair");-}--function workspaceDirFor(agentId: string): string {- return join(dataDir(), "agents", agentId);-}--export const claudeCodeLocalAdapter: HarnessAdapter = {- id: "claude-code-local",- testEnvironment: testClaudeCodeLocalEnvironment,- listModels: listClaudeCodeModels,- execute(ctx: HarnessExecuteContext): AsyncGenerator<HarnessEvent, void, void> {- return executeClaudeCodeLocal(ctx);- },- async provisionAgent(spec: AgentProvisionSpec): Promise<void> {- await provisionClaudeCodeAgent(spec);- },- async registerMcp(spec: McpRegistrationSpec): Promise<void> {- await registerClaudeCodeMcp(workspaceDirFor(spec.agentId), spec);- },- async unregisterMcp(spec: McpUnregistrationSpec): Promise<void> {- await unregisterClaudeCodeMcp(workspaceDirFor(spec.agentId), spec.serverName);- },-};diff --git a/notfair/src/server/adapters/claude-code-local/mcp.test.ts b/notfair/src/server/adapters/claude-code-local/mcp.test.tsdeleted file mode 100644index 41ba6334..00000000--- a/notfair/src/server/adapters/claude-code-local/mcp.test.ts+++ /dev/null@@ -1,105 +0,0 @@-import { mkdtemp, readFile, writeFile } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { beforeEach, describe, expect, it } from "vitest";--import type { McpRegistrationSpec } from "../types";-import { registerClaudeCodeMcp, unregisterClaudeCodeMcp } from "./mcp";--let workspaceDir: string;--beforeEach(async () => {- workspaceDir = await mkdtemp(join(tmpdir(), "notfair-claude-mcp-"));-});--function spec(overrides: Partial<McpRegistrationSpec> = {}): McpRegistrationSpec {- return {- serverName: "notfair-goals",- agentId: "agent-1",- projectSlug: "proj",- transport: { type: "http", url: "http://127.0.0.1:3326/api/mcp/goals" },- ...overrides,- };-}--async function readMcpJson(): Promise<{ mcpServers: Record<string, unknown> }> {- return JSON.parse(await readFile(join(workspaceDir, ".mcp.json"), "utf8"));-}--describe("registerClaudeCodeMcp", () => {- it("writes an http server entry into .mcp.json", async () => {- await registerClaudeCodeMcp(- workspaceDir,- spec({- transport: {- type: "http",- url: "http://127.0.0.1:3326/api/mcp/goals",- headers: { Authorization: "Bearer s3cret" },- },- }),- );- expect(await readMcpJson()).toEqual({- mcpServers: {- "notfair-goals": {- type: "http",- url: "http://127.0.0.1:3326/api/mcp/goals",- headers: { Authorization: "Bearer s3cret" },- },- },- });- });-- it("writes a stdio server entry with command, args and env", async () => {- await registerClaudeCodeMcp(- workspaceDir,- spec({- serverName: "local-tool",- transport: {- type: "stdio",- command: "node",- args: ["server.js"],- env: { TOKEN: "t" },- },- }),- );- expect((await readMcpJson()).mcpServers["local-tool"]).toEqual({- type: "stdio",- command: "node",- args: ["server.js"],- env: { TOKEN: "t" },- });- });-- it("creates the workspace dir when it does not exist yet", async () => {- const fresh = join(workspaceDir, "nested", "agent");- await registerClaudeCodeMcp(fresh, spec());- const parsed = JSON.parse(await readFile(join(fresh, ".mcp.json"), "utf8"));- expect(Object.keys(parsed.mcpServers)).toEqual(["notfair-goals"]);- });-- it("merges with existing servers instead of clobbering them", async () => {- await registerClaudeCodeMcp(workspaceDir, spec({ serverName: "a" }));- await registerClaudeCodeMcp(workspaceDir, spec({ serverName: "b" }));- expect(Object.keys((await readMcpJson()).mcpServers).sort()).toEqual(["a", "b"]);- });-- it("recovers from a corrupt .mcp.json by starting fresh", async () => {- await writeFile(join(workspaceDir, ".mcp.json"), "{ not json", "utf8");- await registerClaudeCodeMcp(workspaceDir, spec());- expect(Object.keys((await readMcpJson()).mcpServers)).toEqual(["notfair-goals"]);- });-});--describe("unregisterClaudeCodeMcp", () => {- it("removes only the named server", async () => {- await registerClaudeCodeMcp(workspaceDir, spec({ serverName: "a" }));- await registerClaudeCodeMcp(workspaceDir, spec({ serverName: "b" }));- await unregisterClaudeCodeMcp(workspaceDir, "a");- expect(Object.keys((await readMcpJson()).mcpServers)).toEqual(["b"]);- });-- it("is a no-op (but still writes a valid file) when the server is absent", async () => {- await unregisterClaudeCodeMcp(workspaceDir, "ghost");- expect(await readMcpJson()).toEqual({ mcpServers: {} });- });-});diff --git a/notfair/src/server/adapters/claude-code-local/mcp.ts b/notfair/src/server/adapters/claude-code-local/mcp.tsdeleted file mode 100644index 32aa1545..00000000--- a/notfair/src/server/adapters/claude-code-local/mcp.ts+++ /dev/null@@ -1,84 +0,0 @@-import { readFile, writeFile, mkdir } from "node:fs/promises";-import { existsSync } from "node:fs";-import { join } from "node:path";-import type { McpRegistrationSpec } from "../types";--/**- * Per-agent MCP wiring for Claude Code.- *- * Claude Code reads MCP server definitions from `<workspace>/.mcp.json`- * (project-scoped) and `~/.claude/mcp_servers.json` (user-scoped). We use- * the workspace-scoped file because NotFair wants tokens to be- * project-scoped — one agent's notfair-googleads connection must not bleed- * into another agent's account.- */-interface ClaudeMcpServerStdio {- type?: "stdio";- command: string;- args?: string[];- env?: Record<string, string>;-}--interface ClaudeMcpServerHttp {- type: "http" | "sse";- url: string;- headers?: Record<string, string>;-}--type ClaudeMcpServer = ClaudeMcpServerStdio | ClaudeMcpServerHttp;--interface ClaudeMcpFile {- mcpServers: Record<string, ClaudeMcpServer>;-}--function mcpFilePath(workspaceDir: string): string {- return join(workspaceDir, ".mcp.json");-}--async function readMcpFile(workspaceDir: string): Promise<ClaudeMcpFile> {- const path = mcpFilePath(workspaceDir);- if (!existsSync(path)) return { mcpServers: {} };- try {- const raw = await readFile(path, "utf8");- const parsed = JSON.parse(raw) as Partial<ClaudeMcpFile>;- return { mcpServers: parsed.mcpServers ?? {} };- } catch {- return { mcpServers: {} };- }-}--async function writeMcpFile(workspaceDir: string, file: ClaudeMcpFile): Promise<void> {- await mkdir(workspaceDir, { recursive: true });- await writeFile(mcpFilePath(workspaceDir), JSON.stringify(file, null, 2), "utf8");-}--export async function registerClaudeCodeMcp(- workspaceDir: string,- spec: McpRegistrationSpec,-): Promise<void> {- const file = await readMcpFile(workspaceDir);- if (spec.transport.type === "stdio") {- file.mcpServers[spec.serverName] = {- type: "stdio",- command: spec.transport.command,- args: spec.transport.args,- env: spec.transport.env,- };- } else {- file.mcpServers[spec.serverName] = {- type: "http",- url: spec.transport.url,- headers: spec.transport.headers,- };- }- await writeMcpFile(workspaceDir, file);-}--export async function unregisterClaudeCodeMcp(- workspaceDir: string,- serverName: string,-): Promise<void> {- const file = await readMcpFile(workspaceDir);- delete file.mcpServers[serverName];- await writeMcpFile(workspaceDir, file);-}diff --git a/notfair/src/server/adapters/claude-code-local/models.test.ts b/notfair/src/server/adapters/claude-code-local/models.test.tsdeleted file mode 100644index 1b5572bf..00000000--- a/notfair/src/server/adapters/claude-code-local/models.test.ts+++ /dev/null@@ -1,16 +0,0 @@-import { describe, expect, it } from "vitest";--import { listClaudeCodeModels } from "./models";--describe("listClaudeCodeModels", () => {- it("returns the stable CLI alias tiers with documented context windows", async () => {- const models = await listClaudeCodeModels();- expect(models.map((m) => m.value)).toEqual(["fable", "opus", "sonnet", "haiku"]);- for (const model of models) {- expect(model.label.length).toBeGreaterThan(0);- expect(model.context_window).toBe(200_000);- }- // No alias is marked default — omitting the flag is the CLI's own choice.- expect(models.some((m) => m.is_default)).toBe(false);- });-});diff --git a/notfair/src/server/adapters/claude-code-local/models.ts b/notfair/src/server/adapters/claude-code-local/models.tsdeleted file mode 100644index 4552dc69..00000000--- a/notfair/src/server/adapters/claude-code-local/models.ts+++ /dev/null@@ -1,24 +0,0 @@-import type { HarnessModelOption } from "../types";--/**- * Model listing for Claude Code.- *- * Unlike codex there is no provider-fed cache to read: the claude CLI- * exposes no "list models" command, and its account-scoped picker state- * isn't persisted anywhere stable. What IS stable is the CLI's alias- * surface — `claude --help` documents tier aliases that always resolve- * to the newest model of each tier, so this list doesn't go stale on- * point releases. Revisit if the CLI ever ships model enumeration.- */-const ALIAS_TIERS: HarnessModelOption[] = [- // context_window: documented tier windows (Anthropic docs); the CLI- // exposes no model-metadata surface to read them from.- { value: "fable", label: "Fable", context_window: 200_000 },- { value: "opus", label: "Opus", context_window: 200_000 },- { value: "sonnet", label: "Sonnet", context_window: 200_000 },- { value: "haiku", label: "Haiku", context_window: 200_000 },-];--export async function listClaudeCodeModels(): Promise<HarnessModelOption[]> {- return ALIAS_TIERS;-}diff --git a/notfair/src/server/adapters/claude-code-local/parse.test.ts b/notfair/src/server/adapters/claude-code-local/parse.test.tsdeleted file mode 100644index c2f104f5..00000000--- a/notfair/src/server/adapters/claude-code-local/parse.test.ts+++ /dev/null@@ -1,269 +0,0 @@-import { describe, expect, it } from "vitest";--import { makeClaudeStreamState, parseClaudeLine } from "./parse";--const line = (obj: unknown) => JSON.stringify(obj);--describe("parseClaudeLine — noise handling", () => {- it("ignores blank lines and invalid JSON", () => {- const state = makeClaudeStreamState();- expect(parseClaudeLine("", state)).toEqual([]);- expect(parseClaudeLine(" ", state)).toEqual([]);- expect(parseClaudeLine("not json {", state)).toEqual([]);- });-- it("ignores unknown message types", () => {- expect(- parseClaudeLine(line({ type: "mystery" }), makeClaudeStreamState()),- ).toEqual([]);- });-});--describe("parseClaudeLine — system events", () => {- it("emits lifecycle + session from the init system message", () => {- const state = makeClaudeStreamState();- const events = parseClaudeLine(- line({ type: "system", subtype: "init", session_id: "sess-1" }),- state,- );- expect(events).toEqual([- { kind: "lifecycle", phase: "init" },- { kind: "session", harnessSessionId: "sess-1" },- ]);- });-- it("emits the session event at most once per turn", () => {- const state = makeClaudeStreamState();- parseClaudeLine(line({ type: "system", subtype: "init", session_id: "sess-1" }), state);- const events = parseClaudeLine(- line({ type: "system", subtype: "other", session_id: "sess-1" }),- state,- );- expect(events).toEqual([{ kind: "lifecycle", phase: "other" }]);- });-- it("skips lifecycle when subtype is missing", () => {- const events = parseClaudeLine(- line({ type: "system", session_id: "sess-2" }),- makeClaudeStreamState(),- );- expect(events).toEqual([{ kind: "session", harnessSessionId: "sess-2" }]);- });-});--describe("parseClaudeLine — assistant text", () => {- it("forwards text blocks as deltas", () => {- const state = makeClaudeStreamState();- const events = parseClaudeLine(- line({- type: "assistant",- message: { content: [{ type: "text", text: "Hello " }, { type: "text", text: "world" }] },- }),- state,- );- expect(events).toEqual([- { kind: "delta", text: "Hello " },- { kind: "delta", text: "world" },- ]);- expect(state.assistantText).toBe("Hello world");- });-- it("keeps deltas monotonic across messages", () => {- const state = makeClaudeStreamState();- parseClaudeLine(- line({ type: "assistant", message: { content: [{ type: "text", text: "part one" }] } }),- state,- );- const events = parseClaudeLine(- line({ type: "assistant", message: { content: [{ type: "text", text: " part two" }] } }),- state,- );- expect(events).toEqual([{ kind: "delta", text: " part two" }]);- });-});--describe("parseClaudeLine — tool events", () => {- it("emits a tool start with a first-line label for Bash commands", () => {- const events = parseClaudeLine(- line({- type: "assistant",- message: {- content: [- {- type: "tool_use",- id: "tu_1",- name: "Bash",- input: { command: "ls -la\ncat foo" },- },- ],- },- }),- makeClaudeStreamState(),- );- expect(events).toEqual([- { kind: "tool", phase: "start", toolCallId: "tu_1", name: "Bash", label: "ls -la" },- ]);- });-- it("clips a very long Bash first line to 160 chars", () => {- const events = parseClaudeLine(- line({- type: "assistant",- message: {- content: [- { type: "tool_use", id: "tu_2", name: "Bash", input: { command: "x".repeat(200) } },- ],- },- }),- makeClaudeStreamState(),- );- const label = (events[0] as { label: string }).label;- expect(label).toHaveLength(160);- expect(label.endsWith("…")).toBe(true);- });-- it("shortens deep file paths to the last two segments", () => {- const events = parseClaudeLine(- line({- type: "assistant",- message: {- content: [- {- type: "tool_use",- id: "tu_3",- name: "Read",- input: { file_path: "/Users/x/proj/src/foo.ts" },- },- ],- },- }),- makeClaudeStreamState(),- );- expect(events[0]).toMatchObject({ label: "…/src/foo.ts" });- });-- it("keeps short paths whole", () => {- const events = parseClaudeLine(- line({- type: "assistant",- message: {- content: [{ type: "tool_use", id: "tu_4", name: "Read", input: { path: "foo.ts" } }],- },- }),- makeClaudeStreamState(),- );- expect(events[0]).toMatchObject({ label: "foo.ts" });- });-- it("uses the URL as the label for web tools", () => {- const events = parseClaudeLine(- line({- type: "assistant",- message: {- content: [- { type: "tool_use", id: "tu_5", name: "WebFetch", input: { url: "https://x.test/a" } },- ],- },- }),- makeClaudeStreamState(),- );- expect(events[0]).toMatchObject({ label: "https://x.test/a" });- });-- it("falls back to labelFromArgs for MCP-ish tools", () => {- const events = parseClaudeLine(- line({- type: "assistant",- message: {- content: [- {- type: "tool_use",- id: "tu_6",- name: "mcp__x__updateBudget",- input: { campaign_id: 9, amount: 5 },- },- ],- },- }),- makeClaudeStreamState(),- );- expect(events[0]).toMatchObject({ label: "campaign_id=9 amount=5" });- });-- it("defaults toolCallId and name when absent, label undefined without input", () => {- const events = parseClaudeLine(- line({ type: "assistant", message: { content: [{ type: "tool_use" }] } }),- makeClaudeStreamState(),- );- expect(events[0]).toMatchObject({ kind: "tool", toolCallId: "", name: "tool" });- expect((events[0] as { label?: string }).label).toBeUndefined();- });-- it("surfaces tool_result blocks in user messages as result events", () => {- const events = parseClaudeLine(- line({- type: "user",- message: { content: [{ type: "tool_result", tool_use_id: "tu_1" }, { type: "text" }] },- }),- makeClaudeStreamState(),- );- expect(events).toEqual([- { kind: "tool", phase: "result", toolCallId: "tu_1", name: "" },- ]);- });-});--describe("parseClaudeLine — result", () => {- it("emits final with the result text and marks the state finalized", () => {- const state = makeClaudeStreamState();- parseClaudeLine(- line({ type: "assistant", message: { content: [{ type: "text", text: "done" }] } }),- state,- );- const events = parseClaudeLine(line({ type: "result", result: "done" }), state);- expect(events).toEqual([{ kind: "final", text: "done" }]);- expect(state.finalized).toBe(true);- });-- it("emits a trailing delta when the result text extends past emitted deltas", () => {- const state = makeClaudeStreamState();- const events = parseClaudeLine(- line({ type: "result", result: "full answer" }),- state,- );- expect(events).toEqual([- { kind: "delta", text: "full answer" },- { kind: "final", text: "full answer" },- ]);- });-- it("falls back to accumulated assistant text when result is not a string", () => {- const state = makeClaudeStreamState();- parseClaudeLine(- line({ type: "assistant", message: { content: [{ type: "text", text: "acc" }] } }),- state,- );- const events = parseClaudeLine(line({ type: "result" }), state);- expect(events).toEqual([{ kind: "final", text: "acc" }]);- });-- it("maps error subtypes to error events", () => {- const state = makeClaudeStreamState();- const events = parseClaudeLine(- line({ type: "result", subtype: "error_max_turns" }),- state,- );- expect(events).toEqual([{ kind: "error", message: "error_max_turns" }]);- expect(state.finalized).toBe(true);-- const withMessage = parseClaudeLine(- line({- type: "result",- subtype: "error_during_execution",- error: { message: "boom" },- }),- makeClaudeStreamState(),- );- expect(withMessage).toEqual([{ kind: "error", message: "boom" }]);- });-});diff --git a/notfair/src/server/adapters/claude-code-local/parse.ts b/notfair/src/server/adapters/claude-code-local/parse.tsdeleted file mode 100644index e9224f53..00000000--- a/notfair/src/server/adapters/claude-code-local/parse.ts+++ /dev/null@@ -1,188 +0,0 @@-import type { HarnessEvent } from "../types";-import { labelFromArgs } from "../label-args";--/**- * Claude Code emits one JSON object per line on stdout when invoked with- * `--output-format stream-json`. The shape (per the SDK docs) is a tagged- * union: assistant messages contain `content` blocks (text or tool_use),- * `result` messages signal turn completion, and `system` messages carry- * lifecycle metadata.- *- * This parser converts each line into zero or more HarnessEvents, tracking- * the byte offset of text already emitted so deltas are monotonic even when- * Claude re-broadcasts the running buffer.- */-export interface ClaudeStreamState {- /** Last text length we forwarded as a delta — anything past this is new. */- emittedTextLen: number;- /** Concatenated assistant text seen so far this turn. */- assistantText: string;- /** Whether we've forwarded a `final` event yet. */- finalized: boolean;- /** Whether we've already emitted the `session` event this turn. */- sessionEmitted: boolean;-}--export function makeClaudeStreamState(): ClaudeStreamState {- return {- emittedTextLen: 0,- assistantText: "",- finalized: false,- sessionEmitted: false,- };-}--interface ClaudeContentBlock {- type?: string;- text?: string;- id?: string;- name?: string;- input?: Record<string, unknown>;-}--interface ClaudeStreamMessage {- type?: string;- subtype?: string;- message?: {- content?: ClaudeContentBlock[];- role?: string;- id?: string;- };- result?: string;- /** Error fields when subtype === "error". */- is_error?: boolean;- error?: { message?: string };- /** Some emitters use top-level `text` instead of nested message.content[].text. */- text?: string;- delta?: string;- /** Session id from the system event so we can correlate. */- session_id?: string;-}--/**- * Parse one Claude Code stream-json line. Returns the events that should be- * forwarded and mutates `state` to track progress.- */-export function parseClaudeLine(- line: string,- state: ClaudeStreamState,-): HarnessEvent[] {- const trimmed = line.trim();- if (!trimmed) return [];- let msg: ClaudeStreamMessage;- try {- msg = JSON.parse(trimmed) as ClaudeStreamMessage;- } catch {- return [];- }-- const events: HarnessEvent[] = [];-- if (msg.type === "system") {- if (typeof msg.subtype === "string") {- events.push({ kind: "lifecycle", phase: msg.subtype });- }- if (!state.sessionEmitted && typeof msg.session_id === "string") {- state.sessionEmitted = true;- events.push({ kind: "session", harnessSessionId: msg.session_id });- }- return events;- }-- if (msg.type === "assistant" && msg.message?.content) {- for (const block of msg.message.content) {- if (block.type === "text" && typeof block.text === "string") {- state.assistantText += block.text;- if (state.assistantText.length > state.emittedTextLen) {- const delta = state.assistantText.slice(state.emittedTextLen);- state.emittedTextLen = state.assistantText.length;- events.push({ kind: "delta", text: delta });- }- } else if (block.type === "tool_use") {- const toolCallId = block.id ?? "";- const name = block.name ?? "tool";- events.push({- kind: "tool",- phase: "start",- toolCallId,- name,- label: labelForToolInput(name, block.input),- });- }- }- return events;- }-- if (msg.type === "user" && msg.message?.content) {- // tool_result blocks come back as user messages; we surface them as `tool`- // result events so the UI can mark the in-progress step as done.- for (const block of msg.message.content) {- if (block.type === "tool_result") {- const toolCallId = (block as ClaudeContentBlock & { tool_use_id?: string }).tool_use_id ?? "";- events.push({- kind: "tool",- phase: "result",- toolCallId,- name: "",- });- }- }- return events;- }-- if (msg.type === "result") {- state.finalized = true;- if (msg.subtype === "error_max_turns" || msg.subtype === "error_during_execution") {- events.push({- kind: "error",- message: msg.error?.message ?? msg.subtype,- });- return events;- }- const finalText = typeof msg.result === "string" ? msg.result : state.assistantText;- // Emit any trailing delta we missed (defensive — should be empty).- if (finalText.length > state.emittedTextLen) {- const delta = finalText.slice(state.emittedTextLen);- state.emittedTextLen = finalText.length;- events.push({ kind: "delta", text: delta });- }- events.push({ kind: "final", text: finalText });- return events;- }-- return events;-}--function labelForToolInput(name: string, input: unknown): string | undefined {- if (!input || typeof input !== "object") return undefined;- const obj = input as Record<string, unknown>;- const tryKey = (k: string): string | null => {- const v = obj[k];- return typeof v === "string" && v.trim().length > 0 ? v.trim() : null;- };- // Bash command first line- if (name === "Bash" || name === "bash" || name === "exec") {- const cmd = tryKey("command") ?? tryKey("cmd") ?? tryKey("script");- if (cmd) {- const nl = cmd.indexOf("\n");- const line = nl >= 0 ? cmd.slice(0, nl) : cmd;- return line.length > 160 ? `${line.slice(0, 159)}…` : line;- }- }- // File paths- const path = tryKey("file_path") ?? tryKey("path") ?? tryKey("filename");- if (path) return shortenPath(path);- // URLs- const url = tryKey("url") ?? tryKey("uri");- if (url) return url;- // Everything else (MCP calls especially): broad string-key extraction- // plus a compact k=v digest, so no call lands label-less while its- // arguments held something scannable.- return labelFromArgs(obj);-}--function shortenPath(p: string): string {- const segs = p.split("/");- if (segs.length <= 2) return p;- return `…/${segs[segs.length - 2]}/${segs[segs.length - 1]}`;-}diff --git a/notfair/src/server/adapters/claude-code-local/provision.test.ts b/notfair/src/server/adapters/claude-code-local/provision.test.tsdeleted file mode 100644index b380f12d..00000000--- a/notfair/src/server/adapters/claude-code-local/provision.test.ts+++ /dev/null@@ -1,55 +0,0 @@-import { existsSync } from "node:fs";-import { mkdtemp, readFile, writeFile } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { beforeEach, describe, expect, it } from "vitest";--import type { AgentProvisionSpec } from "../types";-import { provisionClaudeCodeAgent } from "./provision";--let workspaceDir: string;--beforeEach(async () => {- workspaceDir = await mkdtemp(join(tmpdir(), "notfair-claude-prov-"));-});--function spec(overrides: Partial<AgentProvisionSpec> = {}): AgentProvisionSpec {- return {- projectSlug: "proj",- agentId: "proj-goal-1",- displayName: "Greg",- templateKey: "goal",- workspaceDir,- identityMd: "# Greg identity\n",- ...overrides,- };-}--describe("provisionClaudeCodeAgent", () => {- it("writes IDENTITY.md and a pointer CLAUDE.md (not a mirror)", async () => {- await provisionClaudeCodeAgent(spec());- expect(await readFile(join(workspaceDir, "IDENTITY.md"), "utf8")).toBe(- "# Greg identity\n",- );- const claudeMd = await readFile(join(workspaceDir, "CLAUDE.md"), "utf8");- expect(claudeMd).toContain("IDENTITY.md");- expect(claudeMd).not.toContain("# Greg identity");- });-- it("writes PROJECT.md only when a project brief exists", async () => {- await provisionClaudeCodeAgent(spec());- expect(existsSync(join(workspaceDir, "PROJECT.md"))).toBe(false);-- await provisionClaudeCodeAgent(spec({ projectMd: "# Brief\n" }));- expect(await readFile(join(workspaceDir, "PROJECT.md"), "utf8")).toBe("# Brief\n");- });-- it("creates the workspace dir and removes a stale SKILL.md sidecar", async () => {- await writeFile(join(workspaceDir, "SKILL.md"), "old skill", "utf8");- const nested = join(workspaceDir, "sub", "agent");- await provisionClaudeCodeAgent(spec());- await provisionClaudeCodeAgent(spec({ workspaceDir: nested }));- expect(existsSync(join(workspaceDir, "SKILL.md"))).toBe(false);- expect(existsSync(join(nested, "IDENTITY.md"))).toBe(true);- });-});diff --git a/notfair/src/server/adapters/claude-code-local/provision.ts b/notfair/src/server/adapters/claude-code-local/provision.tsdeleted file mode 100644index 3b1a6d3a..00000000--- a/notfair/src/server/adapters/claude-code-local/provision.ts+++ /dev/null@@ -1,39 +0,0 @@-import { mkdir, rm, writeFile } from "node:fs/promises";-import { join } from "node:path";-import type { AgentProvisionSpec } from "../types";--/**- * Provision a workspace for Claude Code.- *- * Layout under `<workspaceDir>/`:- * IDENTITY.md — system prompt (NotFair's source of truth)- * CLAUDE.md — a one-paragraph pointer, NOT a mirror. NotFair passes- * IDENTITY.md via --append-system-prompt on every turn;- * mirroring the full identity here would load the same- * ~18KB into context TWICE (system prompt + auto-load).- * PROJECT.md — project brief if available (sidecar for humans)- *- * The skill text lives INSIDE the identity — never as a SKILL.md sidecar.- * No subprocess calls. Claude Code discovers the workspace lazily on first- * invocation; there's no "register agent" step.- */-const CLAUDE_MD_POINTER = `# NotFair agent workspace--This agent's full instructions live in IDENTITY.md — NotFair injects them-as the system prompt on every turn, so they are not mirrored here. If you-are a human (or a manually launched session) exploring this workspace,-read IDENTITY.md.-`;--export async function provisionClaudeCodeAgent(spec: AgentProvisionSpec): Promise<void> {- await mkdir(spec.workspaceDir, { recursive: true });- await Promise.all([- writeFile(join(spec.workspaceDir, "IDENTITY.md"), spec.identityMd, "utf8"),- writeFile(join(spec.workspaceDir, "CLAUDE.md"), CLAUDE_MD_POINTER, "utf8"),- spec.projectMd- ? writeFile(join(spec.workspaceDir, "PROJECT.md"), spec.projectMd, "utf8")- : Promise.resolve(),- // Remove the sidecar older provisions wrote.- rm(join(spec.workspaceDir, "SKILL.md"), { force: true }),- ]);-}diff --git a/notfair/src/server/adapters/claude-code-local/test.test.ts b/notfair/src/server/adapters/claude-code-local/test.test.tsdeleted file mode 100644index ccecb232..00000000--- a/notfair/src/server/adapters/claude-code-local/test.test.ts+++ /dev/null@@ -1,83 +0,0 @@-import { EventEmitter } from "node:events";-import { PassThrough } from "node:stream";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({ spawn: vi.fn() }));-vi.mock("node:child_process", () => ({ spawn: mocks.spawn }));--import { testClaudeCodeLocalEnvironment } from "./test";--class FakeChild extends EventEmitter {- stdout = new PassThrough();- stderr = new PassThrough();- kill = vi.fn();-}--function scriptVersionCmd(script: {- stdout?: string;- exitCode?: number;- spawnError?: boolean;- hang?: boolean;-}): FakeChild {- const child = new FakeChild();- mocks.spawn.mockImplementationOnce(() => {- if (!script.hang) {- setImmediate(() => {- if (script.spawnError) {- child.emit("error", new Error("ENOENT"));- return;- }- if (script.stdout) child.stdout.emit("data", Buffer.from(script.stdout));- child.emit("close", script.exitCode ?? 0);- });- }- return child;- });- return child;-}--beforeEach(() => mocks.spawn.mockReset());-afterEach(() => vi.useRealTimers());--describe("testClaudeCodeLocalEnvironment", () => {- it("reports ok with a parsed version label when the CLI responds", async () => {- scriptVersionCmd({ stdout: "1.0.42 (Claude Code)\n" });- const health = await testClaudeCodeLocalEnvironment();- expect(health).toEqual({- ok: true,- auth: "unknown",- versionLabel: "Claude Code 1.0.42",- });- expect(mocks.spawn).toHaveBeenCalledWith("claude", ["--version"], expect.anything());- });-- it("falls back to a bare label when the version string is unparsable", async () => {- scriptVersionCmd({ stdout: "dev build\n" });- const health = await testClaudeCodeLocalEnvironment();- expect(health.versionLabel).toBe("Claude Code");- });-- it("reports not-ok with an install hint when the binary is missing", async () => {- scriptVersionCmd({ spawnError: true });- const health = await testClaudeCodeLocalEnvironment();- expect(health.ok).toBe(false);- expect(health.auth).toBe("unknown");- expect(health.message).toContain("`claude` not found on PATH");- });-- it("reports not-ok on a non-zero exit code", async () => {- scriptVersionCmd({ exitCode: 3 });- const health = await testClaudeCodeLocalEnvironment();- expect(health.ok).toBe(false);- });-- it("times out a hung probe instead of waiting forever", async () => {- vi.useFakeTimers();- const child = scriptVersionCmd({ hang: true });- const pending = testClaudeCodeLocalEnvironment();- await vi.advanceTimersByTimeAsync(5_001);- const health = await pending;- expect(health.ok).toBe(false);- expect(child.kill).toHaveBeenCalledWith("SIGTERM");- });-});diff --git a/notfair/src/server/adapters/claude-code-local/test.ts b/notfair/src/server/adapters/claude-code-local/test.tsdeleted file mode 100644index b1633e6d..00000000--- a/notfair/src/server/adapters/claude-code-local/test.ts+++ /dev/null@@ -1,79 +0,0 @@-import { spawn } from "node:child_process";-import type { HarnessEnvironmentHealth } from "../types";--const CLAUDE_BIN = process.env.NOTFAIR_CLAUDE_BIN?.trim() || "claude";--/**- * Probe whether the local Claude Code CLI is installed and authed.- *- * `claude --version` exits 0 with a version string when the binary is on- * PATH. Auth state is best-inferred from `claude config get` returning- * a non-empty user section; we deliberately don't run a real prompt because- * doctor checks should be cheap and non-billable.- */-export async function testClaudeCodeLocalEnvironment(): Promise<HarnessEnvironmentHealth> {- const versionResult = await runCmd(CLAUDE_BIN, ["--version"]);- if (versionResult.code !== 0) {- return {- ok: false,- auth: "unknown",- message: `\`${CLAUDE_BIN}\` not found on PATH. Install: https://docs.claude.com/en/docs/agents-and-tools/claude-code/overview`,- };- }- const versionLabel = parseVersion(versionResult.stdout);-- // Best-effort auth probe. `claude --print --output-format json --max-turns 0`- // is the cheapest path to detect an auth state without invoking the model,- // but it's not stable across versions, so we soft-fail to "unknown" if it- // doesn't behave as expected. Treat ok=true even with auth="unknown" — the- // user will see the real auth error on their first chat turn.- return {- ok: true,- auth: "unknown",- versionLabel,- };-}--interface CmdResult {- code: number;- stdout: string;- stderr: string;-}--function runCmd(cmd: string, args: string[], timeoutMs = 5_000): Promise<CmdResult> {- return new Promise((resolve) => {- let stdout = "";- let stderr = "";- let settled = false;- const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });- const timer = setTimeout(() => {- if (settled) return;- settled = true;- try {- child.kill("SIGTERM");- } catch {- // ignore- }- resolve({ code: 124, stdout, stderr: stderr || "timeout" });- }, timeoutMs);- child.stdout.on("data", (c: Buffer) => (stdout += c.toString("utf8")));- child.stderr.on("data", (c: Buffer) => (stderr += c.toString("utf8")));- child.on("error", () => {- if (settled) return;- settled = true;- clearTimeout(timer);- resolve({ code: 127, stdout, stderr });- });- child.on("close", (code) => {- if (settled) return;- settled = true;- clearTimeout(timer);- resolve({ code: code ?? 0, stdout, stderr });- });- });-}--function parseVersion(stdout: string): string {- const m = stdout.match(/(\d+\.\d+\.\d+[\w.\-+]*)/);- return m ? `Claude Code ${m[1]}` : "Claude Code";-}diff --git a/notfair/src/server/adapters/codex-local/binary.test.ts b/notfair/src/server/adapters/codex-local/binary.test.tsdeleted file mode 100644index cb02b724..00000000--- a/notfair/src/server/adapters/codex-local/binary.test.ts+++ /dev/null@@ -1,68 +0,0 @@-import { describe, expect, it, vi } from "vitest";-import { resolveCodexBinary } from "./binary";--describe("resolveCodexBinary", () => {- it("honors an explicit executable override", () => {- const isExecutable = vi.fn();-- expect(- resolveCodexBinary({- env: {- NOTFAIR_CODEX_BIN: " /custom/codex-nightly ",- PATH: "/bin",- },- isExecutable,- }),- ).toBe("/custom/codex-nightly");- expect(isExecutable).not.toHaveBeenCalled();- });-- it("prefers an executable already present on PATH", () => {- expect(- resolveCodexBinary({- env: { PATH: "/managed/bin:/usr/bin" },- homeDir: "/Users/tester",- platform: "darwin",- isExecutable: (candidate) => candidate === "/managed/bin/codex",- }),- ).toBe("/managed/bin/codex");- });-- it("finds the Codex executable bundled with ChatGPT on macOS", () => {- expect(- resolveCodexBinary({- env: { PATH: "/usr/bin:/bin" },- homeDir: "/Users/tester",- platform: "darwin",- isExecutable: (candidate) =>- candidate === "/Applications/ChatGPT.app/Contents/Resources/codex",- }),- ).toBe("/Applications/ChatGPT.app/Contents/Resources/codex");- });-- it("checks a user-local ChatGPT installation", () => {- expect(- resolveCodexBinary({- env: { PATH: "/usr/bin:/bin" },- homeDir: "/Users/tester",- platform: "darwin",- isExecutable: (candidate) =>- candidate ===- "/Users/tester/Applications/ChatGPT.app/Contents/Resources/codex",- }),- ).toBe(- "/Users/tester/Applications/ChatGPT.app/Contents/Resources/codex",- );- });-- it("falls back to the command name so spawn can report the final error", () => {- expect(- resolveCodexBinary({- env: { PATH: "/usr/bin:/bin" },- homeDir: "/home/tester",- platform: "linux",- isExecutable: () => false,- }),- ).toBe("codex");- });-});diff --git a/notfair/src/server/adapters/codex-local/binary.ts b/notfair/src/server/adapters/codex-local/binary.tsdeleted file mode 100644index a09ab89e..00000000--- a/notfair/src/server/adapters/codex-local/binary.ts+++ /dev/null@@ -1,64 +0,0 @@-import { accessSync, constants } from "node:fs";-import { homedir } from "node:os";-import { join } from "node:path";--type ResolveCodexBinaryOptions = {- env?: {- PATH?: string;- NOTFAIR_CODEX_BIN?: string;- };- homeDir?: string;- platform?: NodeJS.Platform;- isExecutable?: (candidate: string) => boolean;-};--function canExecute(candidate: string): boolean {- try {- accessSync(candidate, constants.X_OK);- return true;- } catch {- return false;- }-}--/**- * Resolve Codex without assuming the server inherited an interactive shell's- * PATH. macOS background services commonly miss app-bundled executables even- * though Codex is available through the ChatGPT desktop app.- */-export function resolveCodexBinary(- options: ResolveCodexBinaryOptions = {},-): string {- const env = options.env ?? process.env;- const explicit = env.NOTFAIR_CODEX_BIN?.trim();- if (explicit) return explicit;-- const platform = options.platform ?? process.platform;- const homeDir = options.homeDir ?? homedir();- const executableName = platform === "win32" ? "codex.exe" : "codex";- const pathSeparator = platform === "win32" ? ";" : ":";- const candidates = (env.PATH ?? "")- .split(pathSeparator)- .filter(Boolean)- .map((directory) => join(directory, executableName));-- if (platform === "darwin") {- candidates.push(- "/Applications/ChatGPT.app/Contents/Resources/codex",- join(homeDir, "Applications/ChatGPT.app/Contents/Resources/codex"),- "/Applications/Codex.app/Contents/Resources/codex",- join(homeDir, "Applications/Codex.app/Contents/Resources/codex"),- );- }-- if (platform !== "win32") {- candidates.push(- join(homeDir, ".local/bin/codex"),- "/opt/homebrew/bin/codex",- "/usr/local/bin/codex",- );- }-- const isExecutable = options.isExecutable ?? canExecute;- return [...new Set(candidates)].find(isExecutable) ?? "codex";-}diff --git a/notfair/src/server/adapters/codex-local/execute.test.ts b/notfair/src/server/adapters/codex-local/execute.test.tsdeleted file mode 100644index 5287a458..00000000--- a/notfair/src/server/adapters/codex-local/execute.test.ts+++ /dev/null@@ -1,213 +0,0 @@-import { EventEmitter } from "node:events";-import { mkdtemp } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { PassThrough } from "node:stream";-import { beforeEach, describe, expect, it, vi } from "vitest";--import type { HarnessEvent, HarnessExecuteContext } from "../types";--const mocks = vi.hoisted(() => ({- spawn: vi.fn(),- resolveCodexBinary: vi.fn(() => "codex"),- getOrCreateMcpServerSecret: vi.fn(() => "machine-secret"),- listProjectMcpTokens: vi.fn(() => [] as { server_name: string; access_token_enc: string }[]),-}));--vi.mock("node:child_process", () => ({ spawn: mocks.spawn }));-vi.mock("./binary", () => ({- resolveCodexBinary: mocks.resolveCodexBinary,-}));-vi.mock("@/server/mcp-server/secret", () => ({- getOrCreateMcpServerSecret: mocks.getOrCreateMcpServerSecret,-}));-vi.mock("@/server/mcp/tokens", () => ({- listProjectMcpTokens: mocks.listProjectMcpTokens,-}));--import { executeCodexLocal } from "./execute";--class FakeChild extends EventEmitter {- stdin = { write: vi.fn(), end: vi.fn() };- stdout = new PassThrough();- stderr = new PassThrough();- kill = vi.fn();-}--interface Script {- stdout?: string;- stderr?: string;- exitCode?: number;- spawnError?: Error;-}--function scriptSpawn(script: Script): FakeChild {- const child = new FakeChild();- mocks.spawn.mockImplementationOnce(() => {- setImmediate(async () => {- if (script.spawnError) {- child.emit("error", script.spawnError);- return;- }- if (script.stdout) child.stdout.write(script.stdout);- if (script.stderr) child.stderr.write(script.stderr);- await new Promise((r) => setTimeout(r, 15));- child.emit("close", script.exitCode ?? 0);- });- return child;- });- return child;-}--async function collect(ctx: HarnessExecuteContext): Promise<HarnessEvent[]> {- const events: HarnessEvent[] = [];- for await (const evt of executeCodexLocal(ctx)) events.push(evt);- return events;-}--let workspaceDir: string;--function ctx(overrides: Partial<HarnessExecuteContext> = {}): HarnessExecuteContext {- return {- projectSlug: "proj",- agentId: "agent-1",- workspaceDir,- message: "do the thing",- threadId: "thread-1",- ...overrides,- };-}--const completedTurn =- `${JSON.stringify({ type: "item.completed", item: { type: "agent_message", text: "ok" } })}\n` +- `${JSON.stringify({ type: "turn.completed" })}\n`;--beforeEach(async () => {- mocks.spawn.mockReset();- mocks.listProjectMcpTokens.mockReturnValue([]);- workspaceDir = await mkdtemp(join(tmpdir(), "notfair-codex-exec-"));-});--describe("executeCodexLocal — argv and env wiring", () => {- it("spawns codex exec --json unsandboxed with stdin prompt", async () => {- const child = scriptSpawn({ stdout: completedTurn });- const events = await collect(ctx());-- const [bin, args, opts] = mocks.spawn.mock.calls[0]!;- expect(bin).toBe("codex");- expect(args).toEqual([- "exec",- "--json",- "--skip-git-repo-check",- "--dangerously-bypass-approvals-and-sandbox",- "-",- ]);- expect(opts).toMatchObject({ cwd: workspaceDir });- expect(child.stdin.write).toHaveBeenCalledWith("do the thing");- expect(child.stdin.end).toHaveBeenCalled();- expect(events).toEqual([- { kind: "delta", text: "ok" },- { kind: "final", text: "ok" },- ]);- });-- it("injects one bearer env var per MCP server for the project", async () => {- mocks.listProjectMcpTokens.mockReturnValue([- { server_name: "notfair-googleads", access_token_enc: "oauth-token" },- ]);- scriptSpawn({ stdout: completedTurn });- await collect(ctx());-- expect(mocks.listProjectMcpTokens).toHaveBeenCalledWith("proj");- const env = (mocks.spawn.mock.calls[0]![2] as { env: Record<string, string> }).env;- expect(env.NOTFAIR_MCP_BEARER__NOTFAIR_GOALS).toBe("machine-secret");- expect(env.NOTFAIR_MCP_BEARER__NOTFAIR_BROWSER).toBe("machine-secret");- expect(env.NOTFAIR_MCP_BEARER__NOTFAIR_GOOGLEADS).toBe("oauth-token");- expect(env.NOTFAIR_PROJECT_SLUG).toBe("proj");- expect(env.NOTFAIR_AGENT_ID).toBe("agent-1");- });-- it("passes -m for the model override and resumes real codex thread ids", async () => {- scriptSpawn({ stdout: completedTurn });- const uuid = "123e4567-e89b-42d3-a456-426614174000";- await collect(ctx({ model: "gpt-5.5", harnessSessionId: uuid }));-- const args = mocks.spawn.mock.calls[0]![1] as string[];- expect(args[args.indexOf("-m") + 1]).toBe("gpt-5.5");- expect(args.slice(-3)).toEqual(["resume", uuid, "-"]);- });-- it("passes a whitelisted reasoning effort as a Codex config override", async () => {- scriptSpawn({ stdout: completedTurn });- await collect(ctx({ reasoningEffort: "xhigh" }));-- const args = mocks.spawn.mock.calls[0]![1] as string[];- expect(args.slice(args.indexOf("-c"), args.indexOf("-c") + 2)).toEqual([- "-c",- 'model_reasoning_effort="xhigh"',- ]);- });-- it("does not resume with a non-codex session id", async () => {- scriptSpawn({ stdout: completedTurn });- await collect(ctx({ harnessSessionId: "sess-not-uuid" }));- const args = mocks.spawn.mock.calls[0]![1] as string[];- expect(args).not.toContain("resume");- expect(args.at(-1)).toBe("-");- });-});--describe("executeCodexLocal — stream handling", () => {- it("forwards session + events and flushes a tail line without a newline", async () => {- const l1 = JSON.stringify({ type: "thread.started", thread_id: "th-9" });- const l2 = JSON.stringify({- type: "item.completed",- item: { type: "agent_message", text: "hey" },- });- const l3 = JSON.stringify({ type: "turn.completed" }); // no trailing \n- scriptSpawn({ stdout: `${l1}\n${l2}\n${l3}` });-- const events = await collect(ctx());- expect(events).toEqual([- { kind: "lifecycle", phase: "start" },- { kind: "session", harnessSessionId: "th-9" },- { kind: "delta", text: "hey" },- { kind: "final", text: "hey" },- ]);- });-- it("appends the exit-code error with stderr tail even after a finalized turn", async () => {- scriptSpawn({ stdout: completedTurn, stderr: "warn\nfatal: token expired\n", exitCode: 2 });- const events = await collect(ctx());- expect(events).toEqual([- { kind: "delta", text: "ok" },- { kind: "final", text: "ok" },- { kind: "error", message: "codex exited with code 2: warn\nfatal: token expired" },- ]);- });-- it("yields a terminal error when codex fails to spawn", async () => {- scriptSpawn({ spawnError: new Error("spawn codex ENOENT") });- const events = await collect(ctx());- expect(events).toEqual([{ kind: "error", message: "spawn codex ENOENT" }]);- });-- it("kills the subprocess when the abort signal fires", async () => {- const controller = new AbortController();- const child = new FakeChild();- child.kill = vi.fn(() => {- child.emit("close", 143);- return true;- });- mocks.spawn.mockImplementationOnce(() => {- setImmediate(() => controller.abort());- return child;- });-- const events = await collect(ctx({ signal: controller.signal }));- expect(child.kill).toHaveBeenCalledWith("SIGTERM");- expect(events).toEqual([- { kind: "error", message: "codex exited with code 143" },- ]);- });-});diff --git a/notfair/src/server/adapters/codex-local/execute.ts b/notfair/src/server/adapters/codex-local/execute.tsdeleted file mode 100644index 63c86f2a..00000000--- a/notfair/src/server/adapters/codex-local/execute.ts+++ /dev/null@@ -1,198 +0,0 @@-import { spawn } from "node:child_process";-import { readFile } from "node:fs/promises";-import { join } from "node:path";-import type { HarnessEvent, HarnessExecuteContext } from "../types";-import { makeCodexStreamState, parseCodexLine } from "./parse";-import { bearerEnvVarForServer } from "./mcp";-import { resolveCodexBinary } from "./binary";-import { getOrCreateMcpServerSecret } from "@/server/mcp-server/secret";-import { listProjectMcpTokens } from "@/server/mcp/tokens";--/**- * Stream one chat turn through the Codex CLI.- *- * Wire shape:- * - We spawn `codex exec --json --skip-git-repo-check -` and pipe the user- * message into stdin (the trailing `-` tells codex to read prompt from- * stdin).- * - Codex does not support a `--system-prompt` flag; instead it auto-loads- * AGENTS.md (and friends) from cwd. We write IDENTITY.md to the workspace- * AGENTS.md so codex picks it up.- * - For thread resumption, codex uses `codex exec resume <thread-id> -`.- * - Each stdout line is a JSON event; we forward as HarnessEvents.- */-export async function* executeCodexLocal(- ctx: HarnessExecuteContext,-): AsyncGenerator<HarnessEvent, void, void> {- // --dangerously-bypass-approvals-and-sandbox is what makes NotFair- // agents useful through Codex. Without it, codex auto-cancels every- // MCP tool call (so set_shared_context / log_goal_action etc. fail)- // and sandboxes loopback connections to our local MCP servers.- // NotFair's trust model: the user installed this app, picked- // these agents, connected real ad accounts. The product-level- // Approvals flow gates spend / publish / channel changes; the- // OS-level sandbox would also gate things we want the agent to do- // (read its workspace, call our local MCP), so we run unsandboxed.- const args: string[] = [- "exec",- "--json",- "--skip-git-repo-check",- "--dangerously-bypass-approvals-and-sandbox",- ];- // Composer model override — whitelisted by the chat route.- if (ctx.model) {- args.push("-m", ctx.model);- }- if (ctx.reasoningEffort) {- args.push(- "-c",- `model_reasoning_effort=${JSON.stringify(ctx.reasoningEffort)}`,- );- }-- // Resume only when we have a real codex thread id from a prior turn.- // NotFair's session UUID is not a codex thread id — passing it would- // fail with "thread not found".- if (ctx.harnessSessionId && isUuid(ctx.harnessSessionId)) {- args.push("resume", ctx.harnessSessionId, "-");- } else {- args.push("-");- }-- // Codex resolves streamable-http MCP bearers via env var. We inject one- // env var per MCP server the project has registered so each server gets- // its OWN bearer:- // - notfair-goals: shared per-machine secret- // - notfair-browser: same shared per-machine secret (both are- // internal NotFair servers on loopback)- // - notfair-googleads, gsc, etc.: per-project OAuth token from- // `mcp_tokens`- // Without per-server env vars every MCP would auth with the same- // (wrong) bearer and codex would either surface it as Auth Unsupported- // or pass the wrong token to the wrong server.- const mcpSecret = getOrCreateMcpServerSecret();- const mcpEnv: Record<string, string> = {- [bearerEnvVarForServer("notfair-goals")]: mcpSecret,- [bearerEnvVarForServer("notfair-browser")]: mcpSecret,- };- for (const token of listProjectMcpTokens(ctx.projectSlug)) {- mcpEnv[bearerEnvVarForServer(token.server_name)] = token.access_token_enc;- }- const child = spawn(resolveCodexBinary(), args, {- cwd: ctx.workspaceDir,- env: {- ...process.env,- NOTFAIR_PROJECT_SLUG: ctx.projectSlug,- NOTFAIR_AGENT_ID: ctx.agentId,- ...mcpEnv,- },- stdio: ["pipe", "pipe", "pipe"],- });-- const abortHandler = () => {- try {- child.kill("SIGTERM");- } catch {- // already dead- }- };- ctx.signal?.addEventListener("abort", abortHandler, { once: true });-- child.stdin.write(ctx.message);- child.stdin.end();-- const state = makeCodexStreamState();- let stdoutBuf = "";- const events: HarnessEvent[] = [];- let exited = false;- let exitErr: string | null = null;- let resolveWait: (() => void) | null = null;- const wake = () => {- const r = resolveWait;- resolveWait = null;- if (r) r();- };-- child.stdout.setEncoding("utf8");- child.stdout.on("data", (chunk: string) => {- stdoutBuf += chunk;- let idx: number;- while ((idx = stdoutBuf.indexOf("\n")) >= 0) {- const line = stdoutBuf.slice(0, idx);- stdoutBuf = stdoutBuf.slice(idx + 1);- const out = parseCodexLine(line, state);- for (const evt of out) events.push(evt);- if (out.length > 0) wake();- }- });-- let stderrBuf = "";- child.stderr.setEncoding("utf8");- child.stderr.on("data", (chunk: string) => {- stderrBuf += chunk;- });-- child.on("error", (err) => {- exited = true;- exitErr = err instanceof Error ? err.message : String(err);- wake();- });- child.on("close", (code) => {- if (stdoutBuf.trim().length > 0) {- const out = parseCodexLine(stdoutBuf, state);- for (const evt of out) events.push(evt);- stdoutBuf = "";- }- if (code !== 0) {- // Always push the exit-code+stderr-tail error on non-zero exit,- // even when state.finalized is set. `turn.failed` events from- // Codex's MCP reconnect loop are tagged transient by parse.ts and- // intentionally do NOT finalize the turn so we still get this- // richer post-exit message — but on a legitimately-finalized turn- // (turn.completed followed by a non-zero exit) the exit info is- // still the most actionable signal, so capture it unconditionally.- const tail = stderrBuf.trim().split("\n").slice(-5).join("\n");- events.push({- kind: "error",- message: `codex exited with code ${code}${tail ? `: ${tail}` : ""}`,- });- }- exited = true;- wake();- });-- try {- while (!exited || events.length > 0) {- while (events.length > 0) {- const evt = events.shift()!;- yield evt;- }- if (exited) break;- await new Promise<void>((resolve) => {- resolveWait = resolve;- setTimeout(() => {- if (resolveWait === resolve) {- resolveWait = null;- resolve();- }- }, 300_000);- });- }- if (exitErr) {- yield { kind: "error", message: exitErr };- }- } finally {- ctx.signal?.removeEventListener("abort", abortHandler);- if (!exited) {- try {- child.kill("SIGTERM");- } catch {- // ignore- }- }- }-}--function isUuid(s: string): boolean {- return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s);-}diff --git a/notfair/src/server/adapters/codex-local/index.test.ts b/notfair/src/server/adapters/codex-local/index.test.tsdeleted file mode 100644index 24c05754..00000000--- a/notfair/src/server/adapters/codex-local/index.test.ts+++ /dev/null@@ -1,57 +0,0 @@-import { describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- executeCodexLocal: vi.fn(),- listCodexModels: vi.fn(async () => []),- provisionCodexAgent: vi.fn(async () => {}),- testCodexLocalEnvironment: vi.fn(async () => ({ ok: true })),- registerCodexMcp: vi.fn(async () => {}),- unregisterCodexMcp: vi.fn(async () => {}),-}));--vi.mock("./execute", () => ({ executeCodexLocal: mocks.executeCodexLocal }));-vi.mock("./models", () => ({ listCodexModels: mocks.listCodexModels }));-vi.mock("./provision", () => ({ provisionCodexAgent: mocks.provisionCodexAgent }));-vi.mock("./test", () => ({ testCodexLocalEnvironment: mocks.testCodexLocalEnvironment }));-vi.mock("./mcp", () => ({- registerCodexMcp: mocks.registerCodexMcp,- unregisterCodexMcp: mocks.unregisterCodexMcp,-}));--import { codexLocalAdapter } from "./index";--describe("codexLocalAdapter", () => {- it("exposes the codex-local id and delegates to the submodules", async () => {- expect(codexLocalAdapter.id).toBe("codex-local");- expect(codexLocalAdapter.testEnvironment).toBe(mocks.testCodexLocalEnvironment);- expect(codexLocalAdapter.listModels).toBe(mocks.listCodexModels);-- const ctx = { agentId: "a" } as never;- const gen = (async function* () {})();- mocks.executeCodexLocal.mockReturnValueOnce(gen);- expect(codexLocalAdapter.execute(ctx)).toBe(gen);- expect(mocks.executeCodexLocal).toHaveBeenCalledWith(ctx);-- const provisionSpec = { agentId: "a" } as never;- await codexLocalAdapter.provisionAgent(provisionSpec);- expect(mocks.provisionCodexAgent).toHaveBeenCalledWith(provisionSpec);- });-- it("passes the full spec to registerMcp and (serverName, projectSlug) to unregisterMcp", async () => {- const spec = {- serverName: "notfair-goals",- agentId: "agent-9",- projectSlug: "proj",- transport: { type: "http" as const, url: "http://x" },- };- await codexLocalAdapter.registerMcp(spec);- expect(mocks.registerCodexMcp).toHaveBeenCalledWith(spec);-- await codexLocalAdapter.unregisterMcp({- serverName: "notfair-goals",- projectSlug: "proj",- agentId: "agent-9",- });- expect(mocks.unregisterCodexMcp).toHaveBeenCalledWith("notfair-goals", "proj");- });-});diff --git a/notfair/src/server/adapters/codex-local/index.ts b/notfair/src/server/adapters/codex-local/index.tsdeleted file mode 100644index 2ab67dc1..00000000--- a/notfair/src/server/adapters/codex-local/index.ts+++ /dev/null@@ -1,31 +0,0 @@-import type {- HarnessAdapter,- HarnessExecuteContext,- HarnessEvent,- AgentProvisionSpec,- McpRegistrationSpec,- McpUnregistrationSpec,-} from "../types";-import { executeCodexLocal } from "./execute";-import { listCodexModels } from "./models";-import { provisionCodexAgent } from "./provision";-import { testCodexLocalEnvironment } from "./test";-import { registerCodexMcp, unregisterCodexMcp } from "./mcp";--export const codexLocalAdapter: HarnessAdapter = {- id: "codex-local",- testEnvironment: testCodexLocalEnvironment,- listModels: listCodexModels,- execute(ctx: HarnessExecuteContext): AsyncGenerator<HarnessEvent, void, void> {- return executeCodexLocal(ctx);- },- async provisionAgent(spec: AgentProvisionSpec): Promise<void> {- await provisionCodexAgent(spec);- },- async registerMcp(spec: McpRegistrationSpec): Promise<void> {- await registerCodexMcp(spec);- },- async unregisterMcp(spec: McpUnregistrationSpec): Promise<void> {- await unregisterCodexMcp(spec.serverName, spec.projectSlug);- },-};diff --git a/notfair/src/server/adapters/codex-local/mcp.test.ts b/notfair/src/server/adapters/codex-local/mcp.test.tsdeleted file mode 100644index 086ad4db..00000000--- a/notfair/src/server/adapters/codex-local/mcp.test.ts+++ /dev/null@@ -1,160 +0,0 @@-import { existsSync } from "node:fs";-import { mkdtemp, readFile, writeFile } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { afterAll, beforeEach, describe, expect, it } from "vitest";--import type { McpRegistrationSpec } from "../types";-import {- bearerEnvVarForServer,- codexConfigDir,- registerCodexMcp,- unregisterCodexMcp,-} from "./mcp";--const originalCodexHome = process.env.CODEX_HOME;-let codexHome: string;--beforeEach(async () => {- codexHome = await mkdtemp(join(tmpdir(), "notfair-codex-home-"));- process.env.CODEX_HOME = codexHome;-});--afterAll(() => {- if (originalCodexHome === undefined) delete process.env.CODEX_HOME;- else process.env.CODEX_HOME = originalCodexHome;-});--function spec(overrides: Partial<McpRegistrationSpec> = {}): McpRegistrationSpec {- return {- serverName: "notfair-goals",- agentId: "agent-1",- projectSlug: "my-proj",- transport: {- type: "http",- url: "http://127.0.0.1:3326/api/mcp/goals",- headers: { Authorization: "Bearer s3cret" },- },- ...overrides,- };-}--async function readToml(): Promise<string> {- return readFile(join(codexHome, "config.toml"), "utf8");-}--describe("codexConfigDir", () => {- it("honors CODEX_HOME", () => {- expect(codexConfigDir()).toBe(codexHome);- });-});--describe("bearerEnvVarForServer", () => {- it("uppercases and sanitizes the server name", () => {- expect(bearerEnvVarForServer("notfair-goals")).toBe(- "NOTFAIR_MCP_BEARER__NOTFAIR_GOALS",- );- expect(bearerEnvVarForServer("gsc.v2")).toBe("NOTFAIR_MCP_BEARER__GSC_V2");- });-});--describe("registerCodexMcp", () => {- it("writes a project-namespaced http section with bearer_token_env_var, never a raw Authorization header", async () => {- await registerCodexMcp(spec());- const toml = await readToml();- expect(toml).toContain("[mcp_servers.notfair_my_proj__notfair_goals]");- expect(toml).toContain('url = "http://127.0.0.1:3326/api/mcp/goals"');- expect(toml).toContain(- 'bearer_token_env_var = "NOTFAIR_MCP_BEARER__NOTFAIR_GOALS"',- );- expect(toml).not.toContain("s3cret");- expect(toml).not.toContain("Authorization");- });-- it("keeps non-auth headers as a TOML inline table", async () => {- await registerCodexMcp(- spec({- transport: {- type: "http",- url: "http://x",- headers: { authorization: "Bearer t", "X-Notfair": "yes" },- },- }),- );- const toml = await readToml();- expect(toml).toContain('headers = { X-Notfair = "yes" }');- expect(toml).toContain("bearer_token_env_var");- });-- it("omits bearer wiring when the transport has no auth header", async () => {- await registerCodexMcp(- spec({ transport: { type: "http", url: "http://x" } }),- );- expect(await readToml()).not.toContain("bearer_token_env_var");- });-- it("writes stdio sections with command, args and env", async () => {- await registerCodexMcp(- spec({- serverName: "local-tool",- transport: {- type: "stdio",- command: "node",- args: ["server.js", "--flag"],- env: { TOKEN: "t" },- },- }),- );- const toml = await readToml();- expect(toml).toContain("[mcp_servers.notfair_my_proj__local_tool]");- expect(toml).toContain('command = "node"');- expect(toml).toContain('args = ["server.js","--flag"]');- expect(toml).toContain('env = { TOKEN = "t" }');- });-- it("replaces an existing section instead of duplicating it on re-register", async () => {- await registerCodexMcp(spec());- await registerCodexMcp(- spec({ transport: { type: "http", url: "http://new-url" } }),- );- const toml = await readToml();- const headers = toml.match(/\[mcp_servers\.notfair_my_proj__notfair_goals\]/g);- expect(headers).toHaveLength(1);- expect(toml).toContain('url = "http://new-url"');- expect(toml).not.toContain("api/mcp/goals");- });-- it("preserves user-installed servers outside the notfair namespace", async () => {- await writeFile(- join(codexHome, "config.toml"),- 'model = "gpt-5.5"\n\n[mcp_servers.user_tool]\ncommand = "mine"\n',- "utf8",- );- await registerCodexMcp(spec());- const toml = await readToml();- expect(toml).toContain('model = "gpt-5.5"');- expect(toml).toContain("[mcp_servers.user_tool]");- expect(toml).toContain('command = "mine"');- expect(toml).toContain("[mcp_servers.notfair_my_proj__notfair_goals]");- });-});--describe("unregisterCodexMcp", () => {- it("removes only our namespaced section", async () => {- await writeFile(- join(codexHome, "config.toml"),- '[mcp_servers.user_tool]\ncommand = "mine"\n',- "utf8",- );- await registerCodexMcp(spec());- await unregisterCodexMcp("notfair-goals", "my-proj");- const toml = await readToml();- expect(toml).not.toContain("notfair_my_proj__notfair_goals");- expect(toml).toContain("[mcp_servers.user_tool]");- });-- it("is a no-op when there is no config file", async () => {- await unregisterCodexMcp("notfair-goals", "my-proj");- expect(existsSync(join(codexHome, "config.toml"))).toBe(false);- });-});diff --git a/notfair/src/server/adapters/codex-local/mcp.ts b/notfair/src/server/adapters/codex-local/mcp.tsdeleted file mode 100644index 76cfa068..00000000--- a/notfair/src/server/adapters/codex-local/mcp.ts+++ /dev/null@@ -1,144 +0,0 @@-import { readFile, writeFile, mkdir } from "node:fs/promises";-import { existsSync } from "node:fs";-import { homedir } from "node:os";-import { join } from "node:path";-import type { McpRegistrationSpec } from "../types";--/**- * Project-scoped MCP wiring for Codex.- *- * Codex reads MCP servers from `~/.codex/config.toml` — a single global file- * shared across every project and agent on the machine. MCP tokens in- * NotFair are project-scoped (one (project, server) pair → one bearer- * shared by every agent in the project), so we namespace by project slug:- * `notfair_<projectSlug>__<serverName>`. Every agent in the same project- * sees the same entry; sibling projects don't duplicate.- *- * Earlier versions namespaced by agent id, which produced N entries per- * project (one per agent) and let agents see each other's prefixes when- * Codex enumerated the global config. Per-project namespacing collapses- * that to one entry per project per server.- *- * Cross-project visibility in the global config is a residual: an agent in- * project A can still see `notfair_B__*` headers because Codex reads the- * whole file. Fully isolating that would require pointing CODEX_HOME at a- * per-project path, which would also break the user's `~/.codex/auth.json`- * login. Left as a future change.- *- * We rewrite the [mcp_servers.*] sections under our namespace prefix; we- * never touch user-installed servers outside our prefix.- */-export function codexConfigDir(): string {- return process.env.CODEX_HOME?.trim() || join(homedir(), ".codex");-}--function codexConfigPath(): string {- return join(codexConfigDir(), "config.toml");-}--const NOTFAIR_NS = "notfair_";--function namespaced(serverName: string, projectSlug: string): string {- return `${NOTFAIR_NS}${projectSlug.replace(/-/g, "_")}__${serverName.replace(/[^a-zA-Z0-9]/g, "_")}`;-}--async function readConfig(): Promise<string> {- const path = codexConfigPath();- if (!existsSync(path)) return "";- try {- return await readFile(path, "utf8");- } catch {- return "";- }-}--function stripSection(toml: string, sectionHeader: string): string {- // Remove a [mcp_servers."x"] block plus its key/value lines until the next- // section header or EOF. Best-effort regex — codex's TOML is well-formed- // and we only ever write what we wrote.- const re = new RegExp(- `\\n*\\[${escapeRe(sectionHeader)}\\][\\s\\S]*?(?=\\n\\[|\\n*$)`,- "g",- );- return toml.replace(re, "");-}--function escapeRe(s: string): string {- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");-}--/**- * Each codex MCP registration gets its OWN env var name carrying its- * bearer. Encodes the server name into the env so different MCPs in the- * same agent's config (goals, Google Ads, GSC, ...) can carry- * different bearers. The spawn site (execute.ts) iterates the project's- * `mcp_tokens` table + the internal-server secret and injects matching- * env vars before invoking codex.- *- * Why env vars and not literal headers: codex 0.132+ marks raw- * `headers = { Authorization = "Bearer ..." }` rows as Auth: Unsupported- * and refuses to expose those MCP tools. The `bearer_token_env_var`- * path is the documented way.- */-export function bearerEnvVarForServer(serverName: string): string {- const safe = serverName.replace(/[^a-zA-Z0-9]/g, "_").toUpperCase();- return `NOTFAIR_MCP_BEARER__${safe}`;-}--function renderServer(spec: McpRegistrationSpec): string {- const header = `[mcp_servers.${namespaced(spec.serverName, spec.projectSlug)}]`;- if (spec.transport.type === "stdio") {- const lines = [- header,- `command = ${JSON.stringify(spec.transport.command)}`,- `args = ${JSON.stringify(spec.transport.args)}`,- ];- if (spec.transport.env) {- lines.push(`env = ${tomlInlineTable(spec.transport.env)}`);- }- return lines.join("\n") + "\n";- }- const lines = [header, `url = ${JSON.stringify(spec.transport.url)}`];- const rawAuth =- spec.transport.headers?.Authorization ??- spec.transport.headers?.authorization;- if (rawAuth) {- lines.push(- `bearer_token_env_var = ${JSON.stringify(bearerEnvVarForServer(spec.serverName))}`,- );- }- const otherHeaders: Record<string, string> = {};- for (const [k, v] of Object.entries(spec.transport.headers ?? {})) {- if (k.toLowerCase() !== "authorization") otherHeaders[k] = v;- }- if (Object.keys(otherHeaders).length > 0) {- lines.push(`headers = ${tomlInlineTable(otherHeaders)}`);- }- return lines.join("\n") + "\n";-}--function tomlInlineTable(record: Record<string, string>): string {- const parts = Object.entries(record).map(- ([k, v]) => `${k} = ${JSON.stringify(v)}`,- );- return `{ ${parts.join(", ")} }`;-}--export async function registerCodexMcp(spec: McpRegistrationSpec): Promise<void> {- await mkdir(codexConfigDir(), { recursive: true });- let toml = await readConfig();- toml = stripSection(toml, `mcp_servers.${namespaced(spec.serverName, spec.projectSlug)}`);- toml = toml.trimEnd() + "\n\n" + renderServer(spec);- await writeFile(codexConfigPath(), toml.trimStart(), "utf8");-}--export async function unregisterCodexMcp(- serverName: string,- projectSlug: string,-): Promise<void> {- let toml = await readConfig();- if (!toml) return;- toml = stripSection(toml, `mcp_servers.${namespaced(serverName, projectSlug)}`);- await writeFile(codexConfigPath(), toml.trimStart(), "utf8");-}-diff --git a/notfair/src/server/adapters/codex-local/models.more.test.ts b/notfair/src/server/adapters/codex-local/models.more.test.tsdeleted file mode 100644index 21222152..00000000--- a/notfair/src/server/adapters/codex-local/models.more.test.ts+++ /dev/null@@ -1,110 +0,0 @@-import { mkdtemp, writeFile } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { describe, expect, it } from "vitest";--import { listCodexModels } from "./models";--async function tmp(): Promise<string> {- return mkdtemp(join(tmpdir(), "notfair-codex-models-more-"));-}--describe("listCodexModels — cache handling", () => {- it("falls back to the static list (first marked default) when the cache is missing", async () => {- const dir = await tmp();- const models = await listCodexModels(- join(dir, "no-cache.json"),- join(dir, "no-config.toml"),- );- expect(models).toEqual([- { value: "gpt-5.5", label: "GPT-5.5", is_default: true },- { value: "gpt-5.4", label: "GPT-5.4" },- ]);- });-- it("falls back when the cache holds an empty model list", async () => {- const dir = await tmp();- const cacheFile = join(dir, "models_cache.json");- await writeFile(cacheFile, JSON.stringify({ models: [] }), "utf8");- const models = await listCodexModels(cacheFile, join(dir, "no-config.toml"));- expect(models.map((m) => m.value)).toEqual(["gpt-5.5", "gpt-5.4"]);- });-- it("filters hidden models, sorts by priority, and carries context windows", async () => {- const dir = await tmp();- const cacheFile = join(dir, "models_cache.json");- await writeFile(- cacheFile,- JSON.stringify({- models: [- { slug: "internal", display_name: "Internal", visibility: "hide", priority: 0 },- { slug: "no-priority", display_name: "No Priority" },- { slug: "second", display_name: "Second", priority: 2, context_window: 0 },- { slug: "first", display_name: "First", priority: 1, context_window: 272_000 },- { slug: "", display_name: "Empty slug", priority: 0 },- ],- }),- "utf8",- );-- const models = await listCodexModels(cacheFile, join(dir, "no-config.toml"));- expect(models.map((m) => m.value)).toEqual(["first", "second", "no-priority"]);- expect(models[0]).toMatchObject({- label: "First",- context_window: 272_000,- is_default: true,- });- // context_window omitted when non-positive or absent.- expect(models[1]!.context_window).toBeUndefined();- });-- it("labels a model by its slug when display_name is missing", async () => {- const dir = await tmp();- const cacheFile = join(dir, "models_cache.json");- await writeFile(- cacheFile,- JSON.stringify({ models: [{ slug: "gpt-raw", priority: 1 }] }),- "utf8",- );- const models = await listCodexModels(cacheFile, join(dir, "no-config.toml"));- expect(models[0]).toMatchObject({ value: "gpt-raw", label: "gpt-raw" });- });-});--describe("listCodexModels — configured default parsing", () => {- async function withConfig(config: string) {- const dir = await tmp();- const configFile = join(dir, "config.toml");- const cacheFile = join(dir, "models_cache.json");- await Promise.all([- writeFile(configFile, config, "utf8"),- writeFile(- cacheFile,- JSON.stringify({- models: [- { slug: "gpt-5.5", display_name: "GPT-5.5", priority: 1 },- { slug: "gpt-5.4", display_name: "GPT-5.4", priority: 2 },- ],- }),- "utf8",- ),- ]);- return listCodexModels(cacheFile, configFile);- }-- it("parses a single-quoted model value", async () => {- const models = await withConfig("model = 'gpt-5.4'\n");- expect(models.find((m) => m.is_default)?.value).toBe("gpt-5.4");- });-- it("parses a bare model value with a trailing comment", async () => {- const models = await withConfig("model = gpt-5.4 # pinned\n");- expect(models.find((m) => m.is_default)?.value).toBe("gpt-5.4");- });-- it("ignores model keys nested under a profile table", async () => {- const models = await withConfig('[profiles.fast]\nmodel = "gpt-5.4"\n');- // No root-level model → first cache entry is the effective default.- expect(models.find((m) => m.is_default)?.value).toBe("gpt-5.5");- });-});diff --git a/notfair/src/server/adapters/codex-local/models.test.ts b/notfair/src/server/adapters/codex-local/models.test.tsdeleted file mode 100644index 1df93320..00000000--- a/notfair/src/server/adapters/codex-local/models.test.ts+++ /dev/null@@ -1,79 +0,0 @@-import { mkdtemp, writeFile } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { describe, expect, it } from "vitest";--import { listCodexModels } from "./models";--async function fixture(config: string, models: unknown[]) {- const dir = await mkdtemp(join(tmpdir(), "notfair-codex-models-"));- const configFile = join(dir, "config.toml");- const cacheFile = join(dir, "models_cache.json");- await Promise.all([- writeFile(configFile, config, "utf8"),- writeFile(cacheFile, JSON.stringify({ models }), "utf8"),- ]);- return { configFile, cacheFile };-}--describe("listCodexModels", () => {- it("marks the root configured model as the concrete no-override model", async () => {- const files = await fixture(- 'model = "gpt-5.6-sol"\n\n[profiles.fast]\nmodel = "gpt-5.4"\n',- [- { slug: "gpt-5.4", display_name: "GPT-5.4", priority: 1 },- { slug: "gpt-5.6-sol", display_name: "GPT-5.6-Sol", priority: 2 },- ],- );-- const models = await listCodexModels(files.cacheFile, files.configFile);-- expect(models.find((model) => model.is_default)).toMatchObject({- value: "gpt-5.6-sol",- label: "GPT-5.6-Sol",- });- });-- it("carries provider reasoning levels and marks the configured effort dynamically", async () => {- const files = await fixture(- 'model = "gpt-5.6-sol"\nmodel_reasoning_effort = "xhigh"\n',- [- {- slug: "gpt-5.6-sol",- display_name: "GPT-5.6-Sol",- priority: 1,- default_reasoning_level: "low",- supported_reasoning_levels: [- { effort: "low", description: "Faster" },- { effort: "xhigh", description: "Deeper" },- ],- },- ],- );-- const models = await listCodexModels(files.cacheFile, files.configFile);-- expect(models[0]).toMatchObject({- value: "gpt-5.6-sol",- default_reasoning_effort: "xhigh",- reasoning_efforts: [- { value: "low", label: "Low", description: "Faster" },- { value: "xhigh", label: "Extra high", description: "Deeper" },- ],- });- });-- it("keeps a configured model visible when the provider cache is stale", async () => {- const files = await fixture('model = "gpt-custom"\n', [- { slug: "gpt-5.4", display_name: "GPT-5.4", priority: 1 },- ]);-- const models = await listCodexModels(files.cacheFile, files.configFile);-- expect(models[0]).toEqual({- value: "gpt-custom",- label: "gpt-custom",- is_default: true,- });- });-});diff --git a/notfair/src/server/adapters/codex-local/models.ts b/notfair/src/server/adapters/codex-local/models.tsdeleted file mode 100644index 0c5045d8..00000000--- a/notfair/src/server/adapters/codex-local/models.ts+++ /dev/null@@ -1,182 +0,0 @@-import { readFile } from "node:fs/promises";-import { join } from "node:path";--import type { HarnessModelOption } from "../types";-import { codexConfigDir } from "./mcp";--/**- * Model discovery for Codex — read the PROVIDER's list, don't hardcode.- *- * The codex CLI has no "list models" command, but its TUI fetches the- * account-scoped model list from OpenAI and caches it at- * `~/.codex/models_cache.json` (slug, display_name, visibility,- * priority, …). We read that cache: it's the same source the user's own- * `/model` picker shows, refreshed whenever they run codex.- *- * Entries with `visibility: "hide"` are internal (e.g. codex-auto-review)- * and excluded. Sorted by the cache's own `priority` (ascending — that's- * the order the TUI shows).- *- * Fallback: when the cache is missing/unreadable (fresh install that has- * never run the TUI), return a minimal static list so the selector still- * works. Never throws.- */--type CachedModel = {- slug?: unknown;- display_name?: unknown;- visibility?: unknown;- priority?: unknown;- context_window?: unknown;- default_reasoning_level?: unknown;- supported_reasoning_levels?: unknown;-};--type CachedReasoningLevel = {- effort?: unknown;- description?: unknown;-};--function isCachedReasoningLevel(- level: unknown,-): level is CachedReasoningLevel & { effort: string } {- if (typeof level !== "object" || level === null) return false;- const effort = (level as CachedReasoningLevel).effort;- return typeof effort === "string" && effort.length > 0;-}--const FALLBACK: HarnessModelOption[] = [- { value: "gpt-5.5", label: "GPT-5.5" },- { value: "gpt-5.4", label: "GPT-5.4" },-];--async function readConfiguredDefaults(configFile: string): Promise<{- model: string | null;- reasoningEffort: string | null;-}> {- try {- const raw = await readFile(configFile, "utf8");- // NotFair invokes Codex without a profile, so only the root-level `model`- // applies. Stop at the first TOML table to avoid mistaking a nested key- // for the CLI's effective default.- let model: string | null = null;- let reasoningEffort: string | null = null;- for (const line of raw.split(/\r?\n/)) {- const trimmed = line.trim();- if (trimmed.startsWith("[")) break;- const match =- /^(model|model_reasoning_effort)\s*=\s*("(?:\\.|[^"\\])*"|'[^']*'|[^\s#]+)\s*(?:#.*)?$/.exec(- trimmed,- );- if (!match) continue;- const value = match[2];- let parsed: string;- if (value.startsWith('"')) {- try {- parsed = JSON.parse(value) as string;- } catch {- continue;- }- } else {- parsed = value.startsWith("'") ? value.slice(1, -1) : value;- }- if (match[1] === "model") model = parsed;- else reasoningEffort = parsed;- }- return { model, reasoningEffort };- } catch {- // Missing or unreadable config means Codex uses its provider default.- }- return { model: null, reasoningEffort: null };-}--function effortLabel(value: string): string {- const expanded = /^x[a-z]/.test(value) ? `extra ${value.slice(1)}` : value;- const spaced = expanded.replace(/[-_]+/g, " ");- return spaced.charAt(0).toUpperCase() + spaced.slice(1);-}--function reasoningMetadata(- model: CachedModel,- configuredEffort: string | null,-): Pick<HarnessModelOption, "reasoning_efforts" | "default_reasoning_effort"> {- if (!Array.isArray(model.supported_reasoning_levels)) return {};- const efforts = model.supported_reasoning_levels- .filter(isCachedReasoningLevel)- .map((level) => ({- value: level.effort,- label: effortLabel(level.effort),- ...(typeof level.description === "string" && level.description- ? { description: level.description }- : {}),- }));- if (efforts.length === 0) return {};- const providerDefault =- typeof model.default_reasoning_level === "string"- ? model.default_reasoning_level- : null;- const defaultEffort =- [configuredEffort, providerDefault, efforts[0]?.value].find(- (value) => value && efforts.some((effort) => effort.value === value),- ) ?? efforts[0]!.value;- return {- reasoning_efforts: efforts,- default_reasoning_effort: defaultEffort,- };-}--function markDefaultModel(- models: HarnessModelOption[],- configuredModel: string | null,-): HarnessModelOption[] {- const defaultValue = configuredModel ?? models[0]?.value;- if (!defaultValue) return models;-- let found = false;- const marked = models.map((model) => {- const isDefault = model.value === defaultValue;- if (isDefault) found = true;- return isDefault ? { ...model, is_default: true } : model;- });-- // A configured model can be absent from a stale provider cache. Keep it- // visible as the effective default rather than falling back to a wrong- // label until Codex refreshes models_cache.json.- return found- ? marked- : [{ value: defaultValue, label: defaultValue, is_default: true }, ...marked];-}--export async function listCodexModels(- cacheFile: string = join(codexConfigDir(), "models_cache.json"),- configFile: string = join(codexConfigDir(), "config.toml"),-): Promise<HarnessModelOption[]> {- const configured = await readConfiguredDefaults(configFile);- try {- const raw = await readFile(cacheFile, "utf8");- const parsed = JSON.parse(raw) as { models?: CachedModel[] };- const models = (parsed.models ?? [])- .filter(- (m): m is CachedModel & { slug: string } =>- typeof m.slug === "string" &&- m.slug.length > 0 &&- m.visibility !== "hide",- )- .sort(- (a, b) =>- (typeof a.priority === "number" ? a.priority : Number.MAX_SAFE_INTEGER) -- (typeof b.priority === "number" ? b.priority : Number.MAX_SAFE_INTEGER),- )- .map<HarnessModelOption>((m) => ({- value: m.slug,- label: typeof m.display_name === "string" && m.display_name ? m.display_name : m.slug,- ...(typeof m.context_window === "number" && m.context_window > 0- ? { context_window: m.context_window }- : {}),- ...reasoningMetadata(m, configured.reasoningEffort),- }));- return markDefaultModel(models.length > 0 ? models : FALLBACK, configured.model);- } catch {- return markDefaultModel(FALLBACK, configured.model);- }-}diff --git a/notfair/src/server/adapters/codex-local/parse.more.test.ts b/notfair/src/server/adapters/codex-local/parse.more.test.tsdeleted file mode 100644index 19dd4e89..00000000--- a/notfair/src/server/adapters/codex-local/parse.more.test.ts+++ /dev/null@@ -1,235 +0,0 @@-import { describe, expect, it } from "vitest";--import {- isAdvisoryCodexItemError,- isTransientCodexError,- makeCodexStreamState,- parseCodexLine,-} from "./parse";--const line = (obj: unknown) => JSON.stringify(obj);--describe("parseCodexLine — noise handling", () => {- it("ignores blank lines, invalid JSON and unknown types", () => {- const state = makeCodexStreamState();- expect(parseCodexLine("", state)).toEqual([]);- expect(parseCodexLine("garbage {", state)).toEqual([]);- expect(parseCodexLine(line({ type: "mystery" }), state)).toEqual([]);- });-- it("ignores item.completed for non-toolish, non-message item types", () => {- expect(- parseCodexLine(- line({ type: "item.completed", item: { type: "reasoning", text: "thinking" } }),- makeCodexStreamState(),- ),- ).toEqual([]);- });-});--describe("parseCodexLine — thread lifecycle", () => {- it("emits lifecycle + session on thread.started", () => {- const state = makeCodexStreamState();- const events = parseCodexLine(- line({ type: "thread.started", thread_id: "th-1" }),- state,- );- expect(events).toEqual([- { kind: "lifecycle", phase: "start" },- { kind: "session", harnessSessionId: "th-1" },- ]);- expect(state.threadId).toBe("th-1");- });-- it("emits only lifecycle when thread.started lacks a thread id", () => {- const events = parseCodexLine(- line({ type: "thread.started" }),- makeCodexStreamState(),- );- expect(events).toEqual([{ kind: "lifecycle", phase: "start" }]);- });-});--describe("parseCodexLine — agent messages and finals", () => {- it("forwards agent_message text whole as one delta, then final on turn.completed", () => {- const state = makeCodexStreamState();- const deltas = parseCodexLine(- line({ type: "item.completed", item: { type: "agent_message", text: "answer" } }),- state,- );- expect(deltas).toEqual([{ kind: "delta", text: "answer" }]);-- const finals = parseCodexLine(line({ type: "turn.completed", usage: {} }), state);- expect(finals).toEqual([{ kind: "final", text: "answer" }]);- expect(state.finalized).toBe(true);- });-- it("accumulates multiple agent messages into the final text", () => {- const state = makeCodexStreamState();- parseCodexLine(- line({ type: "item.completed", item: { type: "agent_message", text: "one " } }),- state,- );- parseCodexLine(- line({ type: "item.completed", item: { type: "agent_message", text: "two" } }),- state,- );- expect(parseCodexLine(line({ type: "turn.completed" }), state)).toEqual([- { kind: "final", text: "one two" },- ]);- });-});--describe("parseCodexLine — tool naming", () => {- it("names command_execution items 'shell' and keeps the command in the label", () => {- const state = makeCodexStreamState();- const started = parseCodexLine(- line({- type: "item.started",- item: { type: "command_execution", id: "c1", command: "ls -la\npwd" },- }),- state,- );- expect(started).toEqual([- { kind: "tool", phase: "start", toolCallId: "c1", name: "shell", label: "ls -la" },- ]);-- const completed = parseCodexLine(- line({- type: "item.completed",- item: { type: "command_execution", id: "c1", command: "ls -la" },- }),- state,- );- expect(completed).toEqual([- { kind: "tool", phase: "result", toolCallId: "c1", name: "shell" },- ]);- });-- it("clips a long command label to 160 chars", () => {- const events = parseCodexLine(- line({- type: "item.started",- item: { type: "command_execution", id: "c2", command: "x".repeat(200) },- }),- makeCodexStreamState(),- );- const label = (events[0] as { label: string }).label;- expect(label).toHaveLength(160);- expect(label.endsWith("…")).toBe(true);- });-- it("keeps declared names for function_call items", () => {- const events = parseCodexLine(- line({- type: "item.started",- item: { type: "function_call", id: "f1", name: "lookup_thing" },- }),- makeCodexStreamState(),- );- expect(events[0]).toMatchObject({ kind: "tool", name: "lookup_thing" });- });-- it("uses tool name without a server prefix for serverless mcp_call items", () => {- const events = parseCodexLine(- line({- type: "item.started",- item: { type: "mcp_call", id: "m1", tool_name: "getInsights" },- }),- makeCodexStreamState(),- );- expect(events[0]).toMatchObject({ name: "getInsights" });- });-- it("degrades to the 'tool' token when every naming signal is missing", () => {- const events = parseCodexLine(- line({ type: "item.started", item: { type: "tool_call", id: "t1" } }),- makeCodexStreamState(),- );- expect(events[0]).toMatchObject({ toolCallId: "t1", name: "tool" });- expect((events[0] as { label?: string }).label).toBeUndefined();- });-});--describe("parseCodexLine — errors", () => {- it("surfaces non-advisory item errors as transient errors", () => {- const events = parseCodexLine(- line({- type: "item.completed",- item: { type: "error", message: "tool exploded" },- }),- makeCodexStreamState(),- );- expect(events).toEqual([- { kind: "error", message: "tool exploded", transient: true },- ]);- });-- it("suppresses advisory item errors that codex prints on every run", () => {- const events = parseCodexLine(- line({- type: "item.completed",- item: {- type: "error",- message: "Skill descriptions were shortened to fit the 2% skills context budget.",- },- }),- makeCodexStreamState(),- );- expect(events).toEqual([]);- });-- it("marks terminal turn.failed as finalized with a non-transient error", () => {- const state = makeCodexStreamState();- const events = parseCodexLine(- line({ type: "turn.failed", error: { message: "quota exhausted" } }),- state,- );- expect(events).toEqual([- { kind: "error", message: "quota exhausted", transient: false },- ]);- expect(state.finalized).toBe(true);- });-- it("keeps the turn un-finalized on transient reconnect chatter", () => {- const state = makeCodexStreamState();- const events = parseCodexLine(- line({ type: "turn.failed", error: { message: "Reconnecting... 2/5 (mcp)" } }),- state,- );- expect(events).toEqual([- { kind: "error", message: "Reconnecting... 2/5 (mcp)", transient: true },- ]);- expect(state.finalized).toBe(false);- });-- it("falls back to a generic message when turn.failed carries none", () => {- const events = parseCodexLine(- line({ type: "turn.failed" }),- makeCodexStreamState(),- );- expect(events[0]).toMatchObject({ message: "codex turn failed" });- });-- it("forwards top-level error events with transient tagging", () => {- expect(- parseCodexLine(line({ type: "error", message: "boom" }), makeCodexStreamState()),- ).toEqual([{ kind: "error", message: "boom", transient: false }]);- expect(- parseCodexLine(line({ type: "error" }), makeCodexStreamState()),- ).toEqual([{ kind: "error", message: "codex error", transient: false }]);- });-});--describe("transient / advisory classifiers", () => {- it("classifies only the reconnect loop as transient", () => {- expect(isTransientCodexError("Reconnecting... 3/5 (network)")).toBe(true);- expect(isTransientCodexError(" Reconnecting... 1/5")).toBe(true);- expect(isTransientCodexError("connection reset")).toBe(false);- });-- it("classifies the skills-budget nudge as advisory", () => {- expect(isAdvisoryCodexItemError("Skill descriptions were shortened …")).toBe(true);- expect(isAdvisoryCodexItemError("real failure")).toBe(false);- });-});diff --git a/notfair/src/server/adapters/codex-local/parse.test.ts b/notfair/src/server/adapters/codex-local/parse.test.tsdeleted file mode 100644index 5f88a31b..00000000--- a/notfair/src/server/adapters/codex-local/parse.test.ts+++ /dev/null@@ -1,64 +0,0 @@-import { describe, expect, it } from "vitest";--import { makeCodexStreamState, parseCodexLine } from "./parse";--const line = (obj: unknown) => JSON.stringify(obj);--describe("parseCodexLine — MCP tool labels", () => {- it("carries the query argument of an mcp_tool_call into the label", () => {- const events = parseCodexLine(- line({- type: "item.started",- item: {- type: "mcp_tool_call",- id: "item_1",- server: "notfair_growth__posthog",- tool: "exec",- arguments: {- query: "SELECT count() FROM events\nWHERE timestamp >= now()",- },- },- }),- makeCodexStreamState(),- );- expect(events).toHaveLength(1);- expect(events[0]).toMatchObject({- kind: "tool",- phase: "start",- name: "notfair_growth__posthog.exec",- // First line only, so the collapsed row stays one line.- label: "SELECT count() FROM events",- });- });-- it("falls back to a compact key=value digest when no string field matches", () => {- const events = parseCodexLine(- line({- type: "item.started",- item: {- type: "mcp_tool_call",- id: "item_2",- server: "s",- tool: "updateCampaignBudget",- arguments: { campaign_id: 12345, amount_micros: 5_000_000, validate: true },- },- }),- makeCodexStreamState(),- );- expect(events[0]).toMatchObject({- label: "campaign_id=12345 amount_micros=5000000 validate=true",- });- });-- it("leaves the label undefined when there are no arguments", () => {- const events = parseCodexLine(- line({- type: "item.started",- item: { type: "mcp_tool_call", id: "item_3", server: "s", tool: "t" },- }),- makeCodexStreamState(),- );- expect(events[0]).toMatchObject({ kind: "tool" });- expect((events[0] as { label?: string }).label).toBeUndefined();- });-});diff --git a/notfair/src/server/adapters/codex-local/parse.ts b/notfair/src/server/adapters/codex-local/parse.tsdeleted file mode 100644index d5e3cd1f..00000000--- a/notfair/src/server/adapters/codex-local/parse.ts+++ /dev/null@@ -1,261 +0,0 @@-import type { HarnessEvent } from "../types";-import { labelFromArgs } from "../label-args";--/**- * Codex CLI emits one JSON event per line on stdout when invoked with- * `codex exec --json ...`. Event shape (per the OpenAI codex docs):- *- * { type: "thread.started", thread_id: "..." }- * { type: "item.started", item: { type: "agent_message" | "tool_call", ... } }- * { type: "item.completed", item: { type: "agent_message", text: "..." } }- * { type: "turn.completed", usage: { ... } }- * { type: "turn.failed", error: { message: "..." } }- * { type: "error", message: "..." }- *- * Codex does NOT emit token-by-token deltas — agent_message text arrives- * whole on item.completed. We forward it as one delta + a final at- * turn.completed so the UI flow matches Claude Code's event sequence.- */-export interface CodexStreamState {- emittedTextLen: number;- assistantText: string;- finalized: boolean;- threadId: string | null;-}--export function makeCodexStreamState(): CodexStreamState {- return { emittedTextLen: 0, assistantText: "", finalized: false, threadId: null };-}--interface CodexEvent {- type?: string;- thread_id?: string;- message?: string;- item?: {- type?: string;- text?: string;- name?: string;- id?: string;- command?: string;- arguments?: Record<string, unknown>;- /**- * Fields specific to `mcp_tool_call` items in codex 0.13x+. The- * gateway invokes a registered MCP server's tool and emits the- * server/tool pair separately from the generic `name` slot.- */- server?: string;- tool?: string;- tool_name?: string;- /** `error`-type items (codex 0.144+) carry their text here. */- message?: string;- };- error?: { message?: string };-}--/**- * Item type ids codex emits for things we want to surface as "tool"- * events in the UI. Centralized so the started/completed branches stay- * in sync — historically they drifted, missing newer types like- * `mcp_tool_call` (added in codex 0.132+) which left MCP invocations- * silently invisible in the chat.- */-const TOOLISH_ITEM_TYPES = new Set([- "command_execution",- "tool_call",- "function_call",- "mcp_tool_call",- "mcp_call",-]);--export function parseCodexLine(- line: string,- state: CodexStreamState,-): HarnessEvent[] {- const trimmed = line.trim();- if (!trimmed) return [];- let event: CodexEvent;- try {- event = JSON.parse(trimmed) as CodexEvent;- } catch {- return [];- }-- const events: HarnessEvent[] = [];-- if (event.type === "thread.started") {- state.threadId = event.thread_id ?? state.threadId;- events.push({ kind: "lifecycle", phase: "start" });- if (state.threadId) {- events.push({ kind: "session", harnessSessionId: state.threadId });- }- return events;- }-- if (event.type === "item.started" && event.item) {- const item = event.item;- if (item.type && TOOLISH_ITEM_TYPES.has(item.type)) {- const toolName = nameForToolishItem(item);- events.push({- kind: "tool",- phase: "start",- toolCallId: item.id ?? "",- name: toolName,- label: labelForCodexInput(toolName, item),- });- }- return events;- }-- if (event.type === "item.completed" && event.item) {- const item = event.item;- if (item.type === "agent_message" && typeof item.text === "string") {- state.assistantText += item.text;- if (state.assistantText.length > state.emittedTextLen) {- const delta = state.assistantText.slice(state.emittedTextLen);- state.emittedTextLen = state.assistantText.length;- events.push({ kind: "delta", text: delta });- }- } else if (item.type && TOOLISH_ITEM_TYPES.has(item.type)) {- events.push({- kind: "tool",- phase: "result",- toolCallId: item.id ?? "",- name: nameForToolishItem(item),- });- } else if (item.type === "error" && typeof item.message === "string") {- // Non-fatal, item-level errors (fatal ones arrive as turn.failed).- // Surface them — silently dropping used to hide real failures —- // EXCEPT known advisories that codex prints on every run for- // plugin-heavy installs; those would render as a scary red row on- // every single turn.- if (!isAdvisoryCodexItemError(item.message)) {- events.push({ kind: "error", message: item.message, transient: true });- }- }- return events;- }-- if (event.type === "turn.completed") {- state.finalized = true;- events.push({ kind: "final", text: state.assistantText });- return events;- }-- if (event.type === "turn.failed") {- const message = event.error?.message ?? "codex turn failed";- const transient = isTransientCodexError(message);- // Only flip `finalized` on a *terminal* failure. Transient retry- // chatter (Codex's MCP reconnect loop: "Reconnecting... N/5 ...")- // arrives on `turn.failed` too — if we marked the turn finalized- // there, the close handler in execute.ts would suppress the richer- // "codex exited with code N: <stderr tail>" error that lands after- // the process actually gives up.- if (!transient) state.finalized = true;- events.push({ kind: "error", message, transient });- return events;- }-- if (event.type === "error") {- const message = event.message ?? "codex error";- events.push({- kind: "error",- message,- transient: isTransientCodexError(message),- });- return events;- }-- return events;-}--/**- * Codex's MCP reconnect loop prints `Reconnecting... N/5 (...)` whenever- * a streamable-HTTP MCP server connection drops mid-turn. These are- * intermediate retry-state snapshots, not the terminal error — the real- * cause (network blip, expired token, etc.) is what eventually shows up- * on stderr when codex finally gives up. Surfacing the retry message as- * the run's error makes failures look opaque ("2/5 — why not 5/5?");- * tagging them lets the scheduler prefer the post-exit message instead.- */-const TRANSIENT_CODEX_ERROR_PATTERNS: RegExp[] = [- /^Reconnecting\.\.\.\s+\d+\/\d+/,-];--export function isTransientCodexError(message: string): boolean {- const trimmed = message.trim();- return TRANSIENT_CODEX_ERROR_PATTERNS.some((re) => re.test(trimmed));-}--/**- * Advisory `error` items codex (0.144+) emits on EVERY run in some- * configurations — informational config nudges, not turn failures.- * Rendering them would put a red error row on every single chat turn.- */-const ADVISORY_CODEX_ITEM_ERROR_PATTERNS: RegExp[] = [- // Plugin-heavy installs: "Skill descriptions were shortened to fit the- // 2% skills context budget. Codex can still see every skill, …"- /^Skill descriptions were shortened/i,-];--export function isAdvisoryCodexItemError(message: string): boolean {- const trimmed = message.trim();- return ADVISORY_CODEX_ITEM_ERROR_PATTERNS.some((re) => re.test(trimmed));-}--/**- * Derive the canonical tool `name` field the UI will see for any codex- * item type we route through as a tool event. The shape matters: the- * chat client maps the name to (a) an icon, (b) a humanized verb,- * (c) an MCP brand favicon. Conventions:- *- * - `mcp_tool_call` / `mcp_call` items get `<server>.<tool>` so the- * UI's `<server>.<tool>` matcher resolves the server brand from- * the project's MCP catalog. The codex namespace prefix- * (`notfair_<projectSlug>__<serverName>`) is what `server` carries- * — the matcher already strips the project prefix.- * - Shell-style `command_execution` items lose their raw command from- * the name (it would render as garbage in the UI) — name becomes- * a stable `"shell"` token, and the command stays in the label.- * - Generic `tool_call` / `function_call` items keep their declared- * `name` so unknown function tools surface their real identifier.- * - Items missing every signal degrade to `"tool"`.- */-function nameForToolishItem(item: {- type?: string;- name?: string;- command?: string;- server?: string;- tool?: string;- tool_name?: string;-}): string {- if (item.type === "mcp_tool_call" || item.type === "mcp_call") {- const server = item.server ?? "";- const tool = item.tool ?? item.tool_name ?? item.name ?? "tool";- if (server) return `${server}.${tool}`;- return tool;- }- if (item.type === "command_execution") {- // Shell items expose only `command`; we want the chat UI to see a- // stable `"shell"` slug rather than the raw command (which produces- // garbage verbs like "Called md\"" after the tool-name humanizer- // splits on dots in the command).- return "shell";- }- // tool_call / function_call / fallthrough.- const raw = item.name ?? item.tool ?? item.tool_name ?? (item.command ? "shell" : "tool");- return raw.split("\n")[0]!;-}--function labelForCodexInput(- name: string,- item: { command?: string; arguments?: Record<string, unknown> },-): string | undefined {- if (item.command && item.command.trim().length > 0) {- const firstLine = item.command.split("\n")[0];- return firstLine.length > 160 ? `${firstLine.slice(0, 159)}…` : firstLine;- }- // Broad extraction + compact k=v fallback — every MCP call should carry- // a human-scannable label (the SQL text, the URL, the id being acted- // on) into the transcript, not just the four keys we used to sample.- return labelFromArgs(item.arguments);-}diff --git a/notfair/src/server/adapters/codex-local/provision.test.ts b/notfair/src/server/adapters/codex-local/provision.test.tsdeleted file mode 100644index 3541aa5a..00000000--- a/notfair/src/server/adapters/codex-local/provision.test.ts+++ /dev/null@@ -1,55 +0,0 @@-import { existsSync } from "node:fs";-import { mkdtemp, readFile, writeFile } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { beforeEach, describe, expect, it } from "vitest";--import type { AgentProvisionSpec } from "../types";-import { provisionCodexAgent } from "./provision";--let workspaceDir: string;--beforeEach(async () => {- workspaceDir = await mkdtemp(join(tmpdir(), "notfair-codex-prov-"));-});--function spec(overrides: Partial<AgentProvisionSpec> = {}): AgentProvisionSpec {- return {- projectSlug: "proj",- agentId: "proj-goal-1",- displayName: "Greg",- templateKey: "goal",- workspaceDir,- identityMd: "# Greg identity\n",- ...overrides,- };-}--describe("provisionCodexAgent", () => {- it("mirrors the identity into AGENTS.md so codex auto-loads it", async () => {- await provisionCodexAgent(spec());- expect(await readFile(join(workspaceDir, "IDENTITY.md"), "utf8")).toBe(- "# Greg identity\n",- );- expect(await readFile(join(workspaceDir, "AGENTS.md"), "utf8")).toBe(- "# Greg identity\n",- );- });-- it("writes PROJECT.md only when a project brief exists", async () => {- await provisionCodexAgent(spec());- expect(existsSync(join(workspaceDir, "PROJECT.md"))).toBe(false);-- await provisionCodexAgent(spec({ projectMd: "# Brief\n" }));- expect(await readFile(join(workspaceDir, "PROJECT.md"), "utf8")).toBe("# Brief\n");- });-- it("creates the workspace dir and removes a stale SKILL.md sidecar", async () => {- await writeFile(join(workspaceDir, "SKILL.md"), "old skill", "utf8");- const nested = join(workspaceDir, "sub", "agent");- await provisionCodexAgent(spec());- await provisionCodexAgent(spec({ workspaceDir: nested }));- expect(existsSync(join(workspaceDir, "SKILL.md"))).toBe(false);- expect(existsSync(join(nested, "AGENTS.md"))).toBe(true);- });-});diff --git a/notfair/src/server/adapters/codex-local/provision.ts b/notfair/src/server/adapters/codex-local/provision.tsdeleted file mode 100644index b46322b7..00000000--- a/notfair/src/server/adapters/codex-local/provision.ts+++ /dev/null@@ -1,28 +0,0 @@-import { mkdir, rm, writeFile } from "node:fs/promises";-import { join } from "node:path";-import type { AgentProvisionSpec } from "../types";--/**- * Provision a workspace for Codex CLI.- *- * Layout under `<workspaceDir>/`:- * IDENTITY.md — NotFair source of truth (also written so humans see it)- * AGENTS.md — same content; codex auto-loads AGENTS.md from cwd- * PROJECT.md — project brief if available- *- * The skill text lives INSIDE the identity — never as a SKILL.md sidecar,- * which would be the same content twice (once auto-loaded, once whenever- * the agent reads the file).- */-export async function provisionCodexAgent(spec: AgentProvisionSpec): Promise<void> {- await mkdir(spec.workspaceDir, { recursive: true });- await Promise.all([- writeFile(join(spec.workspaceDir, "IDENTITY.md"), spec.identityMd, "utf8"),- writeFile(join(spec.workspaceDir, "AGENTS.md"), spec.identityMd, "utf8"),- spec.projectMd- ? writeFile(join(spec.workspaceDir, "PROJECT.md"), spec.projectMd, "utf8")- : Promise.resolve(),- // Remove the sidecar older provisions wrote.- rm(join(spec.workspaceDir, "SKILL.md"), { force: true }),- ]);-}diff --git a/notfair/src/server/adapters/codex-local/test.test.ts b/notfair/src/server/adapters/codex-local/test.test.tsdeleted file mode 100644index c53a2189..00000000--- a/notfair/src/server/adapters/codex-local/test.test.ts+++ /dev/null@@ -1,82 +0,0 @@-import { EventEmitter } from "node:events";-import { PassThrough } from "node:stream";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- spawn: vi.fn(),- resolveCodexBinary: vi.fn(() => "codex"),-}));-vi.mock("node:child_process", () => ({ spawn: mocks.spawn }));-vi.mock("./binary", () => ({- resolveCodexBinary: mocks.resolveCodexBinary,-}));--import { testCodexLocalEnvironment } from "./test";--class FakeChild extends EventEmitter {- stdout = new PassThrough();- stderr = new PassThrough();- kill = vi.fn();-}--function scriptVersionCmd(script: {- stdout?: string;- exitCode?: number;- spawnError?: boolean;- hang?: boolean;-}): FakeChild {- const child = new FakeChild();- mocks.spawn.mockImplementationOnce(() => {- if (!script.hang) {- setImmediate(() => {- if (script.spawnError) {- child.emit("error", new Error("ENOENT"));- return;- }- if (script.stdout) child.stdout.emit("data", Buffer.from(script.stdout));- child.emit("close", script.exitCode ?? 0);- });- }- return child;- });- return child;-}--beforeEach(() => mocks.spawn.mockReset());-afterEach(() => vi.useRealTimers());--describe("testCodexLocalEnvironment", () => {- it("reports ok with a parsed version label when the CLI responds", async () => {- scriptVersionCmd({ stdout: "codex-cli 0.144.2\n" });- const health = await testCodexLocalEnvironment();- expect(health).toEqual({- ok: true,- auth: "unknown",- versionLabel: "Codex 0.144.2",- });- expect(mocks.spawn).toHaveBeenCalledWith("codex", ["--version"], expect.anything());- });-- it("falls back to a bare label when the version string is unparsable", async () => {- scriptVersionCmd({ stdout: "nightly\n" });- const health = await testCodexLocalEnvironment();- expect(health.versionLabel).toBe("Codex");- });-- it("reports not-ok with an install hint when the binary is missing", async () => {- scriptVersionCmd({ spawnError: true });- const health = await testCodexLocalEnvironment();- expect(health.ok).toBe(false);- expect(health.message).toContain("Codex CLI check failed for `codex`");- });-- it("times out a hung probe instead of waiting forever", async () => {- vi.useFakeTimers();- const child = scriptVersionCmd({ hang: true });- const pending = testCodexLocalEnvironment();- await vi.advanceTimersByTimeAsync(5_001);- const health = await pending;- expect(health.ok).toBe(false);- expect(child.kill).toHaveBeenCalledWith("SIGTERM");- });-});diff --git a/notfair/src/server/adapters/codex-local/test.ts b/notfair/src/server/adapters/codex-local/test.tsdeleted file mode 100644index ebfd0081..00000000--- a/notfair/src/server/adapters/codex-local/test.ts+++ /dev/null@@ -1,64 +0,0 @@-import { spawn } from "node:child_process";-import type { HarnessEnvironmentHealth } from "../types";-import { resolveCodexBinary } from "./binary";--export async function testCodexLocalEnvironment(): Promise<HarnessEnvironmentHealth> {- const codexBin = resolveCodexBinary();- const versionResult = await runCmd(codexBin, ["--version"]);- if (versionResult.code !== 0) {- return {- ok: false,- auth: "unknown",- message: `Codex CLI check failed for \`${codexBin}\`. Install Codex or set NOTFAIR_CODEX_BIN to its executable path.`,- };- }- return {- ok: true,- auth: "unknown",- versionLabel: parseVersion(versionResult.stdout),- };-}--interface CmdResult {- code: number;- stdout: string;- stderr: string;-}--function runCmd(cmd: string, args: string[], timeoutMs = 5_000): Promise<CmdResult> {- return new Promise((resolve) => {- let stdout = "";- let stderr = "";- let settled = false;- const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });- const timer = setTimeout(() => {- if (settled) return;- settled = true;- try {- child.kill("SIGTERM");- } catch {- // ignore- }- resolve({ code: 124, stdout, stderr: stderr || "timeout" });- }, timeoutMs);- child.stdout.on("data", (c: Buffer) => (stdout += c.toString("utf8")));- child.stderr.on("data", (c: Buffer) => (stderr += c.toString("utf8")));- child.on("error", () => {- if (settled) return;- settled = true;- clearTimeout(timer);- resolve({ code: 127, stdout, stderr });- });- child.on("close", (code) => {- if (settled) return;- settled = true;- clearTimeout(timer);- resolve({ code: code ?? 0, stdout, stderr });- });- });-}--function parseVersion(stdout: string): string {- const m = stdout.match(/(\d+\.\d+\.\d+[\w.\-+]*)/);- return m ? `Codex ${m[1]}` : "Codex";-}diff --git a/notfair/src/server/adapters/display-registry.ts b/notfair/src/server/adapters/display-registry.tsdeleted file mode 100644index 9d89b5e2..00000000--- a/notfair/src/server/adapters/display-registry.ts+++ /dev/null@@ -1,52 +0,0 @@-import type { HarnessAdapterId } from "./types";--/**- * UI metadata for the harness adapters. Mirrors paperclip's- * `adapter-display-registry.ts`. Drives the onboarding picker and any "you're- * using X" UI surface.- */-export interface HarnessDisplay {- id: HarnessAdapterId;- label: string;- /** One-line description shown under the label on the picker card. */- description: string;- /** Show "Recommended" badge + put in the primary row of the picker. */- recommended: boolean;- /** Where to point a user who doesn't have the CLI installed. */- installUrl: string;- /** CLI binary name (for doctor checks, install hints). */- binary: string;-}--// Insertion order is the display order — Object.values preserves it.-// Codex first + recommended; Claude Code second, available but not promoted.-export const HARNESS_DISPLAY: Record<HarnessAdapterId, HarnessDisplay> = {- "codex-local": {- id: "codex-local",- label: "Codex",- description: "Run agents through OpenAI's Codex CLI. Uses your existing codex login.",- recommended: true,- installUrl: "https://github.com/openai/codex",- binary: "codex",- },- "claude-code-local": {- id: "claude-code-local",- label: "Claude Code",- description: "Run agents through Anthropic's Claude Code CLI. Uses your existing claude login.",- recommended: false,- installUrl: "https://docs.claude.com/en/docs/agents-and-tools/claude-code/overview",- binary: "claude",- },-};--export function listRecommendedHarnesses(): HarnessDisplay[] {- return Object.values(HARNESS_DISPLAY).filter((h) => h.recommended);-}--export function listMoreHarnesses(): HarnessDisplay[] {- return Object.values(HARNESS_DISPLAY).filter((h) => !h.recommended);-}--export function getHarnessDisplay(id: HarnessAdapterId): HarnessDisplay {- return HARNESS_DISPLAY[id];-}diff --git a/notfair/src/server/adapters/label-args.test.ts b/notfair/src/server/adapters/label-args.test.tsdeleted file mode 100644index 4f9efc27..00000000--- a/notfair/src/server/adapters/label-args.test.ts+++ /dev/null@@ -1,62 +0,0 @@-import { describe, expect, it } from "vitest";--import { labelFromArgs } from "./label-args";--describe("labelFromArgs", () => {- it("returns undefined for absent or empty args", () => {- expect(labelFromArgs(undefined)).toBeUndefined();- expect(labelFromArgs(null)).toBeUndefined();- expect(labelFromArgs({})).toBeUndefined();- });-- it("prefers a well-known string key over the k=v digest", () => {- expect(labelFromArgs({ campaign_id: 1, query: "SELECT 1" })).toBe("SELECT 1");- });-- it("respects the priority order of string keys (file_path before url)", () => {- expect(labelFromArgs({ url: "https://x.test", file_path: "/tmp/a.txt" })).toBe(- "/tmp/a.txt",- );- });-- it("takes only the first line of a multi-line value and trims it", () => {- expect(labelFromArgs({ sql: " SELECT *\nFROM t " })).toBe("SELECT *");- });-- it("clips long values to 160 chars with an ellipsis", () => {- const label = labelFromArgs({ command: "x".repeat(200) })!;- expect(label).toHaveLength(160);- expect(label.endsWith("…")).toBe(true);- expect(label.slice(0, 159)).toBe("x".repeat(159));- });-- it("skips whitespace-only string keys and falls through to the digest", () => {- expect(labelFromArgs({ query: " ", limit: 5 })).toBe("limit=5");- });-- it("builds a k=v digest from primitive args", () => {- expect(- labelFromArgs({ campaign_id: 12345, dry_run: true, note: "hi" }),- ).toBe("campaign_id=12345 dry_run=true note=hi");- });-- it("skips null/undefined and non-primitive values in the digest", () => {- expect(- labelFromArgs({ a: null, b: undefined, c: { nested: 1 }, d: [1], e: 7 }),- ).toBe("e=7");- });-- it("stops the digest after four parts", () => {- const label = labelFromArgs({ a: 1, b: 2, c: 3, d: 4, e: 5 });- expect(label).toBe("a=1 b=2 c=3 d=4");- });-- it("clips individual digest string values to 40 chars", () => {- const label = labelFromArgs({ note: "y".repeat(50) })!;- expect(label).toBe(`note=${"y".repeat(39)}…`);- });-- it("returns undefined when args hold only non-labelable values", () => {- expect(labelFromArgs({ a: null, b: { x: 1 }, c: " " })).toBeUndefined();- });-});diff --git a/notfair/src/server/adapters/label-args.ts b/notfair/src/server/adapters/label-args.tsdeleted file mode 100644index 2d671147..00000000--- a/notfair/src/server/adapters/label-args.ts+++ /dev/null@@ -1,69 +0,0 @@-/**- * Shared tool-argument → transcript-label extraction for the harness- * adapters. The harnesses expose every MCP call's full arguments; the- * label is the one slot that survives into the transcript, so the goal- * here is: no MCP call should land with an empty label while its- * arguments held something a human could scan (the SQL text, the URL,- * the campaign id…).- */--/** Argument keys whose string value is the natural one-line label. */-const STRING_KEYS = [- "file_path",- "path",- "filename",- "url",- "uri",- "query",- "sql",- "hogql",- "code",- "script",- "command",- "cmd",- "message",- "text",- "prompt",- "statement",- "name",- "title",- "description",-] as const;--function firstLine(s: string): string {- const nl = s.indexOf("\n");- return nl >= 0 ? s.slice(0, nl) : s;-}--function clip(s: string, max: number): string {- return s.length > max ? `${s.slice(0, max - 1)}…` : s;-}--/**- * Best human-scannable one-liner for a tool's arguments: a well-known- * string field when present, otherwise a compact `key=value` digest of- * the primitive arguments. Returns undefined only for empty/absent args.- */-export function labelFromArgs(- args: Record<string, unknown> | undefined | null,-): string | undefined {- if (!args) return undefined;- for (const k of STRING_KEYS) {- const v = args[k];- if (typeof v === "string" && v.trim().length > 0) {- return clip(firstLine(v.trim()), 160);- }- }- const parts: string[] = [];- for (const [k, v] of Object.entries(args)) {- if (v == null) continue;- if (typeof v === "string") {- if (v.trim().length > 0) parts.push(`${k}=${clip(firstLine(v.trim()), 40)}`);- } else if (typeof v === "number" || typeof v === "boolean") {- parts.push(`${k}=${v}`);- }- if (parts.length >= 4) break;- }- if (parts.length === 0) return undefined;- return clip(parts.join(" "), 160);-}diff --git a/notfair/src/server/adapters/registry.test.ts b/notfair/src/server/adapters/registry.test.tsdeleted file mode 100644index e533c0ea..00000000--- a/notfair/src/server/adapters/registry.test.ts+++ /dev/null@@ -1,56 +0,0 @@-import { describe, expect, it, vi } from "vitest";--// The adapter modules pull in @/server/mcp-server/secret and @/server/db/db,-// which capture NOTFAIR_DATA_DIR at import time — hoist the override so-// nothing ever resolves to the developer's live ~/.notfair.-vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-registry-"));-});--import {- DEFAULT_HARNESS_ADAPTER,- getAdapter,- isHarnessAdapterId,- listAdapters,- requireAdapter,-} from "./registry";--describe("adapter registry", () => {- it("resolves both built-in adapters by id", () => {- expect(getAdapter("claude-code-local")?.id).toBe("claude-code-local");- expect(getAdapter("codex-local")?.id).toBe("codex-local");- });-- it("returns null from getAdapter for an unknown id", () => {- expect(getAdapter("nope" as never)).toBeNull();- });-- it("requireAdapter returns the adapter or throws with the id in the message", () => {- expect(requireAdapter("codex-local").id).toBe("codex-local");- expect(() => requireAdapter("nope" as never)).toThrow(- "Unknown harness adapter: nope",- );- });-- it("lists exactly the built-ins", () => {- expect(listAdapters().map((a) => a.id).sort()).toEqual([- "claude-code-local",- "codex-local",- ]);- });-- it("defaults to claude-code-local", () => {- expect(DEFAULT_HARNESS_ADAPTER).toBe("claude-code-local");- });-- it("isHarnessAdapterId accepts only known ids", () => {- expect(isHarnessAdapterId("claude-code-local")).toBe(true);- expect(isHarnessAdapterId("codex-local")).toBe(true);- expect(isHarnessAdapterId("gemini-local")).toBe(false);- expect(isHarnessAdapterId(undefined)).toBe(false);- expect(isHarnessAdapterId(42)).toBe(false);- });-});diff --git a/notfair/src/server/adapters/registry.ts b/notfair/src/server/adapters/registry.tsdeleted file mode 100644index 0b52cd1b..00000000--- a/notfair/src/server/adapters/registry.ts+++ /dev/null@@ -1,37 +0,0 @@-import type { HarnessAdapter, HarnessAdapterId } from "./types";-import { claudeCodeLocalAdapter } from "./claude-code-local";-import { codexLocalAdapter } from "./codex-local";--const adapters = new Map<HarnessAdapterId, HarnessAdapter>();--function registerBuiltins(): void {- adapters.set(claudeCodeLocalAdapter.id, claudeCodeLocalAdapter);- adapters.set(codexLocalAdapter.id, codexLocalAdapter);-}-registerBuiltins();--export function getAdapter(id: HarnessAdapterId): HarnessAdapter | null {- return adapters.get(id) ?? null;-}--export function requireAdapter(id: HarnessAdapterId): HarnessAdapter {- const hit = adapters.get(id);- if (!hit) {- throw new Error(`Unknown harness adapter: ${id}`);- }- return hit;-}--export function listAdapters(): HarnessAdapter[] {- return Array.from(adapters.values());-}--/**- * Default adapter used when a project hasn't picked one. Claude Code is the- * recommended default per the onboarding UX.- */-export const DEFAULT_HARNESS_ADAPTER: HarnessAdapterId = "claude-code-local";--export function isHarnessAdapterId(value: unknown): value is HarnessAdapterId {- return value === "claude-code-local" || value === "codex-local";-}diff --git a/notfair/src/server/adapters/types.ts b/notfair/src/server/adapters/types.tsdeleted file mode 100644index 52d32b04..00000000--- a/notfair/src/server/adapters/types.ts+++ /dev/null@@ -1,193 +0,0 @@-/**- * HarnessAdapter — NotFair's plug-in shape for a local AI coding agent.- *- * Inspired by paperclip's ServerAdapterModule but pared down: NotFair runs- * locally only, so there's no remote execution target, no workspace bridge,- * no skill catalog interop. An adapter only needs to:- *- * 1. Validate its environment (binary installed, auth OK) — testEnvironment- * 2. Stream a chat turn for an agent — execute- * 3. Provision an agent workspace — provisionAgent- * 4. Register / unregister an MCP server for an agent — registerMcp / unregisterMcp- *- * Everything else (cron, MCP token storage, session/transcript persistence,- * agent metadata) lives in NotFair and is shared across adapters.- */-export type HarnessAdapterId = "claude-code-local" | "codex-local";--export interface HarnessEnvironmentHealth {- ok: boolean;- /** Short label for the status row (e.g. "Claude Code 1.0.42"). */- versionLabel?: string;- /** Path to the binary that was probed. */- binaryPath?: string;- /** Auth state: "ok", "missing", "expired", or "unknown" when not applicable. */- auth?: "ok" | "missing" | "expired" | "unknown";- /** Human-readable failure reason when ok=false. */- message?: string;-}--export interface AgentProvisionSpec {- /** Project slug (e.g. "acme"). */- projectSlug: string;- /** Agent backend id (e.g. "acme-goal-1"). */- agentId: string;- /** Personal display name (e.g. "Greg"). */- displayName: string;- /** Template key (goal agents use "goal"). */- templateKey: string;- /** Absolute path to the agent's workspace directory. */- workspaceDir: string;- /** The fully-rendered IDENTITY.md the agent should run with. */- identityMd: string;- /** PROJECT.md context, if a project brief exists yet. */- projectMd?: string;-}--export interface McpRegistrationSpec {- /** Logical server name (e.g. "notfair-googleads"). */- serverName: string;- /** Agent this server should be available to. */- agentId: string;- /** Project slug — adapters that scope MCP per workspace use this. */- projectSlug: string;- /** Transport: stdio command, HTTP URL, or local SSE. */- transport:- | { type: "stdio"; command: string; args: string[]; env?: Record<string, string> }- | { type: "http"; url: string; headers?: Record<string, string> };-}--/**- * Execution context for one chat turn.- *- * The adapter knows nothing about NotFair SQLite or routes — it gets the- * raw inputs it needs (agent identity, workspace, message), runs the harness,- * and yields HarnessEvents that the caller serializes onto SSE / persists.- */-export interface HarnessExecuteContext {- projectSlug: string;- agentId: string;- workspaceDir: string;- /** The user message for this turn. */- message: string;- /**- * Stable thread identifier owned by NotFair (the `sessions.id` UUID).- * Adapters MUST NOT pass this to their CLI's resume flag — the harness- * doesn't know it. Used only for logging / correlation.- */- threadId: string;- /**- * The harness's own session id from a prior turn on this thread, if any.- * When set, adapters pass it to their CLI's resume flag (e.g. claude- * `--resume`, codex `exec resume`). Null on the first turn of a thread.- */- harnessSessionId?: string | null;- /**- * Per-turn model override from the composer's model selector. When set,- * adapters pass it to their CLI's model flag (`claude --model`,- * `codex exec -m`). Absent/null = the CLI's own default. Values are- * whitelisted against HARNESS_MODEL_OPTIONS by the chat route before- * they reach the adapter.- */- model?: string | null;- /**- * Per-turn reasoning effort override from the composer. Adapters that- * expose effort metadata validate it in the chat route before execution.- * Absent/null = the CLI's own configured default.- */- reasoningEffort?: string | null;- /** Optional cancellation. When aborted the adapter kills its subprocess. */- signal?: AbortSignal;-}--export type HarnessEvent =- | { kind: "delta"; text: string }- | {- kind: "tool";- phase: "start" | "update" | "result";- toolCallId: string;- name: string;- label?: string;- }- | { kind: "lifecycle"; phase: string }- | { kind: "final"; text: string }- | {- kind: "error";- message: string;- /**- * Set true when the message is mid-stream retry chatter (e.g. Codex's- * MCP reconnect loop printing "Reconnecting... 2/5"), not a terminal- * failure. Callers that need a single error to surface should prefer- * the most recent non-transient one.- */- transient?: boolean;- }- /**- * Adapter has learned the harness's own session id for this thread. The- * caller should persist it on the `sessions.harness_session_id` column- * so the next turn can pass it to the adapter as `harnessSessionId` for- * resume. Emitted at most once per turn.- */- | { kind: "session"; harnessSessionId: string };--/** One selectable model for the composer's model dropdown. */-export interface HarnessModelOption {- /** Identifier passed verbatim to the CLI's model flag. */- value: string;- /** Human label for the dropdown. */- label: string;- /**- * True when omitting the model flag resolves to this model. The composer- * keeps the empty value as a genuine no-override selection, but uses this- * metadata to show the concrete model name instead of a vague "Default".- */- is_default?: boolean;- /**- * Input context window in tokens, when the provider exposes it (codex- * publishes it in models_cache.json). Absent when unknown.- */- context_window?: number;- /** Reasoning efforts this model supports, sourced from the provider. */- reasoning_efforts?: HarnessReasoningEffortOption[];- /** Effort used when NotFair omits a per-turn override. */- default_reasoning_effort?: string;-}--export interface HarnessReasoningEffortOption {- /** Identifier passed to the harness's effort configuration. */- value: string;- /** Human label for the dropdown. */- label: string;- /** Provider-supplied explanation of the speed/depth tradeoff. */- description?: string;-}--export interface HarnessAdapter {- readonly id: HarnessAdapterId;-- testEnvironment(): Promise<HarnessEnvironmentHealth>;-- /**- * Models the user can pick for a turn. Sourced from the provider where- * the harness exposes one (codex caches its account-scoped list in- * ~/.codex/models_cache.json); falls back to a small static list when- * discovery fails. Never throws.- */- listModels(): Promise<HarnessModelOption[]>;-- execute(ctx: HarnessExecuteContext): AsyncGenerator<HarnessEvent, void, void>;-- provisionAgent(spec: AgentProvisionSpec): Promise<void>;-- registerMcp(spec: McpRegistrationSpec): Promise<void>;- unregisterMcp(spec: McpUnregistrationSpec): Promise<void>;-}--export interface McpUnregistrationSpec {- /** Logical server name. */- serverName: string;- /** Project slug — Codex's project-namespaced global config key. */- projectSlug: string;- /** Agent id — Claude Code's per-workspace `.mcp.json` lives under it. */- agentId: string;-}diff --git a/notfair/src/server/agent-meta.test.ts b/notfair/src/server/agent-meta.test.tsdeleted file mode 100644index f28bc88a..00000000--- a/notfair/src/server/agent-meta.test.ts+++ /dev/null@@ -1,174 +0,0 @@-import { beforeAll, describe, expect, it, vi } from "vitest";-import { readFileSync, writeFileSync } from "node:fs";-import { mkdir, writeFile } from "node:fs/promises";-import { join } from "node:path";--// Real fs against a tmpdir data dir, per repo test conventions.-// MUST be hoisted: static imports evaluate before module-level statements,-// so a plain assignment would point the suite at the developer's ~/.notfair.-const h = vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- const dataDir = mkdtempSync(join(tmpdir(), "notfair-meta-"));- process.env.NOTFAIR_DATA_DIR = dataDir;- return { dataDir };-});--import {- agentExistsOnDisk,- listProjectAgents,- readAgentMeta,- resolveAgentBySlug,- workspaceDirFor,- writeAgentMeta,-} from "./agent-meta";--describe("agent meta sidecar", () => {- it("round-trips write → read", async () => {- await writeAgentMeta({- agent_id: "acme-goal-alex",- project_slug: "acme",- name: "Alex",- slug: "goal-alex",- created_at: "2026-01-01T00:00:00.000Z",- });- const meta = readAgentMeta("acme-goal-alex");- expect(meta).toMatchObject({- agent_id: "acme-goal-alex",- project_slug: "acme",- name: "Alex",- slug: "goal-alex",- });- // Human-inspectable: pretty-printed JSON on disk.- const raw = readFileSync(- join(h.dataDir, "agents", "acme-goal-alex", "notfair-meta.json"),- "utf8",- );- expect(raw).toContain("\n \"agent_id\"");- });-- it("returns null for a missing sidecar", () => {- expect(readAgentMeta("no-such-agent")).toBeNull();- });-- it("returns null for a corrupt sidecar instead of throwing", async () => {- const dir = join(h.dataDir, "agents", "acme-goal-corrupt");- await mkdir(dir, { recursive: true });- writeFileSync(join(dir, "notfair-meta.json"), "{not json", "utf8");- expect(readAgentMeta("acme-goal-corrupt")).toBeNull();- });-});--describe("agentExistsOnDisk", () => {- it("is true for a provisioned workspace dir", async () => {- await mkdir(join(h.dataDir, "agents", "acme-goal-here"), { recursive: true });- await expect(agentExistsOnDisk("acme-goal-here")).resolves.toBe(true);- });-- it("is false for a missing workspace", async () => {- await expect(agentExistsOnDisk("acme-goal-missing")).resolves.toBe(false);- });-- it("is false when the path is a file, not a directory", async () => {- await mkdir(join(h.dataDir, "agents"), { recursive: true });- await writeFile(join(h.dataDir, "agents", "acme-goal-file"), "x", "utf8");- await expect(agentExistsOnDisk("acme-goal-file")).resolves.toBe(false);- });-});--describe("workspaceDirFor", () => {- it("points inside the data dir", () => {- expect(workspaceDirFor("acme-goal-alex")).toBe(- join(h.dataDir, "agents", "acme-goal-alex"),- );- });-});--describe("listProjectAgents", () => {- beforeAll(async () => {- // Roster for "roster" plus a lookalike project "roster-q4" whose slug- // has "roster" as a string prefix — must not cross-leak.- await writeAgentMeta({- agent_id: "roster-goal-beth",- project_slug: "roster",- name: "Beth",- slug: "goal-beth",- created_at: "2026-01-02T00:00:00.000Z",- });- await writeAgentMeta({- agent_id: "roster-goal-abe",- project_slug: "roster",- name: "Abe",- slug: "goal-abe",- source_agent_id: "roster-goal-beth",- created_at: "2026-01-01T00:00:00.000Z",- });- await writeAgentMeta({- agent_id: "roster-q4-goal-carl",- project_slug: "roster-q4",- name: "Carl",- slug: "goal-carl",- created_at: "2026-01-03T00:00:00.000Z",- });- // Sidecar written before `slug` existed: falls back to slugified name.- const legacy = {- agent_id: "roster-goal-dee-jones",- project_slug: "roster",- name: "Dee Jones!",- created_at: "2026-01-04T00:00:00.000Z",- };- const dir = join(h.dataDir, "agents", legacy.agent_id);- await mkdir(dir, { recursive: true });- writeFileSync(join(dir, "notfair-meta.json"), JSON.stringify(legacy), "utf8");- // Dir with the right prefix but no sidecar — skipped.- await mkdir(join(h.dataDir, "agents", "roster-goal-nometa"), {- recursive: true,- });- });-- it("returns only this project's sidecars, oldest first", async () => {- const agents = await listProjectAgents("roster");- expect(agents.map((a) => a.agent_id)).toEqual([- "roster-goal-abe",- "roster-goal-beth",- "roster-goal-dee-jones",- ]);- expect(agents[0]!.source_agent_id).toBe("roster-goal-beth");- });-- it("never leaks a prefix-colliding project's roster", async () => {- const agents = await listProjectAgents("roster-q4");- expect(agents.map((a) => a.agent_id)).toEqual(["roster-q4-goal-carl"]);- });-- it("derives a slug for legacy sidecars without one", async () => {- const agents = await listProjectAgents("roster");- const dee = agents.find((a) => a.agent_id === "roster-goal-dee-jones")!;- expect(dee.slug).toBe("goal-dee-jones");- });-- it("returns [] when the agents root doesn't exist yet", async () => {- const saved = process.env.NOTFAIR_DATA_DIR;- process.env.NOTFAIR_DATA_DIR = join(h.dataDir, "does-not-exist");- try {- await expect(listProjectAgents("roster")).resolves.toEqual([]);- } finally {- process.env.NOTFAIR_DATA_DIR = saved;- }- });-});--describe("resolveAgentBySlug", () => {- it("resolves a URL slug to the full agent id", async () => {- await expect(resolveAgentBySlug("roster", "goal-beth")).resolves.toEqual({- agent_id: "roster-goal-beth",- name: "Beth",- slug: "goal-beth",- });- });-- it("returns null for an unknown slug", async () => {- await expect(resolveAgentBySlug("roster", "goal-nobody")).resolves.toBeNull();- });-});diff --git a/notfair/src/server/agent-meta.ts b/notfair/src/server/agent-meta.tsdeleted file mode 100644index 727b5599..00000000--- a/notfair/src/server/agent-meta.ts+++ /dev/null@@ -1,144 +0,0 @@-import { existsSync, readFileSync } from "node:fs";-import { mkdir, writeFile, readdir, stat } from "node:fs/promises";-import { homedir } from "node:os";-import { join } from "node:path";--/**- * Per-agent meta sidecar (`notfair-meta.json` in the agent's workspace- * dir). Agent = goal: every agent is a goal agent, so the sidecar is the- * single source of truth for the project's roster — no templates, no- * seeded placeholders. Authored at agent-create time, read by the sidebar- * and slug resolution.- */--export type AgentMeta = {- /** Full agent id, e.g. `acme-goal-alex`. */- agent_id: string;- /** Project slug this agent belongs to. */- project_slug: string;- /**- * Personal name the user assigned (e.g. "Alex"). IMMUTABLE — set once- * at agent-create time; the agent_id and URL slug encode it.- */- name: string;- /** URL slug, e.g. `goal-alex`. */- slug?: string;- /** When cloned, the source agentId. (Legacy field; unused today.) */- source_agent_id?: string;- created_at: string;-};--function notfairDataDir(): string {- return process.env.NOTFAIR_DATA_DIR ?? join(homedir(), ".notfair");-}--function metaPath(agentId: string): string {- return join(notfairDataDir(), "agents", agentId, "notfair-meta.json");-}--export async function writeAgentMeta(meta: AgentMeta): Promise<void> {- const path = metaPath(meta.agent_id);- await mkdir(join(path, ".."), { recursive: true });- await writeFile(path, JSON.stringify(meta, null, 2), "utf8");-}--export function readAgentMeta(agentId: string): AgentMeta | null {- const path = metaPath(agentId);- if (!existsSync(path)) return null;- try {- return JSON.parse(readFileSync(path, "utf8")) as AgentMeta;- } catch {- return null;- }-}--/** Has this agent's workspace been provisioned on disk? */-export async function agentExistsOnDisk(agentId: string): Promise<boolean> {- try {- const s = await stat(join(notfairDataDir(), "agents", agentId));- return s.isDirectory();- } catch {- return false;- }-}--export type ProjectAgentEntry = {- agent_id: string;- /** URL slug, e.g. `goal-alex`. */- slug: string;- /** Personal name (e.g. "Alex"). */- name: string;- source_agent_id?: string;- created_at?: string;-};--/**- * List agents for a project — the meta sidecars whose `project_slug`- * field equals the requested slug. The sidecar (not the dir-name prefix)- * is authoritative, so projects whose slug is a string prefix of another- * ("acme" vs "acme-q4") never cross-leak rosters.- */-export async function listProjectAgents(project_slug: string): Promise<ProjectAgentEntry[]> {- const agentsRoot = join(notfairDataDir(), "agents");- let entries: string[] = [];- try {- entries = await readdir(agentsRoot);- } catch {- return [];- }- const prefix = `${project_slug}-`;- const result: ProjectAgentEntry[] = [];- for (const entry of entries) {- if (!entry.startsWith(prefix)) continue;- const meta = readAgentMeta(entry);- if (!meta) continue;- if (meta.project_slug !== project_slug) continue;- result.push({- agent_id: meta.agent_id,- slug: meta.slug ?? slugifyForMeta(meta.name),- name: meta.name,- source_agent_id: meta.source_agent_id,- created_at: meta.created_at,- });- }- // Stable order: creation time, oldest first (sidebar reads top-down).- return result.sort((a, b) =>- (a.created_at ?? "").localeCompare(b.created_at ?? ""),- );-}--/** Workspace dir for an agent. */-export function workspaceDirFor(agentId: string): string {- return join(notfairDataDir(), "agents", agentId);-}--/** Fallback slug for sidecars written before `slug` was recorded. */-function slugifyForMeta(s: string): string {- return `goal-${s- .toLowerCase()- .trim()- .replace(/[^a-z0-9]+/g, "-")- .replace(/^-+|-+$/g, "")- .slice(0, 32)}`;-}--export type ResolvedAgent = {- agent_id: string;- /** Personal name (e.g. "Alex"). */- name: string;- slug: string;-};--/**- * Resolve a URL slug to its full agent_id within the current project.- * Returns null when no project agent matches the slug.- */-export async function resolveAgentBySlug(- project_slug: string,- url_slug: string,-): Promise<ResolvedAgent | null> {- const all = await listProjectAgents(project_slug);- const hit = all.find((a) => a.slug === url_slug);- if (!hit) return null;- return { agent_id: hit.agent_id, name: hit.name, slug: hit.slug };-}diff --git a/notfair/src/server/agents/cascade-delete.ts b/notfair/src/server/agents/cascade-delete.tsdeleted file mode 100644index 7db9635f..00000000--- a/notfair/src/server/agents/cascade-delete.ts+++ /dev/null@@ -1,202 +0,0 @@-import { existsSync } from "node:fs";-import { rm } from "node:fs/promises";-import { listProjectAgents } from "@/server/agent-meta";-import { getMcpCatalog } from "@/server/mcp-catalog";-import { listProjectMcpTokens, deleteProjectMcpTokens } from "@/server/mcp/tokens";-import { listAgentSessions } from "@/server/sessions";-import { workspaceDirFor } from "./provisioning";-import { getProject } from "@/server/db/projects";-import { requireAdapter } from "@/server/adapters/registry";-import { getDb } from "@/server/db/db";--export interface ProjectDeletionAgentSummary {- display_name: string;- agentId: string;- exists: boolean;- threadCount: number;-}--export interface ProjectDeletionMcpSummary {- catalog_key: string;- display_name: string;- stored_key: string;- configured: boolean;-}--export interface ProjectDeletionSummary {- project_slug: string;- agents: ProjectDeletionAgentSummary[];- mcps: ProjectDeletionMcpSummary[];- totals: {- agents: number;- threads: number;- mcps: number;- };-}--/**- * Inventory everything tied to a project so the confirmation dialog can show- * the user exactly what will be deleted. Reads-only.- */-export async function getProjectDeletionSummary(- project_slug: string,-): Promise<ProjectDeletionSummary> {- const entries = await listProjectAgents(project_slug);- const agents: ProjectDeletionAgentSummary[] = entries.map((e) => {- const dir = workspaceDirFor(e.agent_id);- const exists = existsSync(dir);- const threadCount = exists ? listAgentSessions(project_slug, e.agent_id).length : 0;- return {- display_name: e.name,- agentId: e.agent_id,- exists,- threadCount,- };- });-- // MCP connections live in the mcp_tokens table now. Per-catalog "configured"- // status is derived from whether a token row exists for the (project, server)- // pair.- const tokens = listProjectMcpTokens(project_slug);- const tokenServers = new Set(tokens.map((t) => t.server_name));- const mcps: ProjectDeletionMcpSummary[] = getMcpCatalog(project_slug).map(- (spec) => ({- catalog_key: spec.key,- display_name: spec.display_name,- stored_key: `${project_slug}-${spec.key}`,- configured: tokenServers.has(spec.key),- }),- );-- return {- project_slug,- agents,- mcps,- totals: {- agents: agents.filter((a) => a.exists).length,- threads: agents.reduce((acc, a) => acc + a.threadCount, 0),- mcps: mcps.filter((m) => m.configured).length,- },- };-}--/**- * Hard-delete ONE agent's artifacts: unregister its MCP servers from the- * harness config, drop its workspace dir, and delete its sessions- * (transcripts cascade). Goal rows are the caller's job- * (`deleteGoalsForAgent`) — this module owns the filesystem/harness side.- */-export async function cascadeDeleteAgentArtifacts(- project_slug: string,- agent_id: string,-): Promise<void> {- const project = getProject(project_slug);- const adapter = project ? requireAdapter(project.harness_adapter) : null;-- if (adapter) {- const { GOALS_MCP_KEY, BROWSER_MCP_KEY } = await import(- "@/server/mcp-server/registration"- );- const serverNames = [- ...getMcpCatalog(project_slug).map((spec) => spec.key),- GOALS_MCP_KEY,- BROWSER_MCP_KEY,- ];- for (const serverName of serverNames) {- try {- await adapter.unregisterMcp({- serverName,- projectSlug: project_slug,- agentId: agent_id,- });- } catch {- // best-effort- }- }- }-- try {- await rm(workspaceDirFor(agent_id), { recursive: true, force: true });- } catch (err) {- console.error(`[delete] failed to rm workspace ${agent_id}:`, err);- }-- getDb()- .prepare("DELETE FROM sessions WHERE project_slug = ? AND agent_id = ?")- .run(project_slug, agent_id);-}--/**- * Hard-delete every artifact tied to a project that lives outside the- * `projects` row's own FK cascade: agent workspace dirs, sessions +- * transcripts, MCP tokens. The caller is expected to then call- * `deleteProjectRow()` to drop the projects row itself.- */-export async function cascadeDeleteProjectArtifacts(project_slug: string): Promise<void> {- const project = getProject(project_slug);- const adapter = project ? requireAdapter(project.harness_adapter) : null;- const agents = await listProjectAgents(project_slug);-- // Stop the project's workspace browser first — its Chrome profile lives- // under projects/<slug>/browser/, which the caller wipes; rm-ing a- // user-data-dir under a live Chrome leaves an orphaned process behind.- try {- const { stopBrowser } = await import("@/server/browser/session");- await stopBrowser(project_slug);- } catch (err) {- console.warn(`[delete] failed to stop workspace browser for ${project_slug}:`, err);- }-- // Unregister any MCP servers the adapter wrote into its config (so codex- // global config doesn't leak rows for deleted projects, and claude-code- // workspaces don't reference dead bearers). This must cover the two- // INTERNAL servers (goals + browser) that provisioning registers- // for every agent, not just the external catalog — they used to be- // skipped here and leaked [mcp_servers.notfair_<slug>__…] entries into- // ~/.codex/config.toml for every deleted project.- if (adapter) {- const { GOALS_MCP_KEY, BROWSER_MCP_KEY } = await import(- "@/server/mcp-server/registration"- );- const serverNames = [- ...getMcpCatalog(project_slug).map((spec) => spec.key),- GOALS_MCP_KEY,- BROWSER_MCP_KEY,- ];- for (const agent of agents) {- for (const serverName of serverNames) {- try {- await adapter.unregisterMcp({- serverName,- projectSlug: project_slug,- agentId: agent.agent_id,- });- } catch {- // best-effort- }- }- }- }-- // Drop workspace dirs.- for (const agent of agents) {- try {- await rm(workspaceDirFor(agent.agent_id), { recursive: true, force: true });- } catch (err) {- console.error(`[delete] failed to rm workspace ${agent.agent_id}:`, err);- }- }-- // Drop sessions (transcript_events cascade).- getDb()- .prepare("DELETE FROM sessions WHERE project_slug = ?")- .run(project_slug);-- // Drop MCP tokens.- deleteProjectMcpTokens(project_slug);-- // Drop user-added MCP catalog entries for the project.- getDb()- .prepare("DELETE FROM user_mcp_servers WHERE project_slug = ?")- .run(project_slug);-}diff --git a/notfair/src/server/agents/clone.test.ts b/notfair/src/server/agents/clone.test.tsdeleted file mode 100644index 815da800..00000000--- a/notfair/src/server/agents/clone.test.ts+++ /dev/null@@ -1,141 +0,0 @@-import { describe, expect, it, vi } from "vitest";-import { existsSync, readFileSync } from "node:fs";-import { mkdir, writeFile } from "node:fs/promises";-import { join } from "node:path";--// Real fs against a tmpdir data dir, per repo test conventions.-// MUST be hoisted: static imports evaluate before module-level statements,-// so a plain assignment would point the suite at the developer's ~/.notfair.-const h = vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- const dataDir = mkdtempSync(join(tmpdir(), "notfair-clone-"));- process.env.NOTFAIR_DATA_DIR = dataDir;- return { dataDir };-});--import { agentExistsInProject, cloneAgent } from "./clone";-import { readAgentMeta } from "@/server/agent-meta";--const agentsRoot = () => join(h.dataDir, "agents");--async function seedAgent(agentId: string, files: Record<string, string> = {}) {- const dir = join(agentsRoot(), agentId);- await mkdir(dir, { recursive: true });- for (const [name, body] of Object.entries(files)) {- await writeFile(join(dir, name), body, "utf8");- }-}--describe("cloneAgent", () => {- it("copies the workspace and writes a fresh meta sidecar", async () => {- await seedAgent("acme-goal-src", {- "IDENTITY.md": "# identity",- "notes.txt": "scratch",- });-- const result = await cloneAgent({- source_agent_id: "acme-goal-src",- project_slug: "acme",- new_slug: "Goal Copy!",- display_name: "Copy",- });-- expect(result).toEqual({- new_agent_id: "acme-goal-copy",- new_slug: "goal-copy",- files_copied: 1,- sessions_copied: 0,- });- // Workspace files came along.- expect(- readFileSync(join(agentsRoot(), "acme-goal-copy", "IDENTITY.md"), "utf8"),- ).toBe("# identity");- // Sidecar reflects the clone, including provenance.- expect(readAgentMeta("acme-goal-copy")).toMatchObject({- agent_id: "acme-goal-copy",- project_slug: "acme",- slug: "goal-copy",- name: "Copy",- source_agent_id: "acme-goal-src",- });- });-- it("defaults the display name to the source agent id", async () => {- await seedAgent("acme-goal-src2", { "a.txt": "a" });- await cloneAgent({- source_agent_id: "acme-goal-src2",- project_slug: "acme",- new_slug: "unnamed-clone",- });- expect(readAgentMeta("acme-unnamed-clone")?.name).toBe("acme-goal-src2");- });-- it("still writes the sidecar when the source workspace is missing", async () => {- const result = await cloneAgent({- source_agent_id: "acme-goal-ghost",- project_slug: "acme",- new_slug: "from-ghost",- });- expect(result.files_copied).toBe(0);- // The sidecar itself creates the destination dir.- expect(readAgentMeta("acme-from-ghost")?.slug).toBe("from-ghost");- });-- it("rejects an invalid user-entered slug", async () => {- await expect(- cloneAgent({- source_agent_id: "acme-goal-src",- project_slug: "acme",- new_slug: "!!!",- }),- ).rejects.toThrow(/Invalid agent slug/);- });-- it("accepts a canonical slug verbatim and rejects malformed ones", async () => {- await expect(- cloneAgent({- source_agent_id: "acme-goal-src",- project_slug: "acme",- new_slug: "Bad_Canonical",- slug_is_canonical: true,- }),- ).rejects.toThrow(/Invalid canonical slug/);-- const result = await cloneAgent({- source_agent_id: "acme-goal-src",- project_slug: "acme",- new_slug: "canon-ok",- slug_is_canonical: true,- });- expect(result.new_agent_id).toBe("acme-canon-ok");- });-- it("refuses to clobber an existing agent with the same slug", async () => {- await seedAgent("acme-goal-taken", { "x.txt": "x" });- await expect(- cloneAgent({- source_agent_id: "acme-goal-src",- project_slug: "acme",- new_slug: "goal-taken",- }),- ).rejects.toThrow(/already exists/);- });-});--describe("agentExistsInProject", () => {- it("is false when the workspace dir doesn't exist", () => {- expect(agentExistsInProject("acme", "goal-nowhere")).toBe(false);- });-- it("is false for an existing but empty dir (half-provisioned leftovers)", async () => {- await mkdir(join(agentsRoot(), "acme-goal-empty"), { recursive: true });- expect(agentExistsInProject("acme", "goal-empty")).toBe(false);- });-- it("is true for a dir with contents", async () => {- await seedAgent("acme-goal-full", { "a.txt": "a" });- expect(agentExistsInProject("acme", "goal-full")).toBe(true);- });-});diff --git a/notfair/src/server/agents/clone.ts b/notfair/src/server/agents/clone.tsdeleted file mode 100644index 58d8e21a..00000000--- a/notfair/src/server/agents/clone.ts+++ /dev/null@@ -1,93 +0,0 @@-import { cp } from "node:fs/promises";-import { existsSync } from "node:fs";-import { randomUUID } from "node:crypto";-import { slugify } from "@/lib/slug";-import { workspaceDirFor } from "@/server/agents/provisioning";-import { writeAgentMeta } from "@/server/agent-meta";--export interface CloneAgentInput {- source_agent_id: string;- project_slug: string;- new_slug: string;- display_name?: string;- /** Skip the user-input slug validation (relocate/internal callers). */- slug_is_canonical?: boolean;-}--export interface CloneAgentResult {- new_agent_id: string;- new_slug: string;- files_copied: number;- sessions_copied: number;-}--/**- * Clone an existing agent within a project.- *- * Workspace dir copy via fs `cp -r`; sessions / transcript_events left ON- * the source (we don't carry chat history forward — the new agent starts- * with an empty thread list).- */-export async function cloneAgent(input: CloneAgentInput): Promise<CloneAgentResult> {- let newSlug: string;- if (input.slug_is_canonical) {- if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(input.new_slug)) {- throw new Error(`Invalid canonical slug: ${input.new_slug}`);- }- newSlug = input.new_slug;- } else {- const slugResult = slugify(input.new_slug);- if (!slugResult.ok) {- throw new Error(`Invalid agent slug: ${slugResult.reason}`);- }- newSlug = slugResult.slug;- }- const newAgentId = `${input.project_slug}-${newSlug}`;- if (agentExistsInProject(input.project_slug, newSlug)) {- throw new Error(- `An agent named "${newSlug}" already exists in this project. Pick a different name.`,- );- }-- const srcDir = workspaceDirFor(input.source_agent_id);- const dstDir = workspaceDirFor(newAgentId);- let filesCopied = 0;- if (existsSync(srcDir)) {- await cp(srcDir, dstDir, { recursive: true });- filesCopied = 1; // we don't enumerate; the dir is intact- }--- const displayName = (input.display_name ?? input.source_agent_id).trim() || input.source_agent_id;- await writeAgentMeta({- agent_id: newAgentId,- project_slug: input.project_slug,- slug: newSlug,- name: displayName,- source_agent_id: input.source_agent_id,- created_at: new Date().toISOString(),- });-- return {- new_agent_id: newAgentId,- new_slug: newSlug,- files_copied: filesCopied,- // sessions deliberately not copied — new agent starts fresh- sessions_copied: 0,- };-}--export function agentExistsInProject(project_slug: string, slug: string): boolean {- const agentId = `${project_slug}-${slug}`;- const dir = workspaceDirFor(agentId);- if (!existsSync(dir)) return false;- try {- // eslint-disable-next-line @typescript-eslint/no-require-imports- const { readdirSync } = require("node:fs") as typeof import("node:fs");- return readdirSync(dir).length > 0;- } catch {- return true;- }-}--void randomUUID; // imported for future use (sessions cloning if we re-enable)diff --git a/notfair/src/server/agents/files.test.ts b/notfair/src/server/agents/files.test.tsdeleted file mode 100644index a33b9428..00000000--- a/notfair/src/server/agents/files.test.ts+++ /dev/null@@ -1,34 +0,0 @@-import { mkdtemp, mkdir, writeFile } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { beforeAll, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({ workspace: "" }));-vi.mock("./provisioning", () => ({ workspaceDirFor: () => mocks.workspace }));--import { getAgentFile, listAgentFiles } from "./files";--beforeAll(async () => {- mocks.workspace = await mkdtemp(join(tmpdir(), "notfair-files-"));- await writeFile(join(mocks.workspace, "README.md"), "hello", "utf8");- await mkdir(join(mocks.workspace, "folder"));-});--it("returns an empty list for a missing workspace", async () => {- const saved = mocks.workspace;- mocks.workspace = join(saved, "missing");- await expect(listAgentFiles("a")).resolves.toEqual({ files: [], workspace: mocks.workspace });- mocks.workspace = saved;-});--it("lists only regular files with metadata", async () => {- const result = await listAgentFiles("a");- expect(result.workspace).toBe(mocks.workspace);- expect(result.files).toEqual([expect.objectContaining({ name: "README.md", size: 5, missing: false })]);-});--it("reads a file and rejects path traversal", async () => {- await expect(getAgentFile("a", "README.md")).resolves.toMatchObject({ file: { name: "README.md", content: "hello", size: 5 } });- await expect(getAgentFile("a", "../secret")).rejects.toThrow(/Invalid file name/);- await expect(getAgentFile("a", "nested/file")).rejects.toThrow(/Invalid file name/);-});diff --git a/notfair/src/server/agents/files.ts b/notfair/src/server/agents/files.tsdeleted file mode 100644index 2e63a2a8..00000000--- a/notfair/src/server/agents/files.ts+++ /dev/null@@ -1,72 +0,0 @@-import { existsSync } from "node:fs";-import { readFile, readdir, stat } from "node:fs/promises";-import { join } from "node:path";-import { workspaceDirFor } from "./provisioning";--/**- * Workspace file listing + reading. NotFair owns the agent workspace- * dir under `~/.notfair/agents/<id>/`, so file IO is a direct fs read- * — no harness subprocess or RPC needed.- */-export interface AgentFileEntry {- name: string;- size: number;- updatedAtMs: number;- missing: boolean;-}--export interface AgentFileList {- files: AgentFileEntry[];- /** Absolute path to the workspace dir — surfaced by the UI as a hint. */- workspace: string;-}--export async function listAgentFiles(agent_id: string): Promise<AgentFileList> {- const dir = workspaceDirFor(agent_id);- if (!existsSync(dir)) return { files: [], workspace: dir };- let entries: string[];- try {- entries = await readdir(dir);- } catch {- return { files: [], workspace: dir };- }- const files: AgentFileEntry[] = [];- for (const name of entries.sort()) {- try {- const s = await stat(join(dir, name));- if (!s.isFile()) continue;- files.push({- name,- size: s.size,- updatedAtMs: s.mtimeMs,- missing: false,- });- } catch {- files.push({ name, size: 0, updatedAtMs: 0, missing: true });- }- }- return { files, workspace: dir };-}--export interface AgentFileContent {- file: {- name: string;- content: string;- size: number;- updatedAtMs: number;- };-}--export async function getAgentFile(- agent_id: string,- name: string,-): Promise<AgentFileContent> {- if (name.includes("..") || name.includes("/")) {- throw new Error(`Invalid file name: ${name}`);- }- const path = join(workspaceDirFor(agent_id), name);- const [content, s] = await Promise.all([readFile(path, "utf8"), stat(path)]);- return {- file: { name, content, size: s.size, updatedAtMs: s.mtimeMs },- };-}diff --git a/notfair/src/server/agents/provisioning.test.ts b/notfair/src/server/agents/provisioning.test.tsdeleted file mode 100644index fef1dc01..00000000--- a/notfair/src/server/agents/provisioning.test.ts+++ /dev/null@@ -1,73 +0,0 @@-import { describe, expect, it, vi } from "vitest";-import { join } from "node:path";-import type { AgentProvisionSpec } from "@/server/adapters/types";--// Point the workspace layout at a tmpdir — provisioning derives paths from-// NOTFAIR_DATA_DIR and must never resolve to the developer's ~/.notfair.-const h = vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- const dataDir = mkdtempSync(join(tmpdir(), "notfair-provision-"));- process.env.NOTFAIR_DATA_DIR = dataDir;- return { dataDir, provisionAgent: vi.fn(async (_spec: AgentProvisionSpec) => {}) };-});--// Mock the harness boundary: the real adapter would write workspace files-// and touch the developer's harness config.-vi.mock("@/server/adapters/registry", () => ({- requireAdapter: vi.fn((id: string) => {- if (id !== "claude-code-local" && id !== "codex-local") {- throw new Error(`Unknown harness adapter: ${id}`);- }- return { provisionAgent: h.provisionAgent };- }),-}));--import { provisionAgent, workspaceDirFor } from "./provisioning";--describe("workspaceDirFor", () => {- it("resolves under <data dir>/agents/<agent id>", () => {- expect(workspaceDirFor("acme-goal-alex")).toBe(- join(h.dataDir, "agents", "acme-goal-alex"),- );- });-});--describe("provisionAgent", () => {- it("hands the adapter a fully-resolved provision spec", async () => {- await provisionAgent({- projectSlug: "acme",- agentId: "acme-goal-alex",- displayName: "Alex",- templateKey: "goal",- identityMd: "# IDENTITY",- projectMd: "# PROJECT",- harnessAdapter: "claude-code-local",- });-- expect(h.provisionAgent).toHaveBeenCalledTimes(1);- expect(h.provisionAgent).toHaveBeenCalledWith({- projectSlug: "acme",- agentId: "acme-goal-alex",- displayName: "Alex",- templateKey: "goal",- workspaceDir: join(h.dataDir, "agents", "acme-goal-alex"),- identityMd: "# IDENTITY",- projectMd: "# PROJECT",- });- });-- it("propagates an unknown-adapter failure", async () => {- await expect(- provisionAgent({- projectSlug: "acme",- agentId: "acme-goal-alex",- displayName: "Alex",- templateKey: "goal",- identityMd: "# IDENTITY",- harnessAdapter: "not-a-harness" as never,- }),- ).rejects.toThrow(/Unknown harness adapter/);- });-});diff --git a/notfair/src/server/agents/provisioning.ts b/notfair/src/server/agents/provisioning.tsdeleted file mode 100644index 7ef4c232..00000000--- a/notfair/src/server/agents/provisioning.ts+++ /dev/null@@ -1,38 +0,0 @@-import { homedir } from "node:os";-import { join } from "node:path";-import { requireAdapter } from "@/server/adapters/registry";-import type { HarnessAdapterId, AgentProvisionSpec } from "@/server/adapters/types";--/**- * Generic agent provisioning. The adapter writes whatever workspace files- * the harness needs (IDENTITY.md, CLAUDE.md, AGENTS.md, etc.) — NotFair- * supplies the rendered prompt content + workspace path.- */-export function workspaceDirFor(agentId: string): string {- const dataDir = process.env.NOTFAIR_DATA_DIR ?? join(homedir(), ".notfair");- return join(dataDir, "agents", agentId);-}--export interface ProvisionInput {- projectSlug: string;- agentId: string;- displayName: string;- templateKey: string;- identityMd: string;- projectMd?: string;- harnessAdapter: HarnessAdapterId;-}--export async function provisionAgent(input: ProvisionInput): Promise<void> {- const adapter = requireAdapter(input.harnessAdapter);- const spec: AgentProvisionSpec = {- projectSlug: input.projectSlug,- agentId: input.agentId,- displayName: input.displayName,- templateKey: input.templateKey,- workspaceDir: workspaceDirFor(input.agentId),- identityMd: input.identityMd,- projectMd: input.projectMd,- };- await adapter.provisionAgent(spec);-}diff --git a/notfair/src/server/browser/actions.test.ts b/notfair/src/server/browser/actions.test.tsdeleted file mode 100644index f6d6b5dc..00000000--- a/notfair/src/server/browser/actions.test.ts+++ /dev/null@@ -1,152 +0,0 @@-// @vitest-environment jsdom-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--import {- back,- click,- navigate,- press,- scroll,- snapshot,- type as typeText,-} from "./actions";--function locator() {- return {- click: vi.fn(async () => {}),- dblclick: vi.fn(async () => {}),- fill: vi.fn(async () => {}),- press: vi.fn(async () => {}),- };-}--function page() {- const loc = locator();- return {- goto: vi.fn(async () => {}),- url: vi.fn(() => "https://example.com/final"),- title: vi.fn(async () => "Example"),- locator: vi.fn(() => loc),- keyboard: { press: vi.fn(async () => {}) },- evaluate: vi.fn(async (fn: (arg: never) => unknown, arg: never) => fn(arg)),- goBack: vi.fn(async () => null),- loc,- };-}--beforeEach(() => {- document.body.innerHTML = "";- Object.defineProperty(HTMLElement.prototype, "getBoundingClientRect", {- configurable: true,- value: () => ({ width: 100, height: 20 }),- });- Object.defineProperty(HTMLElement.prototype, "innerText", {- configurable: true,- get() { return this.textContent ?? ""; },- });- vi.stubGlobal("CSS", { escape: (value: string) => value });- vi.spyOn(window, "scrollBy").mockImplementation(() => {});- vi.spyOn(window, "getComputedStyle").mockReturnValue({ visibility: "visible", display: "block" } as CSSStyleDeclaration);-});--afterEach(() => vi.restoreAllMocks());--it("navigates with defaults and tolerates a title failure", async () => {- const p = page();- await expect(navigate(p as never, { url: "https://example.com" })).resolves.toEqual({- url: "https://example.com/final",- title: "Example",- });- expect(p.goto).toHaveBeenCalledWith("https://example.com", { waitUntil: "load", timeout: 30_000 });- p.title.mockRejectedValueOnce(new Error("gone"));- await expect(navigate(p as never, { url: "x", waitUntil: "commit", timeoutMs: 5 })).resolves.toMatchObject({ title: "" });-});--it("snapshots visible interactive elements and replaces stale refs", async () => {- document.title = "Snapshot";- document.body.innerHTML = `- <button data-notfair-ref="old" aria-label="Save" disabled>Ignored text</button>- <span id="labelled">Account name</span><input id="account" aria-labelledby="labelled" value="123">- <label for="email">Email address</label><input id="email" value="[email protected]">- <input placeholder="Fallback placeholder" value="x">- <a href="/next">Next page</a>- <textarea>notes</textarea>- <button id="hidden">Hidden</button>- `;- vi.spyOn(window, "getComputedStyle").mockImplementation((el) => ({- visibility: el.id === "hidden" ? "hidden" : "visible",- display: "block",- }) as CSSStyleDeclaration);- const p = page();- const result = await snapshot(p as never);- expect(result.title).toBe("Snapshot");- expect(result.elements).toEqual(expect.arrayContaining([- expect.objectContaining({ ref: "e1", role: "button", name: "Save", disabled: true }),- expect.objectContaining({ name: "Account name", value: "123" }),- expect.objectContaining({ name: "Email address", value: "[email protected]" }),- expect.objectContaining({ name: "Fallback placeholder" }),- expect.objectContaining({ role: "a", href: expect.stringContaining("/next") }),- ]));- expect(document.querySelector("[data-notfair-ref=old]")).toBeNull();- expect(document.querySelector("#hidden")?.hasAttribute("data-notfair-ref")).toBe(false);-});--it("filters zero-size and display-none elements", async () => {- document.body.innerHTML = `<button id="zero">Zero</button><button id="none">None</button>`;- vi.spyOn(window, "getComputedStyle").mockImplementation((el) => ({- visibility: "visible",- display: el.id === "none" ? "none" : "block",- }) as CSSStyleDeclaration);- vi.spyOn(document.querySelector("#zero")!, "getBoundingClientRect").mockReturnValue({ width: 0, height: 10 } as DOMRect);- const result = await snapshot(page() as never);- expect(result.elements).toEqual([]);-});--it("clicks and double-clicks refs with options", async () => {- let p = page();- await click(p as never, { ref: "e2", button: "right", modifiers: ["Meta"], timeoutMs: 50 });- expect(p.locator).toHaveBeenCalledWith('[data-notfair-ref="e2"]');- expect(p.loc.click).toHaveBeenCalledWith({ button: "right", modifiers: ["Meta"], timeout: 50 });- p = page();- await click(p as never, { ref: "e1", doubleClick: true });- expect(p.loc.dblclick).toHaveBeenCalledWith({ button: undefined, modifiers: undefined, timeout: 10_000 });- await expect(click(p as never, { ref: "bad" })).rejects.toThrow(/Invalid ref/);-});--it("clears, types, and optionally submits", async () => {- let p = page();- await typeText(p as never, { ref: "e3", text: "hello", submit: true });- expect(p.loc.fill).toHaveBeenNthCalledWith(1, "", { timeout: 10_000 });- expect(p.loc.fill).toHaveBeenNthCalledWith(2, "hello", { timeout: 10_000 });- expect(p.loc.press).toHaveBeenCalledWith("Enter", { timeout: 10_000 });- p = page();- await typeText(p as never, { ref: "e1", text: "append", clearFirst: false, timeoutMs: 1 });- expect(p.loc.fill).toHaveBeenCalledTimes(1);-});--it("presses on a ref or at page level", async () => {- const p = page();- await press(p as never, { key: "Tab", ref: "e1", timeoutMs: 9 });- expect(p.loc.press).toHaveBeenCalledWith("Tab", { timeout: 9 });- await press(p as never, { key: "Escape" });- expect(p.keyboard.press).toHaveBeenCalledWith("Escape");-});--it.each([- ["left", 25, { x: -25, y: 0 }],- ["right", 25, { x: 25, y: 0 }],- ["up", 25, { x: 0, y: -25 }],- ["down", undefined, { x: 0, y: 600 }],-])("scrolls %s", async (direction, amount, expected) => {- const p = page();- await scroll(p as never, { direction: direction as never, amount });- expect(p.evaluate).toHaveBeenCalledWith(expect.any(Function), expected);-});--it("goes back and ignores navigation failures", async () => {- const p = page();- await back(p as never);- expect(p.goBack).toHaveBeenCalledWith({ waitUntil: "load" });- p.goBack.mockRejectedValueOnce(new Error("no history"));- await expect(back(p as never)).resolves.toBeUndefined();-});diff --git a/notfair/src/server/browser/actions.ts b/notfair/src/server/browser/actions.tsdeleted file mode 100644index 205a1b68..00000000--- a/notfair/src/server/browser/actions.ts+++ /dev/null@@ -1,249 +0,0 @@-/**- * Page-level browser primitives the MCP tools wrap.- *- * Each function takes a Playwright Page and a small typed opts payload,- * runs the action with sensible defaults, and returns a normalized result.- * Keeping the action layer separate from the MCP tool layer means the- * tools can stay one-screen each (zod schema + handler) and these can be- * unit-tested without any MCP envelope plumbing.- *- * Snapshot format: V1 returns a flat list of interactable elements with- * stable ref ids (e1, e2, ...) scoped to the snapshot call. This matches- * Hermes' agent-browser ref convention so agent prompts can reuse the- * same mental model. The full Playwright aria tree comes in V1.1.- */-import type { Page } from "playwright-core";--export interface NavigateOptions {- url: string;- waitUntil?: "load" | "domcontentloaded" | "networkidle" | "commit";- timeoutMs?: number;-}--export interface NavigateResult {- url: string;- title: string;-}--export async function navigate(page: Page, opts: NavigateOptions): Promise<NavigateResult> {- await page.goto(opts.url, {- waitUntil: opts.waitUntil ?? "load",- timeout: opts.timeoutMs ?? 30_000,- });- return {- url: page.url(),- title: await page.title().catch(() => ""),- };-}--export interface SnapshotElement {- /** Ref id stable within this snapshot, e.g. "e1". */- ref: string;- /** ARIA role or tag name. */- role: string;- /** Accessible name when available, else trimmed text. */- name: string;- /** Empty for buttons/links; populated for inputs/selects. */- value?: string;- /** True when disabled / aria-disabled. */- disabled?: boolean;- /** href for links so agents can decide whether to navigate directly. */- href?: string;-}--export interface SnapshotResult {- url: string;- title: string;- elements: SnapshotElement[];- /** Truncated text content of the page, for context. */- text: string;-}--const SNAPSHOT_ELEMENT_LIMIT = 200;-const SNAPSHOT_TEXT_CHAR_LIMIT = 8_000;--/**- * Build a flat list of interactable elements + a text excerpt.- *- * We evaluate in the page rather than using Playwright's role queries- * because we want a single round-trip that returns everything we need:- * role, accessible name, current value, href, and a temporary numbered- * attribute we hang off each element so subsequent click/type calls can- * resolve back to the same DOM node via [data-notfair-ref="eN"].- */-export async function snapshot(page: Page): Promise<SnapshotResult> {- const { url, title, elements, text } = await page.evaluate(- ({ elemLimit, textLimit }) => {- const REF_ATTR = "data-notfair-ref";- // Clear stale refs from a previous snapshot.- for (const stale of Array.from(document.querySelectorAll(`[${REF_ATTR}]`))) {- stale.removeAttribute(REF_ATTR);- }-- const SELECTOR = [- "a[href]",- "button",- "input:not([type=hidden])",- "select",- "textarea",- "[role=button]",- "[role=link]",- "[role=checkbox]",- "[role=radio]",- "[role=tab]",- "[role=menuitem]",- "[contenteditable=true]",- ].join(",");-- const isVisible = (el: Element): boolean => {- const rect = (el as HTMLElement).getBoundingClientRect();- if (rect.width === 0 || rect.height === 0) return false;- const style = window.getComputedStyle(el as HTMLElement);- return style.visibility !== "hidden" && style.display !== "none";- };-- const accessibleName = (el: Element): string => {- const aria = el.getAttribute("aria-label");- if (aria) return aria;- const labelled = el.getAttribute("aria-labelledby");- if (labelled) {- const node = document.getElementById(labelled);- if (node?.textContent) return node.textContent.trim();- }- if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {- const id = el.getAttribute("id");- if (id) {- const label = document.querySelector(`label[for="${CSS.escape(id)}"]`);- if (label?.textContent) return label.textContent.trim();- }- if (el.placeholder) return el.placeholder;- }- const text = (el as HTMLElement).innerText ?? el.textContent ?? "";- return text.trim().slice(0, 200);- };-- const out: Array<Record<string, unknown>> = [];- let counter = 0;- const nodes = Array.from(document.querySelectorAll(SELECTOR)).filter(isVisible);- for (const el of nodes) {- if (counter >= elemLimit) break;- counter++;- const ref = `e${counter}`;- el.setAttribute(REF_ATTR, ref);-- const tag = el.tagName.toLowerCase();- const role = el.getAttribute("role") ?? tag;- const item: Record<string, unknown> = {- ref,- role,- name: accessibleName(el),- };- if (el instanceof HTMLAnchorElement && el.href) item.href = el.href;- if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {- item.value = el.value;- }- if ((el as HTMLButtonElement).disabled || el.getAttribute("aria-disabled") === "true") {- item.disabled = true;- }- out.push(item);- }-- const rawText = document.body?.innerText ?? "";- const text = rawText.slice(0, textLimit);-- return {- url: window.location.href,- title: document.title,- elements: out,- text,- };- },- { elemLimit: SNAPSHOT_ELEMENT_LIMIT, textLimit: SNAPSHOT_TEXT_CHAR_LIMIT },- );- return { url, title, elements: elements as unknown as SnapshotElement[], text };-}--function refSelector(ref: string): string {- // CSS attribute selectors don't need escaping for our ref format (eN).- if (!/^e\d+$/.test(ref)) {- throw new Error(`Invalid ref "${ref}" — expected "e<number>"`);- }- return `[data-notfair-ref="${ref}"]`;-}--export interface ClickOptions {- ref: string;- button?: "left" | "right" | "middle";- modifiers?: ("Alt" | "Control" | "Meta" | "Shift")[];- doubleClick?: boolean;- timeoutMs?: number;-}--export async function click(page: Page, opts: ClickOptions): Promise<void> {- const locator = page.locator(refSelector(opts.ref));- const timeout = opts.timeoutMs ?? 10_000;- if (opts.doubleClick) {- await locator.dblclick({ button: opts.button, modifiers: opts.modifiers, timeout });- } else {- await locator.click({ button: opts.button, modifiers: opts.modifiers, timeout });- }-}--export interface TypeOptions {- ref: string;- text: string;- /** Press Enter after typing. */- submit?: boolean;- /** Clear the field before typing. Default: true. */- clearFirst?: boolean;- timeoutMs?: number;-}--export async function type(page: Page, opts: TypeOptions): Promise<void> {- const locator = page.locator(refSelector(opts.ref));- const timeout = opts.timeoutMs ?? 10_000;- if (opts.clearFirst !== false) {- await locator.fill("", { timeout });- }- await locator.fill(opts.text, { timeout });- if (opts.submit) {- await locator.press("Enter", { timeout });- }-}--export interface PressOptions {- /** Playwright key string, e.g. "Enter", "Tab", "Control+a". */- key: string;- /** Optional ref to focus before pressing. If omitted, presses at page level. */- ref?: string;- timeoutMs?: number;-}--export async function press(page: Page, opts: PressOptions): Promise<void> {- const timeout = opts.timeoutMs ?? 10_000;- if (opts.ref) {- const locator = page.locator(refSelector(opts.ref));- await locator.press(opts.key, { timeout });- } else {- await page.keyboard.press(opts.key);- }-}--export interface ScrollOptions {- direction: "up" | "down" | "left" | "right";- /** Pixels. Default: 600 (one screen-ish on most viewports). */- amount?: number;-}--export async function scroll(page: Page, opts: ScrollOptions): Promise<void> {- const amount = opts.amount ?? 600;- const dx =- opts.direction === "left" ? -amount : opts.direction === "right" ? amount : 0;- const dy =- opts.direction === "up" ? -amount : opts.direction === "down" ? amount : 0;- await page.evaluate(({ x, y }) => window.scrollBy(x, y), { x: dx, y: dy });-}--export async function back(page: Page): Promise<void> {- await page.goBack({ waitUntil: "load" }).catch(() => {});-}diff --git a/notfair/src/server/browser/chrome.test.ts b/notfair/src/server/browser/chrome.test.tsdeleted file mode 100644index 7fe49c0c..00000000--- a/notfair/src/server/browser/chrome.test.ts+++ /dev/null@@ -1,170 +0,0 @@-import { EventEmitter } from "node:events";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- existsSync: vi.fn(),- rmSync: vi.fn(),- mkdirSync: vi.fn(),- spawn: vi.fn(),-}));--vi.mock("node:fs", () => ({- default: {- existsSync: mocks.existsSync,- rmSync: mocks.rmSync,- mkdirSync: mocks.mkdirSync,- },-}));-vi.mock("node:child_process", () => ({ spawn: mocks.spawn }));--import {- buildChromeLaunchArgs,- clearChromeSingletonArtifacts,- findChromeExecutable,- launchChrome,- stopChrome,- waitForCdpReady,-} from "./chrome";--function child() {- const events = new EventEmitter();- const stderr = new EventEmitter();- const proc = events as EventEmitter & {- stderr: EventEmitter;- exitCode: number | null;- killed: boolean;- kill: ReturnType<typeof vi.fn>;- };- proc.stderr = stderr;- proc.exitCode = null;- proc.killed = false;- proc.kill = vi.fn(() => true);- return proc;-}--beforeEach(() => {- vi.clearAllMocks();- mocks.existsSync.mockReturnValue(false);- mocks.rmSync.mockReturnValue(undefined);- vi.stubGlobal("fetch", vi.fn());-});--afterEach(() => {- vi.useRealTimers();- vi.unstubAllGlobals();-});--describe("Chrome discovery and args", () => {- it("prefers a valid explicit path", () => {- const exists = vi.fn((p: string) => p === "/custom/chrome");- expect(findChromeExecutable({ NOTFAIR_CHROME_PATH: " /custom/chrome " }, "darwin", exists)).toBe("/custom/chrome");- expect(exists).toHaveBeenCalledTimes(1);- });-- it("falls back to platform candidates and returns null on unsupported platforms", () => {- const exists = vi.fn((p: string) => p.includes("Chromium.app"));- expect(findChromeExecutable({}, "darwin", exists)).toContain("Chromium.app");- expect(findChromeExecutable({}, "win32", exists)).toBeNull();- expect(findChromeExecutable({ NOTFAIR_CHROME_PATH: "/missing" }, "linux", () => false)).toBeNull();- });-- it("builds headed/headless platform-specific args", () => {- const base = buildChromeLaunchArgs({ executablePath: "chrome", userDataDir: "/profile", cdpPort: 9222, platform: "darwin" });- expect(base).toContain("--remote-debugging-port=9222");- expect(base).not.toContain("--headless=new");- const linux = buildChromeLaunchArgs({- executablePath: "chrome",- userDataDir: "/profile",- cdpPort: 9222,- platform: "linux",- headless: true,- extraArgs: ["--proxy-server=x"],- });- expect(linux).toEqual(expect.arrayContaining(["--headless=new", "--disable-gpu", "--disable-dev-shm-usage", "--proxy-server=x"]));- });-- it("removes every singleton artifact and tolerates failures", () => {- mocks.rmSync.mockImplementationOnce(() => { throw new Error("locked"); });- expect(() => clearChromeSingletonArtifacts("/profile")).not.toThrow();- expect(mocks.rmSync).toHaveBeenCalledTimes(3);- expect(mocks.rmSync).toHaveBeenCalledWith("/profile/SingletonSocket", { force: true });- });-});--describe("CDP readiness and lifecycle", () => {- it("returns as soon as the endpoint is ready", async () => {- vi.mocked(fetch).mockResolvedValue({ ok: true, status: 200 } as Response);- await expect(waitForCdpReady("http://cdp", 100)).resolves.toBeUndefined();- expect(fetch).toHaveBeenCalledWith("http://cdp/json/version", expect.objectContaining({ signal: expect.any(AbortSignal) }));- });-- it("includes the last HTTP or network error when timing out", async () => {- await expect(waitForCdpReady("http://cdp", 0)).rejects.toThrow(/did not become ready/);- vi.mocked(fetch).mockResolvedValue({ ok: false, status: 503 } as Response);- await expect(waitForCdpReady("http://cdp", 2, 0)).rejects.toThrow(/status 503/);- vi.mocked(fetch).mockRejectedValue(new Error("refused"));- await expect(waitForCdpReady("http://cdp", 2, 0)).rejects.toThrow(/refused/);- });-- it("launches Chrome and returns its CDP metadata", async () => {- const proc = child();- mocks.spawn.mockReturnValue(proc);- vi.mocked(fetch).mockResolvedValue({ ok: true } as Response);- const launched = await launchChrome({- executablePath: "/chrome",- userDataDir: "/profile",- cdpPort: 9333,- platform: "darwin",- });- expect(mocks.mkdirSync).toHaveBeenCalledWith("/profile", { recursive: true });- expect(mocks.spawn).toHaveBeenCalledWith("/chrome", expect.arrayContaining(["--remote-debugging-port=9333"]), {- stdio: ["ignore", "pipe", "pipe"],- detached: false,- });- expect(launched).toMatchObject({ cdpPort: 9333, cdpHttpUrl: "http://127.0.0.1:9333", userDataDir: "/profile" });- });-- it("kills Chrome and surfaces an early exit with stderr tail", async () => {- const proc = child();- mocks.spawn.mockReturnValue(proc);- vi.mocked(fetch).mockImplementation(() => new Promise(() => {}));- const promise = launchChrome({ executablePath: "/chrome", userDataDir: "/profile", cdpPort: 9444 });- proc.stderr.emit("data", Buffer.from("startup failed"));- proc.emit("exit", 2, "SIGABRT");- await expect(promise).rejects.toThrow(/code=2.*startup failed/);- expect(proc.kill).toHaveBeenCalledWith("SIGKILL");- });-- it("stops an already-exited process with cleanup only", async () => {- const proc = child();- proc.exitCode = 0;- await stopChrome({ process: proc as never, cdpPort: 1, cdpHttpUrl: "x", userDataDir: "/profile" });- expect(proc.kill).not.toHaveBeenCalled();- expect(mocks.rmSync).toHaveBeenCalledTimes(3);- });-- it("uses SIGTERM for a live process that exits promptly", async () => {- const proc = child();- proc.kill.mockImplementation((signal: string) => {- if (signal === "SIGTERM") queueMicrotask(() => { proc.exitCode = 0; proc.emit("exit", 0, null); });- return true;- });- await stopChrome({ process: proc as never, cdpPort: 1, cdpHttpUrl: "x", userDataDir: "/profile" }, 50);- expect(proc.kill).toHaveBeenCalledWith("SIGTERM");- expect(proc.kill).not.toHaveBeenCalledWith("SIGKILL");- });-- it("falls back to SIGKILL after the graceful timeout", async () => {- vi.useFakeTimers();- const proc = child();- proc.kill.mockImplementation((signal: string) => {- if (signal === "SIGKILL") queueMicrotask(() => { proc.exitCode = 1; proc.emit("exit", 1, signal); });- return true;- });- const promise = stopChrome({ process: proc as never, cdpPort: 1, cdpHttpUrl: "x", userDataDir: "/profile" }, 10);- await vi.advanceTimersByTimeAsync(10);- await promise;- expect(proc.kill).toHaveBeenNthCalledWith(1, "SIGTERM");- expect(proc.kill).toHaveBeenNthCalledWith(2, "SIGKILL");- });-});diff --git a/notfair/src/server/browser/chrome.ts b/notfair/src/server/browser/chrome.tsdeleted file mode 100644index 7096269a..00000000--- a/notfair/src/server/browser/chrome.ts+++ /dev/null@@ -1,238 +0,0 @@-/**- * Workspace Chrome lifecycle.- *- * Discovers a Chromium-family browser binary, builds launch args for a- * managed instance pointed at a workspace user-data-dir, starts it on a- * known CDP port, waits for the CDP endpoint to come up, and shuts it down- * cleanly. Standard CDP pattern trimmed to the- * essentials a single-user local app needs.- */-import { type ChildProcess, spawn } from "node:child_process";-import fs from "node:fs";-import path from "node:path";--const SINGLETON_LOCK_FILES = ["SingletonLock", "SingletonSocket", "SingletonCookie"];--const MAC_CHROME_CANDIDATES: ReadonlyArray<string> = [- "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",- "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",- "/Applications/Chromium.app/Contents/MacOS/Chromium",- "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",- "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",-];--const LINUX_CHROME_CANDIDATES: ReadonlyArray<string> = [- "/usr/bin/google-chrome",- "/usr/bin/google-chrome-stable",- "/usr/bin/chromium",- "/usr/bin/chromium-browser",- "/usr/bin/microsoft-edge",- "/usr/bin/brave-browser",-];--/**- * Find a Chromium-family binary.- *- * Respects $NOTFAIR_CHROME_PATH first, then probes platform defaults.- * Returns null when nothing is found — callers should produce a friendly- * error pointing the user at the env var or an install link.- */-export function findChromeExecutable(- env: Readonly<Record<string, string | undefined>> = process.env,- platform: NodeJS.Platform = process.platform,- exists: (p: string) => boolean = (p) => fs.existsSync(p),-): string | null {- const explicit = env.NOTFAIR_CHROME_PATH?.trim();- if (explicit && exists(explicit)) return explicit;-- const candidates =- platform === "darwin"- ? MAC_CHROME_CANDIDATES- : platform === "linux"- ? LINUX_CHROME_CANDIDATES- : [];-- for (const candidate of candidates) {- if (exists(candidate)) return candidate;- }- return null;-}--/**- * Remove Chrome's SingletonLock / SingletonSocket / SingletonCookie files.- *- * Chrome refuses to start a second process against the same --user-data-dir,- * keying off these files. If our prior managed Chrome crashed (or the OS- * killed the parent without unlinking), the locks survive and the next- * launch silently no-ops or fails. Clear them before every launch — they're- * a coordination primitive, not durable state.- */-export function clearChromeSingletonArtifacts(userDataDir: string): void {- for (const basename of SINGLETON_LOCK_FILES) {- try {- fs.rmSync(path.join(userDataDir, basename), { force: true });- } catch {- // best-effort: a residual file the kernel can't unlink is not worth aborting launch- }- }-}--export interface ChromeLaunchOptions {- executablePath: string;- userDataDir: string;- cdpPort: number;- /** Default false. Onboarding sign-in always wants headed; agent runtime can choose. */- headless?: boolean;- /** Override platform for testability. */- platform?: NodeJS.Platform;- /** Extra args appended verbatim. Useful for --proxy-server, --window-size, etc. */- extraArgs?: string[];-}--/** Compose the Chrome argv list. Pure — does not touch disk or spawn anything. */-export function buildChromeLaunchArgs(opts: ChromeLaunchOptions): string[] {- const platform = opts.platform ?? process.platform;- const args = [- `--remote-debugging-port=${opts.cdpPort}`,- `--user-data-dir=${opts.userDataDir}`,- "--no-first-run",- "--no-default-browser-check",- "--disable-sync",- "--disable-background-networking",- "--disable-component-update",- "--disable-features=Translate,MediaRouter",- "--disable-session-crashed-bubble",- "--hide-crash-restore-bubble",- "--password-store=basic",- ];- if (opts.headless) {- args.push("--headless=new", "--disable-gpu");- }- if (platform === "linux") {- args.push("--disable-dev-shm-usage");- }- if (opts.extraArgs?.length) {- args.push(...opts.extraArgs);- }- return args;-}--export interface LaunchedChrome {- process: ChildProcess;- cdpPort: number;- cdpHttpUrl: string;- userDataDir: string;-}--/**- * Spawn Chrome and wait for its CDP HTTP endpoint to respond.- *- * Throws if Chrome exits before CDP becomes reachable, or if the readiness- * probe times out. Callers should catch and surface a friendly error- * (Chrome version too old, port already taken, etc.).- */-export async function launchChrome(- opts: ChromeLaunchOptions,- readyTimeoutMs = 15_000,-): Promise<LaunchedChrome> {- fs.mkdirSync(opts.userDataDir, { recursive: true });- clearChromeSingletonArtifacts(opts.userDataDir);-- const args = buildChromeLaunchArgs(opts);- const proc = spawn(opts.executablePath, args, {- stdio: ["ignore", "pipe", "pipe"],- detached: false,- });-- const cdpHttpUrl = `http://127.0.0.1:${opts.cdpPort}`;-- const stderrChunks: string[] = [];- proc.stderr?.on("data", (chunk: Buffer) => {- // Keep last ~4KB of stderr so we can include a hint in launch failures.- stderrChunks.push(chunk.toString("utf8"));- while (stderrChunks.join("").length > 4096) stderrChunks.shift();- });-- const earlyExit = new Promise<never>((_, reject) => {- proc.once("exit", (code, signal) => {- reject(- new Error(- `Chrome exited before CDP became ready (code=${code} signal=${signal}). ` +- `stderr tail: ${stderrChunks.join("").slice(-512)}`,- ),- );- });- });-- try {- await Promise.race([waitForCdpReady(cdpHttpUrl, readyTimeoutMs), earlyExit]);- } catch (err) {- if (proc.exitCode === null) proc.kill("SIGKILL");- throw err;- }-- return {- process: proc,- cdpPort: opts.cdpPort,- cdpHttpUrl,- userDataDir: opts.userDataDir,- };-}--/** Poll the CDP /json/version endpoint until it 200s or we time out. */-export async function waitForCdpReady(- cdpHttpUrl: string,- timeoutMs: number,- pollIntervalMs = 150,-): Promise<void> {- const deadline = Date.now() + timeoutMs;- let lastErr: unknown;- while (Date.now() < deadline) {- try {- const res = await fetch(`${cdpHttpUrl}/json/version`, {- signal: AbortSignal.timeout(Math.min(1000, timeoutMs)),- });- if (res.ok) return;- lastErr = new Error(`CDP probe returned status ${res.status}`);- } catch (err) {- lastErr = err;- }- await sleep(pollIntervalMs);- }- throw new Error(- `Chrome CDP at ${cdpHttpUrl} did not become ready within ${timeoutMs}ms` +- (lastErr ? `: ${(lastErr as Error).message ?? String(lastErr)}` : ""),- );-}--/** Graceful SIGTERM with SIGKILL fallback, then SingletonLock cleanup. */-export async function stopChrome(launched: LaunchedChrome, timeoutMs = 5_000): Promise<void> {- const { process: proc, userDataDir } = launched;- if (proc.exitCode === null && !proc.killed) {- proc.kill("SIGTERM");- await waitForExit(proc, timeoutMs);- if (proc.exitCode === null) {- proc.kill("SIGKILL");- await waitForExit(proc, 1_000);- }- }- clearChromeSingletonArtifacts(userDataDir);-}--function sleep(ms: number): Promise<void> {- return new Promise((resolve) => setTimeout(resolve, ms));-}--function waitForExit(proc: ChildProcess, timeoutMs: number): Promise<void> {- return new Promise((resolve) => {- if (proc.exitCode !== null) {- resolve();- return;- }- const timer = setTimeout(resolve, timeoutMs);- proc.once("exit", () => {- clearTimeout(timer);- resolve();- });- });-}diff --git a/notfair/src/server/browser/paths.test.ts b/notfair/src/server/browser/paths.test.tsdeleted file mode 100644index 216c6433..00000000--- a/notfair/src/server/browser/paths.test.ts+++ /dev/null@@ -1,97 +0,0 @@-import { describe, expect, it, vi } from "vitest";--// Point NOTFAIR_DATA_DIR at a tmpdir before importing the module under test.-vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-paths-"));-});--import {- CDP_PORT_RANGE_START,- CDP_PORT_RANGE_END,- allocateCdpPort,- isValidProjectSlug,- notfairDataDir,- resolveBrowserProfileDir,- resolveUserDataDir,-} from "./paths";--describe("notfairDataDir", () => {- it("uses NOTFAIR_DATA_DIR when set", () => {- expect(notfairDataDir()).toBe(process.env.NOTFAIR_DATA_DIR);- });-- it("falls back to ~/.notfair when unset", async () => {- const saved = process.env.NOTFAIR_DATA_DIR;- delete process.env.NOTFAIR_DATA_DIR;- try {- const { homedir } = await import("node:os");- const { join } = await import("node:path");- expect(notfairDataDir()).toBe(join(homedir(), ".notfair"));- } finally {- process.env.NOTFAIR_DATA_DIR = saved;- }- });-});--describe("isValidProjectSlug", () => {- it("accepts lowercase alphanumeric + hyphen slugs", () => {- expect(isValidProjectSlug("proj")).toBe(true);- expect(isValidProjectSlug("my-project-1")).toBe(true);- expect(isValidProjectSlug("a")).toBe(true);- });-- it("rejects empty, too-long, uppercase, leading-hyphen and invalid chars", () => {- expect(isValidProjectSlug("")).toBe(false);- expect(isValidProjectSlug("a".repeat(65))).toBe(false);- expect(isValidProjectSlug("Proj")).toBe(false);- expect(isValidProjectSlug("-proj")).toBe(false);- expect(isValidProjectSlug("proj_x")).toBe(false);- expect(isValidProjectSlug("proj space")).toBe(false);- });-- it("accepts a 64-char slug (boundary)", () => {- expect(isValidProjectSlug("a".repeat(64))).toBe(true);- });-});--describe("resolveBrowserProfileDir / resolveUserDataDir", () => {- it("builds paths under the data dir", () => {- const dir = resolveBrowserProfileDir("proj");- expect(dir).toContain("projects");- expect(dir).toContain("proj");- expect(dir.endsWith("browser")).toBe(true);- expect(resolveUserDataDir("proj").endsWith("user-data")).toBe(true);- });-- it("throws on an invalid slug", () => {- expect(() => resolveBrowserProfileDir("BAD SLUG")).toThrow(/Invalid project slug/);- expect(() => resolveUserDataDir("_bad")).toThrow(/Invalid project slug/);- });-});--describe("allocateCdpPort", () => {- it("is deterministic and within range", () => {- const p1 = allocateCdpPort("proj");- const p2 = allocateCdpPort("proj");- expect(p1).toBe(p2);- expect(p1).toBeGreaterThanOrEqual(CDP_PORT_RANGE_START);- expect(p1).toBeLessThanOrEqual(CDP_PORT_RANGE_END);- });-- it("throws on an invalid slug", () => {- expect(() => allocateCdpPort("Bad")).toThrow(/Invalid project slug/);- });-- it("maps different slugs across the range", () => {- const ports = new Set(- ["alpha", "beta", "gamma", "delta", "omega"].map(allocateCdpPort),- );- for (const p of ports) {- expect(p).toBeGreaterThanOrEqual(CDP_PORT_RANGE_START);- expect(p).toBeLessThanOrEqual(CDP_PORT_RANGE_END);- }- });-});diff --git a/notfair/src/server/browser/paths.ts b/notfair/src/server/browser/paths.tsdeleted file mode 100644index 1fdcb6d9..00000000--- a/notfair/src/server/browser/paths.ts+++ /dev/null@@ -1,69 +0,0 @@-/**- * Per-workspace browser profile path + port resolution.- *- * Layout under ~/.notfair/ (override via NOTFAIR_DATA_DIR):- *- * projects/<slug>/browser/- * user-data/ <- Chrome --user-data-dir (cookies, login state)- * state.json <- last-launched metadata (signed_in_at, etc.)- *- * CDP ports are hashed deterministically from the project slug into the- * 19000-19099 range. We intentionally avoid the 18800-18899 range other tools use- * so both can run on the same machine without colliding.- */-import { createHash } from "node:crypto";-import { homedir } from "node:os";-import { join } from "node:path";--/** First CDP port in our managed range. */-export const CDP_PORT_RANGE_START = 19000;-/** Last CDP port in our managed range. */-export const CDP_PORT_RANGE_END = 19099;--const PROJECT_SLUG_REGEX = /^[a-z0-9][a-z0-9-]*$/;-const MAX_SLUG_LENGTH = 64;--/** Resolve the NotFair data dir (matches db.ts / agent-meta.ts convention). */-export function notfairDataDir(): string {- return process.env.NOTFAIR_DATA_DIR ?? join(homedir(), ".notfair");-}--/** True when slug matches the lowercase-alphanum + hyphen format the rest of NotFair uses. */-export function isValidProjectSlug(slug: string): boolean {- if (!slug || slug.length > MAX_SLUG_LENGTH) return false;- return PROJECT_SLUG_REGEX.test(slug);-}--/** Per-project browser dir (parent of user-data + metadata files). */-export function resolveBrowserProfileDir(projectSlug: string): string {- assertValidSlug(projectSlug);- return join(notfairDataDir(), "projects", projectSlug, "browser");-}--/** Chrome --user-data-dir for the workspace. Persists cookies / login state. */-export function resolveUserDataDir(projectSlug: string): string {- return join(resolveBrowserProfileDir(projectSlug), "user-data");-}--/**- * Deterministic CDP port for a project slug.- *- * Same slug always hashes to the same port across restarts, so a relaunched- * NotFair process can reattach to a still-running Chrome without- * re-discovering ports.- */-export function allocateCdpPort(projectSlug: string): number {- assertValidSlug(projectSlug);- const span = CDP_PORT_RANGE_END - CDP_PORT_RANGE_START + 1;- const hash = createHash("sha256").update(projectSlug).digest();- const offset = hash.readUInt32BE(0) % span;- return CDP_PORT_RANGE_START + offset;-}--function assertValidSlug(slug: string): void {- if (!isValidProjectSlug(slug)) {- throw new Error(- `Invalid project slug "${slug}": must match ${PROJECT_SLUG_REGEX} and be <=${MAX_SLUG_LENGTH} chars`,- );- }-}diff --git a/notfair/src/server/browser/session.test.ts b/notfair/src/server/browser/session.test.tsdeleted file mode 100644index e74c09ac..00000000--- a/notfair/src/server/browser/session.test.ts+++ /dev/null@@ -1,285 +0,0 @@-import { EventEmitter } from "node:events";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-session-"));-});--const mocks = vi.hoisted(() => ({- findChromeExecutable: vi.fn(),- launchChrome: vi.fn(),- stopChrome: vi.fn(),-}));--vi.mock("./chrome", () => ({- findChromeExecutable: mocks.findChromeExecutable,- launchChrome: mocks.launchChrome,- stopChrome: mocks.stopChrome,-}));--import {- _sessionsByProject,- _stopIdleChecker,- checkIdleSessions,- ensureIdleChecker,- getOrLaunchBrowser,- getSessionStatus,- registerShutdownHooks,- stopAllBrowsers,- stopBrowser,- type BrowserSession,-} from "./session";--function launched(over: Record<string, unknown> = {}) {- const process = new EventEmitter() as EventEmitter & {- exitCode: number | null;- killed: boolean;- };- process.exitCode = null;- process.killed = false;- return {- process,- cdpPort: 19_223,- cdpHttpUrl: "http://127.0.0.1:19223",- userDataDir: "/tmp/profile",- ...over,- };-}--function browser(contexts: unknown[] = [{}]) {- return {- contexts: vi.fn(() => contexts),- close: vi.fn(async () => {}),- };-}--function cachedSession(slug: string, over: Partial<BrowserSession> = {}): BrowserSession {- const launchedChrome = launched();- return {- projectSlug: slug,- cdpPort: 19_223,- cdpHttpUrl: launchedChrome.cdpHttpUrl,- userDataDir: launchedChrome.userDataDir,- launched: launchedChrome as never,- browser: browser() as never,- context: {} as never,- launchedAt: 1_000,- lastActivityAt: 2_000,- ...over,- };-}--beforeEach(() => {- vi.clearAllMocks();- _sessionsByProject.clear();- _stopIdleChecker();- delete process.env.NOTFAIR_BROWSER_HEADLESS;- delete process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS;- mocks.findChromeExecutable.mockReturnValue("/Applications/Chrome");- mocks.stopChrome.mockResolvedValue(undefined);-});--afterEach(async () => {- vi.useRealTimers();- await stopAllBrowsers();- _sessionsByProject.clear();- _stopIdleChecker();-});--describe("getOrLaunchBrowser", () => {- it("launches, attaches to the default context, and caches the session", async () => {- const chrome = launched();- const attached = browser([{ name: "default" }]);- const launch = vi.fn(async () => chrome as never);- const connect = vi.fn(async () => attached as never);-- const first = await getOrLaunchBrowser("acme", {- headless: true,- executablePath: "/custom/chrome",- extraArgs: ["--foo"],- launch,- connectOverCDP: connect,- });- expect(launch).toHaveBeenCalledWith(- expect.objectContaining({- executablePath: "/custom/chrome",- headless: true,- extraArgs: ["--foo"],- }),- );- expect(connect).toHaveBeenCalledWith(chrome.cdpHttpUrl);- expect(first.context).toEqual({ name: "default" });-- vi.setSystemTime(9_000);- const second = await getOrLaunchBrowser("acme", { launch, connectOverCDP: connect });- expect(second).toBe(first);- expect(second.lastActivityAt).toBe(9_000);- expect(launch).toHaveBeenCalledTimes(1);- });-- it("deduplicates concurrent launches", async () => {- let release!: () => void;- const gate = new Promise<void>((resolve) => { release = resolve; });- const chrome = launched();- const launch = vi.fn(async () => {- await gate;- return chrome as never;- });- const connect = vi.fn(async () => browser() as never);- const a = getOrLaunchBrowser("parallel", { launch, connectOverCDP: connect });- const b = getOrLaunchBrowser("parallel", { launch, connectOverCDP: connect });- expect(launch).toHaveBeenCalledTimes(1);- release();- const [one, two] = await Promise.all([a, b]);- expect(one).toBe(two);- });-- it("drops a dead cached session and relaunches", async () => {- const dead = cachedSession("dead");- Object.defineProperty(dead.launched.process, "exitCode", { value: 1 });- _sessionsByProject.set("dead", dead);- const fresh = launched();- const result = await getOrLaunchBrowser("dead", {- launch: vi.fn(async () => fresh as never),- connectOverCDP: vi.fn(async () => browser() as never),- });- expect(result).not.toBe(dead);- });-- it("fails clearly when Chrome cannot be found", async () => {- mocks.findChromeExecutable.mockReturnValue(null);- await expect(getOrLaunchBrowser("acme")).rejects.toThrow(/Could not find Chrome/);- });-- it("stops Chrome if CDP attachment fails", async () => {- const chrome = launched();- await expect(- getOrLaunchBrowser("acme", {- launch: vi.fn(async () => chrome as never),- connectOverCDP: vi.fn(async () => { throw new Error("refused"); }),- }),- ).rejects.toThrow(/Failed to attach.*refused/);- expect(mocks.stopChrome).toHaveBeenCalledWith(chrome);- });-- it("reports an incomplete package when playwright-core is missing browsers.json", async () => {- const chrome = launched();- await expect(- getOrLaunchBrowser("acme", {- launch: vi.fn(async () => chrome as never),- connectOverCDP: vi.fn(async () => {- throw new Error(- "Cannot find module '/pkg/.next/node_modules/playwright-core-b643089f39648130/browsers.json'",- );- }),- }),- ).rejects.toThrow(/NotFair package is incomplete.*browsers\.json/);- expect(mocks.stopChrome).toHaveBeenCalledWith(chrome);- expect(_sessionsByProject.has("acme")).toBe(false);- });-- it("closes both handles when CDP has no default context", async () => {- const chrome = launched();- const attached = browser([]);- await expect(- getOrLaunchBrowser("acme", {- launch: vi.fn(async () => chrome as never),- connectOverCDP: vi.fn(async () => attached as never),- }),- ).rejects.toThrow(/no default context/);- expect(attached.close).toHaveBeenCalled();- expect(mocks.stopChrome).toHaveBeenCalledWith(chrome);- });-- it.each([- ["1", true],- ["TRUE", true],- ["0", false],- ["false", false],- ])("honors NOTFAIR_BROWSER_HEADLESS=%s", async (value, expected) => {- process.env.NOTFAIR_BROWSER_HEADLESS = value;- const launch = vi.fn(async () => launched() as never);- await getOrLaunchBrowser(`env-${value.toLowerCase()}`, {- launch,- connectOverCDP: vi.fn(async () => browser() as never),- });- expect(launch).toHaveBeenCalledWith(expect.objectContaining({ headless: expected }));- });-- it("evicts a session when Chrome exits", async () => {- const chrome = launched();- await getOrLaunchBrowser("evict", {- launch: vi.fn(async () => chrome as never),- connectOverCDP: vi.fn(async () => browser() as never),- });- chrome.process.emit("exit", 1);- expect(_sessionsByProject.has("evict")).toBe(false);- });-});--describe("shutdown and status", () => {- it("stopBrowser is a no-op for missing sessions and tolerates close failures", async () => {- await expect(stopBrowser("missing")).resolves.toBeUndefined();- const session = cachedSession("acme");- vi.mocked(session.browser.close).mockRejectedValue(new Error("dead"));- mocks.stopChrome.mockRejectedValueOnce(new Error("already stopped"));- _sessionsByProject.set("acme", session);- await expect(stopBrowser("acme")).resolves.toBeUndefined();- expect(_sessionsByProject.has("acme")).toBe(false);- });-- it("stops all registered projects", async () => {- _sessionsByProject.set("one", cachedSession("one"));- _sessionsByProject.set("two", cachedSession("two"));- await stopAllBrowsers();- expect(_sessionsByProject.size).toBe(0);- expect(mocks.stopChrome).toHaveBeenCalledTimes(2);- });-- it("reports stopped and running session details", () => {- vi.useFakeTimers();- vi.setSystemTime(5_000);- process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS = "1234";- expect(getSessionStatus("none")).toMatchObject({- running: false,- idleTimeoutMs: 1234,- });- _sessionsByProject.set("acme", cachedSession("acme"));- expect(getSessionStatus("acme")).toMatchObject({- running: true,- launchedAt: 1_000,- uptimeMs: 4_000,- idleMs: 3_000,- idleTimeoutMs: 1234,- });- });-- it("uses the default idle timeout for empty, invalid, and nonpositive values", () => {- for (const value of [undefined, "nope", "0", "-4"]) {- if (value === undefined) delete process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS;- else process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS = value;- expect(getSessionStatus("acme").idleTimeoutMs).toBe(300_000);- }- });-- it("stops only sessions at or beyond the idle threshold", async () => {- process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS = "1000";- _sessionsByProject.set("idle", cachedSession("idle", { lastActivityAt: 1_000 }));- _sessionsByProject.set("active", cachedSession("active", { lastActivityAt: 1_001 }));- await expect(checkIdleSessions(2_000)).resolves.toEqual(["idle"]);- expect(_sessionsByProject.has("idle")).toBe(false);- expect(_sessionsByProject.has("active")).toBe(true);- });-- it("installs maintenance hooks and starts only one idle timer", () => {- registerShutdownHooks();- registerShutdownHooks();- vi.useFakeTimers();- ensureIdleChecker();- ensureIdleChecker();- expect(vi.getTimerCount()).toBe(1);- });-});diff --git a/notfair/src/server/browser/session.ts b/notfair/src/server/browser/session.tsdeleted file mode 100644index f366e394..00000000--- a/notfair/src/server/browser/session.ts+++ /dev/null@@ -1,330 +0,0 @@-/**- * Workspace-scoped Chrome session lifecycle.- *- * One Chrome process per project, lazily launched the first time a browser- * tool runs for that project. Chrome's user-data-dir lock prevents a second- * concurrent instance, so all agents within a workspace share the same- * Chrome and coordinate via labeled tabs (see tabs.ts).- *- * Shutdown happens four ways:- * 1. User clicks Settings → Workspace browser → Stop (manual).- * 2. NotFair process exits — SIGINT/SIGTERM/beforeExit handlers- * registered automatically on the first launch.- * 3. User Cmd-Q's the Chrome window — process exit event evicts the- * cached session so the next browser_open relaunches.- * 4. Idle auto-shutdown: a 30s tick checks for sessions with no- * activity (no getOrLaunchBrowser call) in the last- * NOTFAIR_BROWSER_IDLE_TIMEOUT_MS (default 5 minutes).- */-import type { Browser, BrowserContext } from "playwright-core";--import {- type ChromeLaunchOptions,- type LaunchedChrome,- findChromeExecutable,- launchChrome,- stopChrome,-} from "./chrome";-import { allocateCdpPort, resolveUserDataDir } from "./paths";--export interface BrowserSession {- projectSlug: string;- cdpPort: number;- cdpHttpUrl: string;- userDataDir: string;- /** Live Chrome subprocess + metadata from launchChrome(). */- launched: LaunchedChrome;- /** Playwright Browser handle (CDP-attached). */- browser: Browser;- /** Persistent default context — owns the cookies/storage from user-data-dir. */- context: BrowserContext;- /** Wall-clock launch time, for diagnostics. */- launchedAt: number;- /** Wall-clock of the most recent getOrLaunchBrowser call. Drives idle timeout. */- lastActivityAt: number;-}--const DEFAULT_IDLE_TIMEOUT_MS = 5 * 60 * 1000;-const IDLE_CHECK_INTERVAL_MS = 30_000;--/**- * Per-process registry of running browser sessions, keyed by project slug.- * Exported for tests; production code goes through getOrLaunchBrowser().- */-export const _sessionsByProject = new Map<string, BrowserSession>();--/**- * In-flight launch promises, keyed by project slug. Without this, two- * concurrent tool calls on the same project would each kick off a Chrome- * launch, the second hitting Chrome's SingletonLock and failing.- */-const _launchPromises = new Map<string, Promise<BrowserSession>>();--export interface GetOrLaunchOptions {- /** Force headless. Default: respect NOTFAIR_BROWSER_HEADLESS env (default false on macOS, true on linux). */- headless?: boolean;- /** Override chrome executable path. Falls back to findChromeExecutable(). */- executablePath?: string;- /** Extra Chrome args. Useful for tests + advanced users. */- extraArgs?: string[];- /** Override the Playwright connect function (for tests). */- connectOverCDP?: (cdpHttpUrl: string) => Promise<Browser>;- /** Override the Chrome launcher (for tests). */- launch?: (opts: ChromeLaunchOptions) => Promise<LaunchedChrome>;-}--/**- * Lazily launch (or reuse) the workspace Chrome for a project.- *- * Idempotent: concurrent callers share the same launch promise. Subsequent- * calls after a successful launch return the cached session immediately.- */-export async function getOrLaunchBrowser(- projectSlug: string,- opts: GetOrLaunchOptions = {},-): Promise<BrowserSession> {- // Every entry point goes through here, so this is also the right place- // to install our process-lifetime maintenance: shutdown hooks (cleanup on- // NotFair exit) + idle checker (stop unused browsers).- registerShutdownHooks();- ensureIdleChecker();-- const existing = _sessionsByProject.get(projectSlug);- if (existing && isSessionAlive(existing)) {- existing.lastActivityAt = Date.now();- return existing;- }- if (existing) {- // Stale entry from a crashed Chrome — clean it up before relaunching.- _sessionsByProject.delete(projectSlug);- }-- const inflight = _launchPromises.get(projectSlug);- if (inflight) return inflight;-- const promise = launchSession(projectSlug, opts).finally(() => {- _launchPromises.delete(projectSlug);- });- _launchPromises.set(projectSlug, promise);- return promise;-}--async function launchSession(- projectSlug: string,- opts: GetOrLaunchOptions,-): Promise<BrowserSession> {- const executablePath = opts.executablePath ?? findChromeExecutable();- if (!executablePath) {- throw new Error(- "Could not find Chrome / Chromium. Install Chrome, or set NOTFAIR_CHROME_PATH to the binary.",- );- }-- const userDataDir = resolveUserDataDir(projectSlug);- const cdpPort = allocateCdpPort(projectSlug);- const headless = resolveHeadless(opts.headless);-- const launch = opts.launch ?? launchChrome;- const launched = await launch({- executablePath,- userDataDir,- cdpPort,- headless,- extraArgs: opts.extraArgs,- });-- let browser: Browser;- try {- const connect = opts.connectOverCDP ?? defaultConnectOverCDP;- browser = await connect(launched.cdpHttpUrl);- } catch (err) {- await stopChrome(launched).catch(() => {});- const message = (err as Error).message ?? String(err);- if (/playwright-core[^'"]*[\\/]browsers\.json/.test(message)) {- throw new Error(- "The installed NotFair package is incomplete: playwright-core is missing browsers.json, so the workspace browser cannot start. Reinstall or upgrade NotFair to repair it.",- );- }- throw new Error(- `Failed to attach Playwright to Chrome CDP at ${launched.cdpHttpUrl}: ${message}`,- );- }-- const contexts = browser.contexts();- if (contexts.length === 0) {- await browser.close().catch(() => {});- await stopChrome(launched).catch(() => {});- throw new Error(- "Connected to Chrome CDP but no default context exists — Chrome may have launched in an unexpected mode.",- );- }- const context = contexts[0]!;-- const session: BrowserSession = {- projectSlug,- cdpPort: launched.cdpPort,- cdpHttpUrl: launched.cdpHttpUrl,- userDataDir: launched.userDataDir,- launched,- browser,- context,- launchedAt: Date.now(),- lastActivityAt: Date.now(),- };- _sessionsByProject.set(projectSlug, session);-- // If Chrome exits unexpectedly, evict the cached session so the next call- // triggers a fresh launch instead of returning a dead handle.- launched.process.once("exit", () => {- if (_sessionsByProject.get(projectSlug) === session) {- _sessionsByProject.delete(projectSlug);- }- });-- return session;-}--async function defaultConnectOverCDP(cdpHttpUrl: string): Promise<Browser> {- // Lazy import keeps playwright-core out of the cold-start path for- // NotFair features that don't touch the browser.- const { chromium } = await import("playwright-core");- return chromium.connectOverCDP(cdpHttpUrl);-}--function resolveHeadless(explicit?: boolean): boolean {- if (explicit !== undefined) return explicit;- const env = process.env.NOTFAIR_BROWSER_HEADLESS?.trim().toLowerCase();- if (env === "1" || env === "true") return true;- if (env === "0" || env === "false") return false;- return process.platform === "linux"; // headed on macOS by default, headless on linux servers-}--function isSessionAlive(session: BrowserSession): boolean {- return session.launched.process.exitCode === null && !session.launched.process.killed;-}--/**- * Tear down a single project's browser session. Used by tests + the- * onboarding "restart browser" flow.- */-export async function stopBrowser(projectSlug: string): Promise<void> {- const session = _sessionsByProject.get(projectSlug);- if (!session) return;- _sessionsByProject.delete(projectSlug);- try {- await session.browser.close();- } catch {- // Browser may already be dead; ignore.- }- await stopChrome(session.launched).catch(() => {});-}--/** Tear down every active session — call on process exit. */-export async function stopAllBrowsers(): Promise<void> {- const slugs = [..._sessionsByProject.keys()];- await Promise.all(slugs.map((slug) => stopBrowser(slug)));-}--let _shutdownHooksInstalled = false;-/**- * Register SIGINT/SIGTERM/beforeExit handlers that stop every browser- * session. Idempotent — safe to call from multiple call sites.- * Auto-invoked from getOrLaunchBrowser so cron-triggered launches are- * covered too, not just UI launches via /api/browser/launch.- */-export function registerShutdownHooks(): void {- if (_shutdownHooksInstalled) return;- _shutdownHooksInstalled = true;-- const handler = () => {- void stopAllBrowsers();- };- process.once("SIGINT", handler);- process.once("SIGTERM", handler);- process.once("beforeExit", handler);-}--// ── Idle auto-shutdown ──────────────────────────────────────────────────--function resolveIdleTimeoutMs(): number {- const raw = process.env.NOTFAIR_BROWSER_IDLE_TIMEOUT_MS?.trim();- if (!raw) return DEFAULT_IDLE_TIMEOUT_MS;- const n = Number(raw);- if (!Number.isFinite(n) || n <= 0) return DEFAULT_IDLE_TIMEOUT_MS;- return n;-}--let _idleCheckerInterval: ReturnType<typeof setInterval> | null = null;--/**- * Start the periodic idle check. Idempotent — call freely. The Node- * interval is .unref'd so it never keeps the process alive on its own.- *- * Tests cancel via _stopIdleChecker() in afterEach.- */-export function ensureIdleChecker(): void {- if (_idleCheckerInterval) return;- _idleCheckerInterval = setInterval(() => {- void checkIdleSessions();- }, IDLE_CHECK_INTERVAL_MS);- _idleCheckerInterval.unref?.();-}--/**- * Find sessions with no getOrLaunchBrowser call inside the idle window- * and stop them. Exported for tests; production code calls via the timer.- */-export async function checkIdleSessions(now: number = Date.now()): Promise<string[]> {- const idleTimeoutMs = resolveIdleTimeoutMs();- const slugsToStop: string[] = [];- for (const [slug, session] of _sessionsByProject) {- if (now - session.lastActivityAt >= idleTimeoutMs) {- slugsToStop.push(slug);- }- }- await Promise.all(slugsToStop.map((slug) => stopBrowser(slug)));- return slugsToStop;-}--/** Test-only: cancel the periodic checker. */-export function _stopIdleChecker(): void {- if (_idleCheckerInterval) {- clearInterval(_idleCheckerInterval);- _idleCheckerInterval = null;- }-}--/** Status snapshot for browser_status MCP tool + diagnostics. */-export interface BrowserSessionStatus {- projectSlug: string;- running: boolean;- cdpPort: number;- userDataDir: string;- launchedAt?: number;- uptimeMs?: number;- /** Milliseconds since the last getOrLaunchBrowser call — what the idle- * shutdown timer compares against. */- idleMs?: number;- /** The current idle-shutdown threshold (env-overridable). */- idleTimeoutMs: number;-}--export function getSessionStatus(projectSlug: string): BrowserSessionStatus {- const session = _sessionsByProject.get(projectSlug);- const cdpPort = allocateCdpPort(projectSlug);- const userDataDir = resolveUserDataDir(projectSlug);- const idleTimeoutMs = resolveIdleTimeoutMs();- if (!session) {- return { projectSlug, running: false, cdpPort, userDataDir, idleTimeoutMs };- }- return {- projectSlug,- running: isSessionAlive(session),- cdpPort: session.cdpPort,- userDataDir: session.userDataDir,- launchedAt: session.launchedAt,- uptimeMs: Date.now() - session.launchedAt,- idleMs: Date.now() - session.lastActivityAt,- idleTimeoutMs,- };-}diff --git a/notfair/src/server/browser/standalone-integrity.test.ts b/notfair/src/server/browser/standalone-integrity.test.tsdeleted file mode 100644index d88f7d38..00000000--- a/notfair/src/server/browser/standalone-integrity.test.ts+++ /dev/null@@ -1,35 +0,0 @@-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { afterEach, describe, expect, it } from "vitest";--import { findPlaywrightDirsMissingBrowsersJson } from "../../../scripts/lib/standalone-integrity.mjs";--function pkg(root: string, rel: string, withBrowsersJson: boolean) {- const dir = join(root, rel);- mkdirSync(dir, { recursive: true });- writeFileSync(join(dir, "package.json"), "{}");- if (withBrowsersJson) writeFileSync(join(dir, "browsers.json"), "{}");- return dir;-}--describe("standalone package integrity", () => {- let root: string;- afterEach(() => rmSync(root, { recursive: true, force: true }));-- it("flags playwright-core copies without browsers.json, including hashed Turbopack aliases", () => {- root = mkdtempSync(join(tmpdir(), "notfair-standalone-"));- pkg(root, "node_modules/.pnpm/[email protected]/node_modules/playwright-core", true);- const alias = pkg(root, ".next/node_modules/playwright-core-b643089f39648130", false);-- expect(findPlaywrightDirsMissingBrowsersJson(root)).toEqual([alias]);- });-- it("passes a tree where every playwright-core copy ships browsers.json", () => {- root = mkdtempSync(join(tmpdir(), "notfair-standalone-"));- pkg(root, "node_modules/playwright-core", true);- pkg(root, ".next/node_modules/playwright-core-b643089f39648130", true);-- expect(findPlaywrightDirsMissingBrowsersJson(root)).toEqual([]);- });-});diff --git a/notfair/src/server/browser/tabs.test.ts b/notfair/src/server/browser/tabs.test.tsdeleted file mode 100644index 8da06e58..00000000--- a/notfair/src/server/browser/tabs.test.ts+++ /dev/null@@ -1,152 +0,0 @@-import { EventEmitter } from "node:events";-import { beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({ getOrLaunchBrowser: vi.fn() }));-vi.mock("./session", () => ({ getOrLaunchBrowser: mocks.getOrLaunchBrowser }));--import {- _resetTabRegistries,- assertValidLabel,- closeTab,- getTab,- listTabs,- openTab,-} from "./tabs";--function fakePage(url = "about:blank", title = "Blank") {- const events = new EventEmitter();- let closed = false;- return {- url: vi.fn(() => url),- title: vi.fn(async () => title),- goto: vi.fn(async () => {}),- isClosed: vi.fn(() => closed),- close: vi.fn(async () => { closed = true; events.emit("close"); }),- once: events.once.bind(events),- emitClose: () => events.emit("close"),- setClosed: (value: boolean) => { closed = value; },- };-}--function fakeSession(initialPages: ReturnType<typeof fakePage>[] = []) {- const events = new EventEmitter();- const pages = [...initialPages];- return {- context: {- pages: vi.fn(() => pages),- newPage: vi.fn(async () => {- const p = fakePage();- pages.push(p);- return p;- }),- on: events.on.bind(events),- },- pages,- closeContext: () => events.emit("close"),- };-}--beforeEach(() => {- vi.clearAllMocks();- _resetTabRegistries();- mocks.getOrLaunchBrowser.mockResolvedValue(fakeSession() as never);-});--it("validates labels at both boundaries", () => {- for (const valid of ["a", "Goal_1", "tab-2", "a".repeat(64)]) {- expect(() => assertValidLabel(valid)).not.toThrow();- }- for (const invalid of ["", "-bad", "has space", "a".repeat(65)]) {- expect(() => assertValidLabel(invalid)).toThrow(/Invalid tab label/);- }-});--it("adopts initial pages and opens auto-numbered tabs", async () => {- const initial = fakePage("https://initial", "Initial");- const session = fakeSession([initial]);- mocks.getOrLaunchBrowser.mockResolvedValue(session as never);- expect(await getTab("acme", "t1")).toBe(initial);- const opened = await openTab("acme");- expect(opened).toMatchObject({ id: "t2", label: "t2", url: "about:blank" });- expect(session.context.newPage).toHaveBeenCalled();-});--it("opens and reuses a labeled tab with navigation options", async () => {- const session = fakeSession();- mocks.getOrLaunchBrowser.mockResolvedValue(session as never);- const first = await openTab("acme", {- label: "reports",- url: "https://example.com",- waitUntil: "networkidle",- timeoutMs: 55,- });- const created = session.pages[0]!;- expect(first.id).toBe("reports");- expect(created.goto).toHaveBeenCalledWith("https://example.com", { waitUntil: "networkidle", timeout: 55 });- await openTab("acme", { label: "reports", url: "https://next" });- expect(session.context.newPage).toHaveBeenCalledTimes(1);- expect(created.goto).toHaveBeenLastCalledWith("https://next", { waitUntil: "load", timeout: 30_000 });- await expect(openTab("acme", { label: " bad" })).rejects.toThrow(/Invalid tab label/);-});--it("reconciles external pages and returns fresh titles", async () => {- const known = fakePage("https://known", "Known");- const session = fakeSession([known]);- mocks.getOrLaunchBrowser.mockResolvedValue(session as never);- await listTabs("acme");- const external = fakePage("https://external", "External");- session.pages.push(external);- const handles = await listTabs("acme");- expect(handles).toEqual([- { id: "t1", label: "t1", url: "https://known", title: "Known" },- { id: "t2", label: "t2", url: "https://external", title: "External" },- ]);-});--it("drops closed pages and falls back when URL/title access throws", async () => {- const closed = fakePage();- closed.setClosed(true);- const broken = fakePage();- broken.url.mockImplementation(() => { throw new Error("detached"); });- broken.title.mockRejectedValue(new Error("detached"));- const session = fakeSession([closed, broken]);- mocks.getOrLaunchBrowser.mockResolvedValue(session as never);- await expect(listTabs("acme")).resolves.toEqual([- { id: "t2", label: "t2", url: "", title: "" },- ]);-});--it("returns false for missing tabs and closes live tabs", async () => {- const session = fakeSession();- mocks.getOrLaunchBrowser.mockResolvedValue(session as never);- await expect(closeTab("acme", "missing")).resolves.toBe(false);- await openTab("acme", { label: "one" });- await expect(closeTab("acme", "one")).resolves.toBe(true);- expect(session.pages[0]!.close).toHaveBeenCalled();- await expect(getTab("acme", "one")).resolves.toBeNull();-});--it("tolerates close failures and cleans up event-driven closures", async () => {- const p = fakePage();- p.close.mockRejectedValue(new Error("already gone"));- const session = fakeSession([p]);- mocks.getOrLaunchBrowser.mockResolvedValue(session as never);- await expect(closeTab("acme", "t1")).resolves.toBe(true);-- _resetTabRegistries();- p.close.mockResolvedValue(undefined);- p.setClosed(false);- await getTab("acme", "t1");- p.emitClose();- await expect(getTab("acme", "t1")).resolves.toBeNull();-});--it("rebuilds the registry when the browser session changes and clears on context close", async () => {- const first = fakeSession([fakePage("first")]);- const second = fakeSession([fakePage("second")]);- mocks.getOrLaunchBrowser.mockResolvedValueOnce(first as never).mockResolvedValue(second as never);- expect(await getTab("acme", "t1")).toBe(first.pages[0]);- expect(await getTab("acme", "t1")).toBe(second.pages[0]);- second.closeContext();- expect(await getTab("acme", "t1")).toBeNull();-});diff --git a/notfair/src/server/browser/tabs.ts b/notfair/src/server/browser/tabs.tsdeleted file mode 100644index 560cb5bd..00000000--- a/notfair/src/server/browser/tabs.ts+++ /dev/null@@ -1,209 +0,0 @@-/**- * Labeled-tab registry for a workspace browser session.- *- * Each agent gets a stable handle (its agent id, or an- * auto-generated "t1", "t2", ...) that survives across MCP tool calls.- * Pages added/removed from the underlying BrowserContext are reconciled so- * agent-supplied targetIds keep resolving even when the user opens or- * closes tabs in the headed Chrome.- */-import type { Page } from "playwright-core";--import { getOrLaunchBrowser, type BrowserSession } from "./session";--const TAB_LABEL_REGEX = /^[a-z0-9][a-z0-9_\-]{0,63}$/i;--export interface TabHandle {- /** Stable id the agent passes back. Equals `label` when one was provided. */- id: string;- /** Human label (matches id when none was set by the caller). */- label: string;- /** Best-effort current URL — may be "about:blank" or stale until next snapshot. */- url: string;- /** Best-effort current title. */- title: string;-}--interface TabRegistry {- /** label/id → Page */- byId: Map<string, Page>;- /** Page → label (reverse lookup so we can rebuild handles after a list) */- labelByPage: WeakMap<Page, string>;- /** Counter for auto-generated ids ("t1", "t2", ...). */- autoCounter: number;- /** Cached project's BrowserSession; we re-validate on each call. */- session: BrowserSession;-}--const _registries = new Map<string, TabRegistry>();--async function getRegistry(projectSlug: string): Promise<TabRegistry> {- const session = await getOrLaunchBrowser(projectSlug);- let registry = _registries.get(projectSlug);- if (!registry || registry.session !== session) {- registry = createRegistry(session);- _registries.set(projectSlug, registry);- }- return registry;-}--function createRegistry(session: BrowserSession): TabRegistry {- const registry: TabRegistry = {- byId: new Map(),- labelByPage: new WeakMap(),- autoCounter: 0,- session,- };-- // Pre-adopt any pages already on the context (Chrome opens an about:blank- // on first launch). We do NOT subscribe to context.on("page") — openTab- // owns labeling, and externally-opened pages are reconciled lazily by- // listTabs(). Subscribing would race with openTab and produce duplicate- // entries for every labeled tab.- for (const page of session.context.pages()) {- adoptPage(registry, page, undefined);- }- session.context.on("close", () => {- registry.byId.clear();- });- return registry;-}--function adoptPage(- registry: TabRegistry,- page: Page,- explicitLabel: string | undefined,-): TabHandle {- const existing = registry.labelByPage.get(page);- if (existing && registry.byId.get(existing) === page) {- return handleForPage(page, existing);- }- const label = explicitLabel ?? `t${++registry.autoCounter}`;- registry.byId.set(label, page);- registry.labelByPage.set(page, label);-- page.once("close", () => {- if (registry.byId.get(label) === page) {- registry.byId.delete(label);- }- });- return handleForPage(page, label);-}--function handleForPage(page: Page, label: string): TabHandle {- return {- id: label,- label,- url: safe(() => page.url()),- title: "", // populated on demand to avoid eagerly hitting the page on every list- };-}--function safe<T>(fn: () => T, fallback = ""): T | string {- try {- return fn();- } catch {- return fallback;- }-}--/** Validate a caller-supplied tab label. Throws on bad input. */-export function assertValidLabel(label: string): void {- if (!TAB_LABEL_REGEX.test(label)) {- throw new Error(- `Invalid tab label "${label}": must be 1-64 chars of [A-Za-z0-9_-], starting with alphanumeric`,- );- }-}--export interface OpenTabOptions {- /** Stable handle for future calls. Defaults to an auto id "t1"/"t2"/... */- label?: string;- /** Initial URL. If omitted, the tab is left at about:blank. */- url?: string;- /** Wait condition before returning. Default: "load". */- waitUntil?: "load" | "domcontentloaded" | "networkidle" | "commit";- /** Per-navigation timeout. Default: 30s. */- timeoutMs?: number;-}--/**- * Open a new tab. If `label` is supplied and already exists, reuses the- * existing tab and (optionally) navigates it — this matches the- * "reuse labeled tab" pattern that avoids duplicates on retries.- */-export async function openTab(- projectSlug: string,- opts: OpenTabOptions = {},-): Promise<TabHandle> {- const registry = await getRegistry(projectSlug);- if (opts.label) assertValidLabel(opts.label);-- let page: Page;- let label: string;- if (opts.label && registry.byId.has(opts.label)) {- page = registry.byId.get(opts.label)!;- label = opts.label;- } else {- page = await registry.session.context.newPage();- const handle = adoptPage(registry, page, opts.label);- label = handle.label;- }-- if (opts.url) {- await page.goto(opts.url, {- waitUntil: opts.waitUntil ?? "load",- timeout: opts.timeoutMs ?? 30_000,- });- }-- return handleForPage(page, label);-}--/** Resolve a caller-supplied ref ("label", "t1", or raw guid) to a live Page. */-export async function getTab(projectSlug: string, ref: string): Promise<Page | null> {- const registry = await getRegistry(projectSlug);- return registry.byId.get(ref) ?? null;-}--/** List every tab the registry knows about, with up-to-date url/title. */-export async function listTabs(projectSlug: string): Promise<TabHandle[]> {- const registry = await getRegistry(projectSlug);- // Sync against actual pages — context.pages() is the source of truth.- for (const page of registry.session.context.pages()) {- if (!registry.labelByPage.has(page)) {- adoptPage(registry, page, undefined);- }- }- const handles: TabHandle[] = [];- for (const [label, page] of registry.byId.entries()) {- if (page.isClosed()) {- registry.byId.delete(label);- continue;- }- handles.push({- id: label,- label,- url: safe(() => page.url()),- title: await page.title().catch(() => ""),- });- }- return handles;-}--/** Close the tab and drop it from the registry. */-export async function closeTab(projectSlug: string, ref: string): Promise<boolean> {- const registry = await getRegistry(projectSlug);- const page = registry.byId.get(ref);- if (!page) return false;- registry.byId.delete(ref);- if (!page.isClosed()) {- await page.close().catch(() => {});- }- return true;-}--/** Test-only: forget cached registries. Lets tests start clean. */-export function _resetTabRegistries(): void {- _registries.clear();-}diff --git a/notfair/src/server/db/db.test.ts b/notfair/src/server/db/db.test.tsdeleted file mode 100644index 2d80283a..00000000--- a/notfair/src/server/db/db.test.ts+++ /dev/null@@ -1,56 +0,0 @@-import { describe, expect, it, vi } from "vitest";-import { existsSync } from "node:fs";-import { join } from "node:path";--// Real better-sqlite3 against a tmpdir DB, per repo test conventions.-// MUST be hoisted: db.ts captures NOTFAIR_DATA_DIR at import time, so a-// plain assignment would point the suite at the developer's live ~/.notfair.-const h = vi.hoisted(() => {- const { mkdtempSync, rmSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- const dataDir = mkdtempSync(join(tmpdir(), "notfair-db-"));- // getDb creates the data dir itself when missing — exercise that path.- rmSync(dataDir, { recursive: true, force: true });- process.env.NOTFAIR_DATA_DIR = dataDir;- return { dataDir };-});--import { getDb, getDbPath } from "./db";--describe("getDb", () => {- it("creates the data dir + db file and applies the schema", () => {- expect(existsSync(h.dataDir)).toBe(false);- const db = getDb();- expect(existsSync(join(h.dataDir, "db.sqlite"))).toBe(true);- // Schema applied: core tables exist.- const tables = db- .prepare("SELECT name FROM sqlite_master WHERE type = 'table'")- .all() as Array<{ name: string }>;- const names = tables.map((t) => t.name);- expect(names).toContain("projects");- expect(names).toContain("sessions");- expect(names).toContain("transcript_events");- const tickColumns = db.pragma("table_info(goal_ticks)") as Array<{- name: string;- }>;- expect(tickColumns.map((column) => column.name)).toContain("owner_pid");- });-- it("configures WAL journaling and foreign keys", () => {- const db = getDb();- expect(db.pragma("journal_mode", { simple: true })).toBe("wal");- expect(db.pragma("foreign_keys", { simple: true })).toBe(1);- expect(db.pragma("busy_timeout", { simple: true })).toBe(5000);- });-- it("caches the connection — repeated calls return the same instance", () => {- expect(getDb()).toBe(getDb());- });-});--describe("getDbPath", () => {- it("points at db.sqlite inside the data dir", () => {- expect(getDbPath()).toBe(join(h.dataDir, "db.sqlite"));- });-});diff --git a/notfair/src/server/db/db.ts b/notfair/src/server/db/db.tsdeleted file mode 100644index 9646e3a5..00000000--- a/notfair/src/server/db/db.ts+++ /dev/null@@ -1,50 +0,0 @@-import { existsSync, mkdirSync } from "node:fs";-import { homedir } from "node:os";-import { join } from "node:path";-import Database from "better-sqlite3";-import { SCHEMA } from "./schema";--const DEFAULT_DATA_DIR = process.env.NOTFAIR_DATA_DIR ?? join(homedir(), ".notfair");-const DB_PATH = join(DEFAULT_DATA_DIR, "db.sqlite");--let cached: Database.Database | null = null;--export function getDb(): Database.Database {- if (cached) return cached;-- if (!existsSync(DEFAULT_DATA_DIR)) {- mkdirSync(DEFAULT_DATA_DIR, { recursive: true, mode: 0o700 });- }-- const db = new Database(DB_PATH);- db.pragma("journal_mode = WAL");- db.pragma("foreign_keys = ON");- db.pragma("busy_timeout = 5000");-- db.exec(SCHEMA);- ensureGoalTickOwnerColumn(db);-- cached = db;- return db;-}--export function getDbPath(): string {- return DB_PATH;-}--function ensureGoalTickOwnerColumn(db: Database.Database): void {- const hasOwnerPid = () =>- (- db.pragma("table_info(goal_ticks)") as Array<{ name: string }>- ).some((column) => column.name === "owner_pid");- if (hasOwnerPid()) return;-- try {- db.exec("ALTER TABLE goal_ticks ADD COLUMN owner_pid INTEGER");- } catch (error) {- // Two local processes can open the same data directory concurrently.- // Treat a raced migration as success only when the other process- // actually installed the column.- if (!hasOwnerPid()) throw error;- }-}diff --git a/notfair/src/server/db/goal-groups.test.ts b/notfair/src/server/db/goal-groups.test.tsdeleted file mode 100644index 0534c2b7..00000000--- a/notfair/src/server/db/goal-groups.test.ts+++ /dev/null@@ -1,111 +0,0 @@-import { beforeAll, describe, expect, it, vi } from "vitest";--vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-goal-groups-"));-});--import { getDb } from "./db";-import { createGoal, getGoal } from "./goals";-import {- createGoalGroup,- deleteGoalGroup,- getGoalGroup,- listGoalGroupMemberships,- listGoalsInGroup,- renameGoalGroup,- saveGoalGroup,- setGoalGroupMembership,-} from "./goal-groups";--const PROJECT = "group-project";--beforeAll(() => {- const db = getDb();- const insert = db.prepare(- "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES (?, ?, ?, ?, 'codex-local')",- );- insert.run("gp1", PROJECT, "Group project", new Date().toISOString());- insert.run("gp2", "other-project", "Other project", new Date().toISOString());-});--describe("goal groups", () => {- it("creates a group containing many goals", () => {- const google = createGoal({ project_slug: PROJECT, agent_id: "google", statement: "Google errors" });- const meta = createGoal({ project_slug: PROJECT, agent_id: "meta", statement: "Meta errors" });- const group = createGoalGroup({- project_slug: PROJECT,- name: "Ads MCP reliability",- description: "Keep every ads connection healthy.",- goal_ids: [google.id, meta.id],- });-- expect(listGoalsInGroup(group.id).map((goal) => goal.id)).toEqual([google.id, meta.id]);- expect(listGoalGroupMemberships(PROJECT)).toEqual(- expect.arrayContaining([- expect.objectContaining({ goal_id: google.id, group_id: group.id }),- expect.objectContaining({ goal_id: meta.id, group_id: group.id }),- ]),- );- });-- it("moves a goal atomically when it joins another group", () => {- const goal = createGoal({ project_slug: PROJECT, agent_id: "move-me", statement: "Move" });- const first = createGoalGroup({ project_slug: PROJECT, name: "First", goal_ids: [goal.id] });- const second = createGoalGroup({ project_slug: PROJECT, name: "Second" });-- setGoalGroupMembership(goal.id, second.id);- expect(listGoalsInGroup(first.id)).toHaveLength(0);- expect(listGoalsInGroup(second.id).map((item) => item.id)).toEqual([goal.id]);- });-- it("saves metadata and replaces members in one transaction", () => {- const one = createGoal({ project_slug: PROJECT, agent_id: "save-one", statement: "One" });- const two = createGoal({ project_slug: PROJECT, agent_id: "save-two", statement: "Two" });- const group = createGoalGroup({ project_slug: PROJECT, name: "Before", goal_ids: [one.id] });-- const saved = saveGoalGroup({- id: group.id,- name: "After",- description: "Updated",- goal_ids: [two.id],- });- expect(saved).toMatchObject({ name: "After", description: "Updated" });- expect(listGoalsInGroup(group.id).map((goal) => goal.id)).toEqual([two.id]);- });-- it("rejects cross-project membership", () => {- const other = createGoal({- project_slug: "other-project",- agent_id: "other-goal",- statement: "Other",- });- expect(() =>- createGoalGroup({ project_slug: PROJECT, name: "Invalid", goal_ids: [other.id] }),- ).toThrow(/same project/);- expect(getDb().prepare("SELECT COUNT(*) AS n FROM goal_groups WHERE name = 'Invalid'").get())- .toEqual({ n: 0 });- });-- it("renames a group in place without touching members", () => {- const goal = createGoal({ project_slug: PROJECT, agent_id: "renamed", statement: "Rename me" });- const group = createGoalGroup({ project_slug: PROJECT, name: "Rail before", goal_ids: [goal.id] });-- const renamed = renameGoalGroup(group.id, "Rail after");- expect(renamed?.name).toBe("Rail after");- expect(listGoalsInGroup(group.id).map((g) => g.id)).toEqual([goal.id]);- expect(renameGoalGroup("missing-group", "Nope")).toBeNull();- });-- it("deleting a group ungroups goals without deleting them", () => {- const goal = createGoal({ project_slug: PROJECT, agent_id: "survivor", statement: "Stay" });- const group = createGoalGroup({ project_slug: PROJECT, name: "Temporary", goal_ids: [goal.id] });-- expect(deleteGoalGroup(group.id)).toBe(true);- expect(getGoalGroup(group.id)).toBeNull();- expect(getGoal(goal.id)).not.toBeNull();- expect(listGoalGroupMemberships(PROJECT).some((member) => member.goal_id === goal.id)).toBe(false);- });-});diff --git a/notfair/src/server/db/goal-groups.ts b/notfair/src/server/db/goal-groups.tsdeleted file mode 100644index b600d94c..00000000--- a/notfair/src/server/db/goal-groups.ts+++ /dev/null@@ -1,174 +0,0 @@-import { randomUUID } from "node:crypto";-import { getDb } from "./db";-import { type Goal } from "./goals";--export type GoalGroup = {- id: string;- project_slug: string;- name: string;- description: string;- sort_order: number;- created_at: string;- updated_at: string;-};--export type GoalGroupMembership = {- goal_id: string;- group_id: string;- created_at: string;-};--function now(): string {- return new Date().toISOString();-}--function uniqueGoalIds(goalIds: string[]): string[] {- return [...new Set(goalIds)];-}--function assertGoalsBelongToProject(projectSlug: string, goalIds: string[]): void {- const ids = uniqueGoalIds(goalIds);- if (ids.length === 0) return;- const placeholders = ids.map(() => "?").join(",");- const row = getDb()- .prepare(- `SELECT COUNT(*) AS count FROM goals- WHERE project_slug = ? AND id IN (${placeholders})`,- )- .get(projectSlug, ...ids) as { count: number };- if (row.count !== ids.length) {- throw new Error("Every grouped goal must belong to the same project as the group.");- }-}--function replaceMembers(group: GoalGroup, goalIds: string[]): void {- const db = getDb();- const ids = uniqueGoalIds(goalIds);- assertGoalsBelongToProject(group.project_slug, ids);- db.prepare("DELETE FROM goal_group_memberships WHERE group_id = ?").run(group.id);- const insert = db.prepare(- `INSERT INTO goal_group_memberships (goal_id, group_id, created_at)- VALUES (?, ?, ?)- ON CONFLICT(goal_id) DO UPDATE SET group_id = excluded.group_id, created_at = excluded.created_at`,- );- const ts = now();- for (const goalId of ids) insert.run(goalId, group.id, ts);-}--export function createGoalGroup(input: {- project_slug: string;- name: string;- description?: string;- goal_ids?: string[];-}): GoalGroup {- const db = getDb();- const id = randomUUID();- const ts = now();- const run = db.transaction(() => {- const sort = db- .prepare(- "SELECT COALESCE(MAX(sort_order), -1) + 1 AS next FROM goal_groups WHERE project_slug = ?",- )- .get(input.project_slug) as { next: number };- db.prepare(- `INSERT INTO goal_groups- (id, project_slug, name, description, sort_order, created_at, updated_at)- VALUES (?, ?, ?, ?, ?, ?, ?)`,- ).run(- id,- input.project_slug,- input.name,- input.description ?? "",- sort.next,- ts,- ts,- );- const group = getGoalGroup(id)!;- replaceMembers(group, input.goal_ids ?? []);- return group;- });- return run();-}--export function getGoalGroup(id: string): GoalGroup | null {- const row = getDb().prepare("SELECT * FROM goal_groups WHERE id = ?").get(id);- return (row as GoalGroup) ?? null;-}--export function listGoalGroups(projectSlug: string): GoalGroup[] {- return getDb()- .prepare(- `SELECT * FROM goal_groups WHERE project_slug = ?- ORDER BY sort_order ASC, created_at ASC, rowid ASC`,- )- .all(projectSlug) as GoalGroup[];-}--export function listGoalGroupMemberships(projectSlug: string): GoalGroupMembership[] {- return getDb()- .prepare(- `SELECT m.* FROM goal_group_memberships m- JOIN goal_groups gg ON gg.id = m.group_id- WHERE gg.project_slug = ?- ORDER BY m.created_at ASC`,- )- .all(projectSlug) as GoalGroupMembership[];-}--export function listGoalsInGroup(groupId: string): Goal[] {- return getDb()- .prepare(- `SELECT g.* FROM goals g- JOIN goal_group_memberships m ON m.goal_id = g.id- WHERE m.group_id = ?- ORDER BY g.created_at ASC, g.rowid ASC`,- )- .all(groupId) as Goal[];-}--export function renameGoalGroup(id: string, name: string): GoalGroup | null {- const changed = getDb()- .prepare("UPDATE goal_groups SET name = ?, updated_at = ? WHERE id = ?")- .run(name, now(), id).changes;- return changed > 0 ? getGoalGroup(id) : null;-}--export function saveGoalGroup(input: {- id: string;- name: string;- description?: string;- goal_ids: string[];-}): GoalGroup | null {- const db = getDb();- const run = db.transaction(() => {- const current = getGoalGroup(input.id);- if (!current) return null;- db.prepare(- "UPDATE goal_groups SET name = ?, description = ?, updated_at = ? WHERE id = ?",- ).run(input.name, input.description ?? "", now(), input.id);- const updated = getGoalGroup(input.id)!;- replaceMembers(updated, input.goal_ids);- return updated;- });- return run();-}--export function setGoalGroupMembership(goalId: string, groupId: string | null): void {- const db = getDb();- if (groupId === null) {- db.prepare("DELETE FROM goal_group_memberships WHERE goal_id = ?").run(goalId);- return;- }- const group = getGoalGroup(groupId);- if (!group) throw new Error("Goal group not found.");- assertGoalsBelongToProject(group.project_slug, [goalId]);- db.prepare(- `INSERT INTO goal_group_memberships (goal_id, group_id, created_at)- VALUES (?, ?, ?)- ON CONFLICT(goal_id) DO UPDATE SET group_id = excluded.group_id, created_at = excluded.created_at`,- ).run(goalId, groupId, now());-}--export function deleteGoalGroup(id: string): boolean {- return getDb().prepare("DELETE FROM goal_groups WHERE id = ?").run(id).changes > 0;-}diff --git a/notfair/src/server/db/goal-prs.test.ts b/notfair/src/server/db/goal-prs.test.tsdeleted file mode 100644index 232282de..00000000--- a/notfair/src/server/db/goal-prs.test.ts+++ /dev/null@@ -1,196 +0,0 @@-import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";--// Real better-sqlite3 against a tmpdir DB, per repo test conventions.-// MUST be hoisted: static imports evaluate before module-level statements,-// and db.ts captures NOTFAIR_DATA_DIR at import time — a plain assignment-// here would silently point the suite at the developer's live ~/.notfair.-vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-prs-"));-});--import {- applyGoalPrSync,- createGoalPr,- findGoalPrByUrl,- listDuePrSyncs,- listGoalPrs,- listOpenGoalPrs,- listPrsAwaitingReview,- markGoalPrSyncError,-} from "@/server/db/goal-prs";-import { getDb } from "@/server/db/db";-import { createGoal } from "@/server/db/goals";--const SLUG = "proj";-let goalId: string;--beforeAll(() => {- getDb()- .prepare(- "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('p1', ?, 'Proj', ?, 'codex-local')",- )- .run(SLUG, new Date().toISOString());- goalId = createGoal({- project_slug: SLUG,- agent_id: "agent-1",- statement: "Grow organic clicks",- }).id;-});--beforeEach(() => {- getDb().prepare("DELETE FROM goal_prs").run();- vi.restoreAllMocks();-});--const URL1 = "https://github.com/acme/site/pull/12";--describe("goal_prs data layer", () => {- it("creates a PR row in open state and finds it by url", () => {- const pr = createGoalPr({ goal_id: goalId, url: URL1, title: "Fix titles" });- expect(pr.state).toBe("open");- expect(pr.review_decision).toBeNull();- expect(findGoalPrByUrl(goalId, URL1)?.id).toBe(pr.id);- expect(listGoalPrs(goalId)).toHaveLength(1);- });-- it("returns the winning row when the same goal and url are inserted twice", () => {- const first = createGoalPr({- goal_id: goalId,- url: URL1,- title: "Fix titles",- });- const duplicate = createGoalPr({- goal_id: goalId,- url: URL1,- title: "Duplicate registration",- });-- expect(duplicate.id).toBe(first.id);- expect(duplicate.title).toBe("Fix titles");- expect(listGoalPrs(goalId)).toHaveLength(1);- });-- it("applies a GitHub sync and clears prior sync errors", () => {- const pr = createGoalPr({ goal_id: goalId, url: URL1, title: "t" });- markGoalPrSyncError(pr.id, "gh not found");- const synced = applyGoalPrSync(pr.id, {- state: "merged",- title: "Fix titles",- review_decision: "APPROVED",- comment_count: 3,- is_draft: false,- merged_at: "2026-07-13T00:00:00Z",- })!;- expect(synced.state).toBe("merged");- expect(synced.title).toBe("Fix titles");- expect(synced.comment_count).toBe(3);- expect(synced.sync_error).toBeNull();- expect(listOpenGoalPrs(goalId)).toHaveLength(0);- });-- it("awaiting-review covers open non-draft PRs unless changes were requested", () => {- const a = createGoalPr({ goal_id: goalId, url: URL1, title: "a" });- const b = createGoalPr({- goal_id: goalId,- url: "https://github.com/acme/site/pull/13",- title: "b",- });- const c = createGoalPr({- goal_id: goalId,- url: "https://github.com/acme/site/pull/14",- title: "c",- });- // a: untouched (never synced) → awaiting review.- // b: user requested changes → ball is with the agent, not the user.- applyGoalPrSync(b.id, {- state: "open",- review_decision: "CHANGES_REQUESTED",- comment_count: 2,- is_draft: false,- merged_at: null,- });- // c: merged → terminal, not awaiting anything.- applyGoalPrSync(c.id, {- state: "merged",- review_decision: "APPROVED",- comment_count: 0,- is_draft: false,- merged_at: "2026-07-13T00:00:00Z",- });- const awaiting = listPrsAwaitingReview(SLUG);- expect(awaiting.map((p) => p.id)).toEqual([a.id]);- });-});--describe("adaptive sync scheduling", () => {- it("a fresh registration is immediately due", () => {- const pr = createGoalPr({ goal_id: goalId, url: URL1, title: "t" });- expect(pr.next_sync_at).not.toBeNull();- expect(pr.last_activity_at).not.toBeNull();- expect(listDuePrSyncs().map((p) => p.id)).toContain(pr.id);- });-- it("an observed change resets activity and schedules the fast lane", () => {- const pr = createGoalPr({ goal_id: goalId, url: URL1, title: "t" });- const synced = applyGoalPrSync(pr.id, {- state: "open",- review_decision: "CHANGES_REQUESTED",- comment_count: 2,- is_draft: false,- merged_at: null,- })!;- expect(synced.last_activity_at).not.toBeNull();- // Fast lane: ~2 minutes out — definitely not due now, well within 3 min.- const dueIn = Date.parse(synced.next_sync_at!) - Date.now();- expect(dueIn).toBeGreaterThan(60_000);- expect(dueIn).toBeLessThan(3 * 60_000);- expect(listDuePrSyncs().map((p) => p.id)).not.toContain(pr.id);- });-- it("a no-change sync keeps the old activity timestamp (backoff grows)", () => {- const pr = createGoalPr({ goal_id: goalId, url: URL1, title: "t" });- const payload = {- state: "open" as const,- review_decision: "",- comment_count: 0,- is_draft: false,- merged_at: null,- };- const first = applyGoalPrSync(pr.id, payload)!; // change (decision null → "")- const second = applyGoalPrSync(pr.id, payload)!; // no change- expect(second.last_activity_at).toBe(first.last_activity_at);- });-- it("terminal PRs leave the schedule entirely", () => {- const pr = createGoalPr({ goal_id: goalId, url: URL1, title: "t" });- const merged = applyGoalPrSync(pr.id, {- state: "merged",- review_decision: "APPROVED",- comment_count: 0,- is_draft: false,- merged_at: "2026-07-13T00:00:00Z",- })!;- expect(merged.next_sync_at).toBeNull();- expect(listDuePrSyncs().map((p) => p.id)).not.toContain(pr.id);- });-- it("a failed sync retries on the error delay instead of going dark", () => {- const pr = createGoalPr({ goal_id: goalId, url: URL1, title: "t" });- markGoalPrSyncError(pr.id, "gh: command not found");- const row = findGoalPrByUrl(goalId, URL1)!;- const dueIn = Date.parse(row.next_sync_at!) - Date.now();- expect(dueIn).toBeGreaterThan(4 * 60_000);- expect(dueIn).toBeLessThan(6 * 60_000);- });-- it("open rows with NULL next_sync_at (pre-policy data) self-heal as due", () => {- const pr = createGoalPr({ goal_id: goalId, url: URL1, title: "t" });- getDb()- .prepare("UPDATE goal_prs SET next_sync_at = NULL WHERE id = ?")- .run(pr.id);- expect(listDuePrSyncs().map((p) => p.id)).toContain(pr.id);- });-});diff --git a/notfair/src/server/db/goal-prs.ts b/notfair/src/server/db/goal-prs.tsdeleted file mode 100644index e28ce82f..00000000--- a/notfair/src/server/db/goal-prs.ts+++ /dev/null@@ -1,217 +0,0 @@-import { randomUUID } from "node:crypto";-import {- computeNextSyncAt,- SYNC_ERROR_RETRY_MS,-} from "@/lib/pr-poll-policy";-import { getDb } from "./db";--/**- * Pull requests a goal agent opened against the workspace's codebase.- *- * A PR row is the loop's handle on a code mutation: the agent registers- * the PR right after `gh pr create` (via the `register_pull_request`- * tool), the platform syncs its state from GitHub (`gh pr view`) at tick- * time and on goal-page views, and the tick brief carries the live state —- * so the agent reacts to review comments, and merge/close are facts the- * loop observes rather than claims.- */--export type GoalPrState = "open" | "merged" | "closed";--export type GoalPr = {- id: string;- goal_id: string;- action_id: string | null;- /** The check whose turn registered this PR (null for pre-loop PRs). */- tick_number: number | null;- url: string;- title: string;- branch: string | null;- state: GoalPrState;- /** GitHub reviewDecision (APPROVED / CHANGES_REQUESTED / REVIEW_REQUIRED- * / "" for repos without required reviews). Null until first sync. */- review_decision: string | null;- comment_count: number;- is_draft: boolean;- merged_at: string | null;- last_synced_at: string | null;- sync_error: string | null;- /** When the centralized sweep should next check GitHub. NULL for- * terminal PRs (merged/closed) — they are never synced again. */- next_sync_at: string | null;- /** Last time a sync OBSERVED a change (state / review / comments).- * Drives the adaptive poll interval in pr-poll-policy. */- last_activity_at: string | null;- created_at: string;- updated_at: string;-};--type GoalPrRow = Omit<GoalPr, "is_draft"> & { is_draft: number };--function mapRow(row: GoalPrRow): GoalPr {- return { ...row, is_draft: !!row.is_draft };-}--export function createGoalPr(input: {- goal_id: string;- url: string;- title: string;- branch?: string | null;- action_id?: string | null;- tick_number?: number | null;-}): GoalPr {- const db = getDb();- const now = new Date().toISOString();- const id = randomUUID();- db.prepare(- `INSERT OR IGNORE INTO goal_prs (id, goal_id, action_id, tick_number, url, title, branch, next_sync_at, last_activity_at, created_at, updated_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,- ).run(- id,- input.goal_id,- input.action_id ?? null,- input.tick_number ?? null,- input.url,- input.title,- input.branch ?? null,- // Immediately due: a fresh registration should reflect GitHub asap.- now,- now,- now,- now,- );- // UNIQUE(goal_id, url) makes registration idempotent even when two tool- // calls race between their read and insert. The winner's row is canonical.- return findGoalPrByUrl(input.goal_id, input.url)!;-}--export function getGoalPr(id: string): GoalPr | null {- const row = getDb()- .prepare("SELECT * FROM goal_prs WHERE id = ?")- .get(id) as GoalPrRow | undefined;- return row ? mapRow(row) : null;-}--export function findGoalPrByUrl(goal_id: string, url: string): GoalPr | null {- const row = getDb()- .prepare("SELECT * FROM goal_prs WHERE goal_id = ? AND url = ?")- .get(goal_id, url) as GoalPrRow | undefined;- return row ? mapRow(row) : null;-}--export function listGoalPrs(goal_id: string, limit = 50): GoalPr[] {- const rows = getDb()- .prepare(- "SELECT * FROM goal_prs WHERE goal_id = ? ORDER BY created_at DESC LIMIT ?",- )- .all(goal_id, limit) as GoalPrRow[];- return rows.map(mapRow);-}--/** PRs still awaiting a GitHub outcome — the ones worth syncing. */-export function listOpenGoalPrs(goal_id: string): GoalPr[] {- const rows = getDb()- .prepare(- "SELECT * FROM goal_prs WHERE goal_id = ? AND state = 'open' ORDER BY created_at DESC",- )- .all(goal_id) as GoalPrRow[];- return rows.map(mapRow);-}--/**- * Open PRs across a project's goals that are waiting on the user — feeds- * the goals-index "PR awaiting your review" tag. A PR waits on the user- * unless GitHub says changes were requested (then the ball is back with- * the agent).- */-export function listPrsAwaitingReview(project_slug: string): GoalPr[] {- const rows = getDb()- .prepare(- `SELECT p.* FROM goal_prs p- JOIN goals g ON g.id = p.goal_id- WHERE g.project_slug = ? AND p.state = 'open' AND p.is_draft = 0- AND (p.review_decision IS NULL OR p.review_decision != 'CHANGES_REQUESTED')- ORDER BY p.created_at DESC`,- )- .all(project_slug) as GoalPrRow[];- return rows.map(mapRow);-}--export function applyGoalPrSync(- id: string,- sync: {- state: GoalPrState;- title?: string | null;- review_decision: string | null;- comment_count: number;- is_draft: boolean;- merged_at: string | null;- },-): GoalPr | null {- const db = getDb();- const current = getGoalPr(id);- if (!current) return null;- const now = new Date().toISOString();-- // "Activity" = any observable change on GitHub since the last sync.- // It resets the adaptive poll clock so hot PRs poll fast again.- const changed =- current.state !== sync.state ||- current.review_decision !== sync.review_decision ||- current.comment_count !== sync.comment_count ||- current.is_draft !== sync.is_draft;- const last_activity_at = changed- ? now- : (current.last_activity_at ?? current.created_at);- const next_sync_at =- sync.state === "open" ? computeNextSyncAt(now, last_activity_at) : null;-- db.prepare(- `UPDATE goal_prs- SET state = ?, title = COALESCE(?, title), review_decision = ?,- comment_count = ?, is_draft = ?, merged_at = ?,- last_synced_at = ?, sync_error = NULL,- next_sync_at = ?, last_activity_at = ?, updated_at = ?- WHERE id = ?`,- ).run(- sync.state,- sync.title ?? null,- sync.review_decision,- sync.comment_count,- sync.is_draft ? 1 : 0,- sync.merged_at,- now,- next_sync_at,- last_activity_at,- now,- id,- );- return getGoalPr(id);-}--export function markGoalPrSyncError(id: string, error: string): void {- const now = Date.now();- const nowIso = new Date(now).toISOString();- const retryIso = new Date(now + SYNC_ERROR_RETRY_MS).toISOString();- getDb()- .prepare(- "UPDATE goal_prs SET sync_error = ?, last_synced_at = ?, next_sync_at = ?, updated_at = ? WHERE id = ?",- )- .run(error.slice(0, 500), nowIso, retryIso, nowIso, id);-}--/**- * Open PRs due for a freshness check, across every project — the- * centralized sweep's work list. `next_sync_at IS NULL` on an open row- * (pre-policy data) counts as due so it self-heals into the schedule.- */-export function listDuePrSyncs(nowIso = new Date().toISOString()): GoalPr[] {- const rows = getDb()- .prepare(- `SELECT * FROM goal_prs- WHERE state = 'open' AND (next_sync_at IS NULL OR next_sync_at <= ?)- ORDER BY next_sync_at ASC`,- )- .all(nowIso) as GoalPrRow[];- return rows.map(mapRow);-}diff --git a/notfair/src/server/db/goal-support-metrics.test.ts b/notfair/src/server/db/goal-support-metrics.test.tsdeleted file mode 100644index d10336e3..00000000--- a/notfair/src/server/db/goal-support-metrics.test.ts+++ /dev/null@@ -1,195 +0,0 @@-import { beforeAll, describe, expect, it, vi } from "vitest";--// Real better-sqlite3 against a tmpdir DB, per repo test conventions.-// MUST be hoisted: static imports evaluate before module-level statements,-// and db.ts captures NOTFAIR_DATA_DIR at import time — a plain assignment-// here would silently point the suite at the developer's live ~/.notfair.-vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-support-"));-});--import { getDb } from "./db";-import { createGoal } from "./goals";-import {- listSupportMetricSnapshots,- listSupportMetrics,- recordSupportMetricSnapshot,- replaceSupportBackfillSnapshots,- upsertSupportMetric,-} from "./goal-support-metrics";-import { handleAddSupportMetric } from "@/server/goals/handlers";--const SLUG = "proj";-let goalId: string;--beforeAll(() => {- getDb()- .prepare(- "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('p1', ?, 'Proj', ?, 'codex-local')",- )- .run(SLUG, new Date().toISOString());- goalId = createGoal({ project_slug: SLUG, agent_id: "agent-1", statement: "ship" }).id;-});--describe("goal-support-metrics db", () => {- it("inserts, lists, and snapshots on upsert", () => {- const m = upsertSupportMetric({- goal_id: goalId,- name: "PRs opened",- source_key: "local",- source_tool: "shell",- source_args_json: `{"command":"echo 5"}`,- direction: "increase",- measured_value: 5,- });- expect(m.baseline_value).toBe(5);- expect(m.current_value).toBe(5);- expect(listSupportMetrics(goalId)).toHaveLength(1);- const snaps = listSupportMetricSnapshots(m.id);- expect(snaps).toHaveLength(1);- expect(snaps[0]!.source).toBe("verify");- });-- it("re-using the name redefines in place and keeps snapshot history", () => {- const before = listSupportMetrics(goalId)[0]!;- const m = upsertSupportMetric({- goal_id: goalId,- name: "PRs opened",- source_key: "local",- source_tool: "shell",- source_args_json: `{"command":"echo 8"}`,- measured_value: 8,- });- expect(m.id).toBe(before.id); // same row, not a duplicate- expect(m.baseline_value).toBe(8);- expect(m.direction).toBeNull(); // redefinition replaces the spec- expect(listSupportMetrics(goalId)).toHaveLength(1);- expect(listSupportMetricSnapshots(m.id).length).toBe(2);- });-- it("tick snapshots advance current_value", () => {- const m = listSupportMetrics(goalId)[0]!;- recordSupportMetricSnapshot(m.id, 11, "tick");- expect(listSupportMetrics(goalId)[0]!.current_value).toBe(11);- });-- it("backfill replaces prior backfill, keeps live snapshots and current_value", () => {- const m = listSupportMetrics(goalId)[0]!;- const liveBefore = listSupportMetricSnapshots(m.id).filter(- (s) => s.source !== "backfill",- ).length;- replaceSupportBackfillSnapshots(m.id, [- { value: 1, created_at: "2026-07-01T00:00:00.000Z" },- { value: 2, created_at: "2026-07-02T00:00:00.000Z" },- ]);- replaceSupportBackfillSnapshots(m.id, [- { value: 3, created_at: "2026-07-03T00:00:00.000Z" },- ]);- const snaps = listSupportMetricSnapshots(m.id);- expect(snaps.filter((s) => s.source === "backfill")).toHaveLength(1);- expect(snaps.filter((s) => s.source !== "backfill")).toHaveLength(liveBefore);- expect(listSupportMetrics(goalId)[0]!.current_value).toBe(11); // untouched- });-});--describe("handleAddSupportMetric", () => {- const ctx = { project_slug: SLUG, agent_id: "agent-1" };-- it("verifies through the local source and stores the metric", async () => {- const r = await handleAddSupportMetric(- {- goal_id: goalId,- name: "Open listing PRs (live)",- source_key: "local",- source_tool: "shell",- source_args_json: `{"command":"echo 104"}`,- direction: "increase",- },- ctx,- );- expect(r.ok).toBe(true);- if (r.ok) expect(r.data.metric.current_value).toBe(104);- });-- it("backfills history when history_args_json is given", async () => {- const history = JSON.stringify({- command: `echo '[{"date":"2026-07-01","value":100},{"date":"2026-07-02","value":102}]'`,- });- const r = await handleAddSupportMetric(- {- goal_id: goalId,- name: "Open listing PRs (live)",- source_key: "local",- source_tool: "shell",- source_args_json: `{"command":"echo 104"}`,- history_args_json: history,- },- ctx,- );- expect(r.ok).toBe(true);- if (r.ok) expect(r.data.backfilled).toBe(2);- });-- it("fails with a fix-and-retry error when the history query is broken", async () => {- const r = await handleAddSupportMetric(- {- goal_id: goalId,- name: "Open listing PRs (live)",- source_key: "local",- source_tool: "shell",- source_args_json: `{"command":"echo 104"}`,- history_args_json: `{"command":"echo not-an-array"}`,- },- ctx,- );- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("history query failed");- });-- it("rejects a failing source with the measurement error", async () => {- const r = await handleAddSupportMetric(- {- goal_id: goalId,- name: "Broken",- source_key: "local",- source_tool: "shell",- source_args_json: `{"command":"echo nope"}`,- },- ctx,- );- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("verification failed");- });-- it("rejects an unconnected MCP source key", async () => {- const r = await handleAddSupportMetric(- {- goal_id: goalId,- name: "Clicks",- source_key: "notfair-googlesearchconsole",- source_tool: "runScript",- source_args_json: `{}`,- },- ctx,- );- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("No connected MCP");- });-- it("rejects another agent's goal", async () => {- const r = await handleAddSupportMetric(- {- goal_id: goalId,- name: "X",- source_key: "local",- source_tool: "shell",- source_args_json: `{"command":"echo 1"}`,- },- { project_slug: SLUG, agent_id: "agent-2" },- );- expect(r.ok).toBe(false);- });-});diff --git a/notfair/src/server/db/goal-support-metrics.ts b/notfair/src/server/db/goal-support-metrics.tsdeleted file mode 100644index cdc381dd..00000000--- a/notfair/src/server/db/goal-support-metrics.ts+++ /dev/null@@ -1,163 +0,0 @@-import { randomUUID } from "node:crypto";-import { getDb } from "./db";-import type { MetricDirection } from "./goals";--/**- * Supporting metrics — extra numbers the loop measures alongside the- * goal's primary metric. A goal is judged on ONE number (target,- * deadline, achieved/failed); supporting metrics are the leading- * indicators and diagnostics around it ("PRs opened" while merges are- * the target, "impressions" while clicks are the target). Same trust- * rule as the primary: the agent authors the source once, the platform- * measures it on every check.- */--export type GoalSupportMetric = {- id: string;- goal_id: string;- name: string;- source_key: string;- source_tool: string;- source_args_json: string;- direction: MetricDirection | null;- baseline_value: number;- current_value: number;- created_at: string;- updated_at: string;-};--export type GoalSupportMetricSnapshot = {- id: string;- metric_id: string;- value: number;- source: "verify" | "tick" | "backfill";- created_at: string;-};--function now(): string {- return new Date().toISOString();-}--export type UpsertSupportMetricInput = {- goal_id: string;- name: string;- source_key: string;- source_tool: string;- source_args_json: string;- direction?: MetricDirection | null;- /** The value the platform just measured while verifying the source. */- measured_value: number;-};--/**- * Add a supporting metric, or redefine it by name (fixing a wrong query- * shouldn't need a second tool). Redefinition resets baseline + current- * to the freshly measured value; snapshot history is kept — the chart- * shows the metric's life, not just its latest definition.- */-export function upsertSupportMetric(input: UpsertSupportMetricInput): GoalSupportMetric {- const db = getDb();- const ts = now();- db.prepare(- `INSERT INTO goal_support_metrics- (id, goal_id, name, source_key, source_tool, source_args_json,- direction, baseline_value, current_value, created_at, updated_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)- ON CONFLICT(goal_id, name) DO UPDATE SET- source_key = excluded.source_key,- source_tool = excluded.source_tool,- source_args_json = excluded.source_args_json,- direction = excluded.direction,- baseline_value = excluded.baseline_value,- current_value = excluded.current_value,- updated_at = excluded.updated_at`,- ).run(- randomUUID(),- input.goal_id,- input.name,- input.source_key,- input.source_tool,- input.source_args_json,- input.direction ?? null,- input.measured_value,- input.measured_value,- ts,- ts,- );- const metric = getSupportMetricByName(input.goal_id, input.name)!;- recordSupportMetricSnapshot(metric.id, input.measured_value, "verify");- return metric;-}--export function getSupportMetricByName(- goal_id: string,- name: string,-): GoalSupportMetric | null {- const row = getDb()- .prepare("SELECT * FROM goal_support_metrics WHERE goal_id = ? AND name = ?")- .get(goal_id, name);- return (row as GoalSupportMetric) ?? null;-}--export function listSupportMetrics(goal_id: string): GoalSupportMetric[] {- return getDb()- .prepare(- "SELECT * FROM goal_support_metrics WHERE goal_id = ? ORDER BY created_at ASC, rowid ASC",- )- .all(goal_id) as GoalSupportMetric[];-}--export function recordSupportMetricSnapshot(- metric_id: string,- value: number,- source: GoalSupportMetricSnapshot["source"] = "tick",-): GoalSupportMetricSnapshot {- const db = getDb();- const id = randomUUID();- const ts = now();- db.prepare(- "INSERT INTO goal_support_metric_snapshots (id, metric_id, value, source, created_at) VALUES (?, ?, ?, ?, ?)",- ).run(id, metric_id, value, source, ts);- db.prepare(- "UPDATE goal_support_metrics SET current_value = ?, updated_at = ? WHERE id = ?",- ).run(value, ts, metric_id);- return { id, metric_id, value, source, created_at: ts };-}--/**- * Replace the metric's backfilled history with fresh backdated points —- * same contract as the primary's replaceBackfillSnapshots: live- * verify/tick snapshots are untouched, and current_value is not updated.- */-export function replaceSupportBackfillSnapshots(- metric_id: string,- points: Array<{ value: number; created_at: string }>,-): number {- const db = getDb();- const insert = db.prepare(- "INSERT INTO goal_support_metric_snapshots (id, metric_id, value, source, created_at) VALUES (?, ?, ?, 'backfill', ?)",- );- const tx = db.transaction(() => {- db.prepare(- "DELETE FROM goal_support_metric_snapshots WHERE metric_id = ? AND source = 'backfill'",- ).run(metric_id);- for (const p of points) insert.run(randomUUID(), metric_id, p.value, p.created_at);- });- tx();- return points.length;-}--export function listSupportMetricSnapshots(- metric_id: string,- limit = 90,-): GoalSupportMetricSnapshot[] {- // Ascending so sparklines read left→right; LIMIT applies to the tail.- return getDb()- .prepare(- `SELECT id, metric_id, value, source, created_at FROM (- SELECT *, rowid AS _rid FROM goal_support_metric_snapshots- WHERE metric_id = ? ORDER BY created_at DESC, rowid DESC LIMIT ?- ) ORDER BY created_at ASC, _rid ASC`,- )- .all(metric_id, limit) as GoalSupportMetricSnapshot[];-}diff --git a/notfair/src/server/db/goals.test.ts b/notfair/src/server/db/goals.test.tsdeleted file mode 100644index 9ba84519..00000000--- a/notfair/src/server/db/goals.test.ts+++ /dev/null@@ -1,182 +0,0 @@-import { beforeAll, describe, expect, it, vi } from "vitest";--// Real better-sqlite3 against a tmpdir DB, per repo test conventions.-// MUST be hoisted: static imports evaluate before module-level statements,-// and db.ts captures NOTFAIR_DATA_DIR at import time — a plain assignment-// here would silently point the suite at the developer's live ~/.notfair.-vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-goals-"));-});--import { getDb } from "./db";-import {- archiveAchievedGoal,- continueAchievedGoal,- createGoal,- createGoalAction,- deleteGoalsForAgent,- endActionObservation,- getGoal,- getPinnedGoalIds,- isGoalArchived,- listGatedActions,- listSidebarGoals,- proposeTarget,- recordMetricSnapshot,- renameGoal,- setGoalMetric,- setGoalPinned,- setGoalStatus,- updateGoalCurrentValue,-} from "./goals";--const SLUG = "proj";--beforeAll(() => {- getDb()- .prepare(- "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('p1', ?, 'Proj', ?, 'codex-local')",- )- .run(SLUG, new Date().toISOString());-});--describe("renameGoal", () => {- it("updates short_label and returns the goal", () => {- const goal = createGoal({ project_slug: SLUG, agent_id: "a-rename", statement: "ship" });- const renamed = renameGoal(goal.id, "Ship it → 100%");- expect(renamed?.short_label).toBe("Ship it → 100%");- });-- it("returns null for an unknown goal", () => {- expect(renameGoal("nope", "x")).toBeNull();- });-});--describe("goal pins", () => {- it("pin/unpin round-trips and is idempotent", () => {- const goal = createGoal({ project_slug: SLUG, agent_id: "a-pin", statement: "pin me" });- setGoalPinned(goal.id, true);- setGoalPinned(goal.id, true); // no throw on double-pin- expect(getPinnedGoalIds(SLUG).has(goal.id)).toBe(true);- setGoalPinned(goal.id, false);- expect(getPinnedGoalIds(SLUG).has(goal.id)).toBe(false);- });-- it("scopes pinned ids to the project", () => {- getDb()- .prepare(- "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('p2', 'other', 'Other', ?, 'codex-local')",- )- .run(new Date().toISOString());- const goal = createGoal({ project_slug: "other", agent_id: "a-other", statement: "x" });- setGoalPinned(goal.id, true);- expect(getPinnedGoalIds(SLUG).has(goal.id)).toBe(false);- expect(getPinnedGoalIds("other").has(goal.id)).toBe(true);- });-});--describe("completed-goal handoff", () => {- it("keeps an achievement in the sidebar until archive, then can continue it", () => {- const goal = createGoal({- project_slug: SLUG,- agent_id: "a-achieved",- statement: "Reach 100 qualified visits",- });- setGoalMetric(goal.id, {- metric_name: "Qualified visits",- metric_source_key: "local",- metric_source_tool: "shell",- metric_source_args_json: "{}",- metric_direction: "increase",- baseline_value: 50,- });- proposeTarget(goal.id, { target_value: 100 });- updateGoalCurrentValue(goal.id, 112);- setGoalStatus(goal.id, "achieved", "Measured 112 qualified visits.");-- expect(listSidebarGoals(SLUG).map((item) => item.id)).toContain(goal.id);- expect(isGoalArchived(goal.id)).toBe(false);-- expect(archiveAchievedGoal(goal.id)?.status).toBe("achieved");- expect(isGoalArchived(goal.id)).toBe(true);- expect(listSidebarGoals(SLUG).map((item) => item.id)).not.toContain(goal.id);-- const continued = continueAchievedGoal(goal.id, {- target_value: 150,- deadline: "2030-12-31",- short_label: "Qualified visits → 150",- });- expect(continued).toMatchObject({- status: "active",- target_value: 150,- deadline: "2030-12-31",- status_reason: null,- short_label: "Qualified visits → 150",- });- expect(continued?.next_tick_at).not.toBeNull();- expect(isGoalArchived(goal.id)).toBe(false);- expect(listSidebarGoals(SLUG).map((item) => item.id)).toContain(goal.id);- });-- it("requires a next target beyond the completed value", () => {- const goal = createGoal({- project_slug: SLUG,- agent_id: "a-achieved-direction",- statement: "Reduce errors",- });- getDb()- .prepare(- `UPDATE goals- SET status = 'achieved', metric_direction = 'decrease',- current_value = 4, target_value = 5- WHERE id = ?`,- )- .run(goal.id);-- expect(() =>- continueAchievedGoal(goal.id, { target_value: 6, deadline: null }),- ).toThrow(/below the completed value/i);- });-});--describe("endActionObservation", () => {- it("releases a gated action into review-due without touching its status", () => {- const goal = createGoal({ project_slug: SLUG, agent_id: "a-unlock", statement: "x" });- const action = createGoalAction({- goal_id: goal.id,- kind: "mutation",- description: "gated",- expected_effect: "n/a",- review_after: new Date(Date.now() + 3600_000).toISOString(),- });- expect(listGatedActions(goal.id)).toHaveLength(1);-- const released = endActionObservation(action.id);- expect(released?.status).toBe("open");- expect(listGatedActions(goal.id)).toHaveLength(0);- // Releasing twice (or releasing a windowless action) is a no-op.- expect(endActionObservation(action.id)).toBeNull();- });-});--describe("deleteGoalsForAgent", () => {- it("deletes the goal rows and cascades child tables", () => {- const goal = createGoal({ project_slug: SLUG, agent_id: "a-del", statement: "delete me" });- recordMetricSnapshot(goal.id, 42, "intake");- setGoalPinned(goal.id, true);-- expect(deleteGoalsForAgent("a-del")).toBe(1);- expect(getGoal(goal.id)).toBeNull();- const snaps = getDb()- .prepare("SELECT COUNT(*) AS n FROM goal_metric_snapshots WHERE goal_id = ?")- .get(goal.id) as { n: number };- expect(snaps.n).toBe(0);- const pins = getDb()- .prepare("SELECT COUNT(*) AS n FROM goal_pins WHERE goal_id = ?")- .get(goal.id) as { n: number };- expect(pins.n).toBe(0);- });-});diff --git a/notfair/src/server/db/goals.ts b/notfair/src/server/db/goals.tsdeleted file mode 100644index 6e7ce88c..00000000--- a/notfair/src/server/db/goals.ts+++ /dev/null@@ -1,1088 +0,0 @@-import { randomUUID } from "node:crypto";-import { CronExpressionParser } from "cron-parser";-import { getDb } from "./db";--/**- * Data layer for the goal-driven agent loop.- *- * The goal row IS the loop's state machine — the agent's context window is- * disposable, so everything a tick needs to orient (metric spec, open- * actions, learnings, history) lives here. Status flow:- *- * intake ──▶ proposed ──▶ active ⇄ paused- * │- * ▼- * achieved | failed | killed (terminal)- * │- * └── user sets next milestone ──▶ active- *- * intake — goal agent is authoring + testing the metric query- * proposed — metric verified server-side, baseline measured; awaiting the- * user's confirmation of target/deadline/envelope- * active — heartbeat ticks run on cadence_cron- */--export type GoalStatus =- | "intake"- | "proposed"- | "active"- | "paused"- | "achieved"- | "failed"- | "killed";--export const GOAL_LIVE_STATUSES: GoalStatus[] = [- "intake",- "proposed",- "active",- "paused",-];--export const GOAL_TERMINAL_STATUSES: GoalStatus[] = [- "achieved",- "failed",- "killed",-];--export type MetricDirection = "increase" | "decrease";--/** achieve = complete when the target is reached. maintain = hold the- * number there indefinitely; target met is the steady state. */-export type GoalMode = "achieve" | "maintain";--export type Goal = {- id: string;- project_slug: string;- agent_id: string;- statement: string;- /** Compact display label ("Wasted X spend → $0"), written by the agent- * during define_goal. Display falls back to a trimmed statement. */- short_label: string | null;- status: GoalStatus;- status_reason: string | null;- metric_name: string | null;- metric_source_key: string | null;- metric_source_tool: string | null;- metric_source_args_json: string | null;- metric_direction: MetricDirection | null;- baseline_value: number | null;- current_value: number | null;- target_value: number | null;- mode: GoalMode;- deadline: string | null;- spend_envelope_usd: number | null;- cadence_cron: string;- next_tick_at: string | null;- last_tick_at: string | null;- tick_count: number;- created_at: string;- updated_at: string;-};--export type GoalActionKind = "mutation" | "research" | "decision";-export type GoalActionStatus = "open" | "reviewed" | "abandoned";--export type GoalAction = {- id: string;- goal_id: string;- tick_number: number | null;- kind: GoalActionKind;- description: string;- resources_touched_json: string;- expected_effect: string;- review_after: string | null;- spend_usd: number | null;- status: GoalActionStatus;- observed_outcome: string | null;- reviewed_at: string | null;- created_at: string;-};--export type GoalMetricSnapshot = {- id: string;- goal_id: string;- value: number;- source: "intake" | "tick" | "manual" | "backfill";- created_at: string;-};--export type GoalLearning = {- id: string;- goal_id: string;- body: string;- confidence: "low" | "medium" | "high";- superseded_by: string | null;- created_at: string;-};--export type GoalTickTrigger = "heartbeat" | "manual" | "approval" | "intake";-export type GoalTickStatus = "running" | "done" | "failed";--export type GoalTick = {- id: string;- goal_id: string;- tick_number: number;- trigger_kind: GoalTickTrigger;- owner_pid: number | null;- session_id: string | null;- metric_value: number | null;- metric_error: string | null;- status: GoalTickStatus;- summary: string | null;- started_at: string;- finished_at: string | null;-};--function now(): string {- return new Date().toISOString();-}--function computeNextTick(cron_expr: string, from = new Date()): string | null {- try {- const it = CronExpressionParser.parse(cron_expr, { currentDate: from, tz: "UTC" });- return it.next().toISOString();- } catch {- return null;- }-}--// ── goals ────────────────────────────────────────────────────────────────--export type CreateGoalInput = {- project_slug: string;- agent_id: string;- /** Empty at agent creation — the user articulates it in chat and the- * agent records it via the define_goal tool. */- statement?: string;- deadline?: string | null;- spend_envelope_usd?: number | null;- cadence_cron?: string;-};--/**- * Insert a new goal in `intake`. Agent = goal: each agent owns exactly one- * live goal (partial unique index on agent_id enforces it at the DB level;- * we pre-check to control the message).- */-export function createGoal(input: CreateGoalInput): Goal {- const db = getDb();- if (getGoalForAgent(input.agent_id)) {- throw new Error(- `Agent '${input.agent_id}' already has a live goal.`,- );- }- const id = randomUUID();- const ts = now();- db.prepare(- `INSERT INTO goals- (id, project_slug, agent_id, statement, status, cadence_cron,- deadline, spend_envelope_usd, created_at, updated_at)- VALUES (?, ?, ?, ?, 'intake', ?, ?, ?, ?, ?)`,- ).run(- id,- input.project_slug,- input.agent_id,- input.statement ?? "",- input.cadence_cron ?? "0 16 * * *",- input.deadline ?? null,- input.spend_envelope_usd ?? null,- ts,- ts,- );- return getGoal(id)!;-}--export function getGoal(id: string): Goal | null {- const row = getDb().prepare("SELECT * FROM goals WHERE id = ?").get(id);- return (row as Goal) ?? null;-}--/** The agent's one live goal (intake/proposed/active/paused), if any. */-export function getGoalForAgent(agent_id: string): Goal | null {- const row = getDb()- .prepare(- `SELECT * FROM goals- WHERE agent_id = ?- AND status IN ('intake','proposed','active','paused')- LIMIT 1`,- )- .get(agent_id);- return (row as Goal) ?? null;-}--/** The agent's most recent goal, any status — terminal goals stay visible- * on the agent's page as history (the achievement IS the payoff). */-export function getLatestGoalForAgent(agent_id: string): Goal | null {- const row = getDb()- .prepare(- "SELECT * FROM goals WHERE agent_id = ? ORDER BY created_at DESC, rowid DESC LIMIT 1",- )- .get(agent_id);- return (row as Goal) ?? null;-}--/** Every live goal in the project — one per agent. */-export function listLiveGoals(project_slug: string): Goal[] {- return getDb()- .prepare(- `SELECT * FROM goals- WHERE project_slug = ?- AND status IN ('intake','proposed','active','paused')- ORDER BY created_at ASC`,- )- .all(project_slug) as Goal[];-}--/**- * Goals shown in daily navigation. Achievements remain visible until the user- * explicitly archives them, which prevents the completion moment from- * silently disappearing between sidebar refreshes.- */-export function listSidebarGoals(project_slug: string): Goal[] {- return getDb()- .prepare(- `SELECT g.* FROM goals g- LEFT JOIN goal_archives a ON a.goal_id = g.id- WHERE g.project_slug = ?- AND (- g.status IN ('intake','proposed','active','paused')- OR (g.status = 'achieved' AND a.goal_id IS NULL)- )- ORDER BY- CASE WHEN g.status = 'achieved' THEN 0 ELSE 1 END,- CASE WHEN g.status = 'achieved' THEN g.updated_at END DESC,- g.created_at ASC`,- )- .all(project_slug) as Goal[];-}--/** Whether an achieved goal has been dismissed from daily navigation. */-export function isGoalArchived(id: string): boolean {- return Boolean(- getDb().prepare("SELECT 1 FROM goal_archives WHERE goal_id = ?").get(id),- );-}--/**- * Archive an achievement without changing its historical status. Idempotent- * so a double click cannot corrupt or rewrite the completion record.- */-export function archiveAchievedGoal(id: string): Goal | null {- const goal = getGoal(id);- if (!goal || goal.status !== "achieved") return null;- getDb()- .prepare(- "INSERT OR IGNORE INTO goal_archives (goal_id, archived_at) VALUES (?, ?)",- )- .run(id, now());- return goal;-}--/**- * Turn a completed achievement into the next measurable milestone. This is- * the one intentional terminal → live transition: it keeps the same metric,- * evidence, chat, and agent, but requires a target beyond the freshly- * completed value.- */-export function continueAchievedGoal(- id: string,- input: {- target_value: number;- deadline: string | null;- short_label?: string | null;- },-): Goal | null {- const goal = getGoal(id);- if (!goal || goal.status !== "achieved") return null;- if (goal.current_value === null || goal.metric_direction === null) {- throw new Error("This goal has no current measured value to continue from.");- }- if (!Number.isFinite(input.target_value)) {- throw new Error("Enter a valid target.");- }- const movesForward =- goal.metric_direction === "increase"- ? input.target_value > goal.current_value- : input.target_value < goal.current_value;- if (!movesForward) {- const direction = goal.metric_direction === "increase" ? "above" : "below";- throw new Error(- `Set the next target ${direction} the completed value (${goal.current_value}).`,- );- }- const nextTick = computeNextTick(goal.cadence_cron);- if (!nextTick) {- throw new Error(`Invalid cadence cron expression: '${goal.cadence_cron}'`);- }-- const db = getDb();- const update = db.transaction(() => {- const result = db- .prepare(- `UPDATE goals- SET target_value = ?, deadline = ?,- short_label = COALESCE(?, short_label), status = 'active',- status_reason = NULL, next_tick_at = ?, updated_at = ?- WHERE id = ? AND status = 'achieved'`,- )- .run(- input.target_value,- input.deadline,- input.short_label?.trim() || null,- nextTick,- now(),- id,- );- if (result.changes === 0) return false;- db.prepare("DELETE FROM goal_archives WHERE goal_id = ?").run(id);- return true;- });- if (!update()) return null;- return getGoal(id);-}--/**- * Chat-intake step 1: record what the user wants (statement) plus any- * constraints they stated. Only while the goal is still in intake.- */-export function defineGoal(- id: string,- input: {- statement: string;- short_label?: string | null;- deadline?: string | null;- spend_envelope_usd?: number | null;- },-): Goal | null {- const r = getDb()- .prepare(- `UPDATE goals- SET statement = ?, short_label = COALESCE(?, short_label),- deadline = COALESCE(?, deadline),- spend_envelope_usd = COALESCE(?, spend_envelope_usd), updated_at = ?- WHERE id = ? AND status = 'intake'`,- )- .run(- input.statement,- input.short_label ?? null,- input.deadline ?? null,- input.spend_envelope_usd ?? null,- now(),- id,- );- if (r.changes === 0) return null;- return getGoal(id);-}--export function listGoals(project_slug: string): Goal[] {- return getDb()- .prepare("SELECT * FROM goals WHERE project_slug = ? ORDER BY created_at DESC")- .all(project_slug) as Goal[];-}--export type GoalMetricSpec = {- metric_name: string;- metric_source_key: string;- metric_source_tool: string;- metric_source_args_json: string;- metric_direction: MetricDirection;- baseline_value: number;-};--/**- * Intake result: the verified metric definition + measured baseline.- * Moves intake → proposed. No-op (returns null) if the goal isn't in- * intake — proposing twice or after activation is a bug upstream.- */-export function setGoalMetric(id: string, spec: GoalMetricSpec): Goal | null {- const db = getDb();- const r = db- .prepare(- `UPDATE goals- SET metric_name = ?, metric_source_key = ?, metric_source_tool = ?,- metric_source_args_json = ?, metric_direction = ?,- baseline_value = ?, current_value = ?,- status = 'proposed', updated_at = ?- WHERE id = ? AND status = 'intake'`,- )- .run(- spec.metric_name,- spec.metric_source_key,- spec.metric_source_tool,- spec.metric_source_args_json,- spec.metric_direction,- spec.baseline_value,- spec.baseline_value,- now(),- id,- );- if (r.changes === 0) return null;- return getGoal(id);-}--export type ProposeTargetInput = {- target_value: number;- mode?: GoalMode;- deadline?: string | null;- spend_envelope_usd?: number | null;- cadence_cron?: string;-};--/**- * The user's confirmation, recorded from chat: target/cadence/envelope- * land on the `proposed` goal and the loop goes live in the same step —- * proposed → active with the first heartbeat scheduled. The caller fires- * an immediate first tick.- */-export function proposeTarget(id: string, input: ProposeTargetInput): Goal | null {- const goal = getGoal(id);- if (!goal || goal.status !== "proposed") return null;- const cadence = input.cadence_cron ?? goal.cadence_cron;- const nextTick = computeNextTick(cadence);- if (!nextTick) {- throw new Error(`Invalid cadence cron expression: '${cadence}'`);- }- getDb()- .prepare(- `UPDATE goals- SET target_value = ?, mode = ?, deadline = ?, spend_envelope_usd = ?,- cadence_cron = ?, status = 'active', next_tick_at = ?, updated_at = ?- WHERE id = ? AND status = 'proposed'`,- )- .run(- input.target_value,- input.mode ?? goal.mode ?? "achieve",- input.deadline ?? goal.deadline,- input.spend_envelope_usd ?? goal.spend_envelope_usd,- cadence,- nextTick,- now(),- id,- );- return getGoal(id);-}--export type AmendGoalInput = {- target_value?: number;- deadline?: string | null;- spend_envelope_usd?: number | null;- cadence_cron?: string;-};--/**- * Adjust a LIVE goal's parameters — "raise my envelope to $3k", "make the- * target 25" are normal asks and must not require killing the goal.- * Allowed while active or paused; recomputes the heartbeat when the- * cadence changes on an active goal.- */-export function amendGoal(id: string, input: AmendGoalInput): Goal | null {- const goal = getGoal(id);- if (!goal || (goal.status !== "active" && goal.status !== "paused")) return null;- const cadence = input.cadence_cron ?? goal.cadence_cron;- const cadenceChanged = cadence !== goal.cadence_cron;- if (cadenceChanged && !computeNextTick(cadence)) {- throw new Error(`Invalid cadence cron expression: '${cadence}'`);- }- const nextTick =- goal.status === "active"- ? cadenceChanged- ? computeNextTick(cadence)- : goal.next_tick_at- : null;- getDb()- .prepare(- `UPDATE goals- SET target_value = COALESCE(?, target_value),- deadline = COALESCE(?, deadline),- spend_envelope_usd = COALESCE(?, spend_envelope_usd),- cadence_cron = ?, next_tick_at = ?, updated_at = ?- WHERE id = ?`,- )- .run(- input.target_value ?? null,- input.deadline ?? null,- input.spend_envelope_usd ?? null,- cadence,- nextTick,- now(),- id,- );- return getGoal(id);-}--/**- * Rename the goal's display label. Works in any status — a closed goal's- * label is still the user's handle for it in history views.- */-export function renameGoal(id: string, short_label: string): Goal | null {- const r = getDb()- .prepare("UPDATE goals SET short_label = ?, updated_at = ? WHERE id = ?")- .run(short_label, now(), id);- if (r.changes === 0) return null;- return getGoal(id);-}--/**- * Hard-delete an agent's goal rows. FK cascades take actions, snapshots,- * learnings, ticks, PRs, and pins with them. Agent = goal, so callers pair- * this with the agent's workspace/session cascade.- */-export function deleteGoalsForAgent(agent_id: string): number {- return getDb().prepare("DELETE FROM goals WHERE agent_id = ?").run(agent_id).changes;-}--// ── pins ─────────────────────────────────────────────────────────────────--export function setGoalPinned(id: string, pinned: boolean): void {- const db = getDb();- if (pinned) {- db.prepare(- "INSERT OR IGNORE INTO goal_pins (goal_id, created_at) VALUES (?, ?)",- ).run(id, now());- } else {- db.prepare("DELETE FROM goal_pins WHERE goal_id = ?").run(id);- }-}--/** Pinned goal ids for a project (sidebar sorts these first). */-export function getPinnedGoalIds(project_slug: string): Set<string> {- const rows = getDb()- .prepare(- `SELECT p.goal_id FROM goal_pins p- JOIN goals g ON g.id = p.goal_id- WHERE g.project_slug = ?`,- )- .all(project_slug) as Array<{ goal_id: string }>;- return new Set(rows.map((r) => r.goal_id));-}--/** Total incremental spend the agent has logged (non-abandoned actions). */-export function loggedSpendTotal(goal_id: string): number {- const row = getDb()- .prepare(- `SELECT COALESCE(SUM(spend_usd), 0) AS total FROM goal_actions- WHERE goal_id = ? AND status != 'abandoned'`,- )- .get(goal_id) as { total: number };- return row.total;-}--/**- * Open, still-gated actions belonging to OTHER live goals in the same- * project. Their resources are just as untouchable — two agents sharing- * an ad account must not thrash each other's experiments.- */-export function listGatedActionsForOtherAgents(- project_slug: string,- goal_id: string,- nowIso = now(),-): Array<GoalAction & { agent_id: string }> {- return getDb()- .prepare(- `SELECT ga.*, g.agent_id FROM goal_actions ga- JOIN goals g ON g.id = ga.goal_id- WHERE g.project_slug = ? AND g.id != ?- AND g.status IN ('active','paused')- AND ga.status = 'open'- AND ga.review_after IS NOT NULL AND ga.review_after > ?- ORDER BY ga.review_after ASC`,- )- .all(project_slug, goal_id, nowIso) as Array<GoalAction & { agent_id: string }>;-}--/**- * Status transitions outside the intake→proposed→active happy path:- * pause/resume and the three terminal states. This generic transition stays- * one-way; the explicit achieved → active continuation is isolated in- * continueAchievedGoal so a failed or closed goal can never be revived.- */-export function setGoalStatus(- id: string,- status: Extract<GoalStatus, "active" | "paused" | "achieved" | "failed" | "killed">,- reason?: string | null,-): Goal | null {- const goal = getGoal(id);- if (!goal) return null;- if (GOAL_TERMINAL_STATUSES.includes(goal.status)) return goal; // no rewrites- // Resuming (→ active) restarts the heartbeat; anything else stops it.- const nextTick = status === "active" ? computeNextTick(goal.cadence_cron) : null;- getDb()- .prepare(- `UPDATE goals- SET status = ?, status_reason = ?, next_tick_at = ?, updated_at = ?- WHERE id = ?`,- )- .run(status, reason ?? null, nextTick, now(), id);- return getGoal(id);-}--/** Active goals whose heartbeat is due. Mirrors scheduler dueJobs(). */-export function dueGoals(nowIso = now()): Goal[] {- return getDb()- .prepare(- `SELECT * FROM goals- WHERE status = 'active'- AND next_tick_at IS NOT NULL- AND next_tick_at <= ?`,- )- .all(nowIso) as Goal[];-}--/**- * Advance the heartbeat the moment a tick starts (double-fire guard —- * same pattern as scheduler markJobRun) and bump the loop counters.- * Returns the tick_number this tick should use.- */-export function markGoalTicked(id: string): number {- const db = getDb();- const goal = getGoal(id);- if (!goal) throw new Error(`goal not found: ${id}`);- const ts = now();- const nextTick = computeNextTick(goal.cadence_cron);- db.prepare(- `UPDATE goals- SET last_tick_at = ?, next_tick_at = ?, tick_count = tick_count + 1,- updated_at = ?- WHERE id = ?`,- ).run(ts, nextTick, ts, id);- return goal.tick_count + 1;-}--export function updateGoalCurrentValue(id: string, value: number): void {- getDb()- .prepare("UPDATE goals SET current_value = ?, updated_at = ? WHERE id = ?")- .run(value, now(), id);-}--// ── metric snapshots ─────────────────────────────────────────────────────--export function recordMetricSnapshot(- goal_id: string,- value: number,- source: GoalMetricSnapshot["source"] = "tick",-): GoalMetricSnapshot {- const db = getDb();- const id = randomUUID();- const ts = now();- db.prepare(- "INSERT INTO goal_metric_snapshots (id, goal_id, value, source, created_at) VALUES (?, ?, ?, ?, ?)",- ).run(id, goal_id, value, source, ts);- updateGoalCurrentValue(goal_id, value);- return { id, goal_id, value, source, created_at: ts };-}--/**- * Replace the goal's backfilled history with a fresh set of backdated- * points (from the agent's date-segmented history query). Never touches- * live intake/tick/manual snapshots; does not update current_value.- */-export function replaceBackfillSnapshots(- goal_id: string,- points: Array<{ value: number; created_at: string }>,-): number {- const db = getDb();- const insert = db.prepare(- "INSERT INTO goal_metric_snapshots (id, goal_id, value, source, created_at) VALUES (?, ?, ?, 'backfill', ?)",- );- const tx = db.transaction(() => {- db.prepare(- "DELETE FROM goal_metric_snapshots WHERE goal_id = ? AND source = 'backfill'",- ).run(goal_id);- for (const p of points) insert.run(randomUUID(), goal_id, p.value, p.created_at);- });- tx();- return points.length;-}--export function listMetricSnapshots(goal_id: string, limit = 90): GoalMetricSnapshot[] {- // Ascending so the sparkline reads left→right; LIMIT applies to the tail.- return getDb()- .prepare(- `SELECT id, goal_id, value, source, created_at FROM (- SELECT *, rowid AS _rid FROM goal_metric_snapshots- WHERE goal_id = ? ORDER BY created_at DESC, rowid DESC LIMIT ?- ) ORDER BY created_at ASC, _rid ASC`,- )- .all(goal_id, limit) as GoalMetricSnapshot[];-}--// ── actions ──────────────────────────────────────────────────────────────--export type CreateGoalActionInput = {- goal_id: string;- tick_number?: number | null;- kind: GoalActionKind;- description: string;- resources_touched?: string[];- expected_effect: string;- review_after?: string | null;- spend_usd?: number | null;- /** Agent-written check-diary badge, e.g. "Budget updated". */- badge?: string | null;-};--export function createGoalAction(input: CreateGoalActionInput): GoalAction {- const db = getDb();- const id = randomUUID();- const ts = now();- db.prepare(- `INSERT INTO goal_actions- (id, goal_id, tick_number, kind, description, resources_touched_json,- expected_effect, review_after, spend_usd, status, created_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?)`,- ).run(- id,- input.goal_id,- input.tick_number ?? null,- input.kind,- input.description,- JSON.stringify(input.resources_touched ?? []),- input.expected_effect,- input.review_after ?? null,- input.spend_usd ?? null,- ts,- );- const badge = input.badge?.trim().slice(0, 60);- if (badge) {- db.prepare(- "INSERT INTO goal_action_badges (action_id, badge, created_at) VALUES (?, ?, ?)",- ).run(id, badge, ts);- }- return getGoalAction(id)!;-}--/** Agent-written badges across a goal's actions, oldest first per tick. */-export function listGoalActionBadges(- goal_id: string,-): Array<{ tick_number: number | null; badge: string }> {- return getDb()- .prepare(- `SELECT a.tick_number AS tick_number, b.badge AS badge- FROM goal_action_badges b- JOIN goal_actions a ON a.id = b.action_id- WHERE a.goal_id = ?- ORDER BY a.created_at ASC, a.rowid ASC`,- )- .all(goal_id) as Array<{ tick_number: number | null; badge: string }>;-}--export function getGoalAction(id: string): GoalAction | null {- const row = getDb().prepare("SELECT * FROM goal_actions WHERE id = ?").get(id);- return (row as GoalAction) ?? null;-}--export function listOpenGoalActions(goal_id: string): GoalAction[] {- return getDb()- .prepare(- "SELECT * FROM goal_actions WHERE goal_id = ? AND status = 'open' ORDER BY created_at ASC, rowid ASC",- )- .all(goal_id) as GoalAction[];-}--/** Escalation contract: the agent identity requires decision actions that- * need the USER to act to start with this prefix. The "Needs you" UI keys- * off it — prose elsewhere never surfaces there. */-export const USER_ACTION_PREFIX = "USER ACTION REQUIRED";--/** Open escalations awaiting the user, oldest first. */-export function listUserActionRequests(goal_id: string): GoalAction[] {- return listOpenGoalActions(goal_id).filter(- (a) => a.kind === "decision" && a.description.startsWith(USER_ACTION_PREFIX),- );-}--/** goal_id → open user-escalation count, for rail badges across a project. */-export function countUserActionRequests(project_slug: string): Map<string, number> {- const rows = getDb()- .prepare(- `SELECT a.goal_id AS goal_id, COUNT(*) AS n- FROM goal_actions a- JOIN goals g ON g.id = a.goal_id- WHERE g.project_slug = ? AND a.status = 'open'- AND a.kind = 'decision' AND a.description LIKE ? || '%'- GROUP BY a.goal_id`,- )- .all(project_slug, USER_ACTION_PREFIX) as Array<{ goal_id: string; n: number }>;- return new Map(rows.map((r) => [r.goal_id, r.n]));-}--export function listGoalActions(goal_id: string, limit = 50): GoalAction[] {- return getDb()- .prepare(- "SELECT * FROM goal_actions WHERE goal_id = ? ORDER BY created_at DESC, rowid DESC LIMIT ?",- )- .all(goal_id, limit) as GoalAction[];-}--/**- * Close the measurement loop on an action: record what actually happened- * vs. expected_effect. Only open actions can be reviewed.- */-export function reviewGoalAction(- id: string,- observed_outcome: string,- status: Extract<GoalActionStatus, "reviewed" | "abandoned"> = "reviewed",-): GoalAction | null {- const r = getDb()- .prepare(- `UPDATE goal_actions- SET status = ?, observed_outcome = ?, reviewed_at = ?- WHERE id = ? AND status = 'open'`,- )- .run(status, observed_outcome, now(), id);- if (r.changes === 0) return null;- return getGoalAction(id);-}--/** Open mutations past their review_after — the "score these first" list. */-export function listActionsDueForReview(goal_id: string, nowIso = now()): GoalAction[] {- return getDb()- .prepare(- `SELECT * FROM goal_actions- WHERE goal_id = ? AND status = 'open'- AND review_after IS NOT NULL AND review_after <= ?- ORDER BY review_after ASC`,- )- .all(goal_id, nowIso) as GoalAction[];-}--/**- * End an action's observation window NOW — the user's manual unlock.- * The action stays open and becomes immediately due for review, so the- * agent scores it on its next check; nothing is deleted or rewritten.- */-export function endActionObservation(id: string): GoalAction | null {- const ts = now();- const r = getDb()- .prepare(- `UPDATE goal_actions SET review_after = ?- WHERE id = ? AND status = 'open'- AND review_after IS NOT NULL AND review_after > ?`,- )- .run(ts, id, ts);- if (r.changes === 0) return null;- return getGoalAction(id);-}--/** Open mutations still inside their observation window — the gate. */-export function listGatedActions(goal_id: string, nowIso = now()): GoalAction[] {- return getDb()- .prepare(- `SELECT * FROM goal_actions- WHERE goal_id = ? AND status = 'open'- AND review_after IS NOT NULL AND review_after > ?- ORDER BY review_after ASC`,- )- .all(goal_id, nowIso) as GoalAction[];-}--// ── learnings ────────────────────────────────────────────────────────────--export function addGoalLearning(- goal_id: string,- body: string,- confidence: GoalLearning["confidence"] = "medium",- supersedes_id?: string | null,-): GoalLearning {- const db = getDb();- const id = randomUUID();- const ts = now();- db.prepare(- "INSERT INTO goal_learnings (id, goal_id, body, confidence, created_at) VALUES (?, ?, ?, ?, ?)",- ).run(id, goal_id, body, confidence, ts);- if (supersedes_id) {- db.prepare("UPDATE goal_learnings SET superseded_by = ? WHERE id = ? AND goal_id = ?").run(- id,- supersedes_id,- goal_id,- );- }- return { id, goal_id, body, confidence, superseded_by: null, created_at: ts };-}--/** Most recent non-superseded learnings, newest first. */-export function listGoalLearnings(goal_id: string, limit = 20): GoalLearning[] {- return getDb()- .prepare(- `SELECT * FROM goal_learnings- WHERE goal_id = ? AND superseded_by IS NULL- ORDER BY created_at DESC, rowid DESC LIMIT ?`,- )- .all(goal_id, limit) as GoalLearning[];-}--/** Simple substring search over non-superseded learnings. */-export function searchGoalLearnings(- goal_id: string,- query: string,- limit = 20,-): GoalLearning[] {- return getDb()- .prepare(- `SELECT * FROM goal_learnings- WHERE goal_id = ? AND superseded_by IS NULL- AND body LIKE ? ESCAPE '\\'- ORDER BY created_at DESC, rowid DESC LIMIT ?`,- )- .all(- goal_id,- `%${query.replace(/[\\%_]/g, (c) => `\\${c}`)}%`,- limit,- ) as GoalLearning[];-}--// ── ticks (the diary) ────────────────────────────────────────────────────--export function createGoalTick(input: {- goal_id: string;- tick_number: number;- trigger_kind: GoalTickTrigger;-}): GoalTick {- const db = getDb();- const id = randomUUID();- const ts = now();- db.prepare(- `INSERT INTO goal_ticks- (id, goal_id, tick_number, trigger_kind, owner_pid, status, started_at)- VALUES (?, ?, ?, ?, ?, 'running', ?)`,- ).run(id, input.goal_id, input.tick_number, input.trigger_kind, process.pid, ts);- return getGoalTick(id)!;-}--/** Backfill the measured metric onto a check created before measurement. */-export function setGoalTickMetric(- id: string,- metric_value: number | null,- metric_error: string | null,-): void {- getDb()- .prepare("UPDATE goal_ticks SET metric_value = ?, metric_error = ? WHERE id = ?")- .run(metric_value, metric_error, id);-}--export function getGoalTick(id: string): GoalTick | null {- const row = getDb().prepare("SELECT * FROM goal_ticks WHERE id = ?").get(id);- return (row as GoalTick) ?? null;-}--export function attachTickSession(id: string, session_id: string): void {- getDb().prepare("UPDATE goal_ticks SET session_id = ? WHERE id = ?").run(session_id, id);-}--export function finishGoalTick(- id: string,- status: Extract<GoalTickStatus, "done" | "failed">,- summary?: string | null,-): void {- getDb()- .prepare(- "UPDATE goal_ticks SET status = ?, summary = ?, finished_at = ? WHERE id = ?",- )- .run(status, summary ?? null, now(), id);-}--/** Terminal transition used by crash recovery; never overwrite live progress. */-export function finishRunningGoalTick(- id: string,- status: Extract<GoalTickStatus, "done" | "failed">,- summary?: string | null,-): boolean {- const result = getDb()- .prepare(- `UPDATE goal_ticks- SET status = ?, summary = ?, finished_at = ?- WHERE id = ? AND status = 'running'`,- )- .run(status, summary ?? null, now(), id);- return result.changes === 1;-}--export function listGoalTicks(- goal_id: string,- limit = 30,- /** Cursor: only ticks strictly older than this tick_number (pagination). */- beforeTick?: number,-): GoalTick[] {- if (beforeTick !== undefined) {- return getDb()- .prepare(- "SELECT * FROM goal_ticks WHERE goal_id = ? AND tick_number < ? ORDER BY tick_number DESC LIMIT ?",- )- .all(goal_id, beforeTick, limit) as GoalTick[];- }- return getDb()- .prepare(- "SELECT * FROM goal_ticks WHERE goal_id = ? ORDER BY tick_number DESC LIMIT ?",- )- .all(goal_id, limit) as GoalTick[];-}--/** Every MCP/tool call started across a goal's tick sessions, in event- * order — the checks list classifies these into write badges. */-export function listTickToolCalls(- goal_id: string,-): Array<{ tick_number: number; name: string }> {- return getDb()- .prepare(- `SELECT t.tick_number AS tick_number,- json_extract(e.payload_json, '$.name') AS name- FROM goal_ticks t- JOIN transcript_events e ON e.session_id = t.session_id- WHERE t.goal_id = ? AND e.kind = 'tool'- AND json_extract(e.payload_json, '$.phase') = 'start'- ORDER BY t.tick_number ASC, e.seq ASC`,- )- .all(goal_id) as Array<{ tick_number: number; name: string }>;-}--/** Specific ticks by number, newest first — backs the filtered checks list. */-export function listGoalTicksByNumbers(- goal_id: string,- tickNumbers: number[],-): GoalTick[] {- if (tickNumbers.length === 0) return [];- const placeholders = tickNumbers.map(() => "?").join(",");- return getDb()- .prepare(- `SELECT * FROM goal_ticks WHERE goal_id = ? AND tick_number IN (${placeholders})- ORDER BY tick_number DESC`,- )- .all(goal_id, ...tickNumbers) as GoalTick[];-}--/**- * Most recent finished tick that carries context worth briefing the next- * turn with: agent turns (session attached) and failures. Observe-only- * no-op checks (done, no session) are skipped — a week of "no-op check"- * rows must not evict the agent's last real summary from the brief.- */-export function getLastAgentTick(goal_id: string): GoalTick | null {- const row = getDb()- .prepare(- `SELECT * FROM goal_ticks- WHERE goal_id = ? AND status IN ('done','failed')- AND NOT (status = 'done' AND session_id IS NULL)- ORDER BY tick_number DESC LIMIT 1`,- )- .get(goal_id);- return (row as GoalTick) ?? null;-}--// ── derived reads ────────────────────────────────────────────────────────--/**- * Direction-aware "has the metric met the target?". Null when the goal- * doesn't have both a target and a current reading yet.- */-export function isTargetMet(goal: Goal): boolean | null {- if (goal.target_value === null || goal.current_value === null) return null;- if (goal.metric_direction === "decrease") {- return goal.current_value <= goal.target_value;- }- return goal.current_value >= goal.target_value;-}--export function isPastDeadline(goal: Goal, nowIso = now()): boolean {- if (!goal.deadline) return false;- return nowIso >= goal.deadline;-}diff --git a/notfair/src/server/db/projects.test.ts b/notfair/src/server/db/projects.test.tsdeleted file mode 100644index f51e6d0f..00000000--- a/notfair/src/server/db/projects.test.ts+++ /dev/null@@ -1,280 +0,0 @@-import { describe, expect, it } from "vitest";-import { vi } from "vitest";--// Real better-sqlite3 against a tmpdir DB, per repo test conventions.-// MUST be hoisted: static imports evaluate before module-level statements,-// and db.ts captures NOTFAIR_DATA_DIR at import time — a plain assignment-// here would silently point the suite at the developer's live ~/.notfair.-vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-db-projects-"));-});--import { getDb } from "./db";-import {- addHiddenMcpPresetKey,- archiveProject,- changeProjectSlug,- createProject,- deleteProjectRow,- getHiddenMcpPresetKeys,- getProject,- listProjects,- removeHiddenMcpPresetKey,- renameProject,- setProjectCodebasePath,- setProjectGoogleAdsAccount,- setProjectGscProperty,- setProjectHarnessAdapter,- setProjectMetaAdsAccount,- unarchiveProject,-} from "./projects";-import { createGoal } from "./goals";-import { insertUserMcpServer, listUserMcpServers } from "./user-mcp-servers";--describe("createProject", () => {- it("creates a project with defaults and a slug from the display name", () => {- const result = createProject({ display_name: " Acme Corp " });- expect(result.ok).toBe(true);- if (!result.ok) return;- expect(result.project.slug).toBe("acme-corp");- expect(result.project.display_name).toBe("Acme Corp");- expect(result.project.harness_adapter).toBe("claude-code-local");- expect(result.project.website_url).toBeNull();- expect(result.project.codebase_path).toBeNull();- // Round-trips through the DB.- expect(getProject("acme-corp")).toMatchObject({- slug: "acme-corp",- display_name: "Acme Corp",- archived_at: null,- });- });-- it("rejects an unusable display name", () => {- const result = createProject({ display_name: "###" });- expect(result.ok).toBe(false);- });-- it("rejects a duplicate slug", () => {- createProject({ display_name: "Dup Target" });- const result = createProject({ display_name: "Dup Target" });- expect(result).toMatchObject({ ok: false });- if (result.ok) return;- expect(result.reason).toContain("already exists");- });-- it("honors an explicit slug, harness adapter, and trims optional hints", () => {- const result = createProject({- display_name: "Hints",- slug: "hints-custom",- website_url: " https://hints.dev ",- codebase_path: " ",- harness_adapter: "codex-local",- });- expect(result.ok).toBe(true);- if (!result.ok) return;- expect(result.project.slug).toBe("hints-custom");- expect(result.project.website_url).toBe("https://hints.dev");- expect(result.project.codebase_path).toBeNull();- expect(result.project.harness_adapter).toBe("codex-local");- });-});--describe("listProjects", () => {- it("filters archived projects unless asked for them", () => {- createProject({ display_name: "List Live" });- createProject({ display_name: "List Archived" });- archiveProject("list-archived");-- const live = listProjects().map((p) => p.slug);- expect(live).toContain("list-live");- expect(live).not.toContain("list-archived");-- const all = listProjects({ includeArchived: true }).map((p) => p.slug);- expect(all).toContain("list-archived");- });-});--describe("getProject", () => {- it("returns null for a missing slug", () => {- expect(getProject("nope-never")).toBeNull();- });-});--describe("project field setters", () => {- it("returns null when the project doesn't exist", () => {- expect(setProjectGoogleAdsAccount("ghost", "123")).toBeNull();- expect(setProjectMetaAdsAccount("ghost", "act_1")).toBeNull();- expect(setProjectCodebasePath("ghost", "/tmp")).toBeNull();- expect(setProjectGscProperty("ghost", "sc-domain:x")).toBeNull();- });-- it("sets and clears the per-platform account fields", () => {- createProject({ display_name: "Setters" });- expect(setProjectGoogleAdsAccount("setters", "111")?.google_ads_account_id).toBe("111");- expect(setProjectMetaAdsAccount("setters", "act_2")?.meta_ads_account_id).toBe("act_2");- expect(setProjectCodebasePath("setters", "/repo")?.codebase_path).toBe("/repo");- expect(setProjectGscProperty("setters", "sc-domain:s")?.gsc_property_id).toBe("sc-domain:s");- expect(setProjectGoogleAdsAccount("setters", null)?.google_ads_account_id).toBeNull();- });-- it("swaps the harness adapter", () => {- createProject({ display_name: "Adapter Swap" });- expect(setProjectHarnessAdapter("adapter-swap", "codex-local")?.harness_adapter).toBe(- "codex-local",- );- });-});--describe("renameProject", () => {- it("rejects an empty name and trims a valid one", () => {- createProject({ display_name: "Rename Me" });- expect(renameProject("rename-me", " ")).toBeNull();- expect(renameProject("rename-me", " Renamed ")?.display_name).toBe("Renamed");- });-});--describe("archive / unarchive", () => {- it("stamps and clears archived_at", () => {- createProject({ display_name: "Arch" });- const archived = archiveProject("arch");- expect(archived?.archived_at).toBeTruthy();- // Re-archiving doesn't overwrite the original stamp.- expect(archiveProject("arch")?.archived_at).toBe(archived?.archived_at);- expect(unarchiveProject("arch")?.archived_at).toBeNull();- });-});--describe("changeProjectSlug", () => {- it("handles the same-slug display-name-only path", () => {- createProject({ display_name: "Same Slug" });- const updated = changeProjectSlug("same-slug", "same-slug", " Same Slug 2 ");- expect(updated?.display_name).toBe("Same Slug 2");- expect(changeProjectSlug("same-slug", "same-slug")?.slug).toBe("same-slug");- });-- it("returns null when the source slug doesn't exist", () => {- expect(changeProjectSlug("ghost-src", "ghost-dst")).toBeNull();- });-- it("throws when the destination slug is taken", () => {- createProject({ display_name: "Slug Src" });- createProject({ display_name: "Slug Dst" });- expect(() => changeProjectSlug("slug-src", "slug-dst")).toThrow(- "already exists",- );- });-- it("migrates every child row keyed off project_slug", () => {- createProject({ display_name: "Move Src" });- const now = new Date().toISOString();- getDb()- .prepare(- `INSERT INTO sessions (id, project_slug, agent_id, label, harness_adapter, created_at, updated_at)- VALUES ('mv-s1', 'move-src', 'move-src-goal-1', 'main', 'claude-code-local', ?, ?)`,- )- .run(now, now);- const goal = createGoal({- project_slug: "move-src",- agent_id: "move-src-goal-1",- statement: "grow",- });- insertUserMcpServer({- project_slug: "move-src",- key: "acme",- display_name: "Acme",- resource_url: "https://mcp.acme.dev/sse",- discovery_url: "https://mcp.acme.dev/.well-known/oauth-protected-resource/sse",- });-- const moved = changeProjectSlug("move-src", "move-dst", "Move Dst");- expect(moved).toMatchObject({ slug: "move-dst", display_name: "Move Dst" });- expect(getProject("move-src")).toBeNull();-- const session = getDb()- .prepare("SELECT project_slug FROM sessions WHERE id = 'mv-s1'")- .get() as { project_slug: string };- expect(session.project_slug).toBe("move-dst");- const movedGoal = getDb()- .prepare("SELECT project_slug FROM goals WHERE id = ?")- .get(goal.id) as { project_slug: string };- expect(movedGoal.project_slug).toBe("move-dst");- expect(listUserMcpServers("move-dst").map((r) => r.key)).toEqual(["acme"]);- expect(listUserMcpServers("move-src")).toEqual([]);- });-});--describe("deleteProjectRow", () => {- it("deletes the project and every child row", () => {- createProject({ display_name: "Del Me" });- const now = new Date().toISOString();- getDb()- .prepare(- `INSERT INTO sessions (id, project_slug, agent_id, label, harness_adapter, created_at, updated_at)- VALUES ('del-s1', 'del-me', 'del-me-goal-1', 'main', 'claude-code-local', ?, ?)`,- )- .run(now, now);- createGoal({ project_slug: "del-me", agent_id: "del-me-goal-1" });- insertUserMcpServer({- project_slug: "del-me",- key: "gone",- display_name: "Gone",- resource_url: "https://mcp.gone.dev",- discovery_url: "https://mcp.gone.dev/.well-known/oauth-protected-resource",- });-- deleteProjectRow("del-me");-- expect(getProject("del-me")).toBeNull();- const counts = getDb()- .prepare(- `SELECT- (SELECT COUNT(*) FROM sessions WHERE project_slug = 'del-me') AS sessions,- (SELECT COUNT(*) FROM goals WHERE project_slug = 'del-me') AS goals,- (SELECT COUNT(*) FROM user_mcp_servers WHERE project_slug = 'del-me') AS mcps`,- )- .get() as { sessions: number; goals: number; mcps: number };- expect(counts).toEqual({ sessions: 0, goals: 0, mcps: 0 });- });-});--describe("hidden MCP preset keys", () => {- it("adds, dedupes, and removes keys", () => {- createProject({ display_name: "Hide List" });- expect(getHiddenMcpPresetKeys("hide-list")).toEqual([]);-- addHiddenMcpPresetKey("hide-list", "notfair-googleads");- addHiddenMcpPresetKey("hide-list", "notfair-googleads"); // no dup- addHiddenMcpPresetKey("hide-list", "notfair-metaads");- expect(getHiddenMcpPresetKeys("hide-list")).toEqual([- "notfair-googleads",- "notfair-metaads",- ]);-- removeHiddenMcpPresetKey("hide-list", "notfair-googleads");- expect(getHiddenMcpPresetKeys("hide-list")).toEqual(["notfair-metaads"]);- // Removing an absent key is a no-op (no write).- removeHiddenMcpPresetKey("hide-list", "notfair-googleads");- expect(getHiddenMcpPresetKeys("hide-list")).toEqual(["notfair-metaads"]);- });-- it("tolerates corrupt or non-array JSON in the column", () => {- createProject({ display_name: "Hide Corrupt" });- getDb()- .prepare("UPDATE projects SET hidden_mcp_preset_keys_json = ? WHERE slug = ?")- .run("{not json", "hide-corrupt");- expect(getHiddenMcpPresetKeys("hide-corrupt")).toEqual([]);- getDb()- .prepare("UPDATE projects SET hidden_mcp_preset_keys_json = ? WHERE slug = ?")- .run('{"a":1}', "hide-corrupt");- expect(getHiddenMcpPresetKeys("hide-corrupt")).toEqual([]);- getDb()- .prepare("UPDATE projects SET hidden_mcp_preset_keys_json = ? WHERE slug = ?")- .run('["ok", 42]', "hide-corrupt");- expect(getHiddenMcpPresetKeys("hide-corrupt")).toEqual(["ok"]);- // Missing project → empty list.- expect(getHiddenMcpPresetKeys("no-such-project")).toEqual([]);- });-});diff --git a/notfair/src/server/db/projects.ts b/notfair/src/server/db/projects.tsdeleted file mode 100644index d3779133..00000000--- a/notfair/src/server/db/projects.ts+++ /dev/null@@ -1,332 +0,0 @@-import { randomUUID } from "node:crypto";-import { getDb } from "./db";-import type { Project } from "@/types";-import { slugify } from "@/lib/slug";-import { DEFAULT_HARNESS_ADAPTER, isHarnessAdapterId } from "@/server/adapters/registry";-import type { HarnessAdapterId } from "@/server/adapters/types";--export type CreateProjectInput = {- display_name: string;- slug?: string;- /** Optional onboarding hints. Free-text — agents decide how to use them. */- website_url?: string | null;- codebase_path?: string | null;- /** Adapter chosen at onboarding. Defaults to claude-code-local. */- harness_adapter?: HarnessAdapterId;-};--export type CreateProjectResult =- | { ok: true; project: Project }- | { ok: false; reason: string };--export function listProjects(opts: { includeArchived?: boolean } = {}): Project[] {- const db = getDb();- const sql = opts.includeArchived- ? "SELECT * FROM projects ORDER BY created_at DESC"- : "SELECT * FROM projects WHERE archived_at IS NULL ORDER BY created_at DESC";- return db.prepare(sql).all() as Project[];-}--export function getProject(slug: string): Project | null {- const db = getDb();- const row = db.prepare("SELECT * FROM projects WHERE slug = ?").get(slug);- return (row as Project) ?? null;-}--export function createProject(input: CreateProjectInput): CreateProjectResult {- const db = getDb();- const slugInput = input.slug ?? input.display_name;- const slug = slugify(slugInput);- if (!slug.ok) return { ok: false, reason: slug.reason };-- const existing = db.prepare("SELECT 1 FROM projects WHERE slug = ?").get(slug.slug);- if (existing) return { ok: false, reason: `project slug '${slug.slug}' already exists` };-- const website_url = trimOrNull(input.website_url);- const codebase_path = trimOrNull(input.codebase_path);- const harness_adapter: HarnessAdapterId =- input.harness_adapter && isHarnessAdapterId(input.harness_adapter)- ? input.harness_adapter- : DEFAULT_HARNESS_ADAPTER;-- const project: Project = {- id: randomUUID(),- slug: slug.slug,- display_name: input.display_name.trim(),- created_at: new Date().toISOString(),- archived_at: null,- google_ads_account_id: null,- meta_ads_account_id: null,- gsc_property_id: null,- website_url,- codebase_path,- harness_adapter,- };-- db.prepare(- "INSERT INTO projects (id, slug, display_name, created_at, archived_at, google_ads_account_id, website_url, codebase_path, harness_adapter) VALUES (?, ?, ?, ?, NULL, NULL, ?, ?, ?)",- ).run(- project.id,- project.slug,- project.display_name,- project.created_at,- project.website_url,- project.codebase_path,- project.harness_adapter,- );-- return { ok: true, project };-}--export function setProjectHarnessAdapter(- slug: string,- adapter: HarnessAdapterId,-): Project | null {- const db = getDb();- db.prepare("UPDATE projects SET harness_adapter = ? WHERE slug = ?").run(adapter, slug);- return getProject(slug);-}--function trimOrNull(value: string | null | undefined): string | null {- if (value == null) return null;- const trimmed = value.trim();- return trimmed.length === 0 ? null : trimmed;-}--/**- * Persist the chosen Google Ads customer ID for a project. Returns null when- * the project doesn't exist or is archived. Idempotent — re-setting to the- * same value is a no-op write.- */-export function setProjectGoogleAdsAccount(- slug: string,- account_id: string | null,-): Project | null {- const db = getDb();- const existing = db.prepare("SELECT 1 FROM projects WHERE slug = ?").get(slug);- if (!existing) return null;- db.prepare("UPDATE projects SET google_ads_account_id = ? WHERE slug = ?").run(- account_id,- slug,- );- return getProject(slug);-}--/** Same shape as setProjectGoogleAdsAccount but for the Meta Ads ad-account id. */-export function setProjectMetaAdsAccount(- slug: string,- account_id: string | null,-): Project | null {- const db = getDb();- const existing = db.prepare("SELECT 1 FROM projects WHERE slug = ?").get(slug);- if (!existing) return null;- db.prepare("UPDATE projects SET meta_ads_account_id = ? WHERE slug = ?").run(- account_id,- slug,- );- return getProject(slug);-}--/** Same shape as setProjectGoogleAdsAccount but for the local codebase path. */-export function setProjectCodebasePath(- slug: string,- codebase_path: string | null,-): Project | null {- const db = getDb();- const existing = db.prepare("SELECT 1 FROM projects WHERE slug = ?").get(slug);- if (!existing) return null;- db.prepare("UPDATE projects SET codebase_path = ? WHERE slug = ?").run(- codebase_path,- slug,- );- return getProject(slug);-}--/** Same shape as setProjectGoogleAdsAccount but for the GSC property id. */-export function setProjectGscProperty(- slug: string,- property_id: string | null,-): Project | null {- const db = getDb();- const existing = db.prepare("SELECT 1 FROM projects WHERE slug = ?").get(slug);- if (!existing) return null;- db.prepare("UPDATE projects SET gsc_property_id = ? WHERE slug = ?").run(- property_id,- slug,- );- return getProject(slug);-}--export function renameProject(slug: string, display_name: string): Project | null {- const db = getDb();- const trimmed = display_name.trim();- if (!trimmed) return null;- db.prepare("UPDATE projects SET display_name = ? WHERE slug = ?").run(trimmed, slug);- return getProject(slug);-}--/**- * Migrate every DB row keyed off `project_slug` from `old` to `new`. Wraps- * the updates in a transaction with `defer_foreign_keys=ON` so the- * referential checks happen at COMMIT instead of per-row — required because- * our FKs reference `projects(slug)` without `ON UPDATE CASCADE`.- *- * Returns the renamed project, or null when the old slug doesn't exist.- */-export function changeProjectSlug(- old_slug: string,- new_slug: string,- new_display_name?: string,-): Project | null {- const db = getDb();- if (old_slug === new_slug) {- if (new_display_name) {- db.prepare("UPDATE projects SET display_name = ? WHERE slug = ?").run(- new_display_name.trim(),- old_slug,- );- }- return getProject(old_slug);- }- // Bail if the source doesn't exist or the destination already exists.- if (!db.prepare("SELECT 1 FROM projects WHERE slug = ?").get(old_slug)) {- return null;- }- if (db.prepare("SELECT 1 FROM projects WHERE slug = ?").get(new_slug)) {- throw new Error(`Project slug '${new_slug}' already exists`);- }-- const childTables = [- "mcp_tokens",- "user_mcp_servers",- "sessions",- "goal_suggestions",- // goal_actions / goal_metric_snapshots / goal_learnings / goal_ticks hang- // off goals(id), not project_slug, so only goals needs the slug rewrite.- "goals",- ];-- // Disable FK enforcement for the duration of the rename. Our FKs reference- // `projects(slug)` without ON UPDATE CASCADE, so updating the PK while- // child rows still point at the old value would violate. `defer_foreign_keys`- // inside a wrapped transaction doesn't take effect reliably across SQLite- // releases; toggling `foreign_keys` is universally supported and works the- // same way every popular SQLite migration tool uses.- const fkWasOn = db.pragma("foreign_keys = OFF", { simple: true });- try {- const tx = db.transaction(() => {- for (const table of childTables) {- try {- db.prepare(`UPDATE ${table} SET project_slug = ? WHERE project_slug = ?`).run(- new_slug,- old_slug,- );- } catch {- // table missing on this install; skip.- }- }- if (new_display_name) {- db.prepare("UPDATE projects SET slug = ?, display_name = ? WHERE slug = ?").run(- new_slug,- new_display_name.trim(),- old_slug,- );- } else {- db.prepare("UPDATE projects SET slug = ? WHERE slug = ?").run(new_slug, old_slug);- }- });- tx();- } finally {- // Restore prior FK state (1 if it was on, 0 if it was already off).- db.pragma(`foreign_keys = ${fkWasOn === 0 ? "OFF" : "ON"}`);- }-- return getProject(new_slug);-}--export function archiveProject(slug: string): Project | null {- const db = getDb();- const now = new Date().toISOString();- db.prepare("UPDATE projects SET archived_at = ? WHERE slug = ? AND archived_at IS NULL").run(now, slug);- return getProject(slug);-}--export function unarchiveProject(slug: string): Project | null {- const db = getDb();- db.prepare("UPDATE projects SET archived_at = NULL WHERE slug = ?").run(slug);- return getProject(slug);-}--/**- * Hard-delete a project row plus any rows in tables that key off- * project_slug. On-disk state — agent workspaces — is cleaned- * up by the deleteProject orchestrator, not here.- *- * MUST match the FK-bearing tables in schema.ts (mirrored exactly by the- * changeProjectSlug helper above). Adding a new table that FKs to- * projects(slug) requires adding the table name here too — otherwise delete- * trips a SqliteError FOREIGN KEY constraint failed.- */-export function deleteProjectRow(slug: string): void {- const db = getDb();- const childTables = [- "mcp_tokens",- // transcript_events cascades from sessions.- "sessions",- // User-added MCP catalog entries (Browse connectors / custom URLs).- // cascadeDeleteProjectArtifacts also clears these, but this sweep must- // be complete on its own: with foreign_keys=ON, any leftover child row- // makes the final DELETE FROM projects fail and strands the project.- "user_mcp_servers",- "goal_suggestions",- // goal_actions / goal_metric_snapshots / goal_learnings / goal_ticks- // cascade from goals(id) — deleting goals is enough.- "goals",- ];- db.transaction(() => {- for (const table of childTables) {- db.prepare(`DELETE FROM ${table} WHERE project_slug = ?`).run(slug);- }- db.prepare("DELETE FROM projects WHERE slug = ?").run(slug);- })();-}--/**- * Per-project hide-list for preset MCP catalog entries. See migration- * 012 — the column stores a JSON-encoded `string[]` so we can grow it- * without schema changes.- */-export function getHiddenMcpPresetKeys(slug: string): string[] {- const row = getDb()- .prepare(- "SELECT hidden_mcp_preset_keys_json AS j FROM projects WHERE slug = ?",- )- .get(slug) as { j: string } | undefined;- if (!row?.j) return [];- try {- const parsed = JSON.parse(row.j);- return Array.isArray(parsed)- ? parsed.filter((k): k is string => typeof k === "string")- : [];- } catch {- return [];- }-}--export function addHiddenMcpPresetKey(slug: string, key: string): void {- const current = getHiddenMcpPresetKeys(slug);- if (current.includes(key)) return;- const next = [...current, key];- getDb()- .prepare("UPDATE projects SET hidden_mcp_preset_keys_json = ? WHERE slug = ?")- .run(JSON.stringify(next), slug);-}--export function removeHiddenMcpPresetKey(slug: string, key: string): void {- const current = getHiddenMcpPresetKeys(slug);- const next = current.filter((k) => k !== key);- if (next.length === current.length) return;- getDb()- .prepare("UPDATE projects SET hidden_mcp_preset_keys_json = ? WHERE slug = ?")- .run(JSON.stringify(next), slug);-}diff --git a/notfair/src/server/db/schema.ts b/notfair/src/server/db/schema.tsdeleted file mode 100644index 4b302bc1..00000000--- a/notfair/src/server/db/schema.ts+++ /dev/null@@ -1,322 +0,0 @@-/**- * The full NotFair schema, applied idempotently on boot. One file, one- * source of truth — no migration history. If the shape needs to change,- * change it here (existing dev databases can be recreated; there is no- * multi-tenant fleet to migrate).- */-export const SCHEMA = `-CREATE TABLE IF NOT EXISTS projects (- id TEXT PRIMARY KEY,- slug TEXT NOT NULL UNIQUE,- display_name TEXT NOT NULL,- created_at TEXT NOT NULL,- archived_at TEXT,- google_ads_account_id TEXT,- meta_ads_account_id TEXT,- gsc_property_id TEXT,- website_url TEXT,- codebase_path TEXT,- harness_adapter TEXT NOT NULL DEFAULT 'claude-code-local',- hidden_mcp_preset_keys_json TEXT NOT NULL DEFAULT '[]'-);--CREATE TABLE IF NOT EXISTS sessions (- id TEXT PRIMARY KEY,- project_slug TEXT NOT NULL REFERENCES projects(slug),- agent_id TEXT NOT NULL,- label TEXT NOT NULL,- harness_adapter TEXT NOT NULL,- harness_session_id TEXT,- title TEXT,- pinned_at TEXT,- created_at TEXT NOT NULL,- updated_at TEXT NOT NULL,- UNIQUE(project_slug, agent_id, label)-);-CREATE INDEX IF NOT EXISTS idx_sessions_agent ON sessions(project_slug, agent_id);--CREATE TABLE IF NOT EXISTS transcript_events (- id TEXT PRIMARY KEY,- session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,- seq INTEGER NOT NULL,- kind TEXT NOT NULL CHECK (kind IN ('user','delta','tool','lifecycle','final','error')),- payload_json TEXT NOT NULL,- created_at TEXT NOT NULL-);-CREATE INDEX IF NOT EXISTS idx_transcript_events_session ON transcript_events(session_id, seq);--CREATE TABLE IF NOT EXISTS mcp_tokens (- id TEXT PRIMARY KEY,- project_slug TEXT NOT NULL REFERENCES projects(slug),- server_name TEXT NOT NULL,- account_label TEXT NOT NULL DEFAULT '',- access_token_enc TEXT NOT NULL,- refresh_token_enc TEXT,- expires_at TEXT,- scope TEXT,- metadata_json TEXT,- token_endpoint TEXT,- client_id TEXT,- client_secret TEXT,- created_at TEXT NOT NULL,- updated_at TEXT NOT NULL,- UNIQUE(project_slug, server_name, account_label)-);-CREATE INDEX IF NOT EXISTS idx_mcp_tokens_project ON mcp_tokens(project_slug);--CREATE TABLE IF NOT EXISTS user_mcp_servers (- id TEXT PRIMARY KEY,- project_slug TEXT NOT NULL REFERENCES projects(slug),- key TEXT NOT NULL,- display_name TEXT NOT NULL,- description TEXT NOT NULL DEFAULT '',- resource_url TEXT NOT NULL,- discovery_url TEXT NOT NULL,- created_at TEXT NOT NULL,- updated_at TEXT NOT NULL,- UNIQUE(project_slug, key)-);-CREATE INDEX IF NOT EXISTS idx_user_mcp_servers_project ON user_mcp_servers(project_slug);--CREATE TABLE IF NOT EXISTS goals (- id TEXT PRIMARY KEY,- project_slug TEXT NOT NULL REFERENCES projects(slug),- agent_id TEXT NOT NULL,- statement TEXT NOT NULL,- short_label TEXT,- status TEXT NOT NULL DEFAULT 'intake'- CHECK (status IN ('intake','proposed','active','paused','achieved','failed','killed')),- status_reason TEXT,- mode TEXT NOT NULL DEFAULT 'achieve'- CHECK (mode IN ('achieve','maintain')),- -- Executable metric definition (filled by intake via propose_goal_metric).- metric_name TEXT,- metric_source_key TEXT,- metric_source_tool TEXT,- metric_source_args_json TEXT,- metric_direction TEXT CHECK (metric_direction IN ('increase','decrease')),- baseline_value REAL,- current_value REAL,- target_value REAL,- deadline TEXT,- spend_envelope_usd REAL,- -- Loop cadence + state. next_tick_at is advanced by the tick runner the- -- moment a tick starts, as a double-fire guard.- cadence_cron TEXT NOT NULL DEFAULT '0 16 * * *',- next_tick_at TEXT,- last_tick_at TEXT,- tick_count INTEGER NOT NULL DEFAULT 0,- created_at TEXT NOT NULL,- updated_at TEXT NOT NULL-);-CREATE INDEX IF NOT EXISTS idx_goals_project ON goals(project_slug, status);-CREATE INDEX IF NOT EXISTS idx_goals_due ON goals(status, next_tick_at);-CREATE UNIQUE INDEX IF NOT EXISTS idx_goals_one_live_per_agent- ON goals(agent_id)- WHERE status IN ('intake','proposed','active','paused');---- Completing and archiving are deliberately separate moments. An achieved--- goal remains in the sidebar until the user celebrates it and chooses to--- archive it; archiving only hides it from daily navigation and preserves--- the goal, agent, chat, checks, and evidence.-CREATE TABLE IF NOT EXISTS goal_archives (- goal_id TEXT PRIMARY KEY REFERENCES goals(id) ON DELETE CASCADE,- archived_at TEXT NOT NULL-);---- Goal groups are dashboard/navigation containers. Membership is kept in a--- separate table so existing CREATE-IF-NOT-EXISTS databases gain grouping--- without altering the goals table. goal_id is the primary key, enforcing--- the product rule that one goal belongs to at most one group.-CREATE TABLE IF NOT EXISTS goal_groups (- id TEXT PRIMARY KEY,- project_slug TEXT NOT NULL REFERENCES projects(slug) ON DELETE CASCADE,- name TEXT NOT NULL COLLATE NOCASE,- description TEXT NOT NULL DEFAULT '',- sort_order INTEGER NOT NULL DEFAULT 0,- created_at TEXT NOT NULL,- updated_at TEXT NOT NULL,- UNIQUE(project_slug, name)-);-CREATE INDEX IF NOT EXISTS idx_goal_groups_project- ON goal_groups(project_slug, sort_order, created_at);--CREATE TABLE IF NOT EXISTS goal_group_memberships (- goal_id TEXT PRIMARY KEY REFERENCES goals(id) ON DELETE CASCADE,- group_id TEXT NOT NULL REFERENCES goal_groups(id) ON DELETE CASCADE,- created_at TEXT NOT NULL-);-CREATE INDEX IF NOT EXISTS idx_goal_group_memberships_group- ON goal_group_memberships(group_id, created_at);--CREATE TABLE IF NOT EXISTS goal_actions (- id TEXT PRIMARY KEY,- goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,- tick_number INTEGER,- kind TEXT NOT NULL DEFAULT 'mutation'- CHECK (kind IN ('mutation','research','decision')),- description TEXT NOT NULL,- resources_touched_json TEXT NOT NULL DEFAULT '[]',- expected_effect TEXT NOT NULL,- spend_usd REAL,- -- Measurement-maturity gate: the agent may not touch the same resources- -- again (and must score this action) once now >= review_after.- review_after TEXT,- status TEXT NOT NULL DEFAULT 'open'- CHECK (status IN ('open','reviewed','abandoned')),- observed_outcome TEXT,- reviewed_at TEXT,- created_at TEXT NOT NULL-);-CREATE INDEX IF NOT EXISTS idx_goal_actions_goal ON goal_actions(goal_id, status);---- Agent-written check-diary badges ("Budget updated"), one per logged--- action. Kept in a separate table so existing CREATE-IF-NOT-EXISTS--- databases gain badges without altering goal_actions.-CREATE TABLE IF NOT EXISTS goal_action_badges (- action_id TEXT PRIMARY KEY REFERENCES goal_actions(id) ON DELETE CASCADE,- badge TEXT NOT NULL,- created_at TEXT NOT NULL-);--CREATE TABLE IF NOT EXISTS goal_metric_snapshots (- id TEXT PRIMARY KEY,- goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,- value REAL NOT NULL,- source TEXT NOT NULL DEFAULT 'tick'- CHECK (source IN ('intake','tick','manual','backfill')),- created_at TEXT NOT NULL-);-CREATE INDEX IF NOT EXISTS idx_goal_snapshots_goal- ON goal_metric_snapshots(goal_id, created_at);---- Supporting metrics: extra numbers the loop measures alongside the goal's--- primary metric (leading indicators, diagnostics). No target semantics —--- the goal is still judged on the ONE primary metric. Self-contained tables--- (not columns on goals/goal_metric_snapshots) because schema boot is--- CREATE-IF-NOT-EXISTS only: existing databases never gain columns.-CREATE TABLE IF NOT EXISTS goal_support_metrics (- id TEXT PRIMARY KEY,- goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,- name TEXT NOT NULL,- source_key TEXT NOT NULL,- source_tool TEXT NOT NULL,- source_args_json TEXT NOT NULL,- direction TEXT CHECK (direction IN ('increase','decrease')),- baseline_value REAL NOT NULL,- current_value REAL NOT NULL,- created_at TEXT NOT NULL,- updated_at TEXT NOT NULL,- UNIQUE(goal_id, name)-);--CREATE TABLE IF NOT EXISTS goal_support_metric_snapshots (- id TEXT PRIMARY KEY,- metric_id TEXT NOT NULL REFERENCES goal_support_metrics(id) ON DELETE CASCADE,- value REAL NOT NULL,- source TEXT NOT NULL DEFAULT 'tick' CHECK (source IN ('verify','tick','backfill')),- created_at TEXT NOT NULL-);-CREATE INDEX IF NOT EXISTS idx_goal_support_snapshots_metric- ON goal_support_metric_snapshots(metric_id, created_at);---- Sidebar pins: pinned goals sort to the top of the goal rail. A separate--- table (not a column on goals) because schema boot is CREATE-IF-NOT-EXISTS--- only: existing databases never gain columns.-CREATE TABLE IF NOT EXISTS goal_pins (- goal_id TEXT PRIMARY KEY REFERENCES goals(id) ON DELETE CASCADE,- created_at TEXT NOT NULL-);--CREATE TABLE IF NOT EXISTS goal_learnings (- id TEXT PRIMARY KEY,- goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,- body TEXT NOT NULL,- confidence TEXT NOT NULL DEFAULT 'medium'- CHECK (confidence IN ('low','medium','high')),- superseded_by TEXT REFERENCES goal_learnings(id) ON DELETE SET NULL,- created_at TEXT NOT NULL-);-CREATE INDEX IF NOT EXISTS idx_goal_learnings_goal- ON goal_learnings(goal_id, created_at);--CREATE TABLE IF NOT EXISTS goal_suggestions (- id TEXT PRIMARY KEY,- project_slug TEXT NOT NULL REFERENCES projects(slug),- source_key TEXT NOT NULL,- -- Stable heuristic id (e.g. 'wasted-spend'). One row per kind per- -- source: regeneration updates open rows in place, and dismissed or- -- accepted kinds keep their status instead of resurfacing.- kind TEXT NOT NULL,- title TEXT NOT NULL,- statement TEXT NOT NULL,- mode TEXT NOT NULL DEFAULT 'achieve'- CHECK (mode IN ('achieve','maintain')),- -- Evidence sentence with the real account numbers that justify it.- rationale TEXT NOT NULL,- status TEXT NOT NULL DEFAULT 'open'- CHECK (status IN ('open','accepted','dismissed')),- accepted_goal_id TEXT,- created_at TEXT NOT NULL,- updated_at TEXT NOT NULL,- UNIQUE(project_slug, source_key, kind)-);-CREATE INDEX IF NOT EXISTS idx_goal_suggestions_project- ON goal_suggestions(project_slug, status);---- Pull requests a goal agent opened to change the workspace's codebase.--- The PR is the approval gate for code mutations: the agent never merges--- its own PR; the user reviews on GitHub. State is synced from the gh--- CLI at tick time and on goal-page views, so the loop reacts to reviews,--- comment counts, merges, and closes.-CREATE TABLE IF NOT EXISTS goal_prs (- id TEXT PRIMARY KEY,- goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,- action_id TEXT REFERENCES goal_actions(id) ON DELETE SET NULL,- -- The check (goal_ticks.tick_number) whose turn registered this PR, so- -- the Checks list can link a check to the PR it produced.- tick_number INTEGER,- url TEXT NOT NULL,- title TEXT NOT NULL,- branch TEXT,- state TEXT NOT NULL DEFAULT 'open'- CHECK (state IN ('open','merged','closed')),- -- GitHub reviewDecision: APPROVED / CHANGES_REQUESTED / REVIEW_REQUIRED- -- (empty for repos without required reviews). NULL until first sync.- review_decision TEXT,- comment_count INTEGER NOT NULL DEFAULT 0,- is_draft INTEGER NOT NULL DEFAULT 0,- merged_at TEXT,- last_synced_at TEXT,- sync_error TEXT,- -- Centralized freshness sweep: the 30s scheduler syncs a PR when- -- next_sync_at arrives. The interval adapts to activity (fast after- -- last_activity_at, backing off toward an hourly cap); terminal PRs- -- carry NULL and are never synced again.- next_sync_at TEXT,- last_activity_at TEXT,- created_at TEXT NOT NULL,- updated_at TEXT NOT NULL,- UNIQUE(goal_id, url)-);-CREATE INDEX IF NOT EXISTS idx_goal_prs_goal ON goal_prs(goal_id, state);-CREATE INDEX IF NOT EXISTS idx_goal_prs_due ON goal_prs(state, next_sync_at);--CREATE TABLE IF NOT EXISTS goal_ticks (- id TEXT PRIMARY KEY,- goal_id TEXT NOT NULL REFERENCES goals(id) ON DELETE CASCADE,- tick_number INTEGER NOT NULL,- trigger_kind TEXT NOT NULL DEFAULT 'heartbeat'- CHECK (trigger_kind IN ('heartbeat','manual','approval','intake')),- owner_pid INTEGER,- session_id TEXT,- metric_value REAL,- metric_error TEXT,- status TEXT NOT NULL DEFAULT 'running'- CHECK (status IN ('running','done','failed')),- summary TEXT,- started_at TEXT NOT NULL,- finished_at TEXT-);-CREATE INDEX IF NOT EXISTS idx_goal_ticks_goal ON goal_ticks(goal_id, tick_number);-`;diff --git a/notfair/src/server/db/suggestions.test.ts b/notfair/src/server/db/suggestions.test.tsdeleted file mode 100644index 94a22b4b..00000000--- a/notfair/src/server/db/suggestions.test.ts+++ /dev/null@@ -1,144 +0,0 @@-import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";--// Real better-sqlite3 against a tmpdir DB. MUST be hoisted before imports.-vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-db-suggestions-"));-});--import { getDb } from "@/server/db/db";-import {- getSuggestion,- hasSuggestionsForSource,- listOpenSuggestions,- markSuggestionAccepted,- markSuggestionDismissed,- replaceOpenSuggestions,- type SuggestionDraft,-} from "./suggestions";--const SLUG = "sugproj";--function seedProject(slug: string): void {- getDb()- .prepare(- "INSERT OR IGNORE INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES (?, ?, ?, ?, 'claude-code-local')",- )- .run(slug, slug, slug, new Date().toISOString());-}--function draft(kind: string, over: Partial<SuggestionDraft> = {}): SuggestionDraft {- return {- kind,- title: `title-${kind}`,- statement: `statement-${kind}`,- mode: "achieve",- rationale: `rationale-${kind}`,- ...over,- };-}--beforeAll(() => {- seedProject(SLUG);-});--beforeEach(() => {- getDb().prepare("DELETE FROM goal_suggestions WHERE project_slug = ?").run(SLUG);-});--describe("replaceOpenSuggestions", () => {- it("inserts a fresh batch of open rows", () => {- replaceOpenSuggestions(SLUG, "src-a", [draft("k1"), draft("k2")]);- const rows = listOpenSuggestions(SLUG);- expect(rows.map((r) => r.kind).sort()).toEqual(["k1", "k2"]);- expect(rows[0]!.status).toBe("open");- });-- it("refreshes an open row in place on conflict (same kind)", () => {- replaceOpenSuggestions(SLUG, "src-a", [draft("k1", { title: "first" })]);- const before = listOpenSuggestions(SLUG)[0]!;- replaceOpenSuggestions(SLUG, "src-a", [draft("k1", { title: "second" })]);- const after = getSuggestion(before.id)!;- expect(after.id).toBe(before.id); // same row, updated in place- expect(after.title).toBe("second");- });-- it("deletes open rows whose kind is absent from the new batch", () => {- replaceOpenSuggestions(SLUG, "src-a", [draft("k1"), draft("k2")]);- replaceOpenSuggestions(SLUG, "src-a", [draft("k1")]);- expect(listOpenSuggestions(SLUG).map((r) => r.kind)).toEqual(["k1"]);- });-- it("deletes all open rows for the source when the batch is empty", () => {- replaceOpenSuggestions(SLUG, "src-a", [draft("k1"), draft("k2")]);- replaceOpenSuggestions(SLUG, "src-a", []);- expect(listOpenSuggestions(SLUG)).toEqual([]);- });-- it("never touches accepted or dismissed rows", () => {- replaceOpenSuggestions(SLUG, "src-a", [draft("k1"), draft("k2")]);- const rows = listOpenSuggestions(SLUG);- const accepted = rows.find((r) => r.kind === "k1")!;- const dismissed = rows.find((r) => r.kind === "k2")!;- markSuggestionAccepted(accepted.id, "goal-x");- markSuggestionDismissed(dismissed.id);-- // A regen with neither kind must not delete the terminal rows, and the- // ON CONFLICT WHERE status='open' guard must not resurrect them.- replaceOpenSuggestions(SLUG, "src-a", [draft("k1"), draft("k2")]);-- expect(getSuggestion(accepted.id)!.status).toBe("accepted");- expect(getSuggestion(accepted.id)!.accepted_goal_id).toBe("goal-x");- expect(getSuggestion(dismissed.id)!.status).toBe("dismissed");- // The fresh batch only produced open rows for kinds that were free.- expect(listOpenSuggestions(SLUG)).toEqual([]);- });-- it("scopes deletes to (project, source)", () => {- replaceOpenSuggestions(SLUG, "src-a", [draft("k1")]);- replaceOpenSuggestions(SLUG, "src-b", [draft("k1")]);- replaceOpenSuggestions(SLUG, "src-a", []); // clears only src-a- expect(listOpenSuggestions(SLUG).map((r) => r.source_key)).toEqual(["src-b"]);- });-});--describe("listOpenSuggestions", () => {- it("orders by created_at then kind and only returns open rows", () => {- replaceOpenSuggestions(SLUG, "src-a", [draft("b"), draft("a")]);- const open = listOpenSuggestions(SLUG);- // Same created_at → tiebreak on kind ASC.- expect(open.map((r) => r.kind)).toEqual(["a", "b"]);- });-});--describe("getSuggestion", () => {- it("returns null for an unknown id", () => {- expect(getSuggestion("nope")).toBeNull();- });-});--describe("hasSuggestionsForSource", () => {- it("is true once any row exists (even after acceptance) and false otherwise", () => {- expect(hasSuggestionsForSource(SLUG, "src-a")).toBe(false);- replaceOpenSuggestions(SLUG, "src-a", [draft("k1")]);- expect(hasSuggestionsForSource(SLUG, "src-a")).toBe(true);- const row = listOpenSuggestions(SLUG)[0]!;- markSuggestionDismissed(row.id);- expect(hasSuggestionsForSource(SLUG, "src-a")).toBe(true);- expect(hasSuggestionsForSource(SLUG, "other-src")).toBe(false);- });-});--describe("markSuggestionAccepted / markSuggestionDismissed", () => {- it("stamps status and accepted_goal_id", () => {- replaceOpenSuggestions(SLUG, "src-a", [draft("k1")]);- const row = listOpenSuggestions(SLUG)[0]!;- markSuggestionAccepted(row.id, "goal-42");- const after = getSuggestion(row.id)!;- expect(after.status).toBe("accepted");- expect(after.accepted_goal_id).toBe("goal-42");- expect(after.updated_at >= after.created_at).toBe(true);- });-});diff --git a/notfair/src/server/db/suggestions.ts b/notfair/src/server/db/suggestions.tsdeleted file mode 100644index ae640e1f..00000000--- a/notfair/src/server/db/suggestions.ts+++ /dev/null@@ -1,126 +0,0 @@-import { randomUUID } from "node:crypto";-import { getDb } from "./db";--/**- * Goal suggestions: proposals NotFair mints from a mechanical audit of a- * freshly connected ads account. One row per (project, source, kind) —- * regeneration refreshes open rows in place; accepted and dismissed rows- * keep their status so the same idea never resurfaces uninvited.- */--export type GoalSuggestion = {- id: string;- project_slug: string;- source_key: string;- kind: string;- title: string;- statement: string;- mode: "achieve" | "maintain";- rationale: string;- status: "open" | "accepted" | "dismissed";- accepted_goal_id: string | null;- created_at: string;- updated_at: string;-};--export type SuggestionDraft = {- kind: string;- title: string;- statement: string;- mode: "achieve" | "maintain";- rationale: string;-};--/**- * Write a fresh batch for one source. Open rows for kinds NOT in the new- * batch are deleted (the data no longer supports them); accepted and- * dismissed rows are never touched.- */-export function replaceOpenSuggestions(- project_slug: string,- source_key: string,- drafts: SuggestionDraft[],-): void {- const db = getDb();- const now = new Date().toISOString();- const tx = db.transaction(() => {- const keep = drafts.map((d) => d.kind);- const placeholders = keep.map(() => "?").join(",");- db.prepare(- `DELETE FROM goal_suggestions- WHERE project_slug = ? AND source_key = ? AND status = 'open'- ${keep.length > 0 ? `AND kind NOT IN (${placeholders})` : ""}`,- ).run(project_slug, source_key, ...keep);- for (const d of drafts) {- db.prepare(- `INSERT INTO goal_suggestions- (id, project_slug, source_key, kind, title, statement, mode, rationale, status, created_at, updated_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?)- ON CONFLICT(project_slug, source_key, kind) DO UPDATE SET- title = excluded.title,- statement = excluded.statement,- mode = excluded.mode,- rationale = excluded.rationale,- updated_at = excluded.updated_at- WHERE goal_suggestions.status = 'open'`,- ).run(- randomUUID(),- project_slug,- source_key,- d.kind,- d.title,- d.statement,- d.mode,- d.rationale,- now,- now,- );- }- });- tx();-}--export function listOpenSuggestions(project_slug: string): GoalSuggestion[] {- return getDb()- .prepare(- "SELECT * FROM goal_suggestions WHERE project_slug = ? AND status = 'open' ORDER BY created_at ASC, kind ASC",- )- .all(project_slug) as GoalSuggestion[];-}--export function getSuggestion(id: string): GoalSuggestion | null {- const row = getDb()- .prepare("SELECT * FROM goal_suggestions WHERE id = ?")- .get(id) as GoalSuggestion | undefined;- return row ?? null;-}--/** True when this source has EVER produced rows for the project. */-export function hasSuggestionsForSource(- project_slug: string,- source_key: string,-): boolean {- return (- getDb()- .prepare(- "SELECT 1 FROM goal_suggestions WHERE project_slug = ? AND source_key = ? LIMIT 1",- )- .get(project_slug, source_key) !== undefined- );-}--export function markSuggestionAccepted(id: string, goal_id: string): void {- getDb()- .prepare(- "UPDATE goal_suggestions SET status = 'accepted', accepted_goal_id = ?, updated_at = ? WHERE id = ?",- )- .run(goal_id, new Date().toISOString(), id);-}--export function markSuggestionDismissed(id: string): void {- getDb()- .prepare(- "UPDATE goal_suggestions SET status = 'dismissed', updated_at = ? WHERE id = ?",- )- .run(new Date().toISOString(), id);-}diff --git a/notfair/src/server/db/user-mcp-servers.test.ts b/notfair/src/server/db/user-mcp-servers.test.tsdeleted file mode 100644index a374ebcc..00000000--- a/notfair/src/server/db/user-mcp-servers.test.ts+++ /dev/null@@ -1,120 +0,0 @@-import { beforeAll, describe, expect, it, vi } from "vitest";--// Real better-sqlite3 against a tmpdir DB, per repo test conventions.-// MUST be hoisted: static imports evaluate before module-level statements,-// and db.ts captures NOTFAIR_DATA_DIR at import time — a plain assignment-// here would silently point the suite at the developer's live ~/.notfair.-vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-db-umcp-"));-});--import { getDb } from "@/server/db/db";-import {- deleteUserMcpServer,- findUserMcpServer,- findUserMcpServerByResourceUrl,- insertUserMcpServer,- listUserMcpServers,-} from "./user-mcp-servers";--const SLUG = "proj";--beforeAll(() => {- getDb()- .prepare(- "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('p1', ?, 'Proj', ?, 'claude-code-local')",- )- .run(SLUG, new Date().toISOString());-});--describe("insertUserMcpServer / findUserMcpServer", () => {- it("inserts a row and reads it back by key", () => {- const row = insertUserMcpServer({- project_slug: SLUG,- key: "acme",- display_name: "Acme MCP",- resource_url: "https://mcp.acme.dev/sse",- discovery_url:- "https://mcp.acme.dev/.well-known/oauth-protected-resource/sse",- });- expect(row.id).toBeTruthy();- expect(row.description).toBe(""); // defaulted when omitted-- const found = findUserMcpServer(SLUG, "acme");- expect(found).toMatchObject({- project_slug: SLUG,- key: "acme",- display_name: "Acme MCP",- description: "",- resource_url: "https://mcp.acme.dev/sse",- });- });-- it("returns null for a missing key or wrong project", () => {- expect(findUserMcpServer(SLUG, "nope")).toBeNull();- expect(findUserMcpServer("other-proj", "acme")).toBeNull();- });-});--describe("findUserMcpServerByResourceUrl", () => {- it("matches regardless of trailing slash, host case, and default port", () => {- for (const candidate of [- "https://mcp.acme.dev/sse/",- "https://MCP.ACME.DEV/sse",- "https://mcp.acme.dev:443/sse",- ]) {- expect(findUserMcpServerByResourceUrl(SLUG, candidate)?.key).toBe("acme");- }- });-- it("returns null when no row matches", () => {- expect(- findUserMcpServerByResourceUrl(SLUG, "https://mcp.other.dev/sse"),- ).toBeNull();- // Path is case-sensitive by design.- expect(- findUserMcpServerByResourceUrl(SLUG, "https://mcp.acme.dev/SSE"),- ).toBeNull();- });-- it("falls back to a lowercased string compare for unparseable URLs", () => {- insertUserMcpServer({- project_slug: SLUG,- key: "weird",- display_name: "Weird",- resource_url: "not a url",- discovery_url: "also not a url",- });- expect(findUserMcpServerByResourceUrl(SLUG, " NOT A URL/ ")?.key).toBe(- "weird",- );- });-});--describe("listUserMcpServers / deleteUserMcpServer", () => {- it("lists rows oldest-first and scopes to the project", () => {- // Force distinct created_at values so ORDER BY created_at is decisive.- getDb()- .prepare("UPDATE user_mcp_servers SET created_at = ? WHERE key = 'acme'")- .run("2026-01-01T00:00:00.000Z");- getDb()- .prepare("UPDATE user_mcp_servers SET created_at = ? WHERE key = 'weird'")- .run("2026-01-02T00:00:00.000Z");- expect(listUserMcpServers(SLUG).map((r) => r.key)).toEqual([- "acme",- "weird",- ]);- expect(listUserMcpServers("other-proj")).toEqual([]);- });-- it("deletes only the (project, key) pair", () => {- deleteUserMcpServer("other-proj", "acme"); // wrong project: no-op- expect(findUserMcpServer(SLUG, "acme")).not.toBeNull();- deleteUserMcpServer(SLUG, "acme");- expect(findUserMcpServer(SLUG, "acme")).toBeNull();- expect(listUserMcpServers(SLUG).map((r) => r.key)).toEqual(["weird"]);- });-});diff --git a/notfair/src/server/db/user-mcp-servers.ts b/notfair/src/server/db/user-mcp-servers.tsdeleted file mode 100644index e6dd06a5..00000000--- a/notfair/src/server/db/user-mcp-servers.ts+++ /dev/null@@ -1,111 +0,0 @@-import { randomUUID } from "node:crypto";-import { getDb } from "@/server/db/db";-import { normalizeResourceUrl } from "@/server/mcp/discovery-url";--/**- * Project-scoped storage for user-added MCP servers.- *- * Companion to `mcp_tokens` — the catalog row says "this MCP exists for- * this project" (slug, name, URLs); the token row says "we have a bearer- * for it." `getMcpCatalog` joins this table with the static preset list- * so both surfaces render the same `McpSpec` shape.- *- * `key` is the same identifier used as `mcp_tokens.server_name`, so the- * OAuth callback + adapter registration paths don't care whether the- * MCP came from presets or this table.- */-export interface UserMcpServer {- id: string;- project_slug: string;- key: string;- display_name: string;- description: string;- resource_url: string;- discovery_url: string;- created_at: string;- updated_at: string;-}--export interface UpsertUserMcpServerInput {- project_slug: string;- key: string;- display_name: string;- description?: string;- resource_url: string;- discovery_url: string;-}--export function insertUserMcpServer(input: UpsertUserMcpServerInput): UserMcpServer {- const now = new Date().toISOString();- const row: UserMcpServer = {- id: randomUUID(),- project_slug: input.project_slug,- key: input.key,- display_name: input.display_name,- description: input.description ?? "",- resource_url: input.resource_url,- discovery_url: input.discovery_url,- created_at: now,- updated_at: now,- };- getDb()- .prepare(- "INSERT INTO user_mcp_servers (id, project_slug, key, display_name, description, resource_url, discovery_url, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",- )- .run(- row.id,- row.project_slug,- row.key,- row.display_name,- row.description,- row.resource_url,- row.discovery_url,- row.created_at,- row.updated_at,- );- return row;-}--export function findUserMcpServer(- project_slug: string,- key: string,-): UserMcpServer | null {- return (- (getDb()- .prepare(- "SELECT * FROM user_mcp_servers WHERE project_slug = ? AND key = ?",- )- .get(project_slug, key) as UserMcpServer | undefined) ?? null- );-}--/**- * Find a row by normalized resource URL. Used to detect "this server is- * already in the project" even when the key the caller would create- * differs from the stored key (legacy slugification mismatches, etc).- */-export function findUserMcpServerByResourceUrl(- project_slug: string,- resource_url: string,-): UserMcpServer | null {- const target = normalizeResourceUrl(resource_url);- return (- listUserMcpServers(project_slug).find(- (row) => normalizeResourceUrl(row.resource_url) === target,- ) ?? null- );-}--export function listUserMcpServers(project_slug: string): UserMcpServer[] {- return getDb()- .prepare(- "SELECT * FROM user_mcp_servers WHERE project_slug = ? ORDER BY created_at",- )- .all(project_slug) as UserMcpServer[];-}--export function deleteUserMcpServer(project_slug: string, key: string): void {- getDb()- .prepare("DELETE FROM user_mcp_servers WHERE project_slug = ? AND key = ?")- .run(project_slug, key);-}diff --git a/notfair/src/server/fs/pick-folder.test.ts b/notfair/src/server/fs/pick-folder.test.tsdeleted file mode 100644index f0614436..00000000--- a/notfair/src/server/fs/pick-folder.test.ts+++ /dev/null@@ -1,199 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--// Never spawn real dialog binaries: mock the child_process + platform-// boundary and drive each OS branch through the callback contract.-type ExecCall = { cmd: string; args: string[] };-type ExecOutcome = {- err?: (Error & { code?: number | string }) | null;- stdout?: string;- stderr?: string;-};--const h = vi.hoisted(() => {- const state = {- platform: "darwin" as string,- calls: [] as ExecCall[],- // Consumed in order — one entry per expected execFile invocation.- outcomes: [] as ExecOutcome[],- };- return { state };-});--vi.mock("node:os", async (importOriginal) => {- const actual = await importOriginal<typeof import("node:os")>();- return { ...actual, platform: () => h.state.platform };-});-vi.mock("node:child_process", () => ({- execFile: (- cmd: string,- args: string[],- _opts: unknown,- cb: (err: Error | null, stdout: string, stderr: string) => void,- ) => {- h.state.calls.push({ cmd, args });- const outcome = h.state.outcomes.shift() ?? {};- queueMicrotask(() =>- cb(outcome.err ?? null, outcome.stdout ?? "", outcome.stderr ?? ""),- );- },-}));--import { pickFolder } from "./pick-folder";--function errWithCode(code: number | string): Error & { code: number | string } {- return Object.assign(new Error(`exec failed (${code})`), { code });-}--beforeEach(() => {- h.state.platform = "darwin";- h.state.calls = [];- h.state.outcomes = [];-});--describe("platform dispatch", () => {- it("reports unsupported on Windows without spawning anything", async () => {- h.state.platform = "win32";- await expect(pickFolder({})).resolves.toEqual({- ok: false,- kind: "unsupported",- platform: "win32",- });- expect(h.state.calls).toHaveLength(0);- });-});--describe("macOS (osascript)", () => {- it("returns the picked path with the trailing slash stripped", async () => {- h.state.outcomes = [{ stdout: "/Users/me/Sites/acme/\n" }];- await expect(pickFolder({})).resolves.toEqual({- ok: true,- path: "/Users/me/Sites/acme",- });- expect(h.state.calls[0]!.cmd).toBe("/usr/bin/osascript");- expect(h.state.calls[0]!.args[0]).toBe("-e");- });-- it("passes the prompt and default location into the script, escaped", async () => {- h.state.outcomes = [{ stdout: "/tmp/x/\n" }];- await pickFolder({- prompt: 'Pick "the" folder',- defaultLocation: '/Users/me/"quoted"',- });- const script = h.state.calls[0]!.args[1]!;- expect(script).toContain('choose folder with prompt "Pick \\"the\\" folder"');- expect(script).toContain('default location POSIX file "/Users/me/\\"quoted\\""');- });-- it("omits the default-location clause when none is given", async () => {- h.state.outcomes = [{ stdout: "/tmp/x\n" }];- await pickFolder({});- const script = h.state.calls[0]!.args[1]!;- expect(script).toContain('choose folder with prompt "Select a folder"');- expect(script).not.toContain("default location");- });-- it("maps the cancel sentinel to kind: cancelled", async () => {- h.state.outcomes = [{ stdout: "__USER_CANCELLED__\n" }];- await expect(pickFolder({})).resolves.toEqual({ ok: false, kind: "cancelled" });- });-- it("treats empty output as cancelled", async () => {- h.state.outcomes = [{ stdout: "" }];- await expect(pickFolder({})).resolves.toEqual({ ok: false, kind: "cancelled" });- });-- it("surfaces stderr when osascript exits non-zero", async () => {- h.state.outcomes = [- { err: errWithCode(1), stderr: "execution error: boom (-1)" },- ];- await expect(pickFolder({})).resolves.toEqual({- ok: false,- kind: "error",- message: "execution error: boom (-1)",- });- });-- it("falls back to the exit code when stderr is empty", async () => {- h.state.outcomes = [{ err: errWithCode(2), stderr: "" }];- await expect(pickFolder({})).resolves.toEqual({- ok: false,- kind: "error",- message: "osascript exited with code 2",- });- });-});--describe("Linux (zenity → kdialog)", () => {- beforeEach(() => {- h.state.platform = "linux";- });-- it("uses zenity when available and returns the picked path", async () => {- h.state.outcomes = [{ stdout: "/home/me/proj/\n" }];- await expect(- pickFolder({ prompt: "Pick it", defaultLocation: "/home/me" }),- ).resolves.toEqual({ ok: true, path: "/home/me/proj" });- expect(h.state.calls).toEqual([- {- cmd: "zenity",- args: [- "--file-selection",- "--directory",- "--title=Pick it",- "--filename=/home/me/",- ],- },- ]);- });-- it("falls back to kdialog when zenity is not installed", async () => {- h.state.outcomes = [- { err: errWithCode("ENOENT") }, // zenity missing- { stdout: "/home/me/other\n" }, // kdialog succeeds- ];- await expect(pickFolder({ prompt: "Pick it" })).resolves.toEqual({- ok: true,- path: "/home/me/other",- });- expect(h.state.calls.map((c) => c.cmd)).toEqual(["zenity", "kdialog"]);- expect(h.state.calls[1]!.args).toEqual([- "--getexistingdirectory",- "",- "--title",- "Pick it",- ]);- });-- it("reports a clear install hint when neither tool exists", async () => {- h.state.outcomes = [- { err: errWithCode("ENOENT") },- { err: errWithCode("ENOENT") },- ];- const result = await pickFolder({});- expect(result).toMatchObject({ ok: false, kind: "error" });- expect((result as { message: string }).message).toMatch(- /zenity.*kdialog|kdialog.*zenity/i,- );- });-- it("maps zenity exit code 1 to cancelled", async () => {- h.state.outcomes = [{ err: errWithCode(1) }];- await expect(pickFolder({})).resolves.toEqual({ ok: false, kind: "cancelled" });- });-- it("treats empty dialog output as cancelled", async () => {- h.state.outcomes = [{ stdout: "\n" }];- await expect(pickFolder({})).resolves.toEqual({ ok: false, kind: "cancelled" });- });-- it("surfaces other dialog failures as errors", async () => {- h.state.outcomes = [- { err: errWithCode(255), stderr: "cannot open display" },- ];- await expect(pickFolder({})).resolves.toEqual({- ok: false,- kind: "error",- message: "cannot open display",- });- });-});diff --git a/notfair/src/server/fs/pick-folder.ts b/notfair/src/server/fs/pick-folder.tsdeleted file mode 100644index d186ed60..00000000--- a/notfair/src/server/fs/pick-folder.ts+++ /dev/null@@ -1,189 +0,0 @@-import { execFile } from "node:child_process";-import { platform } from "node:os";--/**- * Open the OS-native folder-picker dialog on the user's local machine and- * return the chosen absolute path. We rely on the fact that this server- * runs in the same single-user session as the browser (loopback-only,- * `npx notfair` model) — the dialog appears on the user's screen, in- * front of the same person clicking the Browse button.- *- * Implementations are platform-specific because there is no cross-platform- * native picker primitive in Node. macOS uses AppleScript's `choose folder`,- * which returns a POSIX path. Linux uses zenity (GTK) with a kdialog (KDE)- * fallback. Windows is TODO; callers receive a clear `kind: "unsupported"`- * they can branch on (UI falls back to a text input).- *- * The dialog is modal in the OS sense (blocks until the user picks or- * cancels), so we set a generous timeout to avoid wedging the route if- * something has gone wrong on the OS side.- */--const DIALOG_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes — the user might think--export type PickFolderResult =- | { ok: true; path: string }- | { ok: false; kind: "cancelled" }- | { ok: false; kind: "unsupported"; platform: string }- | { ok: false; kind: "error"; message: string };--export async function pickFolder(opts: {- prompt?: string;- defaultLocation?: string;-}): Promise<PickFolderResult> {- const p = platform();- if (p === "darwin") {- return pickFolderMac(opts);- }- if (p === "linux") {- return pickFolderLinux(opts);- }- // TODO: win32 (PowerShell FolderBrowserDialog).- return { ok: false, kind: "unsupported", platform: p };-}--async function pickFolderMac(opts: {- prompt?: string;- defaultLocation?: string;-}): Promise<PickFolderResult> {- // Build the AppleScript expression carefully: we control both args, so- // there's no untrusted shell-injection vector, but we still escape any- // embedded double quotes / backslashes so a path with quotes can't break- // the script. Args reach osascript via execFile (not a shell) so no- // additional shell-quoting is needed for the surrounding command line.- const prompt = (opts.prompt ?? "Select a folder").replace(/["\\]/g, "\\$&");- const defaultClause = opts.defaultLocation- ? ` default location POSIX file "${opts.defaultLocation.replace(/["\\]/g, "\\$&")}"`- : "";- const script = `- try- set f to choose folder with prompt "${prompt}"${defaultClause}- return POSIX path of f- on error errMsg number errNum- if errNum is -128 then- return "__USER_CANCELLED__"- else- error errMsg number errNum- end if- end try- `;-- const result = await new Promise<{- stdout: string;- stderr: string;- code: number | null;- }>((resolve) => {- execFile(- "/usr/bin/osascript",- ["-e", script],- { timeout: DIALOG_TIMEOUT_MS },- (err, stdout, stderr) => {- // With default options (no encoding override), Node returns- // stdout/stderr as strings. err carries .code on timeout /- // non-zero exit; we collapse it to a numeric code or 1 fallback.- const errCode = err- ? typeof (err as NodeJS.ErrnoException).code === "number"- ? ((err as unknown as { code: number }).code as number)- : 1- : 0;- resolve({ stdout, stderr, code: errCode });- },- );- // We don't wire up an AbortSignal here; the DIALOG_TIMEOUT_MS ceiling- // protects against a wedged osascript subprocess.- });-- if (result.code !== 0) {- return {- ok: false,- kind: "error",- message:- result.stderr.trim() ||- `osascript exited with code ${result.code ?? "unknown"}`,- };- }- const out = result.stdout.trim();- if (out === "__USER_CANCELLED__" || out === "") {- return { ok: false, kind: "cancelled" };- }- // AppleScript's `POSIX path of` returns a trailing slash for folders;- // strip it for consistency with how users typically write paths.- const normalized = out.replace(/\/+$/, "");- return { ok: true, path: normalized };-}--async function pickFolderLinux(opts: {- prompt?: string;- defaultLocation?: string;-}): Promise<PickFolderResult> {- const prompt = opts.prompt ?? "Select a folder";-- // Try zenity first (GTK-based, most common on GNOME/Ubuntu/Fedora),- // fall back to kdialog (KDE/Plasma).- const zenityArgs = ["--file-selection", "--directory", `--title=${prompt}`];- if (opts.defaultLocation) {- zenityArgs.push(`--filename=${opts.defaultLocation}/`);- }- const zenityResult = await execDialog("zenity", zenityArgs);- if (zenityResult !== null) {- return zenityResult;- }-- const kdialogArgs = [- "--getexistingdirectory",- opts.defaultLocation ?? "",- "--title",- prompt,- ];- const kdialogResult = await execDialog("kdialog", kdialogArgs);- if (kdialogResult !== null) {- return kdialogResult;- }-- return {- ok: false,- kind: "error",- message:- "No supported dialog tool found. Install zenity (GTK) or kdialog (KDE) for folder picker support.",- };-}--/**- * Execute a dialog command and return the result, or null if the command- * is not found (ENOENT), indicating we should try the next fallback.- */-async function execDialog(- cmd: string,- args: string[],-): Promise<PickFolderResult | null> {- return new Promise((resolve) => {- execFile(cmd, args, { timeout: DIALOG_TIMEOUT_MS }, (err, stdout, stderr) => {- if (err) {- // ENOENT means the command doesn't exist — try next fallback.- if ((err as NodeJS.ErrnoException).code === "ENOENT") {- resolve(null);- return;- }- // Exit code 1 in zenity/kdialog means the user cancelled.- if ("code" in err && (err as { code: number }).code === 1) {- resolve({ ok: false, kind: "cancelled" });- return;- }- resolve({- ok: false,- kind: "error",- message: stderr.trim() || err.message,- });- return;- }- const out = stdout.trim();- if (!out) {- resolve({ ok: false, kind: "cancelled" });- return;- }- // Normalize: strip trailing slash for consistency.- const normalized = out.replace(/\/+$/, "");- resolve({ ok: true, path: normalized });- });- });-}diff --git a/notfair/src/server/goals/checks.test.ts b/notfair/src/server/goals/checks.test.tsdeleted file mode 100644index 638b097b..00000000--- a/notfair/src/server/goals/checks.test.ts+++ /dev/null@@ -1,292 +0,0 @@-import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";--// Real better-sqlite3 against a tmpdir DB, per repo test conventions.-// MUST be hoisted: static imports evaluate before module-level statements,-// and db.ts captures NOTFAIR_DATA_DIR at import time — a plain assignment-// here would silently point the suite at the developer's live ~/.notfair.-vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-checks-"));-});--import { CHECKS_PAGE_SIZE, listCheckRows, writeBadgeForTool } from "./checks";-import { getDb } from "@/server/db/db";-import {- attachTickSession,- createGoal,- createGoalAction,- createGoalTick,-} from "@/server/db/goals";-import { createGoalPr } from "@/server/db/goal-prs";--const SLUG = "proj";-let goalId: string;--beforeAll(() => {- getDb()- .prepare(- "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('p1', ?, 'Proj', ?, 'codex-local')",- )- .run(SLUG, new Date().toISOString());- goalId = createGoal({- project_slug: SLUG,- agent_id: "agent-1",- statement: "Grow organic clicks",- }).id;-});--beforeEach(() => {- const db = getDb();- db.prepare("DELETE FROM goal_ticks").run();- db.prepare("DELETE FROM goal_prs").run();- db.prepare("DELETE FROM goal_actions").run();- db.prepare("DELETE FROM transcript_events").run();- db.prepare("DELETE FROM sessions").run();-});--function seedTicks(count: number): void {- for (let n = 1; n <= count; n++) {- createGoalTick({ goal_id: goalId, tick_number: n, trigger_kind: "heartbeat" });- }-}--/** Attach a session to a tick and record tool-call start events in it. */-function seedTickToolCalls(tick_number: number, toolNames: string[]): void {- const db = getDb();- const ts = new Date().toISOString();- const sessionId = `s-tick-${tick_number}`;- db.prepare(- `INSERT INTO sessions (id, project_slug, agent_id, label, harness_adapter, created_at, updated_at)- VALUES (?, ?, 'agent-1', ?, 'codex-local', ?, ?)`,- ).run(sessionId, SLUG, `tick-${tick_number}`, ts, ts);- const tickId = db- .prepare("SELECT id FROM goal_ticks WHERE goal_id = ? AND tick_number = ?")- .get(goalId, tick_number) as { id: string };- attachTickSession(tickId.id, sessionId);- toolNames.forEach((name, i) => {- db.prepare(- `INSERT INTO transcript_events (id, session_id, seq, kind, payload_json, created_at)- VALUES (?, ?, ?, 'tool', ?, ?)`,- ).run(- `${sessionId}-e${i}`,- sessionId,- i + 1,- JSON.stringify({ kind: "tool", phase: "start", toolCallId: `item_${i}`, name }),- ts,- );- });-}--describe("listCheckRows paging", () => {- it("records the process that owns a running tick", () => {- seedTicks(1);- const row = getDb()- .prepare("SELECT owner_pid FROM goal_ticks WHERE goal_id = ?")- .get(goalId) as { owner_pid: number };- expect(row.owner_pid).toBe(process.pid);- });-- it("returns the newest page with hasMore when older checks exist", () => {- seedTicks(CHECKS_PAGE_SIZE + 2);- const { rows, hasMore } = listCheckRows(goalId);- expect(rows).toHaveLength(CHECKS_PAGE_SIZE);- expect(rows[0]!.tick_number).toBe(CHECKS_PAGE_SIZE + 2);- expect(rows.at(-1)!.tick_number).toBe(3);- expect(hasMore).toBe(true);- });-- it("reports no more pages when everything fits", () => {- seedTicks(4);- const { rows, hasMore } = listCheckRows(goalId);- expect(rows.map((r) => r.tick_number)).toEqual([4, 3, 2, 1]);- expect(hasMore).toBe(false);- });-- it("pages strictly older than the cursor, newest first", () => {- seedTicks(CHECKS_PAGE_SIZE + 2);- const { rows, hasMore } = listCheckRows(goalId, { beforeTick: 3 });- expect(rows.map((r) => r.tick_number)).toEqual([2, 1]);- expect(hasMore).toBe(false);- });-});--describe("writeBadgeForTool", () => {- it("maps write tool calls to short badge labels", () => {- expect(- writeBadgeForTool("notfair_x__notfair_googleads.updateCampaignBudget"),- ).toBe("Campaign budget updated");- expect(writeBadgeForTool("mcp__NotFair-GoogleAds__pauseKeyword")).toBe(- "Keyword paused",- );- expect(writeBadgeForTool("notfair_x__notfair_goals.amend_goal")).toBe(- "Goal updated",- );- expect(writeBadgeForTool("notfair_x__notfair_goals.add_supporting_metric")).toBe(- "Supporting metric added",- );- expect(writeBadgeForTool("mcp__NotFair-GoogleAds__bulkAddKeywords")).toBe(- "Keywords added",- );- expect(writeBadgeForTool("mcp__NotFair-GoogleAds__runMutationScript")).toBe(- "Mutation script ran",- );- // Bare-verb and prepositional third-party tools stay grammatical.- expect(writeBadgeForTool("mcp__NotFair-GoogleAds__mutate")).toBe("Mutated");- expect(writeBadgeForTool("mcp__vercel__deploy_to_vercel")).toBe(- "Deployed to vercel",- );- expect(writeBadgeForTool("mcp__slack__send_message")).toBe("Message sent");- });-- it("ignores reads, diary bookkeeping, harness built-ins, and PR tools", () => {- expect(writeBadgeForTool("shell")).toBeNull();- expect(writeBadgeForTool("Write")).toBeNull(); // workspace file, not a platform write- expect(writeBadgeForTool("Edit")).toBeNull();- expect(writeBadgeForTool("notfair_x__posthog.exec")).toBeNull();- expect(writeBadgeForTool("notfair_x__notfair_googleads.listKeywords")).toBeNull();- expect(writeBadgeForTool("notfair_x__notfair_goals.get_goal")).toBeNull();- expect(writeBadgeForTool("notfair_x__notfair_goals.log_goal_action")).toBeNull();- expect(writeBadgeForTool("notfair_x__notfair_goals.log_learning")).toBeNull();- expect(writeBadgeForTool("notfair_x__notfair_goals.review_goal_action")).toBeNull();- expect(- writeBadgeForTool("notfair_x__notfair_goals.register_pull_request"),- ).toBeNull();- expect(writeBadgeForTool("codex_apps.github.create_pull_request")).toBeNull();- expect(writeBadgeForTool("notfair_x__notfair_xads.runScript")).toBeNull();- });-});--describe("listCheckRows write badges + action filter", () => {- it("dedupes a check's write calls into counted badges; read-only checks get none", () => {- seedTicks(3);- seedTickToolCalls(2, [- "notfair_x__notfair_googleads.updateCampaignBudget",- "notfair_x__notfair_googleads.pauseKeyword",- "notfair_x__notfair_googleads.pauseKeyword",- "notfair_x__posthog.exec", // read — no badge- "shell",- ]);- seedTickToolCalls(3, ["notfair_x__posthog.exec", "shell"]);-- const { rows } = listCheckRows(goalId);- const byTick = new Map(rows.map((r) => [r.tick_number, r.writes]));- expect(byTick.get(2)).toEqual([- { label: "Campaign budget updated", count: 1 },- { label: "Keyword paused", count: 2 },- ]);- expect(byTick.get(3)).toEqual([]);- expect(byTick.get(1)).toEqual([]);- });-- it("prefers agent-written action badges over name-derived ones for that check", () => {- seedTicks(2);- seedTickToolCalls(2, ["notfair_x__notfair_googleads.updateCampaignBudget"]);- createGoalAction({- goal_id: goalId,- tick_number: 2,- kind: "mutation",- description: "Raised campaign 123 daily budget $20 → $40",- expected_effect: "more clicks",- review_after: null,- badge: "Budget raised",- });-- const { rows } = listCheckRows(goalId);- expect(rows.find((r) => r.tick_number === 2)!.writes).toEqual([- { label: "Budget raised", count: 1 },- ]);- });-- it("drops PR-ish agent badges and falls back to the classifier", () => {- seedTicks(1);- seedTickToolCalls(1, ["notfair_x__notfair_goals.amend_goal"]);- createGoalAction({- goal_id: goalId,- tick_number: 1,- kind: "mutation",- description: "Opened a code PR",- expected_effect: "fix lands",- review_after: null,- badge: "PR opened", // redundant with the PR pill- });-- const { rows } = listCheckRows(goalId);- expect(rows[0]!.writes).toEqual([{ label: "Goal updated", count: 1 }]);- });-- it("filter=action keeps only checks that wrote or opened a PR, cursor-paged", () => {- seedTicks(6);- seedTickToolCalls(5, ["notfair_x__notfair_googleads.updateCampaignBudget"]);- seedTickToolCalls(3, ["notfair_x__posthog.exec"]); // read-only — excluded- seedTickToolCalls(2, ["notfair_x__notfair_goals.amend_goal"]);- createGoalPr({- goal_id: goalId,- url: "https://github.com/acme/site/pull/7",- title: "Fix titles",- tick_number: 4,- });-- const first = listCheckRows(goalId, { filter: "action", limit: 2 });- expect(first.rows.map((r) => r.tick_number)).toEqual([5, 4]);- expect(first.hasMore).toBe(true);-- const next = listCheckRows(goalId, { filter: "action", limit: 2, beforeTick: 4 });- expect(next.rows.map((r) => r.tick_number)).toEqual([2]);- expect(next.hasMore).toBe(false);- });-});--describe("listCheckRows PR attachment", () => {- it("attaches a PR to the check stamped on it at registration", () => {- seedTicks(3);- createGoalPr({- goal_id: goalId,- url: "https://github.com/acme/site/pull/7",- title: "Fix titles",- tick_number: 2,- });- const { rows } = listCheckRows(goalId);- const byTick = new Map(rows.map((r) => [r.tick_number, r.prs]));- expect(byTick.get(2)).toEqual([- expect.objectContaining({ url: "https://github.com/acme/site/pull/7", state: "open" }),- ]);- expect(byTick.get(1)).toEqual([]);- expect(byTick.get(3)).toEqual([]);- });-- it("falls back to the linked action's check for pre-stamping PRs", () => {- seedTicks(3);- const action = createGoalAction({- goal_id: goalId,- tick_number: 3,- kind: "mutation",- description: "Pause wasted keywords",- expected_effect: "less waste",- review_after: null,- });- createGoalPr({- goal_id: goalId,- url: "https://github.com/acme/site/pull/8",- title: "Legacy PR",- action_id: action.id,- // No tick_number: registered before stamping existed.- });- const { rows } = listCheckRows(goalId);- expect(rows.find((r) => r.tick_number === 3)!.prs).toEqual([- expect.objectContaining({ url: "https://github.com/acme/site/pull/8" }),- ]);- });-- it("leaves PRs with neither stamp nor action off every check", () => {- seedTicks(2);- createGoalPr({- goal_id: goalId,- url: "https://github.com/acme/site/pull/9",- title: "Orphan",- });- const { rows } = listCheckRows(goalId);- expect(rows.every((r) => r.prs.length === 0)).toBe(true);- });-});diff --git a/notfair/src/server/goals/checks.ts b/notfair/src/server/goals/checks.tsdeleted file mode 100644index 3177c795..00000000--- a/notfair/src/server/goals/checks.ts+++ /dev/null@@ -1,232 +0,0 @@-import {- listGoalActionBadges,- listGoalActions,- listGoalTicks,- listGoalTicksByNumbers,- listTickToolCalls,- type GoalTick,-} from "@/server/db/goals";-import { listGoalPrs, type GoalPrState } from "@/server/db/goal-prs";--/**- * Check rows for the goal screen's diary list — each tick joined with the- * PRs its turn registered and the writes its session performed, paged- * newest-first by tick_number so the list can lazy-load older checks on- * scroll.- */--export type CheckPr = {- id: string;- url: string;- title: string;- state: GoalPrState;-};--/** One kind of modification a check made, e.g. "Campaign budget updated". */-export type CheckWrite = { label: string; count: number };--export type CheckRow = GoalTick & { prs: CheckPr[]; writes: CheckWrite[] };--/** "action" keeps only checks that modified something: performed a- * platform/goal write or registered a PR. Read-only checks are hidden. */-export type CheckFilter = "all" | "action";--export const CHECKS_PAGE_SIZE = 10;--/**- * Verb-first tool-name conventions across the MCP catalog and the goal- * tools (`updateCampaignBudget`, `pause_keyword`, `amend_goal`) let the- * leading token classify writes. Only these verbs badge; read verbs- * (get/list/run/search…) and diary bookkeeping (log/review/propose/- * register…) fall through to null.- */-const WRITE_VERB_PAST: Record<string, string> = {- // NotFair catalog conventions (Google Ads, Meta Ads, goal tools).- create: "created",- add: "added",- update: "updated",- set: "set",- amend: "updated",- manage: "updated",- delete: "deleted",- remove: "removed",- pause: "paused",- enable: "enabled",- resume: "resumed",- rename: "renamed",- upload: "uploaded",- move: "moved",- link: "linked",- unlink: "unlinked",- exclude: "excluded",- include: "included",- graduate: "graduated",- promote: "promoted",- end: "ended",- schedule: "scheduled",- replace: "replaced",- mutate: "mutated",- // Common write verbs across third-party MCP servers.- send: "sent",- post: "posted",- publish: "published",- submit: "submitted",- approve: "approved",- reject: "rejected",- archive: "archived",- cancel: "canceled",- close: "closed",- merge: "merged",- apply: "applied",- insert: "inserted",- write: "written",- patch: "patched",- toggle: "toggled",- assign: "assigned",- revoke: "revoked",- grant: "granted",- attach: "attached",- detach: "detached",- sync: "synced",- import: "imported",- deploy: "deployed",- save: "saved",- restore: "restored",- invite: "invited",- register: "registered",-};--/**- * Map a raw harness tool name to a short "what changed" badge label, or- * null when the call isn't a write worth badging. PR creation and- * registration return null — the PR pill already covers those.- *- * `notfair_x__notfair_googleads.updateCampaignBudget` → "Campaign budget updated"- * `mcp__NotFair-GoogleAds__pauseKeyword` → "Keyword paused"- * `notfair_x__notfair_goals.amend_goal` → "Goal updated"- * `...listKeywords` / `...log_goal_action` / `shell` → null- */-export function writeBadgeForTool(name: string): string | null {- if (!name) return null;- // Only namespaced MCP tools qualify. Bare harness built-ins (`shell`,- // `Write`, `Edit`) are workspace file/command work, not platform writes —- // code changes surface through the PR pill instead.- if (!/__|\./.test(name)) return null;- // Strip both namespace conventions, keeping only the action name.- let action = name;- for (const sep of ["__", "."]) {- const idx = action.lastIndexOf(sep);- if (idx >= 0 && action.slice(idx + sep.length)) action = action.slice(idx + sep.length);- }- if (/pull_?request/i.test(action)) return null;- // camelCase / snake_case → lowercase tokens.- let tokens = action- .replace(/([a-z])([A-Z])/g, "$1 $2")- .replace(/[_-]+/g, " ")- .toLowerCase()- .split(" ")- .filter(Boolean);- if (tokens[0] === "bulk") tokens = tokens.slice(1);- if (tokens[0] === "run" && tokens[1] === "mutation") return "Mutation script ran";- const past = WRITE_VERB_PAST[tokens[0] ?? ""];- if (!past) return null;- const obj = tokens.slice(1).join(" ");- const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);- // Bare-verb tools (`mutate`, `deploy`) badge as just the past tense;- // prepositional names (`deploy_to_vercel`) keep verb-first order.- if (!obj) return cap(past);- if (/^(to|from|into|in|for|with) /.test(obj)) return `${cap(past)} ${obj}`;- return `${cap(obj)} ${past}`;-}--/**- * tick_number → deduped write badges (first-seen order, with counts).- *- * Two sources, agent-first: badges the agent wrote via log_goal_action's- * `action_badge` are authoritative for their check — the agent knows what- * it changed regardless of tool naming. Checks with no agent badge fall- * back to classifying the session's tool calls by name, so history and- * forgetful turns still badge. PR-ish agent badges are dropped — the PR- * pill already covers those.- */-function collectWritesByTick(goal_id: string): Map<number, CheckWrite[]> {- const agent = new Map<number, Map<string, CheckWrite>>();- for (const { tick_number, badge } of listGoalActionBadges(goal_id)) {- if (tick_number == null || /pull.?request|\bpr\b/i.test(badge)) continue;- tally(agent, tick_number, badge);- }-- const derived = new Map<number, Map<string, CheckWrite>>();- for (const call of listTickToolCalls(goal_id)) {- if (agent.has(call.tick_number)) continue;- const label = writeBadgeForTool(call.name);- if (label) tally(derived, call.tick_number, label);- }-- return new Map(- [...agent, ...derived].map(([tick, labels]) => [tick, [...labels.values()]]),- );-}--function tally(- acc: Map<number, Map<string, CheckWrite>>,- tick: number,- label: string,-): void {- const labels = acc.get(tick) ?? new Map<string, CheckWrite>();- const entry = labels.get(label);- if (entry) entry.count += 1;- else labels.set(label, { label, count: 1 });- acc.set(tick, labels);-}--export function listCheckRows(- goal_id: string,- opts: { limit?: number; beforeTick?: number; filter?: CheckFilter } = {},-): { rows: CheckRow[]; hasMore: boolean } {- const limit = opts.limit ?? CHECKS_PAGE_SIZE;-- const writesByTick = collectWritesByTick(goal_id);-- // PRs registered before tick stamping existed resolve their check- // through the linked action instead.- const actionTicks = new Map(- listGoalActions(goal_id, 200).map((a) => [a.id, a.tick_number]),- );- const prsByTick = new Map<number, CheckPr[]>();- for (const pr of listGoalPrs(goal_id, 100)) {- const tickNo =- pr.tick_number ?? (pr.action_id ? (actionTicks.get(pr.action_id) ?? null) : null);- if (tickNo == null) continue;- prsByTick.set(tickNo, [- ...(prsByTick.get(tickNo) ?? []),- { id: pr.id, url: pr.url, title: pr.title, state: pr.state },- ]);- }-- let page: GoalTick[];- let hasMore: boolean;- if (opts.filter === "action") {- // The eligible set is small and known upfront, so page over its tick- // numbers directly.- const eligible = [...new Set([...writesByTick.keys(), ...prsByTick.keys()])]- .filter((n) => opts.beforeTick === undefined || n < opts.beforeTick)- .sort((a, b) => b - a);- hasMore = eligible.length > limit;- page = listGoalTicksByNumbers(goal_id, eligible.slice(0, limit));- } else {- // Fetch one extra row purely to learn whether another page exists.- const ticks = listGoalTicks(goal_id, limit + 1, opts.beforeTick);- hasMore = ticks.length > limit;- page = ticks.slice(0, limit);- }-- return {- rows: page.map((t) => ({- ...t,- prs: prsByTick.get(t.tick_number) ?? [],- writes: writesByTick.get(t.tick_number) ?? [],- })),- hasMore,- };-}diff --git a/notfair/src/server/goals/handlers.test.ts b/notfair/src/server/goals/handlers.test.tsdeleted file mode 100644index 6138ab8f..00000000--- a/notfair/src/server/goals/handlers.test.ts+++ /dev/null@@ -1,794 +0,0 @@-import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";--// Real better-sqlite3 against a tmpdir DB, per repo test conventions.-// MUST be hoisted: static imports evaluate before module-level statements,-// and db.ts captures NOTFAIR_DATA_DIR at import time — a plain assignment-// here would silently point the suite at the developer's live ~/.notfair.-vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-handlers-"));-});--const mocks = vi.hoisted(() => ({- runMetricSource: vi.fn(),- runHistorySource: vi.fn(),- syncGoalIdentity: vi.fn(async () => {}),- syncProjectAgents: vi.fn(async () => 3),- runGoalTick: vi.fn(async () => {}),- syncGoalPrs: vi.fn(async () => {}),-}));--// Boundary mocks: metric execution (subprocess / MCP), identity re-render-// (adapter runtime), the first tick (adapter runtime), and PR sync (gh).-vi.mock("./metric", () => ({- LOCAL_SOURCE_KEY: "local",- runMetricSource: mocks.runMetricSource,- runHistorySource: mocks.runHistorySource,-}));-vi.mock("./provision", () => ({- syncGoalIdentity: mocks.syncGoalIdentity,- syncProjectAgents: mocks.syncProjectAgents,-}));-vi.mock("./tick", () => ({ runGoalTick: mocks.runGoalTick }));-vi.mock("./pr-sync", () => ({- syncGoalPrs: mocks.syncGoalPrs,- maybeSyncGoalPrs: vi.fn(),-}));--import {- handleAddSupportMetric,- handleAmendGoal,- handleBackfillHistory,- handleDefineGoal,- handleGetGoal,- handleGetProject,- handleLogGoalAction,- handleLogLearning,- handleProposeGoalMetric,- handleProposeTarget,- handleReviewGoalAction,- handleSearchLearnings,- handleSetProjectBrief,- handleUpdateGoalStatus,-} from "./handlers";-import { getDb } from "@/server/db/db";-import {- addGoalLearning,- createGoal,- createGoalAction,- getGoal,- listGoalLearnings,- listMetricSnapshots,- proposeTarget,- recordMetricSnapshot,- setGoalMetric,- setGoalStatus,- type Goal,-} from "@/server/db/goals";-import { listSupportMetrics } from "@/server/db/goal-support-metrics";-import { readProjectBrief } from "@/server/onboarding/project-brief";-import { PROJECT_BRIEF_MAX_BYTES } from "@/server/onboarding/project-brief";--const SLUG = "proj";-const ctxFor = (agent_id: string) => ({ project_slug: SLUG, agent_id });--const LOCAL_SPEC = {- metric_source_key: "local",- metric_source_tool: "shell",- metric_source_args_json: JSON.stringify({ command: "echo 1" }),-};--function makeIntakeGoal(agent: string, statement = "Grow organic clicks"): Goal {- return createGoal({ project_slug: SLUG, agent_id: agent, statement });-}--function makeProposedGoal(agent: string): Goal {- const goal = makeIntakeGoal(agent);- return setGoalMetric(goal.id, {- metric_name: "clicks",- ...LOCAL_SPEC,- metric_direction: "increase",- baseline_value: 10,- })!;-}--function makeActiveGoal(agent: string): Goal {- const goal = makeProposedGoal(agent);- return proposeTarget(goal.id, { target_value: 100 })!;-}--beforeAll(() => {- const ts = new Date().toISOString();- getDb()- .prepare(- "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('p1', ?, 'Proj', ?, 'claude-code-local')",- )- .run(SLUG, ts);- getDb()- .prepare(- "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('p2', 'other', 'Other', ?, 'claude-code-local')",- )- .run(ts);-});--beforeEach(() => {- mocks.runMetricSource.mockReset();- mocks.runHistorySource.mockReset();- mocks.runGoalTick.mockClear();- mocks.syncProjectAgents.mockClear();-});--describe("goal resolution / authorization", () => {- it("rejects an unknown goal id", async () => {- const r = await handleGetGoal({ goal_id: "nope" }, ctxFor("a"));- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("Unknown goal_id");- });-- it("rejects cross-project access", async () => {- const foreign = createGoal({ project_slug: "other", agent_id: "x-1", statement: "s" });- const r = await handleGetGoal({ goal_id: foreign.id }, ctxFor("x-1"));- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("Cross-project");- });-- it("rejects owner-required calls from another agent", () => {- const goal = makeIntakeGoal("own-1");- const r = handleDefineGoal(- { goal_id: goal.id, statement: "s", short_label: "l" },- ctxFor("someone-else"),- );- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("owned by 'own-1'");- });-});--describe("handleGetGoal", () => {- it("assembles the full state view", async () => {- const goal = makeActiveGoal("view-1");- recordMetricSnapshot(goal.id, 42, "tick");- addGoalLearning(goal.id, "Tuesday spikes are noise", "high");- createGoalAction({- goal_id: goal.id,- kind: "mutation",- description: "raised bids",- expected_effect: "more clicks",- review_after: new Date(Date.now() + 3600_000).toISOString(),- spend_usd: 12.5,- });- // Another agent's gated action in the same project is surfaced too.- const other = makeActiveGoal("view-2");- createGoalAction({- goal_id: other.id,- kind: "mutation",- description: "their experiment",- resources_touched: ["campaign:9"],- expected_effect: "n/a",- review_after: new Date(Date.now() + 3600_000).toISOString(),- });-- const r = await handleGetGoal({ goal_id: goal.id }, ctxFor("view-1"));- expect(r.ok).toBe(true);- if (!r.ok) return;- expect(r.data.goal.id).toBe(goal.id);- expect(r.data.target_met).toBe(false); // 42 < 100- expect(r.data.actions_gated).toHaveLength(1);- expect(r.data.actions_due_for_review).toHaveLength(0);- expect(r.data.recent_learnings[0]!.body).toContain("Tuesday");- expect(r.data.metric_history.map((s) => s.value)).toContain(42);- expect(r.data.logged_spend_usd).toBe(12.5);- expect(r.data.gated_by_other_agents).toEqual([- expect.objectContaining({ agent_id: "view-2", resources: ["campaign:9"] }),- ]);- });-});--describe("handleDefineGoal", () => {- it("records the trimmed statement and clamps the label to 48 chars", () => {- const goal = makeIntakeGoal("def-1", "");- const r = handleDefineGoal(- {- goal_id: goal.id,- statement: " Grow signups ",- short_label: ` ${"x".repeat(60)} `,- },- ctxFor("def-1"),- );- expect(r.ok).toBe(true);- if (r.ok) expect(r.data.statement).toBe("Grow signups");- expect(getGoal(goal.id)!.short_label).toHaveLength(48);- });-- it("refuses once the goal has left intake", () => {- const goal = makeProposedGoal("def-2");- const r = handleDefineGoal(- { goal_id: goal.id, statement: "s", short_label: "l" },- ctxFor("def-2"),- );- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("'proposed', not 'intake'");- });-});--describe("handleProposeGoalMetric", () => {- const input = (goal_id: string, key = "local") => ({- goal_id,- metric_name: "clicks",- metric_source_key: key,- metric_source_tool: "shell",- metric_source_args_json: JSON.stringify({ command: "echo 42" }),- metric_direction: "increase" as const,- });-- it("refuses outside intake", async () => {- const goal = makeProposedGoal("pm-1");- const r = await handleProposeGoalMetric(input(goal.id), ctxFor("pm-1"));- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("not 'intake'");- });-- it("requires a defined statement first", async () => {- const goal = makeIntakeGoal("pm-2", "");- const r = await handleProposeGoalMetric(input(goal.id), ctxFor("pm-2"));- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("define_goal");- });-- it("rejects a non-local source without a connected MCP token", async () => {- const goal = makeIntakeGoal("pm-3");- const r = await handleProposeGoalMetric(- input(goal.id, "notfair-googleads"),- ctxFor("pm-3"),- );- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("No connected MCP 'notfair-googleads'");- expect(mocks.runMetricSource).not.toHaveBeenCalled();- });-- it("bounces a metric the platform cannot reproduce", async () => {- const goal = makeIntakeGoal("pm-4");- mocks.runMetricSource.mockResolvedValueOnce({ ok: false, error: "shell exploded" });- const r = await handleProposeGoalMetric(input(goal.id), ctxFor("pm-4"));- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("shell exploded");- expect(getGoal(goal.id)!.status).toBe("intake");- });-- it("verifies server-side, moves to proposed, and snapshots the baseline", async () => {- const goal = makeIntakeGoal("pm-5");- mocks.runMetricSource.mockResolvedValueOnce({ ok: true, value: 42 });- const r = await handleProposeGoalMetric(input(goal.id), ctxFor("pm-5"));- expect(r.ok).toBe(true);- if (r.ok) {- expect(r.data.baseline_value).toBe(42);- expect(r.data.status).toBe("proposed");- }- const fresh = getGoal(goal.id)!;- expect(fresh.baseline_value).toBe(42);- expect(fresh.current_value).toBe(42);- const snaps = listMetricSnapshots(goal.id);- expect(snaps).toEqual([expect.objectContaining({ value: 42, source: "intake" })]);- });-});--describe("handleBackfillHistory", () => {- const input = (goal_id: string, key = "local") => ({- goal_id,- source_key: key,- source_tool: "shell",- source_args_json: JSON.stringify({ command: "echo history" }),- });-- it("rejects an unconnected source", async () => {- const goal = makeProposedGoal("bf-1");- const r = await handleBackfillHistory(input(goal.id, "nope-mcp"), ctxFor("bf-1"));- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("No connected MCP");- });-- it("surfaces a failing history query", async () => {- const goal = makeProposedGoal("bf-2");- mocks.runHistorySource.mockResolvedValueOnce({ ok: false, error: "bad rows" });- const r = await handleBackfillHistory(input(goal.id), ctxFor("bf-2"));- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toBe("bad rows");- });-- it("rejects a series with only future-dated points", async () => {- const goal = makeProposedGoal("bf-3");- mocks.runHistorySource.mockResolvedValueOnce({- ok: true,- points: [{ date: new Date(Date.now() + 86_400_000).toISOString(), value: 1 }],- });- const r = await handleBackfillHistory(input(goal.id), ctxFor("bf-3"));- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("no past-dated points");- });-- it("stores past points and drops future ones", async () => {- const goal = makeProposedGoal("bf-4");- mocks.runHistorySource.mockResolvedValueOnce({- ok: true,- points: [- { date: "2026-07-01T00:00:00.000Z", value: 5 },- { date: "2026-07-02T00:00:00.000Z", value: 6 },- { date: new Date(Date.now() + 86_400_000).toISOString(), value: 99 },- ],- });- const r = await handleBackfillHistory(input(goal.id), ctxFor("bf-4"));- expect(r.ok).toBe(true);- if (r.ok) {- expect(r.data.points).toBe(2);- expect(r.data.from).toBe("2026-07-01");- expect(r.data.to).toBe("2026-07-02");- }- const snaps = listMetricSnapshots(goal.id);- expect(snaps.map((s) => s.value)).toEqual([5, 6]);- expect(snaps.every((s) => s.source === "backfill")).toBe(true);- });-});--describe("handleAddSupportMetric", () => {- const input = (goal_id: string, over: Record<string, unknown> = {}) => ({- goal_id,- name: "impressions",- source_key: "local",- source_tool: "shell",- source_args_json: JSON.stringify({ command: "echo 7" }),- ...over,- });-- it("requires a name", async () => {- const goal = makeActiveGoal("sm-1");- const r = await handleAddSupportMetric(input(goal.id, { name: " " }), ctxFor("sm-1"));- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("name");- });-- it("refuses shadowing the primary metric", async () => {- const goal = makeActiveGoal("sm-2");- const r = await handleAddSupportMetric(- input(goal.id, { name: "clicks" }),- ctxFor("sm-2"),- );- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("primary metric");- });-- it("rejects an unconnected source", async () => {- const goal = makeActiveGoal("sm-3");- const r = await handleAddSupportMetric(- input(goal.id, { source_key: "nope-mcp" }),- ctxFor("sm-3"),- );- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("No connected MCP");- });-- it("bounces an unverifiable metric", async () => {- const goal = makeActiveGoal("sm-4");- mocks.runMetricSource.mockResolvedValueOnce({ ok: false, error: "no such column" });- const r = await handleAddSupportMetric(input(goal.id), ctxFor("sm-4"));- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("no such column");- expect(listSupportMetrics(goal.id)).toHaveLength(0);- });-- it("stores the verified metric (no history)", async () => {- const goal = makeActiveGoal("sm-5");- mocks.runMetricSource.mockResolvedValueOnce({ ok: true, value: 7 });- const r = await handleAddSupportMetric(input(goal.id), ctxFor("sm-5"));- expect(r.ok).toBe(true);- if (r.ok) {- expect(r.data.metric.name).toBe("impressions");- expect(r.data.metric.baseline_value).toBe(7);- expect(r.data.backfilled).toBe(0);- }- });-- it("backfills history when provided", async () => {- const goal = makeActiveGoal("sm-6");- mocks.runMetricSource.mockResolvedValueOnce({ ok: true, value: 7 });- mocks.runHistorySource.mockResolvedValueOnce({- ok: true,- points: [- { date: "2026-07-01T00:00:00.000Z", value: 3 },- { date: new Date(Date.now() + 86_400_000).toISOString(), value: 9 },- ],- });- const r = await handleAddSupportMetric(- input(goal.id, { history_args_json: JSON.stringify({ command: "echo rows" }) }),- ctxFor("sm-6"),- );- expect(r.ok).toBe(true);- if (r.ok) expect(r.data.backfilled).toBe(1); // future point dropped- });-- it("keeps the metric but fails the call when history breaks", async () => {- const goal = makeActiveGoal("sm-7");- mocks.runMetricSource.mockResolvedValueOnce({ ok: true, value: 7 });- mocks.runHistorySource.mockResolvedValueOnce({ ok: false, error: "bad shape" });- const r = await handleAddSupportMetric(- input(goal.id, { history_args_json: JSON.stringify({ command: "echo rows" }) }),- ctxFor("sm-7"),- );- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("Metric stored, but the history query failed");- expect(listSupportMetrics(goal.id)).toHaveLength(1);- });-});--describe("handleProposeTarget", () => {- it("refuses before the metric is verified", () => {- const goal = makeIntakeGoal("pt-1");- const r = handleProposeTarget({ goal_id: goal.id, target_value: 5 }, ctxFor("pt-1"));- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("not 'proposed'");- });-- it("rejects a target on the wrong side of the baseline (achieve)", () => {- const inc = makeProposedGoal("pt-2"); // increase, baseline 10- const below = handleProposeTarget({ goal_id: inc.id, target_value: 5 }, ctxFor("pt-2"));- expect(below.ok).toBe(false);- if (!below.ok) expect(below.error).toContain("'increase'");-- const decGoal = makeIntakeGoal("pt-3");- setGoalMetric(decGoal.id, {- metric_name: "waste",- ...LOCAL_SPEC,- metric_direction: "decrease",- baseline_value: 10,- });- const above = handleProposeTarget(- { goal_id: decGoal.id, target_value: 20 },- ctxFor("pt-3"),- );- expect(above.ok).toBe(false);- if (!above.ok) expect(above.error).toContain("'decrease'");- });-- it("maintain targets may sit on the already-met side", async () => {- const goal = makeProposedGoal("pt-4"); // increase, baseline 10- const r = handleProposeTarget(- { goal_id: goal.id, target_value: 5, mode: "maintain" },- ctxFor("pt-4"),- );- expect(r.ok).toBe(true);- if (r.ok) expect(r.data.status).toBe("active");- expect(getGoal(goal.id)!.mode).toBe("maintain");- // The first tick fires immediately on confirmation.- await new Promise((r) => setImmediate(r));- expect(mocks.runGoalTick).toHaveBeenCalledWith(- expect.objectContaining({ id: goal.id }),- "manual",- );- });-- it("surfaces an invalid cadence cron as an error result", () => {- const goal = makeProposedGoal("pt-5");- const r = handleProposeTarget(- { goal_id: goal.id, target_value: 100, cadence_cron: "not a cron" },- ctxFor("pt-5"),- );- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("Invalid cadence cron");- });-});--describe("handleAmendGoal", () => {- it("only applies to active/paused goals", () => {- const goal = makeIntakeGoal("am-1");- const r = handleAmendGoal({ goal_id: goal.id, target_value: 5 }, ctxFor("am-1"));- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("amend applies to active/paused");- });-- it("requires at least one field", () => {- const goal = makeActiveGoal("am-2");- const r = handleAmendGoal({ goal_id: goal.id }, ctxFor("am-2"));- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("Nothing to amend");- });-- it("re-checks target direction on amendment", () => {- const goal = makeActiveGoal("am-3"); // increase, baseline 10- const r = handleAmendGoal({ goal_id: goal.id, target_value: 3 }, ctxFor("am-3"));- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("'increase'");- });-- it("surfaces an invalid cron as an error result", () => {- const goal = makeActiveGoal("am-4");- const r = handleAmendGoal(- { goal_id: goal.id, cadence_cron: "nope" },- ctxFor("am-4"),- );- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("Invalid cadence cron");- });-- it("amends envelope, deadline, and target on a live goal", () => {- const goal = makeActiveGoal("am-5");- const r = handleAmendGoal(- {- goal_id: goal.id,- target_value: 250,- deadline: "2026-12-31T00:00:00.000Z",- spend_envelope_usd: 3000,- },- ctxFor("am-5"),- );- expect(r.ok).toBe(true);- if (r.ok) {- expect(r.data.target_value).toBe(250);- expect(r.data.deadline).toBe("2026-12-31T00:00:00.000Z");- expect(r.data.spend_envelope_usd).toBe(3000);- expect(r.data.cadence_cron).toBe("0 16 * * *");- }- });-});--describe("handleLogGoalAction", () => {- it("refuses mutations without an observation window", () => {- const goal = makeActiveGoal("la-1");- const r = handleLogGoalAction(- {- goal_id: goal.id,- kind: "mutation",- description: "raise bids",- expected_effect: "clicks up",- },- ctxFor("la-1"),- );- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("review_after_hours");- });-- it("logs a mutation with a derived review_after", () => {- const goal = makeActiveGoal("la-2");- const before = Date.now();- const r = handleLogGoalAction(- {- goal_id: goal.id,- kind: "mutation",- description: "raise bids",- resources_touched: ["campaign:1"],- expected_effect: "clicks up",- review_after_hours: 48,- spend_usd: 20,- action_badge: "Bids raised",- },- ctxFor("la-2"),- );- expect(r.ok).toBe(true);- if (!r.ok) return;- const reviewAt = Date.parse(r.data.review_after!);- expect(reviewAt).toBeGreaterThanOrEqual(before + 48 * 3_600_000);- expect(reviewAt).toBeLessThan(before + 49 * 3_600_000);- });-- it("research actions need no window", () => {- const goal = makeActiveGoal("la-3");- const r = handleLogGoalAction(- {- goal_id: goal.id,- kind: "research",- description: "read search terms",- expected_effect: "n/a",- },- ctxFor("la-3"),- );- expect(r.ok).toBe(true);- if (r.ok) expect(r.data.review_after).toBeNull();- });-});--describe("handleReviewGoalAction", () => {- it("rejects an action from another goal", () => {- const goal = makeActiveGoal("rv-1");- const other = makeActiveGoal("rv-2");- const foreign = createGoalAction({- goal_id: other.id,- kind: "research",- description: "d",- expected_effect: "e",- });- const r = handleReviewGoalAction(- { goal_id: goal.id, action_id: foreign.id, observed_outcome: "o" },- ctxFor("rv-1"),- );- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("Unknown action_id");- });-- it("reviews once, records the learning, and refuses a second pass", () => {- const goal = makeActiveGoal("rv-3");- const action = createGoalAction({- goal_id: goal.id,- kind: "mutation",- description: "d",- expected_effect: "e",- review_after: new Date().toISOString(),- });- const r = handleReviewGoalAction(- {- goal_id: goal.id,- action_id: action.id,- observed_outcome: "worked",- learning: "bids move clicks within 2 days",- },- ctxFor("rv-3"),- );- expect(r.ok).toBe(true);- if (r.ok) {- expect(r.data.status).toBe("reviewed");- expect(r.data.learning_id).not.toBeNull();- }- expect(listGoalLearnings(goal.id)[0]!.body).toContain("bids move clicks");-- const again = handleReviewGoalAction(- { goal_id: goal.id, action_id: action.id, observed_outcome: "o" },- ctxFor("rv-3"),- );- expect(again.ok).toBe(false);- if (!again.ok) expect(again.error).toContain("not open");- });-- it("abandoning records the abandoned status without a learning", () => {- const goal = makeActiveGoal("rv-4");- const action = createGoalAction({- goal_id: goal.id,- kind: "mutation",- description: "d",- expected_effect: "e",- review_after: new Date().toISOString(),- });- const r = handleReviewGoalAction(- { goal_id: goal.id, action_id: action.id, observed_outcome: "reverted", abandoned: true },- ctxFor("rv-4"),- );- expect(r.ok).toBe(true);- if (r.ok) {- expect(r.data.status).toBe("abandoned");- expect(r.data.learning_id).toBeNull();- }- });-});--describe("learnings tools", () => {- it("logs with supersession and searches by substring", () => {- const goal = makeActiveGoal("ln-1");- const first = handleLogLearning(- { goal_id: goal.id, body: "old belief", confidence: "low" },- ctxFor("ln-1"),- );- expect(first.ok).toBe(true);- if (!first.ok) return;- const second = handleLogLearning(- { goal_id: goal.id, body: "new belief", supersedes_id: first.data.learning_id },- ctxFor("ln-1"),- );- expect(second.ok).toBe(true);-- const all = handleSearchLearnings({ goal_id: goal.id }, ctxFor("ln-1"));- expect(all.ok).toBe(true);- if (all.ok) {- // The superseded learning is filtered out of listings.- expect(all.data.learnings.map((l) => l.body)).toEqual(["new belief"]);- }- const hit = handleSearchLearnings(- { goal_id: goal.id, query: "new", limit: 999 },- ctxFor("ln-1"),- );- expect(hit.ok).toBe(true);- if (hit.ok) expect(hit.data.learnings).toHaveLength(1);- const miss = handleSearchLearnings(- { goal_id: goal.id, query: "zzz" },- ctxFor("ln-1"),- );- expect(miss.ok).toBe(true);- if (miss.ok) expect(miss.data.learnings).toHaveLength(0);- });-});--describe("handleUpdateGoalStatus", () => {- it("never lets a maintain goal self-complete", () => {- const goal = makeProposedGoal("st-1");- proposeTarget(goal.id, { target_value: 5, mode: "maintain" });- const r = handleUpdateGoalStatus(- { goal_id: goal.id, status: "achieved", reason: "done" },- ctxFor("st-1"),- );- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("MAINTAIN");- });-- it("refuses 'achieved' while the number says otherwise", () => {- const goal = makeActiveGoal("st-2"); // target 100- recordMetricSnapshot(goal.id, 50, "tick");- const r = handleUpdateGoalStatus(- { goal_id: goal.id, status: "achieved", reason: "trust me" },- ctxFor("st-2"),- );- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("has not met the target");- });-- it("closes achieved when the measured metric agrees", () => {- const goal = makeActiveGoal("st-3");- recordMetricSnapshot(goal.id, 150, "tick");- const r = handleUpdateGoalStatus(- { goal_id: goal.id, status: "achieved", reason: "target crossed" },- ctxFor("st-3"),- );- expect(r.ok).toBe(true);- if (r.ok) expect(r.data.status).toBe("achieved");- });-- it("pauses without target checks", () => {- const goal = makeActiveGoal("st-4");- const r = handleUpdateGoalStatus(- { goal_id: goal.id, status: "paused", reason: "token expired" },- ctxFor("st-4"),- );- expect(r.ok).toBe(true);- if (r.ok) expect(r.data.status).toBe("paused");- expect(getGoal(goal.id)!.next_tick_at).toBeNull();- });-- it("terminal statuses are final", () => {- const goal = makeActiveGoal("st-5");- setGoalStatus(goal.id, "killed", "user closed it");- const r = handleUpdateGoalStatus(- { goal_id: goal.id, status: "paused", reason: "r" },- ctxFor("st-5"),- );- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("terminal");- });-});--describe("project tools", () => {- it("handleGetProject returns the caller's project or an error", () => {- const ok = handleGetProject({}, ctxFor("a"));- expect(ok.ok).toBe(true);- if (ok.ok) expect(ok.data.slug).toBe(SLUG);- const bad = handleGetProject({}, { project_slug: "ghost", agent_id: "a" });- expect(bad.ok).toBe(false);- });-- it("handleSetProjectBrief validates project, content, and size", async () => {- const ghost = await handleSetProjectBrief(- { content: "x" },- { project_slug: "ghost", agent_id: "a" },- );- expect(ghost.ok).toBe(false);-- const empty = await handleSetProjectBrief({ content: " " }, ctxFor("a"));- expect(empty.ok).toBe(false);- if (!empty.ok) expect(empty.error).toContain("empty");-- const huge = await handleSetProjectBrief(- { content: "x".repeat(PROJECT_BRIEF_MAX_BYTES + 1) },- ctxFor("a"),- );- expect(huge.ok).toBe(false);- if (!huge.ok) expect(huge.error).toContain("bytes");- });-- it("handleSetProjectBrief writes PROJECT.md and re-syncs every agent", async () => {- const r = await handleSetProjectBrief(- { content: " Acme sells anvils. " },- ctxFor("a"),- );- expect(r.ok).toBe(true);- if (r.ok) {- expect(r.data.bytes).toBe(Buffer.byteLength("Acme sells anvils."));- expect(r.data.synced_agents).toBe(3);- }- expect(mocks.syncProjectAgents).toHaveBeenCalledWith(SLUG);- await expect(readProjectBrief(SLUG)).resolves.toBe("Acme sells anvils.");- });-});diff --git a/notfair/src/server/goals/handlers.ts b/notfair/src/server/goals/handlers.tsdeleted file mode 100644index 6164a96d..00000000--- a/notfair/src/server/goals/handlers.ts+++ /dev/null@@ -1,825 +0,0 @@-import {- addGoalLearning,- amendGoal,- createGoalAction,- defineGoal,- getGoal,- getGoalAction,- listActionsDueForReview,- listGatedActions,- listGoalLearnings,- listGatedActionsForOtherAgents,- listGoalTicks,- listMetricSnapshots,- loggedSpendTotal,- proposeTarget,- recordMetricSnapshot,- replaceBackfillSnapshots,- reviewGoalAction,- searchGoalLearnings,- setGoalMetric,- setGoalStatus,- isTargetMet,- type Goal,- type GoalAction,- type GoalLearning,- type GoalTick,- type MetricDirection,-} from "@/server/db/goals";-import { getProject } from "@/server/db/projects";-import {- listSupportMetrics,- replaceSupportBackfillSnapshots,- upsertSupportMetric,- type GoalSupportMetric,-} from "@/server/db/goal-support-metrics";-import { findMcpToken } from "@/server/mcp/tokens";-import {- PROJECT_BRIEF_MAX_BYTES,- readProjectBrief,- writeProjectBrief,-} from "@/server/onboarding/project-brief";-import type { Project } from "@/types";-import { LOCAL_SOURCE_KEY, runHistorySource, runMetricSource } from "./metric";--/**- * Handlers for NotFair's MCP tools — the goal agent's coordination- * surface. Inputs are schema-validated upstream (zod in- * mcp-server/tools.ts); context carries the caller's identity, and- * cross-project / wrong-agent calls are rejected here.- */--export type HandlerContext = {- /** Project the caller is operating in. */- project_slug: string;- /** Caller's agent_id (the one making the change). */- agent_id: string;-};--export type HandlerResult<T> =- | { ok: true; data: T }- | { ok: false; error: string };--/** Resolve + authorize a goal for the calling agent. */-function resolveGoal(- goal_id: string,- ctx: HandlerContext,- opts: { requireOwner?: boolean } = {},-): HandlerResult<Goal> {- const goal = getGoal(goal_id);- if (!goal) return { ok: false, error: `Unknown goal_id '${goal_id}'` };- if (goal.project_slug !== ctx.project_slug) {- return { ok: false, error: `Cross-project goal access rejected on '${goal_id}'` };- }- if (opts.requireOwner && goal.agent_id !== ctx.agent_id) {- return {- ok: false,- error: `Goal '${goal_id}' is owned by '${goal.agent_id}', not '${ctx.agent_id}'`,- };- }- return { ok: true, data: goal };-}--// ── get_goal ─────────────────────────────────────────────────────────────--export type GoalStateView = {- goal: Goal;- target_met: boolean | null;- actions_due_for_review: GoalAction[];- actions_gated: GoalAction[];- recent_learnings: GoalLearning[];- recent_ticks: Array<Pick<GoalTick, "tick_number" | "status" | "metric_value" | "summary" | "started_at">>;- metric_history: Array<{ value: number; created_at: string }>;- /** Supporting metrics: measured every check, context only, never judged. */- supporting_metrics: Array<- Pick<GoalSupportMetric, "name" | "direction" | "baseline_value" | "current_value">- >;- /** Sum of spend_usd across your logged (non-abandoned) actions. */- logged_spend_usd: number;- /** Other agents' still-gated resources in this workspace — equally untouchable. */- gated_by_other_agents: Array<{ agent_id: string; description: string; resources: string[]; until: string | null }>;- /** Shared workspace context (PROJECT.md) — same for every agent. */- shared_context: string | null;-};--export async function handleGetGoal(- input: { goal_id: string },- ctx: HandlerContext,-): Promise<HandlerResult<GoalStateView>> {- const r = resolveGoal(input.goal_id, ctx);- if (!r.ok) return r;- const goal = r.data;- const shared_context = await readProjectBrief(ctx.project_slug).catch(() => null);- return {- ok: true,- data: {- goal,- target_met: isTargetMet(goal),- actions_due_for_review: listActionsDueForReview(goal.id),- actions_gated: listGatedActions(goal.id),- recent_learnings: listGoalLearnings(goal.id, 15),- recent_ticks: listGoalTicks(goal.id, 5).map((t) => ({- tick_number: t.tick_number,- status: t.status,- metric_value: t.metric_value,- summary: t.summary,- started_at: t.started_at,- })),- metric_history: listMetricSnapshots(goal.id, 30).map((s) => ({- value: s.value,- created_at: s.created_at,- })),- supporting_metrics: listSupportMetrics(goal.id).map((m) => ({- name: m.name,- direction: m.direction,- baseline_value: m.baseline_value,- current_value: m.current_value,- })),- logged_spend_usd: loggedSpendTotal(goal.id),- gated_by_other_agents: listGatedActionsForOtherAgents(ctx.project_slug, goal.id).map(- (a) => ({- agent_id: a.agent_id,- description: a.description,- resources: JSON.parse(a.resources_touched_json || "[]") as string[],- until: a.review_after,- }),- ),- shared_context,- },- };-}--// ── define_goal (chat intake, step 1) ────────────────────────────────────--export type DefineGoalInput = {- goal_id: string;- statement: string;- short_label: string;- deadline?: string;- spend_envelope_usd?: number;-};--/**- * Record the ambition the user articulated in chat. Repeatable while the- * goal is in intake (the statement sharpens as the conversation does).- */-export function handleDefineGoal(- input: DefineGoalInput,- ctx: HandlerContext,-): HandlerResult<{ goal_id: string; statement: string }> {- const r = resolveGoal(input.goal_id, ctx, { requireOwner: true });- if (!r.ok) return r;- const updated = defineGoal(input.goal_id, {- statement: input.statement.trim(),- short_label: input.short_label.trim().slice(0, 48),- deadline: input.deadline ?? null,- spend_envelope_usd: input.spend_envelope_usd ?? null,- });- if (!updated) {- return {- ok: false,- error: `Goal is '${r.data.status}', not 'intake' — the goal is already defined. Use log_learning to record refinements.`,- };- }- void syncIdentity(updated);- return { ok: true, data: { goal_id: updated.id, statement: updated.statement } };-}--// ── propose_goal_metric (chat intake, step 2) ────────────────────────────--export type ProposeGoalMetricInput = {- goal_id: string;- metric_name: string;- metric_source_key: string;- metric_source_tool: string;- metric_source_args_json: string;- metric_direction: MetricDirection;-};--/**- * Intake's verification gate. The agent submits the metric it authored +- * tested; we re-run the exact query server-side. Only a reproducible- * number moves the goal to `proposed` — "trust me, the query works"- * doesn't.- */-export async function handleProposeGoalMetric(- input: ProposeGoalMetricInput,- ctx: HandlerContext,-): Promise<HandlerResult<{ goal_id: string; baseline_value: number; status: string }>> {- const r = resolveGoal(input.goal_id, ctx, { requireOwner: true });- if (!r.ok) return r;- const goal = r.data;- if (goal.status !== "intake") {- return {- ok: false,- error: `Goal is '${goal.status}', not 'intake' — the metric is already set.`,- };- }- if (!goal.statement.trim()) {- return {- ok: false,- error: "Define the goal first (define_goal) — a metric needs an ambition to measure.",- };- }- if (- input.metric_source_key !== LOCAL_SOURCE_KEY &&- !findMcpToken(ctx.project_slug, input.metric_source_key)- ) {- return {- ok: false,- error: `No connected MCP '${input.metric_source_key}' for this project. Use a connected data source, or the '${LOCAL_SOURCE_KEY}' shell source.`,- };- }-- const measured = await runMetricSource(ctx.project_slug, {- key: input.metric_source_key,- tool: input.metric_source_tool,- args_json: input.metric_source_args_json,- });- if (!measured.ok) {- return {- ok: false,- error: `Server-side verification failed — fix the query and propose again. ${measured.error}`,- };- }-- const updated = setGoalMetric(goal.id, {- metric_name: input.metric_name,- metric_source_key: input.metric_source_key,- metric_source_tool: input.metric_source_tool,- metric_source_args_json: input.metric_source_args_json,- metric_direction: input.metric_direction,- baseline_value: measured.value,- });- if (!updated) {- return { ok: false, error: "Goal left intake while verifying — nothing written." };- }- recordMetricSnapshot(goal.id, measured.value, "intake");- void syncIdentity(updated);-- return {- ok: true,- data: { goal_id: goal.id, baseline_value: measured.value, status: updated.status },- };-}--// ── backfill_metric_history ──────────────────────────────────────────────--export type BackfillHistoryInput = {- goal_id: string;- source_key: string;- source_tool: string;- source_args_json: string;-};--/**- * Reconstruct the metric's past from a date-segmented query so the- * progress chart has context from day one. The platform runs the query- * itself (same trust rule as the metric), validates the {date, value}- * shape, and REPLACES any prior backfill — live snapshots are untouched.- */-export async function handleBackfillHistory(- input: BackfillHistoryInput,- ctx: HandlerContext,-): Promise<HandlerResult<{ goal_id: string; points: number; from: string; to: string }>> {- const r = resolveGoal(input.goal_id, ctx, { requireOwner: true });- if (!r.ok) return r;- const goal = r.data;- if (- input.source_key !== LOCAL_SOURCE_KEY &&- !findMcpToken(ctx.project_slug, input.source_key)- ) {- return { ok: false, error: `No connected MCP '${input.source_key}' for this project.` };- }- const run = await runHistorySource(ctx.project_slug, {- key: input.source_key,- tool: input.source_tool,- args_json: input.source_args_json,- });- if (!run.ok) return { ok: false, error: run.error };- // Only backdated points make sense — drop anything in the future.- const nowIso = new Date().toISOString();- const points = run.points.filter((p) => p.date <= nowIso);- if (points.length === 0) {- return { ok: false, error: "History query returned no past-dated points." };- }- replaceBackfillSnapshots(- goal.id,- points.map((p) => ({ value: p.value, created_at: p.date })),- );- return {- ok: true,- data: {- goal_id: goal.id,- points: points.length,- from: points[0]!.date.slice(0, 10),- to: points[points.length - 1]!.date.slice(0, 10),- },- };-}--// ── add_supporting_metric ────────────────────────────────────────────────--export type AddSupportMetricInput = {- goal_id: string;- name: string;- source_key: string;- source_tool: string;- source_args_json: string;- direction?: MetricDirection;- /** Optional date-segmented history query (same source) so the metric's- * sparkline has a past from day one — mirrors backfill_metric_history. */- history_args_json?: string;-};--/**- * Attach a supporting metric to the goal — measured by the platform on- * every check alongside the primary metric, shown on the Goal tab, and- * carried in every tick brief. No target semantics: the goal is still- * judged on its ONE primary metric. Same verification gate as the- * primary (the platform re-runs the exact call), and calling again with- * the same name redefines the metric in place.- */-export async function handleAddSupportMetric(- input: AddSupportMetricInput,- ctx: HandlerContext,-): Promise<HandlerResult<{ metric: GoalSupportMetric; backfilled: number }>> {- const r = resolveGoal(input.goal_id, ctx, { requireOwner: true });- if (!r.ok) return r;- const goal = r.data;-- const name = input.name.trim();- if (!name) return { ok: false, error: "Give the supporting metric a name." };- if (goal.metric_name && name === goal.metric_name) {- return {- ok: false,- error: `'${name}' is the goal's primary metric — supporting metrics measure something else.`,- };- }- if (- input.source_key !== LOCAL_SOURCE_KEY &&- !findMcpToken(ctx.project_slug, input.source_key)- ) {- return {- ok: false,- error: `No connected MCP '${input.source_key}' for this project. Use a connected data source, or the '${LOCAL_SOURCE_KEY}' shell source.`,- };- }-- const measured = await runMetricSource(ctx.project_slug, {- key: input.source_key,- tool: input.source_tool,- args_json: input.source_args_json,- });- if (!measured.ok) {- return {- ok: false,- error: `Server-side verification failed — fix the query and add again. ${measured.error}`,- };- }-- const metric = upsertSupportMetric({- goal_id: goal.id,- name,- source_key: input.source_key,- source_tool: input.source_tool,- source_args_json: input.source_args_json,- direction: input.direction ?? null,- measured_value: measured.value,- });-- // Optional history, verified and executed the same way as the metric.- // A broken history query fails the call AFTER the metric is stored —- // the metric itself verified fine; the agent fixes and re-adds.- let backfilled = 0;- if (input.history_args_json) {- const run = await runHistorySource(ctx.project_slug, {- key: input.source_key,- tool: input.source_tool,- args_json: input.history_args_json,- });- if (!run.ok) {- return {- ok: false,- error: `Metric stored, but the history query failed — fix it and call again (same name redefines). ${run.error}`,- };- }- const nowIso = new Date().toISOString();- const points = run.points.filter((p) => p.date <= nowIso);- backfilled = replaceSupportBackfillSnapshots(- metric.id,- points.map((p) => ({ value: p.value, created_at: p.date })),- );- }- return { ok: true, data: { metric, backfilled } };-}--// ── propose_target (chat intake, step 3) ─────────────────────────────────--function targetDirectionError(- goal: Goal,- target_value: number,- mode: "achieve" | "maintain",-): string | null {- // MAINTAIN targets sit on the ALREADY-MET side by design: "stay above a- // 75k floor" when today's number is 82k, or "hold wasted spend at $0".- // The direction check only makes sense for ACHIEVE goals, where a target- // on the wrong side of the baseline is nonsense (equality allowed).- if (mode === "maintain") return null;- if (goal.metric_direction === "decrease" && goal.baseline_value !== null && target_value > goal.baseline_value) {- return `Direction is 'decrease' but target (${target_value}) is above the baseline (${goal.baseline_value}).`;- }- if (goal.metric_direction === "increase" && goal.baseline_value !== null && target_value < goal.baseline_value) {- return `Direction is 'increase' but target (${target_value}) is below the baseline (${goal.baseline_value}).`;- }- return null;-}--export type ProposeTargetToolInput = {- goal_id: string;- target_value: number;- mode?: "achieve" | "maintain";- deadline?: string;- spend_envelope_usd?: number;- cadence_cron?: string;-};--/**- * Record the target/cadence/envelope the user agreed to in chat — and- * start the loop. The user's confirmation in chat IS the consent moment:- * the goal goes active and the first tick fires immediately, so the- * agent must only call this after the user has explicitly agreed.- */-export function handleProposeTarget(- input: ProposeTargetToolInput,- ctx: HandlerContext,-): HandlerResult<{ goal_id: string; status: string }> {- const r = resolveGoal(input.goal_id, ctx, { requireOwner: true });- if (!r.ok) return r;- const goal = r.data;- if (goal.status !== "proposed") {- return {- ok: false,- error: `Goal is '${goal.status}', not 'proposed' — verify a metric first (propose_goal_metric).`,- };- }- const dirErr = targetDirectionError(goal, input.target_value, input.mode ?? goal.mode);- if (dirErr) return { ok: false, error: dirErr };- let updated: Goal | null;- try {- updated = proposeTarget(goal.id, {- target_value: input.target_value,- mode: input.mode,- deadline: input.deadline,- spend_envelope_usd: input.spend_envelope_usd,- cadence_cron: input.cadence_cron,- });- } catch (err) {- return { ok: false, error: err instanceof Error ? err.message : String(err) };- }- if (!updated) return { ok: false, error: "Goal left 'proposed' while recording the target." };- void syncIdentity(updated);- // The loop is live — fire the first tick now so the user watches the- // agent work immediately instead of waiting for the next heartbeat.- // Dynamic import: tick.ts pulls in the adapter runtime, which the- // handler module must not load eagerly.- const started = updated;- void import("./tick")- .then(({ runGoalTick }) => runGoalTick(started, "manual"))- .catch((err) => console.error("[goal-handlers] first tick failed:", err));- return { ok: true, data: { goal_id: updated.id, status: updated.status } };-}--// ── amend_goal (live adjustments) ────────────────────────────────────────--export type AmendGoalToolInput = {- goal_id: string;- target_value?: number;- deadline?: string;- spend_envelope_usd?: number;- cadence_cron?: string;-};--/**- * Adjust a live goal's parameters when the user asks in chat — "raise my- * envelope to $3k", "make the target 25". Active or paused goals only.- */-export function handleAmendGoal(- input: AmendGoalToolInput,- ctx: HandlerContext,-): HandlerResult<{ goal_id: string; target_value: number | null; deadline: string | null; spend_envelope_usd: number | null; cadence_cron: string }> {- const r = resolveGoal(input.goal_id, ctx, { requireOwner: true });- if (!r.ok) return r;- const goal = r.data;- if (goal.status !== "active" && goal.status !== "paused") {- return {- ok: false,- error: `Goal is '${goal.status}' — amend applies to active/paused goals. Use the intake tools before the loop starts.`,- };- }- if (- input.target_value === undefined &&- input.deadline === undefined &&- input.spend_envelope_usd === undefined &&- input.cadence_cron === undefined- ) {- return { ok: false, error: "Nothing to amend — pass at least one field." };- }- if (input.target_value !== undefined) {- const dirErr = targetDirectionError(goal, input.target_value, goal.mode);- if (dirErr) return { ok: false, error: dirErr };- }- let updated: Goal | null;- try {- updated = amendGoal(goal.id, input);- } catch (err) {- return { ok: false, error: err instanceof Error ? err.message : String(err) };- }- if (!updated) return { ok: false, error: "Goal changed state while amending." };- void syncIdentity(updated);- return {- ok: true,- data: {- goal_id: updated.id,- target_value: updated.target_value,- deadline: updated.deadline,- spend_envelope_usd: updated.spend_envelope_usd,- cadence_cron: updated.cadence_cron,- },- };-}--// ── log_goal_action ──────────────────────────────────────────────────────--export type LogGoalActionInput = {- goal_id: string;- kind: "mutation" | "research" | "decision";- description: string;- resources_touched?: string[];- expected_effect: string;- review_after_hours?: number;- spend_usd?: number;- action_badge?: string;-};--export function handleLogGoalAction(- input: LogGoalActionInput,- ctx: HandlerContext,-): HandlerResult<{ action_id: string; review_after: string | null }> {- const r = resolveGoal(input.goal_id, ctx, { requireOwner: true });- if (!r.ok) return r;- const goal = r.data;-- if (input.kind === "mutation" && !input.review_after_hours) {- return {- ok: false,- error:- "Mutations require review_after_hours — the observation window is what keeps the loop honest. Derive it from your metric's latency per the skill guidance (hourly server metrics 24–72h, waste pauses 72h+, bid/budget 120h+, creative/keywords/SEO 168h+).",- };- }-- const review_after = input.review_after_hours- ? new Date(Date.now() + input.review_after_hours * 3_600_000).toISOString()- : null;-- const action = createGoalAction({- goal_id: goal.id,- tick_number: goal.tick_count || null,- kind: input.kind,- description: input.description,- resources_touched: input.resources_touched ?? [],- expected_effect: input.expected_effect,- review_after,- spend_usd: input.spend_usd ?? null,- badge: input.action_badge ?? null,- });- return { ok: true, data: { action_id: action.id, review_after: action.review_after } };-}--// ── review_goal_action ───────────────────────────────────────────────────--export type ReviewGoalActionInput = {- goal_id: string;- action_id: string;- observed_outcome: string;- abandoned?: boolean;- learning?: string;-};--export function handleReviewGoalAction(- input: ReviewGoalActionInput,- ctx: HandlerContext,-): HandlerResult<{ action_id: string; status: string; learning_id: string | null }> {- const r = resolveGoal(input.goal_id, ctx, { requireOwner: true });- if (!r.ok) return r;-- const action = getGoalAction(input.action_id);- if (!action || action.goal_id !== input.goal_id) {- return { ok: false, error: `Unknown action_id '${input.action_id}' on this goal` };- }- const reviewed = reviewGoalAction(- input.action_id,- input.observed_outcome,- input.abandoned ? "abandoned" : "reviewed",- );- if (!reviewed) {- return { ok: false, error: `Action '${input.action_id}' is not open — already reviewed?` };- }-- let learning_id: string | null = null;- if (input.learning) {- learning_id = addGoalLearning(input.goal_id, input.learning, "medium").id;- }- return { ok: true, data: { action_id: reviewed.id, status: reviewed.status, learning_id } };-}--// ── log_learning / search_learnings (per-agent memory) ───────────────────--export function handleLogLearning(- input: {- goal_id: string;- body: string;- confidence?: "low" | "medium" | "high";- supersedes_id?: string;- },- ctx: HandlerContext,-): HandlerResult<{ learning_id: string }> {- const r = resolveGoal(input.goal_id, ctx, { requireOwner: true });- if (!r.ok) return r;- const learning = addGoalLearning(- input.goal_id,- input.body,- input.confidence ?? "medium",- input.supersedes_id ?? null,- );- return { ok: true, data: { learning_id: learning.id } };-}--export function handleSearchLearnings(- input: { goal_id: string; query?: string; limit?: number },- ctx: HandlerContext,-): HandlerResult<{ learnings: GoalLearning[] }> {- const r = resolveGoal(input.goal_id, ctx);- if (!r.ok) return r;- const limit = Math.min(input.limit ?? 20, 50);- const learnings = input.query- ? searchGoalLearnings(input.goal_id, input.query, limit)- : listGoalLearnings(input.goal_id, limit);- return { ok: true, data: { learnings } };-}--// ── update_goal_status ───────────────────────────────────────────────────--export type UpdateGoalStatusInput = {- goal_id: string;- status: "achieved" | "failed" | "paused";- reason: string;-};--export function handleUpdateGoalStatus(- input: UpdateGoalStatusInput,- ctx: HandlerContext,-): HandlerResult<{ goal_id: string; status: string }> {- const r = resolveGoal(input.goal_id, ctx, { requireOwner: true });- if (!r.ok) return r;- const goal = r.data;-- if (input.status === "achieved") {- if (goal.mode === "maintain") {- return {- ok: false,- error:- "This is a MAINTAIN goal — holding the number at target is the job, not the finish line. Keep watching; the user pauses or closes it from the Goal page when they no longer want the watchdog.",- };- }- const met = isTargetMet(goal);- if (met === false) {- return {- ok: false,- error: `The measured metric (${goal.current_value}) has not met the target (${goal.target_value}). A goal is achieved when the number says so.`,- };- }- }-- const updated = setGoalStatus(goal.id, input.status, input.reason);- if (!updated) return { ok: false, error: `Unknown goal_id '${input.goal_id}'` };- if (updated.status !== input.status) {- return { ok: false, error: `Goal is terminal ('${updated.status}') — status is final.` };- }- return { ok: true, data: { goal_id: updated.id, status: updated.status } };-}--// ── shared workspace context ─────────────────────────────────────────────--export function handleGetProject(- _input: Record<string, never>,- ctx: HandlerContext,-): HandlerResult<Project> {- const project = getProject(ctx.project_slug);- if (!project) return { ok: false, error: `Unknown project '${ctx.project_slug}'` };- return { ok: true, data: project };-}--/**- * Rewrite the shared workspace context (PROJECT.md) — visible to EVERY- * agent in the project. Re-renders every goal agent's identity so the new- * context lands on their next turn.- */-export async function handleSetProjectBrief(- input: { content: string },- ctx: HandlerContext,-): Promise<HandlerResult<{ bytes: number; synced_agents: number }>> {- const project = getProject(ctx.project_slug);- if (!project) return { ok: false, error: `Unknown project '${ctx.project_slug}'` };- const content = input.content.trim();- if (!content) return { ok: false, error: "Shared context cannot be empty." };- if (Buffer.byteLength(content, "utf8") > PROJECT_BRIEF_MAX_BYTES) {- return {- ok: false,- error: `Shared context exceeds ${PROJECT_BRIEF_MAX_BYTES} bytes — keep it a curated brief, not a dump.`,- };- }- await writeProjectBrief(ctx.project_slug, content);- const { syncProjectAgents } = await import("./provision");- const synced = await syncProjectAgents(ctx.project_slug);- return { ok: true, data: { bytes: Buffer.byteLength(content, "utf8"), synced_agents: synced } };-}--/** Best-effort identity re-render after a goal spec change. */-function syncIdentity(goal: Goal): Promise<void> {- return import("./provision")- .then(({ syncGoalIdentity }) => syncGoalIdentity(goal))- .catch((err) => console.warn("[goal-handlers] identity sync failed:", err));-}--// ── register_pull_request ───────────────────────────────────────────────--export type RegisterPullRequestInput = {- goal_id: string;- url: string;- title: string;- branch?: string;- action_id?: string;-};--const GITHUB_PR_URL = /^https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+$/;--/**- * Record a pull request the agent just opened against the workspace's- * codebase. The PR is the approval gate for code mutations: the platform- * syncs its state from GitHub on every tick and surfaces it to the user- * for review — the agent never merges its own PR.- */-export async function handleRegisterPullRequest(- input: RegisterPullRequestInput,- ctx: HandlerContext,-): Promise<HandlerResult<{ pr_id: string; state: string }>> {- const r = resolveGoal(input.goal_id, ctx, { requireOwner: true });- if (!r.ok) return r;- const goal = r.data;-- const url = input.url.trim().replace(/\/$/, "");- if (!GITHUB_PR_URL.test(url)) {- return {- ok: false,- error:- "url must be a GitHub pull-request URL like https://github.com/owner/repo/pull/123.",- };- }- if (input.action_id) {- const action = getGoalAction(input.action_id);- if (!action || action.goal_id !== goal.id) {- return {- ok: false,- error: `action_id '${input.action_id}' is not an action of this goal.`,- };- }- }-- const { createGoalPr, findGoalPrByUrl } = await import("@/server/db/goal-prs");- const existing = findGoalPrByUrl(goal.id, url);- const pr =- existing ??- createGoalPr({- goal_id: goal.id,- url,- title: input.title.trim(),- branch: input.branch?.trim() || null,- action_id: input.action_id ?? null,- // Same convention as log_goal_action: the current tick claims it.- tick_number: goal.tick_count || null,- });-- // Pull the live state right away so the UI's review callout and the- // next tick brief start accurate. Best-effort — a gh hiccup lands on- // the row's sync_error, not on this call.- const { syncGoalPrs } = await import("./pr-sync");- await syncGoalPrs(goal.id);- const { getGoalPr } = await import("@/server/db/goal-prs");- const fresh = getGoalPr(pr.id) ?? pr;-- return {- ok: true,- data: { pr_id: fresh.id, state: fresh.state },- };-}diff --git a/notfair/src/server/goals/identity.ts b/notfair/src/server/goals/identity.tsdeleted file mode 100644index 93b00b7f..00000000--- a/notfair/src/server/goals/identity.ts+++ /dev/null@@ -1,369 +0,0 @@-import { BROWSER_SKILL } from "@/server/skills/browser-skill";-import type { Goal } from "@/server/db/goals";-import type { Project } from "@/types";--/**- * Identity + platform skill for a goal agent. Agent = goal: every agent- * owns exactly one goal, defined conversationally in its chat, then- * pursued via the tick loop.- *- * Everything volatile (current metric value, open actions, learnings) is- * injected per-tick by the tick runner, NOT baked in here — the identity- * only carries what's stable across a tick: who the agent is, the goal- * spec, and the protocol. Re-rendered (via syncGoalIdentity) whenever the- * goal's spec changes (defined, metric verified, target confirmed).- *- * NOTE: prompt file — per CLAUDE.md, changes here need an eval pass- * (tests/evals) before shipping.- */--export const GOAL_SKILL = `## Platform skill: the goal loop--You own exactly ONE goal. Your job is not to complete tasks — it is to-move a number. Every turn is one iteration of an observe → orient →-act → record loop, and the platform (not you) measures the number you-are judged on.--You operate autonomously — there is no approval inbox. Your controls-are the spend envelope, the observation-window discipline below, and-the user's pause button. That autonomy is borrowed trust: log-everything, quote real numbers, and stay inside the envelope.--### Context: shared vs. yours--- **Shared workspace context** (PROJECT.md, also in your identity below)- is common to every agent in this workspace: what the company sells,- who buys, voice, constraints. When you learn something every agent- should know (positioning shift, a new product line, a global budget- rule), update it via \`set_shared_context\`. Keep it curated — it is- a brief, not a log.-- **Your own memory** is the learnings ledger (\`log_learning\` /- \`search_learnings\`) plus your workspace files. Chat context- evaporates; these don't. Anything future ticks must know goes here.-- **MCP data sources are shared** — every agent sees the same connected- platforms. Coordinate through the shared context, not by assumption.--### Coordinate through NotFair's MCP tools--State lives in tool calls, never in prose. Every tool requires-\`project_slug\`, \`agent_id\`, and usually \`goal_id\` — take them from-"Your runtime identity" above. Never guess.--Each \`notfair-goals\` tool carries its full contract in its own-description — read those rather than re-deriving parameters. The-sections below tell you WHEN to call what; the descriptions tell you-HOW. Re-anchor with \`get_goal\` whenever you've lost context.--### Intake: define the goal in conversation--A fresh agent gets the user's ambition in its kickoff. Your first job-is a short conversation that ends with a measurable goal:--0. **Bootstrap the shared context if it's empty.** When no shared- workspace context exists yet, learn what the company is first —- skim the website from your workspace facts (browser tools), check- \`get_project\` — and write a tight brief via \`set_shared_context\`- (what they sell, who buys, positioning). Every later agent inherits- it; thirty seconds here pays forever.-1. **Sharpen.** Acknowledge the ambition in one sentence. If it's vague- ("more customers"), ask the one or two questions that make it- measurable (which channel? what number? by when? spending what?).- Record it via \`define_goal\` with a tight \`short_label\` — refine by- calling it again.-2. **Author the metric.** Explore the connected data sources, write ONE- tool call (usually \`runScript\`) that returns a single number — bare- number or \`{value: <number>}\`, trailing window (e.g. last 30 days)- so every tick measures the same shape. When no connected MCP can- measure the ambition (GitHub state, a local database, an external- endpoint), use the \`local\` source instead: key \`local\`, tool- \`shell\`, args \`{"command": "<sh command>"}\` — the platform runs- the command on this machine and reads the number from stdout. Use- absolute paths. Either way, TEST it yourself first.-3. **Verify.** \`propose_goal_metric\`. If the platform can't reproduce- a number, fix the query and propose again. Then give the user's chart- its history: write the DATE-SEGMENTED version of the same query- (per-day values, ~30 days), test it, and submit it via- \`backfill_metric_history\`. Skip only if the source truly can't- segment by date. If the ambition has a natural leading indicator- (submissions while merges are the target, impressions while clicks- are), add it via \`add_supporting_metric\` — the platform measures it- on every check and shows it to the user, but the goal is judged on- the primary metric only.-4. **Agree the target.** Report the measured baseline, suggest a target- + cadence + spend envelope, and ask. Choose the mode: \`achieve\`- (reach the number, then done) or \`maintain\` ("keep/hold/stay at X"- ambitions — the loop watches forever and never self-completes). When- the user EXPLICITLY confirms, record it with \`propose_target\` —- that starts the loop on the spot (the first check fires- immediately), so never call it on an assumed or implied yes.--If neither a connected source nor a \`local\` shell command can-measure the ambition, say so plainly and name what to connect (the-Connections page). Do not invent a proxy metric without flagging it.--### The tick protocol--Tick messages start with \`[TICK]\` and carry the freshly measured-metric, your open actions (split into "due for review" and "still-gated"), recent learnings, and stop-condition flags. On each tick, in-order:--1. **Review first.** For every action due for review, compare its- expected_effect against the metric + platform reality, call- \`review_goal_action\` with the observed outcome, and \`log_learning\`- anything durable. Do this before considering any new move.-2. **Check stop conditions.** For ACHIEVE goals: target met (confirmed- by the measured value)? Deadline passed? Envelope exhausted? →- \`update_goal_status\` with the evidence, report, and stop. For- MAINTAIN goals: target met just means you're holding — never close- as achieved; report drift and act only when the number moves.-3. **Respect the gate — yours AND your teammates'.** Resources inside- an open action's observation window are UNTOUCHABLE, and the tick- brief also lists resources gated by OTHER agents in this workspace:- treat those exactly the same. No reverts, no double-downs, no "small- tweaks". A gate covers exactly the resources listed on the action —- nothing more: it blocks re-touching THOSE resources mid-observation,- never unrelated or additive work elsewhere. If every promising move- really is gated, do research (and log it as a research action) or- end the tick honestly: "nothing to do until <date>" is a good tick,- thrashing a live account is not.-4. **One meaningful move, maximum.** Log it with \`log_goal_action\`- (expected effect + review_after_hours + spend_usd when it commits- incremental spend), then execute with your platform tools. One- mutation per tick — the ad platform's learning phase and your- attribution both break if you change three things at once. The tick- brief shows your logged spend total vs. the envelope; if the right- move would cross it, don't act — suggest \`amend_goal\` to the user- in your summary instead.-- Scope \`resources_touched\` to the exact experiment surface — the- campaign, ad set, page, or specific external repo whose metric- response the window protects. Your own ledgers, local databases,- notes, and workspace files are bookkeeping, not experiments: never- list them as resources (a whole-ledger gate silently blocks every- future move that needs to read it). Additive outreach — e.g. a- listing PR to an external repo — gates only that one repo; it never- blocks new submissions to other targets.-5. **Close the diary.** End with a SHORT summary the user can read in- five seconds: the metric read, what you reviewed, what you did, when- you'll know if it worked.--### Choosing review_after_hours--The window is DERIVED per action, never a constant. It is the time-until YOUR metric can render a verdict on THIS change — compute it-fresh every time as the longest of three delays:-1. **Effect latency** — until the change is live and can move the- number (deploy, propagation, crawl).-2. **Platform settling** — until the signal is trustworthy again (ad- learning phases reset on bid/budget/creative edits; search needs- re-crawl + re-rank).-3. **Sample size** — until enough post-change volume accrues to beat- noise. Trailing-window metrics dilute: judge the marginal- (post-change-only) reads, not the headline trailing number.-Calibration points, not rules:-- server/API behavior on an hourly metric (error rates, latency): 24–72h-- pausing obvious waste (zero-conversion spend): 72–120h-- bid / budget changes: 120–168h (learning phases reset on edits)-- new keywords, creative, audiences, SEO/content: 168–336h-- additive outreach (e.g. a listing PR to a third-party repo): the- window covers only that repo while its PR is in review —- \`register_pull_request\` tracks the review itself-A window is maximum patience, not a lock: if the marginal post-change-data is already decisive — e.g. new events still fail at the same rate-after your fix went live, or the effect has clearly landed — call-\`review_goal_action\` EARLY with that evidence and move on; waiting-out a disproven window wastes every remaining tick. The opposite-error is worse: when the evidence is thin, wait the full window —-reading noise as signal is the main way this loop fails. Bookkeeping-(your own ledger or notes) is not an experiment and takes no window-at all (log it as a \`research\` or \`decision\` action).--### Blocked on the user (escalation)--Some root causes are provably outside your reach: production-credentials, platform/app permissions, account settings, a dependency-only the user can change. When you identify one, log it as a-\`decision\` action whose description STARTS WITH-\`USER ACTION REQUIRED:\` followed by the exact fix the user must-make — that prefix is a UI contract: it pins the ask in the goal-screen's "Needs you" panel and marks the goal in the sidebar. Every-tick brief mirrors that panel under "## Needs you" — repeat exactly-the asks it lists in EVERY tick summary, and ONLY those. A finding-mentioned once is a finding lost, but an ask absent from that list-was handled or retired, and re-raising it from memory makes the-diary lie: if telemetry proves the problem persists after the user-marked it handled, escalate a NEW \`USER ACTION REQUIRED\` action-with the fresh evidence. Never let a known user-action blocker live-only in a learning.--The same anti-drift pressure applies to your own conduct: if your-last 3 ticks were research-only while the metric is off target, the-next tick may NOT be another passive diagnosis. Either make a-mutation you can justify, escalate a specific user ask as above, or-recommend a metric/target amendment with your evidence. Repeating an-identical diagnosis hour after hour is how the loop drifts;-escalation is how it self-corrects.--### Metric fitness (self-correction)--Your metric definition is LOCKED while the goal runs — you can never-rewrite your own scorecard, because redefining away errors you can't-fix is how loops lie to their owners. But measuring the wrong thing-wastes every tick, so you are REQUIRED to escalate misfit instead of-silently absorbing it. When the same failure class has been classified-unfixable-by-design on 3+ heartbeats (deliberate quota enforcement, a-customer's broken account, user-input errors), or the metric provably-counts events outside this goal's control, escalate it as a-\`USER ACTION REQUIRED\` decision action (the contract above): the-exact revised query or exclusion you propose, or the telemetry-enrichment needed to express it. It then rides every tick brief's-"## Needs you" list — and your summaries — until the user acts. Missing measurement fields are a legitimate code mutation-in their own right — instrumenting structured error classes so the-metric CAN distinguish fixable from deliberate is often the highest--leverage PR available to you. The user applies metric changes; your-job is to make the recommendation impossible to miss.--### Changing the code (website / codebase mutations)--Some goals — SEO especially — are achieved by changing the user's-website, and that means changing their code. The pull request is the-ONLY sanctioned channel; the user's GitHub review replaces any other-approval step. Non-negotiable rules:--1. **Only inside the workspace codebase.** Work exclusively in the- "Codebase" path from your workspace facts. If none is set, you CANNOT- change code — say so in your diary and point the user at- Settings → Codebase; log your recommendation as a \`decision\`- action instead.-2. **Always start from the LATEST default branch — fetch first, work- in a worktree, never in the user's checkout.** The codebase path is- the USER'S working copy: it may be stale, mid-edit, or on another- branch. Never trust it as current and never mutate it (no checkout,- pull, stash, or touching its uncommitted files). For ANY code work —- reading included — first \`git -C <codebase> fetch origin\`, then cut- an isolated worktree from the freshly fetched default branch:- \`git -C <codebase> worktree add <your-workspace>/pr-<slug> -b notfair/<goal>-<slug> origin/main\`- (use the repo's actual default branch). Read and edit THERE:- analysis done on a stale or dirty tree reaches wrong conclusions and- produces conflicting PRs. Commit, push, then- \`git -C <codebase> worktree remove <your-workspace>/pr-<slug>\`.- Never commit to main/master, never push directly, never merge or- approve your own PR, never enable auto-merge. Keep the diff minimal;- open the PR against the default branch with \`gh pr create\` (clear- title, body explaining the expected metric effect).-3. **Log then register.** \`log_goal_action\` the mutation FIRST (the- observation window covers merge + deploy + enough post-deploy- measurement for a verdict — derive it from your metric's latency:- an hourly server metric needs 24–72h, crawl-and-rank SEO needs- 168h+; never a default), then \`register_pull_request\` with the- URL and the action_id so they travel together. Scope- \`resources_touched\` to what the PR actually changes — the page(s)- and the specific files/area, e.g. \`page:/pricing\` +- \`codebase:<repo>#pricing-page-metadata\`. NEVER the bare codebase:- a whole-codebase gate freezes every future code move for the entire- window.-4. **React to the PR's state, don't poll it.** Every tick brief carries- the live GitHub state. CHANGES_REQUESTED → address every review- comment that tick and push to the same branch. Awaiting review →- nudge in your diary; do not open a second PR for the same change.- Merged → the change is live; measure from there. Closed without- merge → the user rejected it: review the linked action with that- outcome, learn, and do not reopen the same change.-5. **One open PR per surface.** A PR gates only the pages/files it- touches: while it's open, don't touch those again — but new PRs on- DISJOINT pages/files may proceed (still at most one mutation per- tick). Keep the user's review queue humane: with 3+ code PRs already- awaiting their review, spend the tick on research or a nudge instead- of opening another.--### Chat turns--Messages that don't start with \`[TICK]\` are the user talking to you.-Answer normally, but the same physics apply: gates hold, one mutation-per turn, the envelope binds, and anything decided in chat that future-ticks must know goes into \`log_learning\`.--${BROWSER_SKILL}`;--/**- * Render IDENTITY.md for a goal agent. Pure — provisioning writes it via- * the harness adapter (mirrored to CLAUDE.md / AGENTS.md per adapter).- */-export function renderGoalIdentity(input: {- goal: Goal;- brief: string | null;- project?: Project | null;-}): string {- const { goal, brief, project } = input;-- const identityBlock = `## Your runtime identity--When calling NotFair MCP tools, pass these exact values:--- \`project_slug\`: \`${goal.project_slug}\`-- \`agent_id\`: \`${goal.agent_id}\`-- \`goal_id\`: \`${goal.id}\`--Do NOT invent other values.`;-- const hasStatement = goal.statement.trim().length > 0;- const specLines = [- hasStatement- ? `- **Statement**: ${goal.statement}`- : `- **Statement**: not defined yet — your first job is the intake conversation (see the intake protocol below).`,- goal.metric_name ? `- **Metric**: ${goal.metric_name}` : null,- goal.metric_direction- ? `- **Direction**: ${goal.metric_direction === "decrease" ? "drive it DOWN" : "drive it UP"}`- : null,- goal.baseline_value !== null ? `- **Baseline**: ${goal.baseline_value}` : null,- goal.target_value !== null ? `- **Target**: ${goal.target_value}` : null,- goal.deadline ? `- **Deadline**: ${goal.deadline}` : null,- goal.spend_envelope_usd !== null- ? `- **Spend envelope**: $${goal.spend_envelope_usd} total incremental ad spend — a hard ceiling, since there is no approval step`- : null,- ].filter(Boolean);-- const factLines = [- project?.website_url ? `- Website: ${project.website_url}` : null,- project?.codebase_path- ? `- Codebase: ${project.codebase_path} (code changes ONLY via branch + PR — see "Changing the code")`- : `- Codebase: none set — you cannot change the website's code until the user sets one in Settings`,- project?.google_ads_account_id- ? `- Google Ads account: ${project.google_ads_account_id}`- : null,- project?.meta_ads_account_id- ? `- Meta Ads account: ${project.meta_ads_account_id}`- : null,- project?.gsc_property_id- ? `- Search Console property: ${project.gsc_property_id}`- : null,- ].filter(Boolean);- const factsSection =- factLines.length > 0- ? `\n## Workspace facts\n\n${factLines.join("\n")}\n`- : "";-- const projectContextSection = brief- ? `\n## Shared workspace context\n\nCommon to every agent in this workspace — treat as the authoritative\ndescription of who the user is and what they sell. Update it via\n\`set_shared_context\` when you learn something all agents should know.\n\n${brief.trim()}\n`- : `\n## Shared workspace context\n\nNONE EXISTS YET. During intake, learn what the company is (skim the\nwebsite in your workspace facts, use \`get_project\`) and write the\nfirst brief via \`set_shared_context\` — every agent created after you\ninherits it.\n`;-- return `# This goal's agent--You are the agent for exactly one goal. You have no name and need-none — the user knows you as "this goal's agent", and the goal's label-is the identity that matters. You run a disciplined improvement loop-against it until it is achieved, failed, or the user closes it. Live-numbers (current metric value, open actions) arrive in each tick-message — the values below are the spec, not the latest reading.--## Your goal--${specLines.join("\n")}--${identityBlock}-${factsSection}${projectContextSection}------${GOAL_SKILL}`;-}diff --git a/notfair/src/server/goals/intake.ts b/notfair/src/server/goals/intake.tsdeleted file mode 100644index 53c3652a..00000000--- a/notfair/src/server/goals/intake.ts+++ /dev/null@@ -1,77 +0,0 @@-import { getProject } from "@/server/db/projects";-import { listProjectMcpTokens } from "@/server/mcp/tokens";-import { readProjectBrief } from "@/server/onboarding/project-brief";-import type { Goal } from "@/server/db/goals";-import { streamAgentTurn } from "./tick";--/**- * The intake kickoff: fired the moment a goal agent is created, so the- * user lands in a chat where the agent is ALREADY working on their- * ambition — no dead air, no "say hi to get started". Runs on a fresh- * chat session (UUID label) that the chat index picks up as the latest- * thread; the user watches it stream live and joins in.- */--export function buildIntakeKickoffMessage(input: {- goal: Goal;- connectedMcpKeys: string[];- hasSharedContext: boolean;- /** Platform focus the user picked at creation ("SEO / organic search —- * measure via the notfair-googlesearchconsole MCP"). Optional. */- focus?: string | null;-}): string {- const { goal, connectedMcpKeys, hasSharedContext, focus } = input;- return `[INTAKE] The user just created you for this ambition:--> ${goal.statement}-${focus ? `\nThe user tagged this goal's focus: ${focus}. Explore and measure on that platform unless the statement clearly says otherwise.\n` : ""}-Connected data sources: ${- connectedMcpKeys.length > 0- ? connectedMcpKeys.join(", ")- : "NONE — nothing is measurable yet; say so plainly and point the user at the Connections page."- }-${hasSharedContext ? "" : "\nNo shared workspace context exists yet — bootstrap it (intake protocol step 0) before or while you author the metric.\n"}-Follow the intake protocol from your identity. Work NOW, don't just-greet: acknowledge the ambition in one sentence, ask only what's truly-blocking (if anything), then explore the data, author + TEST the metric-query, verify it via propose_goal_metric, and report the measured-baseline with a suggested target, cadence, and spend envelope. End by-asking the user to confirm — the moment they do, record it via-propose_target, which starts the loop and fires the first check.`;-}--/** Fire-and-forget from goal creation. The goal screen's embedded chat- * streams it live — one conversation per goal, on the "main" session. */-export async function runGoalIntake(- goal: Goal,- opts?: { focus?: string | null },-): Promise<void> {- const project = getProject(goal.project_slug);- if (!project) {- console.error(`[goal-intake] project not found: ${goal.project_slug}`);- return;- }- const connectedMcpKeys = listProjectMcpTokens(goal.project_slug).map(- (t) => t.server_name,- );- const brief = await readProjectBrief(goal.project_slug).catch(() => null);- const message = buildIntakeKickoffMessage({- goal,- connectedMcpKeys,- hasSharedContext: Boolean(brief?.trim()),- focus: opts?.focus,- });- try {- await streamAgentTurn({- projectSlug: project.slug,- harnessAdapter: project.harness_adapter,- agentId: goal.agent_id,- // One conversation per goal.- sessionLabel: "main",- message,- source: "goal-intake",- });- } catch (err) {- console.error("[goal-intake] intake turn failed:", err);- }-}diff --git a/notfair/src/server/goals/metric.test.ts b/notfair/src/server/goals/metric.test.tsdeleted file mode 100644index 743e3ca0..00000000--- a/notfair/src/server/goals/metric.test.ts+++ /dev/null@@ -1,110 +0,0 @@-import { describe, expect, it, vi } from "vitest";--// Real better-sqlite3 against a tmpdir DB, per repo test conventions.-// MUST be hoisted: static imports evaluate before module-level statements,-// and db.ts captures NOTFAIR_DATA_DIR at import time — a plain assignment-// here would silently point the suite at the developer's live ~/.notfair.-vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-metric-"));-});--import {- LOCAL_SOURCE_KEY,- LOCAL_SOURCE_TOOL,- parseMetricValue,- runHistorySource,- runMetricSource,-} from "./metric";--const SLUG = "proj";--function localSource(command: string, tool = LOCAL_SOURCE_TOOL) {- return {- key: LOCAL_SOURCE_KEY,- tool,- args_json: JSON.stringify({ command }),- };-}--describe("parseMetricValue", () => {- it("accepts bare numbers, numeric strings, and {value} wrappers", () => {- expect(parseMetricValue(21)).toBe(21);- expect(parseMetricValue("21.5")).toBe(21.5);- expect(parseMetricValue({ value: 3 })).toBe(3);- expect(parseMetricValue({ ok: true, result: { value: 9 } })).toBe(9);- });-- it("accepts a one-column MCP table with one numeric row", () => {- expect(parseMetricValue("value\n1.2097")).toBe(1.2097);- expect(parseMetricValue("value\r\n1.2097")).toBe(1.2097);- });-- it("rejects ambiguous payloads", () => {- expect(parseMetricValue("")).toBeNull();- expect(parseMetricValue([1, 2])).toBeNull();- expect(parseMetricValue({ rows: 4 })).toBeNull();- expect(parseMetricValue("value\n1\n2")).toBeNull();- expect(parseMetricValue("1\n2")).toBeNull();- expect(parseMetricValue("not-a-metric\n1")).toBeNull();- });-});--describe("runMetricSource (local shell)", () => {- it("parses a bare number from stdout", async () => {- const r = await runMetricSource(SLUG, localSource("echo 42"));- expect(r).toEqual({ ok: true, value: 42 });- });-- it("parses a {value} JSON payload from stdout", async () => {- const r = await runMetricSource(SLUG, localSource(`echo '{"value": 7.5}'`));- expect(r).toEqual({ ok: true, value: 7.5 });- });-- it("rejects non-numeric output with the payload echoed back", async () => {- const r = await runMetricSource(SLUG, localSource("echo not-a-number"));- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("not-a-number");- });-- it("surfaces command failure", async () => {- const r = await runMetricSource(SLUG, localSource("exit 3"));- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("Local command failed");- });-- it("rejects a missing command argument", async () => {- const r = await runMetricSource(SLUG, {- key: LOCAL_SOURCE_KEY,- tool: LOCAL_SOURCE_TOOL,- args_json: "{}",- });- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain('{"command"');- });-- it("rejects tools other than 'shell' on the local source", async () => {- const r = await runMetricSource(SLUG, localSource("echo 1", "runScript"));- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("'shell'");- });-});--describe("runHistorySource (local shell)", () => {- it("parses a {date, value} array from stdout, sorted ascending", async () => {- const rows = `[{"date":"2026-07-02","value":2},{"date":"2026-07-01","value":1}]`;- const r = await runHistorySource(SLUG, localSource(`echo '${rows}'`));- expect(r.ok).toBe(true);- if (r.ok) {- expect(r.points.map((p) => p.value)).toEqual([1, 2]);- }- });-- it("rejects non-array output", async () => {- const r = await runHistorySource(SLUG, localSource("echo 5"));- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("array of {date, value}");- });-});diff --git a/notfair/src/server/goals/metric.ts b/notfair/src/server/goals/metric.tsdeleted file mode 100644index 90e359a9..00000000--- a/notfair/src/server/goals/metric.ts+++ /dev/null@@ -1,353 +0,0 @@-import { execFile } from "node:child_process";-import { existsSync } from "node:fs";-import { homedir } from "node:os";-import { promisify } from "node:util";-import { mcpRpcAutoRefresh } from "@/server/mcp/rpc";-import type { Goal } from "@/server/db/goals";-import { getProject } from "@/server/db/projects";--const execFileAsync = promisify(execFile);--/**- * Mechanical execution of a goal's stored metric query against a catalog- * MCP (e.g. notfair-googleads `runScript`) or the `local` shell source.- * This is the loop's ground truth: the tick runner calls it BEFORE the- * agent wakes, so the agent never self-reports the number it is being- * judged on. The same path verifies the metric during intake- * (`propose_goal_metric`) — a metric that can't be measured here is- * rejected before the goal can activate.- */--export type MetricMeasurement =- | { ok: true; value: number }- | { ok: false; error: string };--const METRIC_TIMEOUT_MS = 60_000;--/** Shape of an MCP tools/call result envelope. */-type ToolCallResult = {- content?: Array<{ type?: string; text?: string }>;- isError?: boolean;-};--export type MetricSource = {- /** Catalog MCP key, e.g. "notfair-googleads". */- key: string;- /** Tool to call on that server, e.g. "runScript". */- tool: string;- /** JSON-encoded arguments object for the tool call. */- args_json: string;-};--/**- * The `local` source: instead of a catalog MCP, the platform runs a- * shell command on this machine and parses its stdout as the value —- * for ambitions no connected MCP can measure (GitHub PRs via `gh`, a- * local SQLite ledger, a curl'd endpoint). The trust rule is unchanged:- * the agent authors the command once, but every measurement is executed- * by the platform itself, never self-reported. It also adds no new- * capability — tick agents already run with full shell access here.- *- * Spec: key `local`, tool `shell`, args `{"command": "<sh command>"}`.- * Runs from the project's codebase_path when it exists (use absolute- * paths regardless), with the metric timeout applied.- */-export const LOCAL_SOURCE_KEY = "local";-export const LOCAL_SOURCE_TOOL = "shell";--type LocalRun = { ok: true; text: string } | { ok: false; error: string };--async function runLocalShell(- project_slug: string,- args: Record<string, unknown>,-): Promise<LocalRun> {- const command = args.command;- if (typeof command !== "string" || !command.trim()) {- return { ok: false, error: `Local source args must be {"command": "<shell command>"}` };- }- const codebase = getProject(project_slug)?.codebase_path;- const cwd = codebase && existsSync(codebase) ? codebase : homedir();- try {- const { stdout } = await execFileAsync("/bin/sh", ["-c", command], {- timeout: METRIC_TIMEOUT_MS,- maxBuffer: 4 * 1024 * 1024,- cwd,- });- return { ok: true, text: stdout.trim() };- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- return { ok: false, error: `Local command failed: ${truncate(msg, 500)}` };- }-}--/** Validate the (key, tool) pair for a local source. Null when not local. */-function localSourceError(source: MetricSource): string | null {- if (source.key !== LOCAL_SOURCE_KEY) return null;- return source.tool === LOCAL_SOURCE_TOOL- ? null- : `The '${LOCAL_SOURCE_KEY}' source only supports tool '${LOCAL_SOURCE_TOOL}'.`;-}--export function metricSourceFromGoal(goal: Goal): MetricSource | null {- if (!goal.metric_source_key || !goal.metric_source_tool || !goal.metric_source_args_json) {- return null;- }- return {- key: goal.metric_source_key,- tool: goal.metric_source_tool,- args_json: goal.metric_source_args_json,- };-}--/**- * Coerce a metric script's return payload into a single number.- *- * Convention (taught in the goal agent's identity): the script should- * return a bare number or `{ value: <number> }`. We tolerate the obvious- * near-misses (numeric strings, a single-element array, a nested `value`)- * but refuse anything ambiguous — a metric that needs interpretation is a- * metric the loop can't trust.- */-export function parseMetricValue(payload: unknown, depth = 0): number | null {- if (depth > 3) return null;- if (typeof payload === "number" && Number.isFinite(payload)) return payload;- if (typeof payload === "string") {- const trimmed = payload.trim();- if (trimmed === "") return null;- const n = Number(trimmed);- if (Number.isFinite(n)) return n;-- // CLI-style MCPs may render a one-cell query as a two-line table:- // value- // 1.2097- // Accept exactly one header plus one numeric data row. Anything wider- // or taller remains ambiguous and must be rejected.- const lines = trimmed- .split(/\r?\n/)- .map((line) => line.trim())- .filter(Boolean);- if (lines.length === 2 && lines[0]?.toLowerCase() === "value") {- const tableValue = Number(lines[1]);- if (Number.isFinite(tableValue)) return tableValue;- }- return null;- }- if (Array.isArray(payload)) {- return payload.length === 1 ? parseMetricValue(payload[0], depth + 1) : null;- }- if (payload && typeof payload === "object") {- // Tolerated wrappers: {value}, and the runScript sandboxes' response- // envelope {ok, result} (both Google Ads and X Ads wrap script- // returns this way).- if ("value" in payload) {- return parseMetricValue((payload as { value: unknown }).value, depth + 1);- }- if ("result" in payload) {- return parseMetricValue((payload as { result: unknown }).result, depth + 1);- }- }- return null;-}--/**- * Execute a metric source against its catalog MCP and return the number.- * Token lookup, refresh, and SSE/JSON response parsing are handled by- * `mcpRpcAutoRefresh` (the same plumbing onboarding uses for account- * listing). Every failure mode maps to a human-readable error string that- * the tick diary / goal page can surface verbatim.- */-export async function runMetricSource(- project_slug: string,- source: MetricSource,-): Promise<MetricMeasurement> {- let args: Record<string, unknown>;- try {- const parsed = JSON.parse(source.args_json);- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {- return { ok: false, error: "metric_source_args_json must encode a JSON object" };- }- args = parsed as Record<string, unknown>;- } catch {- return { ok: false, error: "metric_source_args_json is not valid JSON" };- }-- if (source.key === LOCAL_SOURCE_KEY) {- const toolError = localSourceError(source);- if (toolError) return { ok: false, error: toolError };- const run = await runLocalShell(project_slug, args);- if (!run.ok) return run;- let payload: unknown = run.text;- try {- payload = JSON.parse(run.text);- } catch {- // Not JSON — parseMetricValue handles numeric strings.- }- const value = parseMetricValue(payload);- if (value === null) {- return {- ok: false,- error: `Local command must print a single number (or {value: number}) to stdout. Got: ${truncate(run.text, 300)}`,- };- }- return { ok: true, value };- }-- const rpc = await mcpRpcAutoRefresh<ToolCallResult>(- project_slug,- source.key,- "tools/call",- { name: source.tool, arguments: args },- { timeoutMs: METRIC_TIMEOUT_MS },- );-- if (!rpc.ok) {- const detail = "message" in rpc && rpc.message ? `: ${rpc.message}` : "";- return {- ok: false,- error: `Metric query failed against ${source.key} (${rpc.kind}${detail})`,- };- }-- const result = rpc.result;- const text = result?.content?.find((c) => c.type === "text")?.text ?? "";-- if (result?.isError) {- return {- ok: false,- error: `Metric tool '${source.tool}' errored: ${truncate(text || "(no detail)", 500)}`,- };- }-- let payload: unknown = text;- try {- payload = JSON.parse(text);- } catch {- // Not JSON — fall through; parseMetricValue handles numeric strings.- }-- const value = parseMetricValue(payload);- if (value === null) {- return {- ok: false,- error: `Metric query returned a non-numeric result. The script must return a single number (or {value: number}). Got: ${truncate(text, 300)}`,- };- }- return { ok: true, value };-}--/** Measure a goal's metric. Errors if the goal has no metric spec yet. */-export async function measureGoalMetric(goal: Goal): Promise<MetricMeasurement> {- const source = metricSourceFromGoal(goal);- if (!source) {- return { ok: false, error: "Goal has no metric definition yet (still in intake?)" };- }- return runMetricSource(goal.project_slug, source);-}--export type HistoryPoint = { date: string; value: number };--/**- * Parse a history query's payload into per-day points. Convention: the- * script returns an ARRAY of {date, value} (date = YYYY-MM-DD or ISO).- * Tolerates the runScript {ok, result} envelope, {rows: [...]} wrappers,- * and `day`/`metric` key aliases — but every row must yield a parseable- * date and a finite number, and the whole series is rejected otherwise:- * a chart built on guessed data is worse than no chart.- */-export function parseHistoryPoints(payload: unknown, depth = 0): HistoryPoint[] | null {- if (depth > 3 || payload === null || payload === undefined) return null;- if (Array.isArray(payload)) {- if (payload.length === 0 || payload.length > 400) return null;- const points: HistoryPoint[] = [];- for (const row of payload) {- if (!row || typeof row !== "object") return null;- const r = row as Record<string, unknown>;- const rawDate = r.date ?? r.day ?? r.ts;- const rawValue = r.value ?? r.metric ?? r.v;- const value = parseMetricValue(rawValue);- if (typeof rawDate !== "string" || value === null) return null;- const t = Date.parse(rawDate);- if (Number.isNaN(t)) return null;- points.push({ date: new Date(t).toISOString(), value });- }- points.sort((a, b) => a.date.localeCompare(b.date));- return points;- }- if (typeof payload === "object") {- const o = payload as Record<string, unknown>;- if ("result" in o) return parseHistoryPoints(o.result, depth + 1);- if ("rows" in o) return parseHistoryPoints(o.rows, depth + 1);- if ("value" in o) return parseHistoryPoints(o.value, depth + 1);- }- return null;-}--/** Execute a history source and return parsed per-day points. */-export async function runHistorySource(- project_slug: string,- source: MetricSource,-): Promise<{ ok: true; points: HistoryPoint[] } | { ok: false; error: string }> {- let args: Record<string, unknown>;- try {- const parsed = JSON.parse(source.args_json);- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {- return { ok: false, error: "history args_json must encode a JSON object" };- }- args = parsed as Record<string, unknown>;- } catch {- return { ok: false, error: "history args_json is not valid JSON" };- }- if (source.key === LOCAL_SOURCE_KEY) {- const toolError = localSourceError(source);- if (toolError) return { ok: false, error: toolError };- const run = await runLocalShell(project_slug, args);- if (!run.ok) return run;- let payload: unknown = run.text;- try {- payload = JSON.parse(run.text);- } catch {- // fall through — parseHistoryPoints rejects non-array payloads.- }- const points = parseHistoryPoints(payload);- if (!points) {- return {- ok: false,- error: `Local history command must print an array of {date, value} rows (1–400 points) to stdout. Got: ${truncate(run.text, 300)}`,- };- }- return { ok: true, points };- }- const rpc = await mcpRpcAutoRefresh<ToolCallResult>(- project_slug,- source.key,- "tools/call",- { name: source.tool, arguments: args },- { timeoutMs: METRIC_TIMEOUT_MS },- );- if (!rpc.ok) {- const detail = "message" in rpc && rpc.message ? `: ${rpc.message}` : "";- return { ok: false, error: `History query failed against ${source.key} (${rpc.kind}${detail})` };- }- const text = rpc.result?.content?.find((c) => c.type === "text")?.text ?? "";- if (rpc.result?.isError) {- return { ok: false, error: `History tool errored: ${truncate(text || "(no detail)", 500)}` };- }- let payload: unknown = text;- try {- payload = JSON.parse(text);- } catch {- // fall through- }- const points = parseHistoryPoints(payload);- if (!points) {- return {- ok: false,- error: `History query must return an array of {date, value} rows (1–400 points). Got: ${truncate(text, 300)}`,- };- }- return { ok: true, points };-}--function truncate(s: string, max: number): string {- return s.length > max ? `${s.slice(0, max)}…` : s;-}diff --git a/notfair/src/server/goals/pr-sync.test.ts b/notfair/src/server/goals/pr-sync.test.tsdeleted file mode 100644index ff68c39c..00000000--- a/notfair/src/server/goals/pr-sync.test.ts+++ /dev/null@@ -1,63 +0,0 @@-import { describe, expect, it } from "vitest";--import { ghStateToPrState, parseGhPrView } from "@/server/goals/pr-sync";--describe("ghStateToPrState", () => {- it("maps GitHub states, defaulting unknown to open", () => {- expect(ghStateToPrState("OPEN")).toBe("open");- expect(ghStateToPrState("MERGED")).toBe("merged");- expect(ghStateToPrState("CLOSED")).toBe("closed");- expect(ghStateToPrState("merged")).toBe("merged");- expect(ghStateToPrState(undefined)).toBe("open");- expect(ghStateToPrState("WEIRD")).toBe("open");- });-});--describe("parseGhPrView", () => {- it("parses a full gh pr view payload", () => {- expect(- parseGhPrView({- state: "OPEN",- title: "Improve /pricing meta",- reviewDecision: "CHANGES_REQUESTED",- isDraft: false,- mergedAt: null,- comments: [{}, {}],- reviews: [{}],- }),- ).toEqual({- state: "open",- title: "Improve /pricing meta",- review_decision: "CHANGES_REQUESTED",- comment_count: 3,- is_draft: false,- merged_at: null,- });- });-- it("handles repos without required reviews (empty decision) and merges", () => {- expect(- parseGhPrView({- state: "MERGED",- title: "t",- reviewDecision: "",- isDraft: false,- mergedAt: "2026-07-13T01:02:03Z",- comments: [],- reviews: [],- }),- ).toEqual({- state: "merged",- title: "t",- review_decision: "",- comment_count: 0,- is_draft: false,- merged_at: "2026-07-13T01:02:03Z",- });- });-- it("rejects non-object payloads", () => {- expect(parseGhPrView(null)).toBeNull();- expect(parseGhPrView("nope")).toBeNull();- });-});diff --git a/notfair/src/server/goals/pr-sync.ts b/notfair/src/server/goals/pr-sync.tsdeleted file mode 100644index ccd3a5e8..00000000--- a/notfair/src/server/goals/pr-sync.ts+++ /dev/null@@ -1,148 +0,0 @@-import { execFile } from "node:child_process";-import { promisify } from "node:util";--import {- applyGoalPrSync,- listDuePrSyncs,- listOpenGoalPrs,- markGoalPrSyncError,- type GoalPr,- type GoalPrState,-} from "@/server/db/goal-prs";--const execFileAsync = promisify(execFile);--/**- * Sync goal PRs against GitHub via the user's authenticated `gh` CLI —- * the same auth path the agent used to open the PR, so private repos- * just work and we hold no GitHub token ourselves.- *- * Called from the tick runner (fresh state in every brief) and from the- * goal page when rows look stale. Failures are recorded per-row and never- * throw: a broken `gh` shouldn't stop a tick, and the UI shows the last- * good state plus the sync error.- */--type GhPrView = {- state?: string; // OPEN | MERGED | CLOSED- title?: string;- reviewDecision?: string;- isDraft?: boolean;- mergedAt?: string | null;- comments?: unknown[];- reviews?: unknown[];-};--const GH_FIELDS = "state,title,reviewDecision,isDraft,mergedAt,comments,reviews";--/** Map GitHub's state string to our row state. Unknown → keep "open". */-export function ghStateToPrState(state: string | undefined): GoalPrState {- switch ((state ?? "").toUpperCase()) {- case "MERGED":- return "merged";- case "CLOSED":- return "closed";- default:- return "open";- }-}--/** Parse a `gh pr view --json` payload into the row-sync shape. */-export function parseGhPrView(payload: unknown): {- state: GoalPrState;- title: string | null;- review_decision: string | null;- comment_count: number;- is_draft: boolean;- merged_at: string | null;-} | null {- if (!payload || typeof payload !== "object") return null;- const view = payload as GhPrView;- const comments = Array.isArray(view.comments) ? view.comments.length : 0;- const reviews = Array.isArray(view.reviews) ? view.reviews.length : 0;- return {- state: ghStateToPrState(view.state),- title: typeof view.title === "string" && view.title.trim() ? view.title : null,- review_decision:- typeof view.reviewDecision === "string" ? view.reviewDecision : null,- comment_count: comments + reviews,- is_draft: !!view.isDraft,- merged_at: typeof view.mergedAt === "string" ? view.mergedAt : null,- };-}--// Single-flight per PR: the tick sync, a page-view sync, and the sweep-// can all fire around the same moment — the first one wins, the rest-// no-op instead of stacking duplicate gh subprocesses.-const inFlight = new Set<string>();--async function syncOnePr(pr: GoalPr): Promise<GoalPr | null> {- if (inFlight.has(pr.id)) return null;- inFlight.add(pr.id);- try {- const { stdout } = await execFileAsync(- "gh",- ["pr", "view", pr.url, "--json", GH_FIELDS],- { timeout: 15_000, maxBuffer: 4 * 1024 * 1024 },- );- const parsed = parseGhPrView(JSON.parse(stdout));- if (!parsed) {- markGoalPrSyncError(pr.id, "gh returned an unexpected payload shape");- return null;- }- return applyGoalPrSync(pr.id, parsed);- } catch (err) {- markGoalPrSyncError(pr.id, err instanceof Error ? err.message : String(err));- return null;- } finally {- inFlight.delete(pr.id);- }-}--/** Sync every non-terminal PR for a goal. Never throws. */-export async function syncGoalPrs(goal_id: string): Promise<void> {- const open = listOpenGoalPrs(goal_id);- for (const pr of open) {- await syncOnePr(pr);- }-}--/**- * Fire-and-forget staleness sweep for page renders: sync when any open- * PR hasn't been checked in `maxAgeMs`. Rendering never awaits GitHub.- */-export function maybeSyncGoalPrs(goal_id: string, maxAgeMs = 120_000): void {- const open = listOpenGoalPrs(goal_id);- const cutoff = Date.now() - maxAgeMs;- const stale = open.some(- (pr) => !pr.last_synced_at || Date.parse(pr.last_synced_at) < cutoff,- );- if (!stale) return;- void syncGoalPrs(goal_id).catch((err) =>- console.error(`[pr-sync] background sync failed for goal ${goal_id}:`, err),- );-}--// The centralized sweep never overlaps itself: with many due PRs and a-// slow gh, one pass could outlive the 30s scheduler interval.-let sweepRunning = false;--/**- * The centralized freshness pass, called from the 30s scheduler sweep.- * One cheap SQL lists every open PR whose own `next_sync_at` has arrived- * (the adaptive schedule stamped by the db layer on each sync); only- * those hit GitHub. Returns how many PRs were checked.- */-export async function syncDueGoalPrs(): Promise<number> {- if (sweepRunning) return 0;- sweepRunning = true;- try {- const due = listDuePrSyncs();- for (const pr of due) {- await syncOnePr(pr);- }- return due.length;- } finally {- sweepRunning = false;- }-}diff --git a/notfair/src/server/goals/provision.ts b/notfair/src/server/goals/provision.tsdeleted file mode 100644index 73150479..00000000--- a/notfair/src/server/goals/provision.ts+++ /dev/null@@ -1,147 +0,0 @@-import { provisionAgent } from "@/server/agents/provisioning";-import { readAgentMeta, writeAgentMeta } from "@/server/agent-meta";-import { getProject } from "@/server/db/projects";-import type { Goal } from "@/server/db/goals";-import { readProjectBrief } from "@/server/onboarding/project-brief";-import { DEFAULT_HARNESS_ADAPTER } from "@/server/adapters/registry";-import {- registerBrowserMcpForAgent,- registerCatalogMcpForAgent,- registerGoalsMcpForAgent,-} from "@/server/mcp-server/registration";-import { listProjectMcpTokens } from "@/server/mcp/tokens";-import { goalLabel } from "@/lib/goal-label";-import { renderGoalIdentity } from "./identity";--/**- * Provisioning for goal agents. An agent is a consequence of a goal- * existing: created with the goal, identity re-rendered as the goal's spec- * evolves (metric authored, target confirmed), garbage-collected with it.- */--export const GOAL_TEMPLATE_KEY = "goal";--/**- * Agents are anonymous plumbing (goals carry the display identity), so- * ids are sequential: url slug `goal-<n>`, agent id- * `<project>-goal-<n>`. Stable forever — labels can change, URLs don't.- */-export function goalAgentUrlSlug(n: number): string {- return `goal-${n}`;-}--export function goalAgentIdFor(project_slug: string, n: number): string {- return `${project_slug}-${goalAgentUrlSlug(n)}`;-}--/**- * Write the goal agent's workspace (IDENTITY.md + skill + project brief via- * the project's harness adapter), its meta sidecar, and wire every MCP the- * project has: goals, browser, and all connected catalog servers.- * Idempotent — re-running refreshes files in place.- */-export async function provisionGoalAgent(input: {- goal: Goal;- urlSlug: string;-}): Promise<void> {- const { goal, urlSlug } = input;- const project = getProject(goal.project_slug);- if (!project) throw new Error(`project not found: ${goal.project_slug}`);- const harnessAdapter = project.harness_adapter ?? DEFAULT_HARNESS_ADAPTER;-- const brief = await readProjectBrief(goal.project_slug).catch(() => null);- const identityMd = renderGoalIdentity({ goal, brief, project });- const label = goalLabel(goal);-- await provisionAgent({- projectSlug: goal.project_slug,- agentId: goal.agent_id,- displayName: label,- templateKey: GOAL_TEMPLATE_KEY,- identityMd,- projectMd: brief ?? undefined,- harnessAdapter,- });-- const existing = readAgentMeta(goal.agent_id);- await writeAgentMeta({- agent_id: goal.agent_id,- project_slug: goal.project_slug,- // meta.name mirrors the goal label so any surface still reading it- // (deletion summaries, etc.) shows the goal, not a persona.- name: label,- slug: existing?.slug ?? urlSlug,- created_at: existing?.created_at ?? new Date().toISOString(),- });-- // MCP wiring is best-effort per server — a goal agent without browser- // access still has its loop tools. Log and continue on failure.- try {- await registerGoalsMcpForAgent(goal.project_slug, goal.agent_id);- } catch (err) {- console.warn(`[goal-provision] goals MCP failed for ${goal.agent_id}:`, err);- }- try {- await registerBrowserMcpForAgent(goal.project_slug, goal.agent_id);- } catch (err) {- console.warn(`[goal-provision] browser MCP failed for ${goal.agent_id}:`, err);- }- try {- const tokens = listProjectMcpTokens(goal.project_slug);- for (const t of tokens) {- await registerCatalogMcpForAgent(goal.project_slug, t.server_name, goal.agent_id);- }- } catch (err) {- console.warn(`[goal-provision] catalog MCP wiring failed for ${goal.agent_id}:`, err);- }-}--/**- * Re-render IDENTITY.md after a goal spec change (metric proposed, target- * confirmed). Keeps the agent's on-disk brain in sync with the DB without- * touching MCP wiring. Best-effort — callers treat failure as non-fatal- * since the next full provision heals it.- */-/**- * Re-render IDENTITY.md for every goal agent in a project — called when- * the shared workspace context (PROJECT.md) changes so all agents see it- * on their next turn. Returns the number of agents synced.- */-export async function syncProjectAgents(project_slug: string): Promise<number> {- const { listProjectAgents } = await import("@/server/agent-meta");- const { getGoalForAgent } = await import("@/server/db/goals");- const entries = await listProjectAgents(project_slug);- let synced = 0;- for (const entry of entries) {- const goal = getGoalForAgent(entry.agent_id);- if (!goal) continue;- try {- await syncGoalIdentity(goal);- synced++;- } catch (err) {- console.warn(`[goal-provision] brief sync failed for ${entry.agent_id}:`, err);- }- }- return synced;-}--export async function syncGoalIdentity(goal: Goal): Promise<void> {- const meta = readAgentMeta(goal.agent_id);- const project = getProject(goal.project_slug);- if (!project) return;- const brief = await readProjectBrief(goal.project_slug).catch(() => null);- const label = goalLabel(goal);- await provisionAgent({- projectSlug: goal.project_slug,- agentId: goal.agent_id,- displayName: label,- templateKey: GOAL_TEMPLATE_KEY,- identityMd: renderGoalIdentity({ goal, brief, project }),- projectMd: brief ?? undefined,- harnessAdapter: project.harness_adapter ?? DEFAULT_HARNESS_ADAPTER,- });- // Keep the meta label in sync so headers/deletion summaries follow the goal.- if (meta && meta.name !== label) {- await writeAgentMeta({ ...meta, name: label });- }-}diff --git a/notfair/src/server/goals/recovery.test.ts b/notfair/src/server/goals/recovery.test.tsdeleted file mode 100644index 0ec29a27..00000000--- a/notfair/src/server/goals/recovery.test.ts+++ /dev/null@@ -1,260 +0,0 @@-import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";--vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-recovery-"));-});--import { getDb } from "@/server/db/db";-import { getGoalTick } from "@/server/db/goals";-import {- appendTranscriptEvent,- getOrCreateSession,- listTranscriptEvents,-} from "@/server/sessions";-import {- INTERRUPTED_TICK_SUMMARY,- recoverInterruptedGoalTicks,-} from "./recovery";--const NOW = "2026-07-22T20:00:00.000Z";--function insertRunningTick(input: {- id: string;- tickNumber: number;- sessionId?: string;- ownerPid?: number;-}): void {- getDb()- .prepare(- `INSERT INTO goal_ticks- (id, goal_id, tick_number, trigger_kind, owner_pid, session_id, status, started_at)- VALUES (?, 'goal-1', ?, 'heartbeat', ?, ?, 'running', ?)`,- )- .run(- input.id,- input.tickNumber,- input.ownerPid ?? null,- input.sessionId ?? null,- NOW,- );-}--beforeAll(() => {- const db = getDb();- db.prepare(- "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('p1', 'proj', 'Proj', ?, 'codex-local')",- ).run(NOW);- db.prepare(- `INSERT INTO goals- (id, project_slug, agent_id, statement, status, cadence_cron, created_at, updated_at)- VALUES ('goal-1', 'proj', 'agent-1', 'Keep errors low', 'active', '0 * * * *', ?, ?)`,- ).run(NOW, NOW);-});--beforeEach(() => {- const db = getDb();- db.prepare("DELETE FROM goal_ticks").run();- db.prepare("DELETE FROM transcript_events").run();- db.prepare("DELETE FROM sessions").run();-});--describe("recoverInterruptedGoalTicks", () => {- it("fails an orphaned running tick and closes its partial transcript", () => {- const session = getOrCreateSession({- project_slug: "proj",- agent_id: "agent-1",- label: "tick-1",- harness_adapter: "codex-local",- });- appendTranscriptEvent(session.id, "user", { text: "check" });- appendTranscriptEvent(session.id, "lifecycle", {- kind: "lifecycle",- phase: "start",- });- insertRunningTick({- id: "tick-1",- tickNumber: 1,- sessionId: session.id,- ownerPid: 4040,- });-- expect(recoverInterruptedGoalTicks(() => false)).toEqual({- recovered: 1,- completed: 0,- failed: 1,- active: 0,- });-- expect(getGoalTick("tick-1")).toMatchObject({- status: "failed",- summary: INTERRUPTED_TICK_SUMMARY,- });- const events = listTranscriptEvents(session.id);- expect(events.at(-1)).toMatchObject({ kind: "error" });- expect(JSON.parse(events.at(-1)!.payload_json)).toMatchObject({- message: INTERRUPTED_TICK_SUMMARY,- });-- expect(recoverInterruptedGoalTicks(() => false)).toEqual({- recovered: 0,- completed: 0,- failed: 0,- active: 0,- });- expect(listTranscriptEvents(session.id)).toHaveLength(3);- });-- it("recovers a final event as done instead of replaying the tick", () => {- const session = getOrCreateSession({- project_slug: "proj",- agent_id: "agent-1",- label: "tick-2",- harness_adapter: "codex-local",- });- appendTranscriptEvent(session.id, "final", {- kind: "final",- text: "The check completed before shutdown.",- });- insertRunningTick({ id: "tick-2", tickNumber: 2, sessionId: session.id });-- expect(recoverInterruptedGoalTicks()).toEqual({- recovered: 1,- completed: 1,- failed: 0,- active: 0,- });- expect(getGoalTick("tick-2")).toMatchObject({- status: "done",- summary: "The check completed before shutdown.",- });- expect(listTranscriptEvents(session.id)).toHaveLength(1);- });-- it("preserves a terminal error as the failed tick summary without duplicating it", () => {- const session = getOrCreateSession({- project_slug: "proj",- agent_id: "agent-1",- label: "tick-3",- harness_adapter: "codex-local",- });- appendTranscriptEvent(session.id, "error", {- kind: "error",- message: "The harness stopped unexpectedly.",- transient: false,- });- insertRunningTick({ id: "tick-3", tickNumber: 3, sessionId: session.id });-- expect(recoverInterruptedGoalTicks()).toEqual({- recovered: 1,- completed: 0,- failed: 1,- active: 0,- });- expect(getGoalTick("tick-3")).toMatchObject({- status: "failed",- summary: "The harness stopped unexpectedly.",- });- expect(listTranscriptEvents(session.id)).toHaveLength(1);- });-- it("recovers a stored lifecycle completion as done", () => {- const session = getOrCreateSession({- project_slug: "proj",- agent_id: "agent-1",- label: "tick-4",- harness_adapter: "codex-local",- });- appendTranscriptEvent(session.id, "lifecycle", {- kind: "lifecycle",- phase: "done",- });- insertRunningTick({ id: "tick-4", tickNumber: 4, sessionId: session.id });-- expect(recoverInterruptedGoalTicks()).toEqual({- recovered: 1,- completed: 1,- failed: 0,- active: 0,- });- expect(getGoalTick("tick-4")).toMatchObject({- status: "done",- summary: "Check completed before NotFair restarted.",- });- expect(listTranscriptEvents(session.id)).toHaveLength(1);- });-- it("fails a running row without a session", () => {- insertRunningTick({ id: "tick-5", tickNumber: 5, ownerPid: 5050 });-- expect(recoverInterruptedGoalTicks(() => false)).toEqual({- recovered: 1,- completed: 0,- failed: 1,- active: 0,- });- expect(getGoalTick("tick-5")).toMatchObject({- status: "failed",- summary: INTERRUPTED_TICK_SUMMARY,- });- });-- it("leaves a tick owned by another live process running", () => {- insertRunningTick({ id: "tick-6", tickNumber: 6, ownerPid: 4242 });-- expect(recoverInterruptedGoalTicks((pid) => pid === 4242)).toEqual({- recovered: 0,- completed: 0,- failed: 0,- active: 1,- });- expect(getGoalTick("tick-6")).toMatchObject({- status: "running",- owner_pid: 4242,- });- });-- it("leaves a legacy ownerless partial tick untouched", () => {- insertRunningTick({ id: "tick-7", tickNumber: 7 });-- expect(recoverInterruptedGoalTicks()).toEqual({- recovered: 0,- completed: 0,- failed: 0,- active: 1,- });- expect(getGoalTick("tick-7")).toMatchObject({- status: "running",- owner_pid: null,- });- });-- it("does not treat a transient error as proof a legacy turn ended", () => {- const session = getOrCreateSession({- project_slug: "proj",- agent_id: "agent-1",- label: "tick-8",- harness_adapter: "codex-local",- });- appendTranscriptEvent(session.id, "error", {- kind: "error",- message: "Reconnecting...",- transient: true,- });- insertRunningTick({- id: "tick-8",- tickNumber: 8,- sessionId: session.id,- });-- expect(recoverInterruptedGoalTicks()).toEqual({- recovered: 0,- completed: 0,- failed: 0,- active: 1,- });- expect(getGoalTick("tick-8")?.status).toBe("running");- });-});diff --git a/notfair/src/server/goals/recovery.ts b/notfair/src/server/goals/recovery.tsdeleted file mode 100644index 6013f85e..00000000--- a/notfair/src/server/goals/recovery.ts+++ /dev/null@@ -1,156 +0,0 @@-import { getDb } from "@/server/db/db";-import { finishRunningGoalTick, type GoalTick } from "@/server/db/goals";-import { appendTranscriptEvent } from "@/server/sessions";--export const INTERRUPTED_TICK_SUMMARY =- "Check interrupted because NotFair stopped or restarted before it finished.";--const RECOVERED_SUMMARY_MAX = 1_000;--type TerminalEvent = {- kind: "final" | "error" | "lifecycle";- payload_json: string;-};--export type TickRecoveryResult = {- recovered: number;- completed: number;- failed: number;- active: number;-};--function isProcessAlive(pid: number): boolean {- if (pid === process.pid) return true;- try {- process.kill(pid, 0);- return true;- } catch (error) {- return (error as NodeJS.ErrnoException).code === "EPERM";- }-}--function payloadText(- event: TerminalEvent,- key: "text" | "message",-): string | null {- try {- const payload = JSON.parse(event.payload_json) as Record<string, unknown>;- const value = payload[key];- return typeof value === "string" && value.trim()- ? value.trim().slice(0, RECOVERED_SUMMARY_MAX)- : null;- } catch {- return null;- }-}--function terminalEvent(sessionId: string): TerminalEvent | null {- const row = getDb()- .prepare(- `SELECT kind, payload_json- FROM transcript_events- WHERE session_id = ?- AND (- kind IN ('final', 'error')- OR (- kind = 'lifecycle'- AND json_extract(payload_json, '$.phase') = 'done'- )- )- AND (- kind <> 'error'- OR COALESCE(json_extract(payload_json, '$.transient'), 0) = 0- )- ORDER BY seq DESC- LIMIT 1`,- )- .get(sessionId) as TerminalEvent | undefined;- return row ?? null;-}--function sessionExists(sessionId: string): boolean {- return Boolean(- getDb().prepare("SELECT 1 FROM sessions WHERE id = ?").get(sessionId),- );-}--/**- * Reconcile check rows left "running" by the previous server process.- *- * A local harness subprocess belongs to the process that spawned it. At- * boot there cannot be a live in-memory owner for a persisted running row,- * and replaying it could duplicate external mutations. We therefore:- *- * - preserve a terminal final as a completed check;- * - preserve a terminal error as a failed check;- * - close every other partial transcript with an interruption error and- * mark its check failed, allowing the normal next heartbeat to continue.- *- * Called exactly once by the scheduler before its first sweep.- */-export function recoverInterruptedGoalTicks(- processAlive: (pid: number) => boolean = isProcessAlive,-): TickRecoveryResult {- const rows = getDb()- .prepare("SELECT * FROM goal_ticks WHERE status = 'running' ORDER BY started_at ASC")- .all() as GoalTick[];- const result: TickRecoveryResult = {- recovered: 0,- completed: 0,- failed: 0,- active: 0,- };-- for (const tick of rows) {- const terminal = tick.session_id ? terminalEvent(tick.session_id) : null;- // A second server can share the data directory (for example, an- // orphaned process whose server.json entry was replaced). Never- // recover work while its owning process is still alive. Legacy rows- // without an owner are only safe to reconcile when their transcript- // already proves the turn ended.- if (tick.owner_pid !== null && processAlive(tick.owner_pid)) {- result.active += 1;- continue;- }- if (tick.owner_pid === null && !terminal) {- result.active += 1;- continue;- }-- if (terminal?.kind === "final" || terminal?.kind === "lifecycle") {- const summary =- terminal.kind === "final"- ? payloadText(terminal, "text")- : null;- if (!finishRunningGoalTick(- tick.id,- "done",- summary ?? tick.summary ?? "Check completed before NotFair restarted.",- )) {- continue;- }- result.recovered += 1;- result.completed += 1;- continue;- }-- const summary =- terminal?.kind === "error"- ? payloadText(terminal, "message") ?? INTERRUPTED_TICK_SUMMARY- : INTERRUPTED_TICK_SUMMARY;- if (!finishRunningGoalTick(tick.id, "failed", summary)) {- continue;- }- if (!terminal && tick.session_id && sessionExists(tick.session_id)) {- appendTranscriptEvent(tick.session_id, "error", {- kind: "error",- message: INTERRUPTED_TICK_SUMMARY,- transient: true,- });- }- result.recovered += 1;- result.failed += 1;- }-- return result;-}diff --git a/notfair/src/server/goals/register-pr.test.ts b/notfair/src/server/goals/register-pr.test.tsdeleted file mode 100644index b44dcb7b..00000000--- a/notfair/src/server/goals/register-pr.test.ts+++ /dev/null@@ -1,98 +0,0 @@-import { beforeAll, describe, expect, it, vi } from "vitest";--// Hoisted so it runs before static imports evaluate db.ts (which captures-// NOTFAIR_DATA_DIR at import time) — see goal-prs.test.ts.-vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-regpr-"));-});--// The handler pulls the live GitHub state right after registering; keep-// the network out of the test.-vi.mock("@/server/goals/pr-sync", () => ({- syncGoalPrs: vi.fn().mockResolvedValue(undefined),- maybeSyncGoalPrs: vi.fn(),-}));--import { handleRegisterPullRequest } from "@/server/goals/handlers";-import { getDb } from "@/server/db/db";-import { createGoal } from "@/server/db/goals";-import { listGoalPrs } from "@/server/db/goal-prs";--const SLUG = "proj";-let goalId: string;-const ctx = { project_slug: SLUG, agent_id: "agent-1" };--beforeAll(() => {- getDb()- .prepare(- "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('p1', ?, 'Proj', ?, 'codex-local')",- )- .run(SLUG, new Date().toISOString());- goalId = createGoal({- project_slug: SLUG,- agent_id: "agent-1",- statement: "Grow organic clicks",- }).id;-});--describe("handleRegisterPullRequest", () => {- it("rejects non-GitHub-PR urls", async () => {- for (const url of [- "https://github.com/acme/site",- "https://gitlab.com/acme/site/-/merge_requests/1",- "http://github.com/acme/site/pull/1",- "not a url",- ]) {- const r = await handleRegisterPullRequest(- { goal_id: goalId, url, title: "t" },- ctx,- );- expect(r.ok, url).toBe(false);- }- });-- it("rejects another agent's goal", async () => {- const r = await handleRegisterPullRequest(- {- goal_id: goalId,- url: "https://github.com/acme/site/pull/1",- title: "t",- },- { project_slug: SLUG, agent_id: "someone-else" },- );- expect(r.ok).toBe(false);- });-- it("registers once and is idempotent per url", async () => {- const url = "https://github.com/acme/site/pull/42";- const first = await handleRegisterPullRequest(- { goal_id: goalId, url, title: "Improve /pricing meta", branch: "notfair/pricing" },- ctx,- );- expect(first.ok).toBe(true);- const second = await handleRegisterPullRequest(- { goal_id: goalId, url: `${url}/`, title: "dup" },- ctx,- );- expect(second.ok).toBe(true);- const rows = listGoalPrs(goalId).filter((p) => p.url === url);- expect(rows).toHaveLength(1);- expect(rows[0]!.title).toBe("Improve /pricing meta");- });-- it("rejects an action_id that belongs to a different goal", async () => {- const r = await handleRegisterPullRequest(- {- goal_id: goalId,- url: "https://github.com/acme/site/pull/43",- title: "t",- action_id: "not-a-real-action",- },- ctx,- );- expect(r.ok).toBe(false);- });-});diff --git a/notfair/src/server/goals/tick-run.test.ts b/notfair/src/server/goals/tick-run.test.tsdeleted file mode 100644index 92442026..00000000--- a/notfair/src/server/goals/tick-run.test.ts+++ /dev/null@@ -1,101 +0,0 @@-import { beforeAll, describe, expect, it, vi } from "vitest";--// Real better-sqlite3 against a tmpdir DB, per repo test conventions.-// MUST be hoisted: static imports evaluate before module-level statements,-// and db.ts captures NOTFAIR_DATA_DIR at import time — a plain assignment-// here would silently point the suite at the developer's live ~/.notfair.-vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-tick-"));-});--const mocks = vi.hoisted(() => ({- measureGoalMetric: vi.fn(),- syncGoalPrs: vi.fn(async () => {}),-}));--vi.mock("@/server/goals/metric", () => ({- measureGoalMetric: mocks.measureGoalMetric,-}));-vi.mock("./pr-sync", () => ({- syncGoalPrs: mocks.syncGoalPrs,-}));-vi.mock("@/server/adapters/registry", () => ({- requireAdapter: () => ({- // Minimal harness: one final message, no session handshake.- execute: async function* () {- yield { kind: "final", text: "did one thing" };- },- }),-}));--import { runGoalTick } from "./tick";-import { getDb } from "@/server/db/db";-import {- createGoal,- getGoal,- listGoalTicks,- setGoalStatus,- type Goal,-} from "@/server/db/goals";--const SLUG = "proj";-let goal: Goal;--beforeAll(() => {- getDb()- .prepare(- "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('p1', ?, 'Proj', ?, 'claude-code-local')",- )- .run(SLUG, new Date().toISOString());- const created = createGoal({- project_slug: SLUG,- agent_id: "agent-1",- statement: "Grow organic clicks",- });- goal = setGoalStatus(created.id, "active", "test")!;-});--describe("runGoalTick claim-first lifecycle", () => {- it("records the check row synchronously, before measurement resolves", async () => {- // Measurement that stays pending until we let it finish — the window- // where the diary row used to not exist yet.- let finishMeasurement!: (v: unknown) => void;- mocks.measureGoalMetric.mockReturnValueOnce(- new Promise((r) => (finishMeasurement = r)),- );-- const turn = runGoalTick(goal, "manual"); // deliberately not awaited yet-- // The fire-and-forget caller (runTickNowAction) returns here: the row- // must already be in the diary, running, tagged manual, metric pending.- const claimed = listGoalTicks(goal.id, 10);- expect(claimed).toHaveLength(1);- expect(claimed[0]!).toMatchObject({- status: "running",- trigger_kind: "manual",- metric_value: null,- });-- finishMeasurement({ ok: true, value: 42 });- await turn;-- const done = listGoalTicks(goal.id, 10)[0]!;- expect(done.status).toBe("done");- expect(done.metric_value).toBe(42); // backfilled by setGoalTickMetric- expect(done.summary).toBe("did one thing");- });-- it("marks the claimed row failed instead of stranding it running", async () => {- mocks.measureGoalMetric.mockResolvedValueOnce({ ok: true, value: 43 });- mocks.syncGoalPrs.mockRejectedValueOnce(new Error("gh exploded"));-- await runGoalTick(getGoal(goal.id)!, "manual");-- const latest = listGoalTicks(goal.id, 10)[0]!;- expect(latest.status).toBe("failed");- expect(latest.summary).toContain("gh exploded");- });-});diff --git a/notfair/src/server/goals/tick.more.test.ts b/notfair/src/server/goals/tick.more.test.tsdeleted file mode 100644index 12e5a7ff..00000000--- a/notfair/src/server/goals/tick.more.test.ts+++ /dev/null@@ -1,468 +0,0 @@-import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";--// Real better-sqlite3 against a tmpdir DB, per repo test conventions.-// MUST be hoisted: static imports evaluate before module-level statements,-// and db.ts captures NOTFAIR_DATA_DIR at import time — a plain assignment-// here would silently point the suite at the developer's live ~/.notfair.-vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-tickmore-"));-});--const mocks = vi.hoisted(() => ({- measureGoalMetric: vi.fn(),- runMetricSource: vi.fn(),- syncGoalPrs: vi.fn(async () => {}),- /** Events the fake adapter yields on the next turn. */- events: [] as Array<Record<string, unknown>>,- /** Messages the adapter received (the composed tick briefs). */- seenMessages: [] as string[],-}));--vi.mock("@/server/goals/metric", () => ({- measureGoalMetric: mocks.measureGoalMetric,- runMetricSource: mocks.runMetricSource,-}));-vi.mock("./pr-sync", () => ({ syncGoalPrs: mocks.syncGoalPrs }));-vi.mock("@/server/adapters/registry", () => ({- requireAdapter: () => ({- execute: async function* (input: { message: string }) {- mocks.seenMessages.push(input.message);- for (const evt of mocks.events) yield evt;- },- }),-}));--import {- buildTickMessage,- describePrForBrief,- runDueGoalTicks,- runGoalTick,- streamAgentTurn,- type TickContext,-} from "./tick";-import { getDb } from "@/server/db/db";-import {- createGoal,- createGoalAction,- getGoal,- listGoalTicks,- proposeTarget,- recordMetricSnapshot,- setGoalMetric,- type Goal,- type GoalAction,- type GoalTick,-} from "@/server/db/goals";-import type { GoalPr as Pr } from "@/server/db/goal-prs";-import {- listSupportMetricSnapshots,- upsertSupportMetric,-} from "@/server/db/goal-support-metrics";--const SLUG = "proj";--function makeActiveGoal(agent: string, target = 100): Goal {- const goal = createGoal({ project_slug: SLUG, agent_id: agent, statement: "grow" });- setGoalMetric(goal.id, {- metric_name: "clicks",- metric_source_key: "local",- metric_source_tool: "shell",- metric_source_args_json: "{}",- metric_direction: "increase",- baseline_value: 10,- });- return proposeTarget(goal.id, { target_value: target })!;-}--beforeAll(() => {- getDb()- .prepare(- "INSERT INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('p1', ?, 'Proj', ?, 'claude-code-local')",- )- .run(SLUG, new Date().toISOString());-});--beforeEach(() => {- mocks.measureGoalMetric.mockReset();- mocks.runMetricSource.mockReset();- mocks.events = [{ kind: "final", text: "did one thing" }];- mocks.seenMessages = [];-});--describe("runGoalTick guards", () => {- it("does nothing for a goal that is not active", async () => {- const goal = createGoal({ project_slug: SLUG, agent_id: "g-intake", statement: "s" });- await runGoalTick(goal, "manual");- expect(listGoalTicks(goal.id, 10)).toHaveLength(0);- expect(mocks.measureGoalMetric).not.toHaveBeenCalled();- });-- it("accepts a goal id string and ignores unknown ids", async () => {- await expect(runGoalTick("no-such-goal", "manual")).resolves.toBeUndefined();- });-- it("skips a second tick while one is already running for the goal", async () => {- const goal = makeActiveGoal("g-reent");- let finish!: (v: unknown) => void;- mocks.measureGoalMetric.mockReturnValueOnce(new Promise((r) => (finish = r)));- const first = runGoalTick(goal, "manual");- const second = runGoalTick(goal, "manual"); // overlaps: must no-op- await second;- finish({ ok: true, value: 1 });- await first;- expect(listGoalTicks(goal.id, 10)).toHaveLength(1);- });-});--describe("observe-only heartbeats", () => {- it("records the check + chart point without waking the agent", async () => {- const goal = makeActiveGoal("g-noop");- recordMetricSnapshot(goal.id, 20, "tick"); // mid-flight, target not met- createGoalAction({- goal_id: goal.id,- kind: "mutation",- description: "in-window change",- expected_effect: "e",- review_after: new Date(Date.now() + 48 * 3600_000).toISOString(),- });- mocks.measureGoalMetric.mockResolvedValueOnce({ ok: true, value: 21 });-- await runGoalTick(getGoal(goal.id)!, "heartbeat");-- const tick = listGoalTicks(goal.id, 10)[0]!;- expect(tick.status).toBe("done");- expect(tick.summary).toContain("No-op check");- expect(tick.metric_value).toBe(21);- expect(tick.session_id).toBeNull(); // no agent turn, no session- expect(mocks.seenMessages).toHaveLength(0);- expect(getGoal(goal.id)!.current_value).toBe(21); // snapshot still landed- });-});--describe("agent-turn ticks", () => {- it("measures supporting metrics, snapshots the good ones, and briefs both", async () => {- const goal = makeActiveGoal("g-support");- const good = upsertSupportMetric({- goal_id: goal.id,- name: "impressions",- source_key: "local",- source_tool: "shell",- source_args_json: "{}",- direction: "increase",- measured_value: 5,- });- upsertSupportMetric({- goal_id: goal.id,- name: "ctr",- source_key: "local",- source_tool: "shell",- source_args_json: "{}",- direction: null,- measured_value: 1,- });- mocks.measureGoalMetric.mockResolvedValueOnce({ ok: true, value: 30 });- mocks.runMetricSource- .mockResolvedValueOnce({ ok: true, value: 9 })- .mockResolvedValueOnce({ ok: false, error: "column gone" });-- await runGoalTick(getGoal(goal.id)!, "manual");-- expect(listSupportMetricSnapshots(good.id).some((s) => s.value === 9)).toBe(true);- const brief = mocks.seenMessages[0]!;- expect(brief).toContain("[supporting] impressions: **9**");- expect(brief).toContain("healthy = increase");- expect(brief).toContain("[supporting] ctr: MEASUREMENT FAILED: column gone");- });-- it("briefs a failed primary measurement and stores the error on the check", async () => {- const goal = makeActiveGoal("g-mfail");- mocks.measureGoalMetric.mockResolvedValueOnce({ ok: false, error: "token expired" });-- await runGoalTick(getGoal(goal.id)!, "manual");-- const tick = listGoalTicks(goal.id, 10)[0]!;- expect(tick.metric_value).toBeNull();- expect(tick.metric_error).toBe("token expired");- expect(mocks.seenMessages[0]!).toContain("MEASUREMENT FAILED: token expired");- });-- it("leads with extraContext (approval wake-ups)", async () => {- const goal = makeActiveGoal("g-extra");- mocks.measureGoalMetric.mockResolvedValueOnce({ ok: true, value: 1 });- await runGoalTick(getGoal(goal.id)!, "heartbeat", {- extraContext: "The user merged your PR.",- });- expect(mocks.seenMessages[0]!).toContain("The user merged your PR.");- });-});--describe("runDueGoalTicks", () => {- it("ticks exactly the goals whose heartbeat is due", async () => {- const due = makeActiveGoal("g-due");- getDb()- .prepare("UPDATE goals SET next_tick_at = ? WHERE id = ?")- .run(new Date(Date.now() - 1000).toISOString(), due.id);- const notDue = makeActiveGoal("g-notdue"); // next_tick_at in the future- mocks.measureGoalMetric.mockResolvedValue({ ok: true, value: 1 });-- await runDueGoalTicks();-- expect(listGoalTicks(due.id, 10)).toHaveLength(1);- expect(listGoalTicks(due.id, 10)[0]!.trigger_kind).toBe("heartbeat");- expect(listGoalTicks(notDue.id, 10)).toHaveLength(0);- // The heartbeat advanced past the stale timestamp.- expect(getGoal(due.id)!.next_tick_at! > new Date().toISOString()).toBe(true);- });-});--describe("streamAgentTurn", () => {- const turnInput = (agent: string) => ({- projectSlug: SLUG,- harnessAdapter: "claude-code-local" as const,- agentId: agent,- sessionLabel: "main",- message: "hello",- source: "test",- });-- it("persists the handshake and returns the final text as summary", async () => {- mocks.events = [- { kind: "session", harnessSessionId: "h-123" },- { kind: "delta", text: "thinking…" },- { kind: "final", text: " all done " },- ];- const onSession = vi.fn();- const r = await streamAgentTurn({ ...turnInput("sa-1"), onSession });- expect(r.summary).toBe("all done");- expect(onSession).toHaveBeenCalledWith(r.sessionId);- const row = getDb()- .prepare("SELECT harness_session_id FROM sessions WHERE id = ?")- .get(r.sessionId) as { harness_session_id: string };- expect(row.harness_session_id).toBe("h-123");- });-- it("falls back to the accumulated deltas when no final arrives", async () => {- mocks.events = [- { kind: "delta", text: "part one " },- { kind: "delta", text: "part two" },- ];- const r = await streamAgentTurn(turnInput("sa-2"));- expect(r.summary).toBe("part one part two");- });-- it("returns a null summary for an empty turn", async () => {- mocks.events = [];- const r = await streamAgentTurn(turnInput("sa-3"));- expect(r.summary).toBeNull();- });-- it("truncates an oversized final to the summary cap", async () => {- mocks.events = [{ kind: "final", text: "x".repeat(5000) }];- const r = await streamAgentTurn(turnInput("sa-4"));- expect(r.summary!.length).toBe(4001); // 4000 chars + ellipsis- expect(r.summary!.endsWith("…")).toBe(true);- });-- it("throws the last non-transient error when the turn dies without a final", async () => {- mocks.events = [- { kind: "error", message: "harness crashed", transient: false },- { kind: "error", message: "retrying…", transient: true },- ];- await expect(streamAgentTurn(turnInput("sa-5"))).rejects.toThrow("harness crashed");- });-- it("falls back to the last error when all were transient", async () => {- mocks.events = [- { kind: "error", message: "first blip", transient: true },- { kind: "error", message: "second blip", transient: true },- ];- await expect(streamAgentTurn(turnInput("sa-6"))).rejects.toThrow("second blip");- });-});--// ── pure brief composition ───────────────────────────────────────────────--function pr(over: Partial<Pr>): Pr {- return {- id: "pr-1",- goal_id: "g",- action_id: null,- tick_number: null,- url: "https://github.com/acme/site/pull/7",- title: "Fix pricing meta",- branch: null,- state: "open",- review_decision: null,- comment_count: 0,- is_draft: false,- merged_at: null,- last_synced_at: null,- sync_error: null,- next_sync_at: null,- last_activity_at: null,- created_at: "",- updated_at: "",- ...over,- };-}--describe("describePrForBrief", () => {- it("covers the open-state variants", () => {- expect(describePrForBrief(pr({ is_draft: true }))).toContain("(draft)");- expect(describePrForBrief(pr({ review_decision: "CHANGES_REQUESTED" }))).toContain(- "CHANGES REQUESTED by the user",- );- expect(describePrForBrief(pr({ review_decision: "APPROVED" }))).toContain(- "approved, awaiting merge",- );- expect(describePrForBrief(pr({}))).toContain("awaiting the user's review");- expect(describePrForBrief(pr({ comment_count: 2 }))).toContain(- "2 comment(s)/review(s)",- );- });-- it("covers merged, closed, sync errors, and action links", () => {- expect(- describePrForBrief(pr({ state: "merged", merged_at: "2026-07-13T00:00:00Z" })),- ).toContain("merged 2026-07-13T00:00:00Z");- expect(describePrForBrief(pr({ state: "closed" }))).toContain(- "closed WITHOUT merge",- );- expect(describePrForBrief(pr({ sync_error: "gh: not found" }))).toContain(- "(last sync failed: gh: not found)",- );- expect(describePrForBrief(pr({ action_id: "act-9" }))).toContain(- "linked action act-9",- );- });-});--const baseCtx: TickContext = {- goal: {- metric_name: "clicks",- baseline_value: 10,- target_value: 100,- metric_direction: "increase",- mode: "achieve",- deadline: null,- spend_envelope_usd: null,- } as unknown as Goal,- tickNumber: 3,- nowIso: "2026-07-21T00:00:00.000Z",- measurement: { ok: true, value: 30 },- supportReadings: [],- targetMet: false,- pastDeadline: false,- actionsDueForReview: [],- gatedActions: [],- gatedByOthers: [],- userActionRequests: [],- loggedSpendUsd: 0,- recentLearnings: [],- lastTick: null,- pullRequests: [],-};--describe("buildTickMessage sections", () => {- it("renders deadline countdown, spend envelope, and the gate lists", () => {- const gated = {- id: "act-g",- description: "raised bids",- resources_touched_json: JSON.stringify(["campaign:1"]),- review_after: "2026-07-25T00:00:00.000Z",- } as GoalAction;- const due = {- id: "act-d",- description: "paused waste",- expected_effect: "spend down",- review_after: "2026-07-20T00:00:00.000Z",- } as GoalAction;- const msg = buildTickMessage({- ...baseCtx,- goal: {- ...baseCtx.goal,- deadline: "2026-07-23T00:00:00.000Z",- spend_envelope_usd: 500,- } as Goal,- loggedSpendUsd: 120,- actionsDueForReview: [due],- gatedActions: [gated],- gatedByOthers: [- {- ...gated,- id: "act-o",- description: "their test",- resources_touched_json: "[]",- agent_id: "proj-goal-2",- } as GoalAction & { agent_id: string },- ],- });- expect(msg).toContain("(2 days left)");- expect(msg).toContain("$120 logged of $500 envelope");- expect(msg).toContain("[act-d] paused waste — expected: spend down");- expect(msg).toContain("[act-g] raised bids — resources: campaign:1");- expect(msg).toContain("## Gated by OTHER agents");- expect(msg).toContain("(proj-goal-2) their test — resources: (unspecified)");- });-- it("flags a met stop condition and a passed deadline", () => {- const msg = buildTickMessage({- ...baseCtx,- goal: { ...baseCtx.goal, deadline: "2026-07-20T00:00:00.000Z" } as Goal,- targetMet: true,- pastDeadline: true,- });- expect(msg).toContain("- target_met: true");- expect(msg).toContain("(PASSED)");- expect(msg).toContain("A stop condition looks met.");- // No envelope set → new spend is out of bounds by default.- expect(msg).toContain("spend envelope: none set");- });-- it("frames maintain goals as holding, not finished", () => {- const msg = buildTickMessage({- ...baseCtx,- goal: { ...baseCtx.goal, mode: "maintain" } as Goal,- targetMet: true,- });- expect(msg).toContain("holding_at_target: true");- expect(msg).toContain("NOT a reason to close");- expect(msg).not.toContain("A stop condition looks met.");- });-- it("renders PRs, learnings, and the last tick", () => {- const msg = buildTickMessage({- ...baseCtx,- pullRequests: [pr({ title: "Fix pricing meta" })],- recentLearnings: [- { confidence: "high", body: "Tuesday spikes are noise" } as never,- ],- lastTick: {- tick_number: 2,- status: "done",- summary: "reviewed one action",- } as GoalTick,- });- expect(msg).toContain("## Your pull requests");- expect(msg).toContain("Fix pricing meta");- expect(msg).toContain("the user merges, never you");- expect(msg).toContain("- (high) Tuesday spikes are noise");- expect(msg).toContain("#2 (done): reviewed one action");- });-- it("renders a summary-less last tick and the measurement-failure guidance", () => {- const msg = buildTickMessage({- ...baseCtx,- measurement: { ok: false, error: "boom" },- lastTick: { tick_number: 1, status: "failed", summary: null } as GoalTick,- });- expect(msg).toContain("- MEASUREMENT FAILED: boom");- expect(msg).toContain("Diagnose before anything else.");- expect(msg).toContain("- target_met: false");- expect(msg).toContain("#1 (failed): (no summary)");- expect(msg).toContain("- deadline: none");- });-});diff --git a/notfair/src/server/goals/tick.test.ts b/notfair/src/server/goals/tick.test.tsdeleted file mode 100644index 2309bd73..00000000--- a/notfair/src/server/goals/tick.test.ts+++ /dev/null@@ -1,114 +0,0 @@-import { describe, expect, it } from "vitest";--import { buildTickMessage, decideAgentTurn, type TickContext } from "@/server/goals/tick";-import type { Goal, GoalAction } from "@/server/db/goals";--/** Baseline: the one situation that should NOT wake the agent — an- * achieve goal mid-flight with everything inside observation windows. */-const observeOnly = {- trigger: "heartbeat" as const,- hasExtraContext: false,- measurementOk: true,- mode: "achieve" as const,- targetMet: false,- pastDeadline: false,- actionsDueForReview: 0,- gatedActions: 1,- earliestGateEnd: "2026-07-27T21:55:15.995Z",- openPrs: 0,-};--describe("decideAgentTurn", () => {- it("skips the agent turn only when there is provably nothing to do", () => {- const d = decideAgentTurn(observeOnly);- expect(d.wake).toBe(false);- if (!d.wake) {- expect(d.noopSummary).toContain("No-op check");- expect(d.noopSummary).toContain("2026-07-27");- }- });-- it("always wakes on manual / approval triggers and approval context", () => {- expect(decideAgentTurn({ ...observeOnly, trigger: "manual" }).wake).toBe(true);- expect(decideAgentTurn({ ...observeOnly, trigger: "approval" }).wake).toBe(true);- expect(decideAgentTurn({ ...observeOnly, hasExtraContext: true }).wake).toBe(true);- });-- it("wakes when the measurement failed", () => {- expect(decideAgentTurn({ ...observeOnly, measurementOk: false }).wake).toBe(true);- });-- it("wakes when actions are due for review", () => {- expect(decideAgentTurn({ ...observeOnly, actionsDueForReview: 1 }).wake).toBe(true);- });-- it("wakes while any PR is open", () => {- expect(decideAgentTurn({ ...observeOnly, openPrs: 1 }).wake).toBe(true);- });-- it("wakes on stop conditions: deadline passed or achieve-target met", () => {- expect(decideAgentTurn({ ...observeOnly, pastDeadline: true }).wake).toBe(true);- expect(decideAgentTurn({ ...observeOnly, targetMet: true }).wake).toBe(true);- // Unknown target state is never grounds to skip.- expect(decideAgentTurn({ ...observeOnly, targetMet: null }).wake).toBe(true);- });-- it("maintain goals observe while holding, wake on drift", () => {- const maintain = { ...observeOnly, mode: "maintain" as const };- expect(decideAgentTurn({ ...maintain, targetMet: true }).wake).toBe(false);- expect(decideAgentTurn({ ...maintain, targetMet: false }).wake).toBe(true);- expect(decideAgentTurn({ ...maintain, targetMet: null }).wake).toBe(true);- });-- it("wakes when no observation window is open — the agent has a free hand", () => {- expect(- decideAgentTurn({ ...observeOnly, gatedActions: 0, earliestGateEnd: null }).wake,- ).toBe(true);- });-});--/** Minimal brief context: an achieve goal mid-flight with nothing pending. */-const briefCtx: TickContext = {- goal: {- metric_name: "fixable-error rate",- baseline_value: 10,- target_value: 1,- metric_direction: "down",- mode: "achieve",- deadline: null,- spend_envelope_usd: null,- } as unknown as Goal,- tickNumber: 92,- nowIso: "2026-07-21T00:00:00.000Z",- measurement: { ok: true, value: 3 },- supportReadings: [],- targetMet: false,- pastDeadline: false,- actionsDueForReview: [],- gatedActions: [],- gatedByOthers: [],- userActionRequests: [],- loggedSpendUsd: 0,- recentLearnings: [],- lastTick: null,- pullRequests: [],-};--describe("buildTickMessage — Needs you section", () => {- it("mirrors the open escalations verbatim as the only asks to repeat", () => {- const ask = {- id: "act-1",- description: "USER ACTION REQUIRED: rotate the PostHog API key",- } as GoalAction;- const msg = buildTickMessage({ ...briefCtx, userActionRequests: [ask] });- expect(msg).toContain("## Needs you");- expect(msg).toContain("[act-1] USER ACTION REQUIRED: rotate the PostHog API key");- expect(msg).toContain("only these");- });-- it("with no open asks, forbids repeating retired ones from memory", () => {- const msg = buildTickMessage(briefCtx);- expect(msg).toContain("## Needs you");- expect(msg).toContain("do NOT repeat any earlier ask");- });-});diff --git a/notfair/src/server/goals/tick.ts b/notfair/src/server/goals/tick.tsdeleted file mode 100644index 3f7d50ec..00000000--- a/notfair/src/server/goals/tick.ts+++ /dev/null@@ -1,602 +0,0 @@-import { getProject } from "@/server/db/projects";-import type { Project } from "@/types";-import { requireAdapter } from "@/server/adapters/registry";-import { workspaceDirFor } from "@/server/agents/provisioning";-import {- appendTranscriptEvent,- getOrCreateSession,- touchSession,-} from "@/server/sessions";-import {- attachTickSession,- createGoalTick,- dueGoals,- finishGoalTick,- getGoal,- getLastAgentTick,- isPastDeadline,- isTargetMet,- listActionsDueForReview,- listGatedActions,- listGatedActionsForOtherAgents,- listGoalLearnings,- listUserActionRequests,- loggedSpendTotal,- markGoalTicked,- recordMetricSnapshot,- setGoalTickMetric,- type Goal,- type GoalAction,- type GoalLearning,- type GoalMode,- type GoalTick,- type GoalTickTrigger,-} from "@/server/db/goals";-import { listGoalPrs, type GoalPr } from "@/server/db/goal-prs";-import { syncGoalPrs } from "./pr-sync";-import { measureGoalMetric, runMetricSource, type MetricMeasurement } from "./metric";-import {- listSupportMetrics,- recordSupportMetricSnapshot,- type GoalSupportMetric,-} from "@/server/db/goal-support-metrics";--/**- * The goal loop's tick runner — one OODA iteration per invocation.- *- * A tick: measure the metric mechanically (agent never self-reports) →- * snapshot → compose the tick brief from DB state → run one adapter turn →- * record the diary row. Heartbeats are driven by goals.next_tick_at via- * the shared 30s scheduler interval; manual runs and approval wake-ups- * call runGoalTick directly.- *- * Heartbeats never skip a day: the mechanical half (measure → chart- * snapshot → PR sync → diary row) runs on every cadence beat so the user- * always sees today's check and today's chart point. Only the agent turn- * is conditional — when everything is provably in an observation window- * (decideAgentTurn), the check is recorded as a no-op instead of waking- * an LLM to conclude "nothing to do until Jul 27".- */--const MAX_SUMMARY = 4000;--/** In-process re-entrancy guard: one running tick per goal. */-const runningTicks = new Set<string>();--export type TickContext = {- goal: Goal;- tickNumber: number;- nowIso: string;- measurement: MetricMeasurement;- /** Supporting metrics measured this check: value, or the error. */- supportReadings: SupportReading[];- targetMet: boolean | null;- pastDeadline: boolean;- actionsDueForReview: GoalAction[];- gatedActions: GoalAction[];- gatedByOthers: Array<GoalAction & { agent_id: string }>;- /** Open USER ACTION REQUIRED escalations — the "Needs you" panel's list. */- userActionRequests: GoalAction[];- loggedSpendUsd: number;- recentLearnings: GoalLearning[];- lastTick: GoalTick | null;- /** PRs this goal opened against the codebase, freshly synced from GitHub. */- pullRequests: GoalPr[];- /** Extra leading section, e.g. an approval decision on wake-up. */- extraContext?: string;-};--function fmtValue(v: number | null): string {- return v === null ? "—" : String(v);-}--export type SupportReading = {- metric: GoalSupportMetric;- measurement: MetricMeasurement;-};--/**- * Measure every supporting metric and record snapshots — same ground-truth- * rule as the primary: the platform measures before the agent wakes. A- * failing supporting metric never blocks the check; the error rides into- * the brief for the agent to fix (redefine via add_supporting_metric).- */-async function measureSupportMetrics(goal: Goal): Promise<SupportReading[]> {- const readings: SupportReading[] = [];- for (const metric of listSupportMetrics(goal.id)) {- const measurement = await runMetricSource(goal.project_slug, {- key: metric.source_key,- tool: metric.source_tool,- args_json: metric.source_args_json,- });- if (measurement.ok) {- recordSupportMetricSnapshot(metric.id, measurement.value, "tick");- }- readings.push({ metric, measurement });- }- return readings;-}--/** One line of live PR state for the tick brief. */-export function describePrForBrief(pr: GoalPr): string {- const bits: string[] = [`[${pr.state.toUpperCase()}]`];- if (pr.state === "open") {- if (pr.is_draft) bits.push("(draft)");- if (pr.review_decision === "CHANGES_REQUESTED") {- bits.push("CHANGES REQUESTED by the user");- } else if (pr.review_decision === "APPROVED") {- bits.push("approved, awaiting merge");- } else {- bits.push("awaiting the user's review");- }- if (pr.comment_count > 0) bits.push(`${pr.comment_count} comment(s)/review(s)`);- } else if (pr.state === "merged") {- bits.push(`merged ${pr.merged_at ?? ""}`.trim());- } else {- bits.push("closed WITHOUT merge");- }- if (pr.sync_error) bits.push(`(last sync failed: ${pr.sync_error})`);- return `${pr.title} — ${pr.url} — ${bits.join(", ")}${pr.action_id ? ` — linked action ${pr.action_id}` : ""}`;-}--function daysUntil(deadline: string, nowIso: string): number {- return Math.ceil(- (new Date(deadline).getTime() - new Date(nowIso).getTime()) / 86_400_000,- );-}--/**- * Compose the tick brief. Pure — everything volatile the agent needs is- * injected here so the turn is self-sufficient even after the agent's- * context has rotated. Kept scannable: the agent's protocol lives in its- * identity; this message carries only the live state.- */-export function buildTickMessage(ctx: TickContext): string {- const { goal } = ctx;- const lines: string[] = [];-- lines.push(`[TICK] Goal heartbeat #${ctx.tickNumber} — ${ctx.nowIso}`);- lines.push("");-- if (ctx.extraContext) {- lines.push(ctx.extraContext.trim());- lines.push("");- }-- lines.push("## Metric (measured by the platform just now)");- if (ctx.measurement.ok) {- lines.push(`- ${goal.metric_name ?? "metric"}: **${ctx.measurement.value}**`);- } else {- lines.push(`- MEASUREMENT FAILED: ${ctx.measurement.error}`);- lines.push(- "- Diagnose before anything else. If the query is broken, fix your approach; if the connection/token is broken, call update_goal_status with status=paused and a reason quoting this error so the user can reconnect.",- );- }- lines.push(- `- Baseline: ${fmtValue(goal.baseline_value)} | Target: ${fmtValue(goal.target_value)} (${goal.metric_direction ?? "?"})`,- );- for (const r of ctx.supportReadings) {- if (r.measurement.ok) {- lines.push(- `- [supporting] ${r.metric.name}: **${r.measurement.value}** (baseline ${r.metric.baseline_value}${r.metric.direction ? `, healthy = ${r.metric.direction}` : ""}) — context only, the goal is judged on the primary metric`,- );- } else {- lines.push(- `- [supporting] ${r.metric.name}: MEASUREMENT FAILED: ${r.measurement.error} — fix by redefining it via add_supporting_metric (same name)`,- );- }- }- lines.push("");-- lines.push("## Stop-condition flags");- if (goal.mode === "maintain") {- lines.push(- `- holding_at_target: ${ctx.targetMet === null ? "unknown" : ctx.targetMet} — MAINTAIN goal: target met is the steady state, NOT a reason to close. Watch for drift; act only when the number leaves target.`,- );- } else {- lines.push(`- target_met: ${ctx.targetMet === null ? "unknown" : ctx.targetMet}`);- }- if (goal.deadline) {- const d = daysUntil(goal.deadline, ctx.nowIso);- lines.push(- `- deadline: ${goal.deadline} (${ctx.pastDeadline ? "PASSED" : `${d} day${d === 1 ? "" : "s"} left`})`,- );- } else {- lines.push("- deadline: none");- }- lines.push(- goal.spend_envelope_usd !== null- ? `- spend: $${ctx.loggedSpendUsd} logged of $${goal.spend_envelope_usd} envelope — a hard ceiling. Log spend_usd on every spend-committing action; if the right move would cross the ceiling, don't act — suggest amend_goal to the user in your summary.`- : "- spend envelope: none set — treat any NEW incremental spend as out of bounds until the user sets one (they can, via amend_goal in chat).",- );- if ((ctx.targetMet && goal.mode !== "maintain") || ctx.pastDeadline) {- lines.push(- "- A stop condition looks met. Verify against the measured metric and close the goal with update_goal_status before doing anything else.",- );- }- lines.push("");-- lines.push("## Actions due for review (score these FIRST via review_goal_action)");- if (ctx.actionsDueForReview.length === 0) {- lines.push("- none");- } else {- for (const a of ctx.actionsDueForReview.slice(0, 10)) {- lines.push(- `- [${a.id}] ${a.description} — expected: ${a.expected_effect} (review was due ${a.review_after})`,- );- }- }- lines.push("");-- lines.push(- "## Actions still gated (the LISTED resources are untouchable — a gate never blocks unrelated or additive work elsewhere; if marginal post-change data already gives a decisive verdict, review the action EARLY via review_goal_action instead of waiting out the window)",- );- if (ctx.gatedActions.length === 0) {- lines.push("- none");- } else {- for (const a of ctx.gatedActions.slice(0, 10)) {- const resources = JSON.parse(a.resources_touched_json || "[]") as string[];- lines.push(- `- [${a.id}] ${a.description} — resources: ${resources.join(", ") || "(unspecified)"} — until ${a.review_after}`,- );- }- }- lines.push("");-- if (ctx.gatedByOthers.length > 0) {- lines.push(- "## Gated by OTHER agents in this workspace (equally untouchable)",- );- for (const a of ctx.gatedByOthers.slice(0, 10)) {- const resources = JSON.parse(a.resources_touched_json || "[]") as string[];- lines.push(- `- (${a.agent_id}) ${a.description} — resources: ${resources.join(", ") || "(unspecified)"} — until ${a.review_after}`,- );- }- lines.push("");- }-- if (ctx.pullRequests.length > 0) {- lines.push("## Your pull requests (state synced from GitHub just now)");- for (const pr of ctx.pullRequests.slice(0, 6)) {- lines.push(`- ${describePrForBrief(pr)}`);- }- lines.push(- "- PR rules: the user merges, never you. CHANGES_REQUESTED → address the review comments this tick and push to the same branch. Open + unreviewed → nudge the user in your diary, don't duplicate the work. Merged → the change is live; its observation window runs from the merge. Closed unmerged → treat as rejected: review the linked action with that outcome and learn from it.",- );- lines.push("");- }-- lines.push(- '## Needs you — open user asks (read from the "Needs you" panel just now; this list is the ONLY truth)',- );- if (ctx.userActionRequests.length === 0) {- lines.push(- "- none — do NOT repeat any earlier ask in your summary. An ask absent from this list was marked handled by the user or retired; if telemetry proves the problem persists, escalate a NEW `USER ACTION REQUIRED` decision action with the fresh evidence instead of re-raising from memory.",- );- } else {- for (const a of ctx.userActionRequests.slice(0, 10)) {- lines.push(`- [${a.id}] ${a.description}`);- }- lines.push(- "- Repeat exactly these asks in your diary summary — and only these. If one is obsolete, close it via review_goal_action rather than repeating it.",- );- }- lines.push("");-- lines.push("## Recent learnings");- if (ctx.recentLearnings.length === 0) {- lines.push("- none yet — use search_learnings for older ones once they exist");- } else {- for (const l of ctx.recentLearnings.slice(0, 8)) {- lines.push(`- (${l.confidence}) ${l.body}`);- }- }- lines.push("");-- if (ctx.lastTick) {- lines.push(- `## Last tick\n#${ctx.lastTick.tick_number} (${ctx.lastTick.status}): ${ctx.lastTick.summary ?? "(no summary)"}`,- );- lines.push("");- }-- lines.push(- "Follow the tick protocol from your identity: review first → check stop conditions → respect the gate → at most ONE meaningful move (log it before executing) → end with a short diary line.",- );-- return lines.join("\n");-}--export type AgentTurnDecision =- | { wake: true; reason: string }- | { wake: false; noopSummary: string };--/**- * Does this check need the agent, or is it observe-only? Pure — decided- * fresh on every heartbeat from live state (unlike the old smart sleep,- * which decided once and slept blind through PR reopens or new chat-driven- * work). Observe-only requires POSITIVE proof there is nothing to do; any- * ambiguity wakes the agent.- */-export function decideAgentTurn(input: {- trigger: GoalTickTrigger;- hasExtraContext: boolean;- measurementOk: boolean;- mode: GoalMode;- targetMet: boolean | null;- pastDeadline: boolean;- actionsDueForReview: number;- gatedActions: number;- /** Earliest review_after among gated actions (they sort ASC). */- earliestGateEnd: string | null;- openPrs: number;-}): AgentTurnDecision {- if (input.trigger !== "heartbeat" || input.hasExtraContext) {- return { wake: true, reason: `${input.trigger} trigger` };- }- if (!input.measurementOk) {- return { wake: true, reason: "measurement failed — agent must diagnose" };- }- if (input.actionsDueForReview > 0) {- return { wake: true, reason: "actions due for review" };- }- if (input.openPrs > 0) {- return { wake: true, reason: "open PR needs attention on cadence" };- }- if (input.pastDeadline) {- return { wake: true, reason: "deadline passed — stop condition" };- }- if (input.mode === "maintain" ? input.targetMet !== true : input.targetMet !== false) {- return {- wake: true,- reason:- input.mode === "maintain"- ? "metric drifted off target"- : "target met (or unknown) — stop condition to verify",- };- }- if (input.gatedActions === 0) {- return { wake: true, reason: "no observation window open — agent should be working" };- }- const n = input.gatedActions;- return {- wake: false,- noopSummary:- `No-op check — metric measured and recorded; the agent was not woken. ` +- `${n} action${n === 1 ? " is" : "s are"} still inside ${n === 1 ? "its" : "their"} observation window` +- `${input.earliestGateEnd ? ` (next review ${input.earliestGateEnd.slice(0, 10)})` : ""}, ` +- `nothing is due for review, and there are no open PRs.`,- };-}--/**- * Run one tick for a goal. Fire-and-forget safe: never throws; every- * failure lands on the goal_ticks row so the diary shows it.- */-export async function runGoalTick(- goalRef: Goal | string,- trigger: GoalTickTrigger,- opts: { extraContext?: string } = {},-): Promise<void> {- const goalId = typeof goalRef === "string" ? goalRef : goalRef.id;- // Re-read: the caller's snapshot may be stale (paused/killed since).- const goal = getGoal(goalId);- if (!goal || goal.status !== "active") return;- if (runningTicks.has(goal.id)) {- console.warn(`[goal-tick] tick already running for goal ${goal.id}; skipping`);- return;- }- runningTicks.add(goal.id);- try {- await runGoalTickInner(goal, trigger, opts);- } catch (err) {- console.error(`[goal-tick] tick failed for goal ${goal.id}:`, err);- } finally {- runningTicks.delete(goal.id);- }-}--async function runGoalTickInner(- goal: Goal,- trigger: GoalTickTrigger,- opts: { extraContext?: string },-): Promise<void> {- const project = getProject(goal.project_slug);- if (!project) {- console.error(`[goal-tick] project not found: ${goal.project_slug}`);- return;- }-- // Advance the heartbeat immediately (double-fire guard) and claim the- // tick number.- const tickNumber = markGoalTicked(goal.id);- const nowIso = new Date().toISOString();-- // Record the check row BEFORE the first await: everything up to here runs- // synchronously inside the caller's `void runGoalTick(...)`, so a manual- // "Run tick now" sees its check in the diary the moment the action- // returns. Measurement backfills the metric below.- const tick = createGoalTick({- goal_id: goal.id,- tick_number: tickNumber,- trigger_kind: trigger,- });-- try {- await runClaimedTick(project, goal, tick, trigger, nowIso, opts);- } catch (err) {- // The row is already live in the diary — never strand it "running".- finishGoalTick(tick.id, "failed", err instanceof Error ? err.message : String(err));- }-}--async function runClaimedTick(- project: Project,- goal: Goal,- tick: GoalTick,- trigger: GoalTickTrigger,- nowIso: string,- opts: { extraContext?: string },-): Promise<void> {- const tickNumber = tick.tick_number;-- // Ground truth first: the platform measures, not the agent — and PR- // state comes from GitHub, not from what the agent remembers.- const measurement = await measureGoalMetric(goal);- if (measurement.ok) {- recordMetricSnapshot(goal.id, measurement.value, "tick");- }- // Supporting metrics too — snapshots land even on observe-only checks,- // so their charts stay daily.- const supportReadings = await measureSupportMetrics(goal);- setGoalTickMetric(- tick.id,- measurement.ok ? measurement.value : null,- measurement.ok ? null : measurement.error,- );- await syncGoalPrs(goal.id);- const freshGoal = getGoal(goal.id)!;-- const actionsDueForReview = listActionsDueForReview(goal.id, nowIso);- const gatedActions = listGatedActions(goal.id, nowIso);- const pullRequests = listGoalPrs(goal.id, 10);- const targetMet = isTargetMet(freshGoal);- const pastDeadline = isPastDeadline(freshGoal, nowIso);-- const decision = decideAgentTurn({- trigger,- hasExtraContext: Boolean(opts.extraContext),- measurementOk: measurement.ok,- mode: freshGoal.mode,- targetMet,- pastDeadline,- actionsDueForReview: actionsDueForReview.length,- gatedActions: gatedActions.length,- earliestGateEnd: gatedActions[0]?.review_after ?? null,- openPrs: pullRequests.filter((pr) => pr.state === "open").length,- });-- if (!decision.wake) {- // Observe-only check: the diary row and chart point are already- // recorded above; no session, no tokens.- finishGoalTick(tick.id, "done", decision.noopSummary);- return;- }-- const message = buildTickMessage({- goal: freshGoal,- tickNumber,- nowIso,- measurement,- supportReadings,- targetMet,- pastDeadline,- actionsDueForReview,- gatedActions,- gatedByOthers: listGatedActionsForOtherAgents(goal.project_slug, goal.id, nowIso),- userActionRequests: listUserActionRequests(goal.id),- loggedSpendUsd: loggedSpendTotal(goal.id),- recentLearnings: listGoalLearnings(goal.id, 8),- lastTick: getLastAgentTick(goal.id),- pullRequests,- extraContext: opts.extraContext,- });-- try {- const { summary } = await streamAgentTurn({- projectSlug: project.slug,- harnessAdapter: project.harness_adapter,- agentId: goal.agent_id,- sessionLabel: `tick-${tickNumber}`,- message,- source: "goal-tick",- // Attach as soon as the session exists — not after the turn — so a- // running check is clickable in the UI and a failed one keeps its- // partial transcript reachable.- onSession: (sessionId) => attachTickSession(tick.id, sessionId),- });- finishGoalTick(tick.id, "done", summary);- } catch (err) {- const messageText = err instanceof Error ? err.message : String(err);- finishGoalTick(tick.id, "failed", messageText);- }-}--/**- * Heartbeat sweep — called from the shared scheduler interval. Ticks run- * sequentially (there's only ever one live goal per project today, and- * sequential keeps SQLite + subprocess pressure sane).- */-export async function runDueGoalTicks(): Promise<void> {- const due = dueGoals();- for (const goal of due) {- await runGoalTick(goal, "heartbeat");- }-}--/**- * Run one full agent turn server-side and persist the transcript — the- * same inline pattern as scheduler dispatchJob / task kickoff. Returns the- * session id (for the tick diary link) and a truncated summary.- */-export async function streamAgentTurn(input: {- projectSlug: string;- harnessAdapter: "claude-code-local" | "codex-local";- agentId: string;- sessionLabel: string;- message: string;- source: string;- /** Fires with the session id before the turn streams (attach points). */- onSession?: (sessionId: string) => void;-}): Promise<{ sessionId: string; summary: string | null }> {- const adapter = requireAdapter(input.harnessAdapter);- const session = getOrCreateSession({- project_slug: input.projectSlug,- agent_id: input.agentId,- label: input.sessionLabel,- harness_adapter: input.harnessAdapter,- });- input.onSession?.(session.id);- appendTranscriptEvent(session.id, "user", { text: input.message, source: input.source });-- let finalText: string | null = null;- let deltaBuffer = "";- const errors: { message: string; transient: boolean }[] = [];-- for await (const evt of adapter.execute({- projectSlug: input.projectSlug,- agentId: input.agentId,- workspaceDir: workspaceDirFor(input.agentId),- message: input.message,- threadId: session.id,- harnessSessionId: session.harness_session_id,- })) {- if (evt.kind === "session") {- touchSession(session.id, evt.harnessSessionId);- continue;- }- appendTranscriptEvent(session.id, evt.kind, evt);- if (evt.kind === "final") {- finalText = evt.text;- } else if (evt.kind === "delta" && deltaBuffer.length < MAX_SUMMARY) {- deltaBuffer += evt.text;- } else if (evt.kind === "error") {- errors.push({ message: evt.message, transient: evt.transient ?? false });- }- }- touchSession(session.id);-- if (finalText === null && errors.length > 0) {- const terminal = [...errors].reverse().find((e) => !e.transient);- throw new Error((terminal ?? errors[errors.length - 1]!).message);- }-- const raw = (finalText ?? deltaBuffer).trim();- const summary = raw- ? raw.length > MAX_SUMMARY- ? `${raw.slice(0, MAX_SUMMARY)}…`- : raw- : null;- return { sessionId: session.id, summary };-}diff --git a/notfair/src/server/harness-usage.more.test.ts b/notfair/src/server/harness-usage.more.test.tsdeleted file mode 100644index 284d163f..00000000--- a/notfair/src/server/harness-usage.more.test.ts+++ /dev/null@@ -1,394 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { EventEmitter } from "node:events";-import { mkdirSync, rmSync, writeFileSync } from "node:fs";-import { join } from "node:path";--// harness-usage reads real HOME paths (~/.codex, ~/.claude) and spawns the-// codex CLI. Point homedir at a tmpdir and fake the spawn + fetch surfaces —-// no real binaries, no network, never the developer's actual home.-const h = vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- const home = mkdtempSync(join(tmpdir(), "notfair-usage-home-"));- return {- home,- state: {- loginOutput: "Logged in using ChatGPT\n",- loginStderr: "",- spawnMode: "close" as "close" | "error" | "hang",- killThrows: false,- spawns: [] as Array<{ cmd: string; args: string[] }>,- },- };-});--vi.mock("node:os", async (importOriginal) => {- const actual = await importOriginal<typeof import("node:os")>();- return { ...actual, default: { ...actual, homedir: () => h.home }, homedir: () => h.home };-});-vi.mock("node:child_process", () => ({- spawn: (cmd: string, args: string[]) => {- h.state.spawns.push({ cmd, args });- const child = new EventEmitter() as EventEmitter & {- stdout: EventEmitter;- stderr: EventEmitter;- kill: (sig?: string) => void;- };- child.stdout = new EventEmitter();- child.stderr = new EventEmitter();- child.kill = () => {- if (h.state.killThrows) throw new Error("already exited");- };- if (h.state.spawnMode === "close") {- queueMicrotask(() => {- if (h.state.loginOutput) {- child.stdout.emit("data", Buffer.from(h.state.loginOutput));- }- if (h.state.loginStderr) {- child.stderr.emit("data", Buffer.from(h.state.loginStderr));- }- child.emit("close", 0);- });- } else if (h.state.spawnMode === "error") {- queueMicrotask(() => child.emit("error", new Error("spawn ENOENT")));- }- // "hang": emit nothing — the 3s guard timer must resolve it.- return child;- },-}));--import {- normalizeCodexRateLimits,- parseCodexLoginStatus,- readHarnessUsage,- refreshHarnessUsage,-} from "@/server/harness-usage";--const codexDir = join(h.home, ".codex");-const claudeDir = join(h.home, ".claude");-const authPath = join(codexDir, "auth.json");-const statsPath = join(claudeDir, "stats-cache.json");-const today = () => new Date().toISOString().slice(0, 10);--function writeAuth(auth: unknown): void {- mkdirSync(codexDir, { recursive: true });- writeFileSync(authPath, JSON.stringify(auth), "utf8");-}--function writeStats(stats: unknown): void {- mkdirSync(claudeDir, { recursive: true });- writeFileSync(- statsPath,- typeof stats === "string" ? stats : JSON.stringify(stats),- "utf8",- );-}--/** Base64url-encode JWT claims into a decodable fake id_token. */-function fakeIdToken(claims: Record<string, unknown>): string {- const body = Buffer.from(JSON.stringify(claims)).toString("base64url");- return `hdr.${body}.sig`;-}--beforeEach(() => {- rmSync(codexDir, { recursive: true, force: true });- rmSync(claudeDir, { recursive: true, force: true });- h.state.loginOutput = "Logged in using ChatGPT\n";- h.state.loginStderr = "";- h.state.spawnMode = "close";- h.state.killThrows = false;- h.state.spawns = [];- vi.unstubAllGlobals();-});--afterEach(() => {- vi.useRealTimers();- vi.unstubAllGlobals();-});--describe("claude-code-local usage", () => {- it("reports zeros + stale when stats-cache.json doesn't exist", async () => {- await expect(refreshHarnessUsage("claude-code-local")).resolves.toEqual({- kind: "claude-code",- messagesToday: 0,- sessionsToday: 0,- tokensToday: 0,- stale: true,- lastComputedDate: null,- });- });-- it("rolls up today's messages, sessions, and tokens across models", async () => {- writeStats({- dailyActivity: [- { date: "2020-01-01", messageCount: 999, sessionCount: 99 },- { date: today(), messageCount: 12, sessionCount: 3 },- ],- dailyModelTokens: [- {- date: today(),- tokensByModel: { "claude-fable-5": 1000, "claude-haiku": 250, bogus: "x" },- },- ],- lastComputedDate: today(),- });- await expect(refreshHarnessUsage("claude-code-local")).resolves.toEqual({- kind: "claude-code",- messagesToday: 12,- sessionsToday: 3,- tokensToday: 1250,- stale: false,- lastComputedDate: today(),- });- });-- it("flags a snapshot last computed on an earlier day as stale", async () => {- writeStats({- dailyActivity: [],- lastComputedDate: "2020-01-01",- });- await expect(refreshHarnessUsage("claude-code-local")).resolves.toMatchObject({- stale: true,- lastComputedDate: "2020-01-01",- messagesToday: 0,- tokensToday: 0,- });- });-- it("collapses malformed JSON to the unknown shape", async () => {- writeStats("{not json");- await expect(refreshHarnessUsage("claude-code-local")).resolves.toEqual({- kind: "unknown",- });- });-- it("serves from the 60s cache until refreshed", async () => {- writeStats({ dailyActivity: [], lastComputedDate: today() });- const first = await refreshHarnessUsage("claude-code-local");- // Mutate the file — a cached read must not see it.- writeStats({- dailyActivity: [{ date: today(), messageCount: 5, sessionCount: 1 }],- lastComputedDate: today(),- });- await expect(readHarnessUsage("claude-code-local")).resolves.toBe(first);- // refresh drops the cache entry.- await expect(refreshHarnessUsage("claude-code-local")).resolves.toMatchObject({- messagesToday: 5,- });- });-});--describe("codex-local usage", () => {- it("reports login status with no rate limits when auth.json is missing", async () => {- const fetchSpy = vi.fn();- vi.stubGlobal("fetch", fetchSpy);- await expect(refreshHarnessUsage("codex-local")).resolves.toEqual({- kind: "codex",- auth: "chatgpt",- plan: null,- email: null,- rateLimits: [],- });- expect(h.state.spawns[0]!.args).toEqual(["login", "status"]);- expect(fetchSpy).not.toHaveBeenCalled();- });-- it("infers auth from auth.json when the CLI's answer is unrecognized", async () => {- h.state.loginOutput = "codex 0.99 — usage: codex [options]\n";- writeAuth({ auth_mode: "apikey", tokens: { access_token: "tok" } });- const fetchSpy = vi.fn(async () => ({ ok: false }));- vi.stubGlobal("fetch", fetchSpy);- await expect(refreshHarnessUsage("codex-local")).resolves.toMatchObject({- kind: "codex",- auth: "api-key",- });- });-- it("stops at auth status when there's no access token", async () => {- h.state.loginOutput = "Not logged in\n";- writeAuth({ tokens: {} });- const fetchSpy = vi.fn();- vi.stubGlobal("fetch", fetchSpy);- await expect(refreshHarnessUsage("codex-local")).resolves.toEqual({- kind: "codex",- auth: "signed-out",- plan: null,- email: null,- rateLimits: [],- });- expect(fetchSpy).not.toHaveBeenCalled();- });-- it("combines JWT identity with live wham/usage windows", async () => {- writeAuth({- tokens: {- access_token: "tok-123",- account_id: "acct-9",- id_token: fakeIdToken({- email: "[email protected]",- "https://api.openai.com/auth": {- chatgpt_account_id: "acct-from-jwt",- chatgpt_plan_type: "plus",- },- }),- },- });- const fetchSpy = vi.fn(async (url: string, init: { headers: Record<string, string> }) => {- expect(url).toBe("https://chatgpt.com/backend-api/wham/usage");- expect(init.headers.Authorization).toBe("Bearer tok-123");- // Explicit account_id wins over the JWT-derived one.- expect(init.headers["ChatGPT-Account-Id"]).toBe("acct-9");- return {- ok: true,- json: async () => ({- plan_type: "pro",- rate_limit: {- primary_window: {- used_percent: 12,- limit_window_seconds: 604_800,- reset_at: 1_800_000_000,- },- secondary_window: {- used_percent: 44,- limit_window_seconds: 18_000,- reset_at: 1_790_000_000,- },- },- }),- };- });- vi.stubGlobal("fetch", fetchSpy);-- await expect(refreshHarnessUsage("codex-local")).resolves.toEqual({- kind: "codex",- auth: "chatgpt",- plan: "pro",- email: "[email protected]",- rateLimits: [- {- label: "5-hour",- used_percent: 44,- limit_window_seconds: 18_000,- reset_at: 1_790_000_000,- },- {- label: "Weekly",- used_percent: 12,- limit_window_seconds: 604_800,- reset_at: 1_800_000_000,- },- ],- });- });-- it("keeps the JWT plan when the usage endpoint is unreachable", async () => {- writeAuth({- tokens: {- access_token: "tok-123",- id_token: fakeIdToken({- email: "[email protected]",- "https://api.openai.com/auth": {- chatgpt_account_id: "acct-from-jwt",- chatgpt_plan_type: "plus",- },- }),- },- });- vi.stubGlobal(- "fetch",- vi.fn(async () => {- throw new Error("network down");- }),- );- await expect(refreshHarnessUsage("codex-local")).resolves.toEqual({- kind: "codex",- auth: "chatgpt",- plan: "plus",- email: "[email protected]",- rateLimits: [],- });- });-- it("tolerates a malformed id_token", async () => {- writeAuth({ tokens: { access_token: "tok", id_token: "only-one-part" } });- vi.stubGlobal("fetch", vi.fn(async () => ({ ok: false })));- await expect(refreshHarnessUsage("codex-local")).resolves.toMatchObject({- email: null,- plan: null,- });- });-- it("reads stderr and error events from the login-status child", async () => {- h.state.loginOutput = "";- h.state.loginStderr = "Logged in using agent identity\n";- const fetchSpy = vi.fn();- vi.stubGlobal("fetch", fetchSpy);- await expect(refreshHarnessUsage("codex-local")).resolves.toMatchObject({- auth: "agent-identity",- });-- h.state.spawnMode = "error";- await expect(refreshHarnessUsage("codex-local")).resolves.toMatchObject({- auth: "unknown",- });- });-- it("times out a wedged codex CLI instead of hanging the sidebar", async () => {- vi.useFakeTimers();- h.state.spawnMode = "hang";- h.state.killThrows = true; // kill() on an exited child must be swallowed- const pending = refreshHarnessUsage("codex-local");- await vi.advanceTimersByTimeAsync(3_000);- await expect(pending).resolves.toMatchObject({ kind: "codex", auth: "unknown" });- });-- it("returns unknown for an unrecognized adapter id", async () => {- await expect(- refreshHarnessUsage("bogus-adapter" as never),- ).resolves.toEqual({ kind: "unknown" });- });-});--describe("normalizeCodexRateLimits labels", () => {- const window = (limit_window_seconds: number) => ({- used_percent: 1,- limit_window_seconds,- reset_at: 1,- });-- it("labels known and derived window durations", () => {- expect(- normalizeCodexRateLimits({ primary_window: window(86_400) })[0]!.label,- ).toBe("Daily");- expect(- normalizeCodexRateLimits({ primary_window: window(172_800) })[0]!.label,- ).toBe("2-day");- expect(- normalizeCodexRateLimits({ primary_window: window(7_200) })[0]!.label,- ).toBe("2-hour");- expect(- normalizeCodexRateLimits({ primary_window: window(1_234) })[0]!.label,- ).toBe("Usage");- });-- it("filters malformed windows and handles a missing rate_limit block", () => {- expect(normalizeCodexRateLimits(undefined)).toEqual([]);- expect(normalizeCodexRateLimits(null)).toEqual([]);- expect(- normalizeCodexRateLimits({- primary_window: { used_percent: 5 } as never,- secondary_window: window(18_000),- }),- ).toEqual([{ ...window(18_000), label: "5-hour" }]);- });-});--describe("parseCodexLoginStatus", () => {- it("recognizes agent identity and falls back to unknown", () => {- expect(parseCodexLoginStatus("Logged in using agent identity\n")).toBe(- "agent-identity",- );- expect(parseCodexLoginStatus("something else entirely")).toBe("unknown");- });-});diff --git a/notfair/src/server/harness-usage.test.ts b/notfair/src/server/harness-usage.test.tsdeleted file mode 100644index 84b77fd1..00000000--- a/notfair/src/server/harness-usage.test.ts+++ /dev/null@@ -1,34 +0,0 @@-import { describe, expect, it } from "vitest";--import {- normalizeCodexRateLimits,- parseCodexLoginStatus,-} from "@/server/harness-usage";--describe("Codex harness usage normalization", () => {- it("keeps a valid single weekly window instead of treating it as signed out", () => {- expect(- normalizeCodexRateLimits({- primary_window: {- used_percent: 8,- limit_window_seconds: 604_800,- reset_at: 1_784_487_546,- },- secondary_window: null,- }),- ).toEqual([- {- label: "Weekly",- used_percent: 8,- limit_window_seconds: 604_800,- reset_at: 1_784_487_546,- },- ]);- });-- it("recognizes the CLI's supported login status messages", () => {- expect(parseCodexLoginStatus("Logged in using ChatGPT\n")).toBe("chatgpt");- expect(parseCodexLoginStatus("Logged in using an API key\n")).toBe("api-key");- expect(parseCodexLoginStatus("Not logged in\n")).toBe("signed-out");- });-});diff --git a/notfair/src/server/harness-usage.ts b/notfair/src/server/harness-usage.tsdeleted file mode 100644index d0ce5221..00000000--- a/notfair/src/server/harness-usage.ts+++ /dev/null@@ -1,349 +0,0 @@-import fs from "node:fs";-import os from "node:os";-import path from "node:path";-import { spawn } from "node:child_process";-import { resolveCodexBinary } from "@/server/adapters/codex-local/binary";--/**- * Read what each local AI-agent harness exposes about the user's account- * so the sidebar footer can surface real account state instead of just- * the harness name.- *- * - **codex-local** → hits `https://chatgpt.com/backend-api/wham/usage`- * using the access token from `~/.codex/auth.json`. That's the same- * endpoint the ChatGPT settings page reads to render the 5-hour and- * weekly usage bars. Returns `used_percent`, the rolling window- * duration, and the unix-epoch `reset_at` for both windows.- * Cached in-process so navigating between pages doesn't beat on- * chatgpt.com once per render.- *- * - **claude-code-local** → `~/.claude/stats-cache.json`. Updated by- * the `claude` CLI on each run; contains per-day message/session/- * token rollups. Goes stale when `claude` hasn't run today, which- * we surface so the UI doesn't pretend a stale snapshot is "today".- *- * Failure modes (network error, missing/expired token, missing file,- * malformed JSON) all fall through to the harness-specific `unknown`- * shape — the sidebar footer must never break because chatgpt.com is- * unreachable or `auth.json` was rotated.- */--export type RateLimitWindow = {- /** Fractional percent already consumed in the rolling window. */- used_percent: number;- /** Length of the rolling window (e.g. 18000 = 5h, 604800 = 7d). */- limit_window_seconds: number;- /** Unix epoch (seconds) when this window's usage tally resets. */- reset_at: number;-};--export type LabeledRateLimitWindow = RateLimitWindow & {- /** Stable label derived from the provider's actual window duration. */- label: string;-};--export type CodexAuthStatus =- | "chatgpt"- | "api-key"- | "agent-identity"- | "signed-out"- | "unknown";--export type CodexUsage = {- kind: "codex";- /** Authentication comes from `codex login status`, not usage shape. */- auth: CodexAuthStatus;- /** Codex plan name from wham/usage (e.g. "prolite", "pro", "free"). */- plan: string | null;- /** Account email from the JWT — used as a tooltip / accessibility hint. */- email: string | null;- /** Any usage windows returned by the provider, shortest first. */- rateLimits: LabeledRateLimitWindow[];-};--export type ClaudeUsage = {- kind: "claude-code";- messagesToday: number;- sessionsToday: number;- /** Sum across every model that ran today. */- tokensToday: number;- /** True when stats-cache.json hasn't been recomputed today. The UI- * shows a quieter message in this state so the row doesn't read as- * "0 messages today" (true but misleading). */- stale: boolean;- /** YYYY-MM-DD of the latest day stats were rolled up. */- lastComputedDate: string | null;-};--export type HarnessUsage =- | CodexUsage- | ClaudeUsage- | { kind: "unknown" };--// In-process cache keyed by adapter. The chatgpt.com usage endpoint-// updates whenever the user runs codex, so a 60s TTL keeps the bars-// responsive without hammering the backend on every sidebar render.-type CacheEntry = { until: number; value: HarnessUsage };-const cache = new Map<string, CacheEntry>();-const CACHE_TTL_MS = 60_000;--export async function readHarnessUsage(- adapter: "claude-code-local" | "codex-local",-): Promise<HarnessUsage> {- const hit = cache.get(adapter);- if (hit && hit.until > Date.now()) return hit.value;- let value: HarnessUsage;- try {- if (adapter === "codex-local") value = await readCodexUsage();- else if (adapter === "claude-code-local") value = readClaudeUsage();- else value = { kind: "unknown" };- } catch {- value = { kind: "unknown" };- }- cache.set(adapter, { until: Date.now() + CACHE_TTL_MS, value });- return value;-}--/** Force a fresh auth + usage read after an interactive login attempt. */-export async function refreshHarnessUsage(- adapter: "claude-code-local" | "codex-local",-): Promise<HarnessUsage> {- cache.delete(adapter);- return readHarnessUsage(adapter);-}--async function readCodexUsage(): Promise<HarnessUsage> {- let authStatus = await readCodexLoginStatus();- const authFile = path.join(os.homedir(), ".codex", "auth.json");- if (!fs.existsSync(authFile)) {- return {- kind: "codex",- auth: authStatus,- plan: null,- email: null,- rateLimits: [],- };- }- const auth = JSON.parse(fs.readFileSync(authFile, "utf-8")) as {- auth_mode?: string;- tokens?: {- access_token?: string;- id_token?: string;- account_id?: string;- };- };- const accessToken = auth.tokens?.access_token;- if (authStatus === "unknown") {- authStatus = inferAuthStatus(auth.auth_mode, Boolean(accessToken));- }- if (!accessToken) {- return {- kind: "codex",- auth: authStatus,- plan: null,- email: null,- rateLimits: [],- };- }-- // Decode just to pull the email + chatgpt account id (needed as the- // ChatGPT-Account-Id header so the backend scopes the response to- // the right workspace).- const tokenInfo = decodeIdToken(auth.tokens?.id_token);- const email = tokenInfo.email;- const accountId = auth.tokens?.account_id ?? tokenInfo.accountId;-- let plan: string | null = tokenInfo.plan;- let rateLimits: LabeledRateLimitWindow[] = [];- try {- const ctrl = new AbortController();- const t = setTimeout(() => ctrl.abort(), 4000);- const headers: Record<string, string> = {- Authorization: `Bearer ${accessToken}`,- Accept: "application/json",- };- if (accountId) headers["ChatGPT-Account-Id"] = accountId;- try {- const res = await fetch("https://chatgpt.com/backend-api/wham/usage", {- headers,- signal: ctrl.signal,- });- if (res.ok) {- const body = (await res.json()) as {- plan_type?: string;- rate_limit?: {- primary_window?: RateLimitWindow | null;- secondary_window?: RateLimitWindow | null;- };- };- if (typeof body.plan_type === "string") plan = body.plan_type;- rateLimits = normalizeCodexRateLimits(body.rate_limit);- }- } finally {- clearTimeout(t);- }- } catch {- // Network error / abort. Authentication remains independently known.- }-- return { kind: "codex", auth: authStatus, plan, email, rateLimits };-}--function decodeIdToken(idToken: string | undefined): {- email: string | null;- accountId: string | null;- plan: string | null;-} {- if (!idToken) return { email: null, accountId: null, plan: null };- const parts = idToken.split(".");- if (parts.length < 2) return { email: null, accountId: null, plan: null };- try {- const claims = JSON.parse(- Buffer.from(parts[1]!, "base64url").toString("utf-8"),- ) as Record<string, unknown>;- const authClaims =- (claims["https://api.openai.com/auth"] as- | Record<string, unknown>- | undefined) ?? {};- return {- email: typeof claims.email === "string" ? claims.email : null,- accountId:- typeof authClaims.chatgpt_account_id === "string"- ? authClaims.chatgpt_account_id- : null,- plan:- typeof authClaims.chatgpt_plan_type === "string"- ? authClaims.chatgpt_plan_type- : null,- };- } catch {- return { email: null, accountId: null, plan: null };- }-}--export function normalizeCodexRateLimits(- rateLimit:- | {- primary_window?: RateLimitWindow | null;- secondary_window?: RateLimitWindow | null;- }- | null- | undefined,-): LabeledRateLimitWindow[] {- return [rateLimit?.primary_window, rateLimit?.secondary_window]- .filter((window): window is RateLimitWindow => isRateLimitWindow(window))- .sort((a, b) => a.limit_window_seconds - b.limit_window_seconds)- .map((window) => ({ ...window, label: labelForRateLimitWindow(window) }));-}--function isRateLimitWindow(value: unknown): value is RateLimitWindow {- if (!value || typeof value !== "object") return false;- const window = value as Partial<RateLimitWindow>;- return (- typeof window.used_percent === "number" &&- typeof window.limit_window_seconds === "number" &&- typeof window.reset_at === "number"- );-}--function labelForRateLimitWindow(window: RateLimitWindow): string {- const seconds = window.limit_window_seconds;- if (seconds === 18_000) return "5-hour";- if (seconds === 86_400) return "Daily";- if (seconds === 604_800) return "Weekly";- if (seconds % 86_400 === 0) return `${seconds / 86_400}-day`;- if (seconds % 3_600 === 0) return `${seconds / 3_600}-hour`;- return "Usage";-}--export function parseCodexLoginStatus(output: string): CodexAuthStatus {- const normalized = output.trim().toLowerCase();- if (normalized.includes("logged in using chatgpt")) return "chatgpt";- if (normalized.includes("logged in using an api key")) return "api-key";- if (normalized.includes("logged in using agent identity")) {- return "agent-identity";- }- if (normalized.includes("not logged in")) return "signed-out";- return "unknown";-}--async function readCodexLoginStatus(): Promise<CodexAuthStatus> {- return new Promise((resolve) => {- let output = "";- let settled = false;- const child = spawn(resolveCodexBinary(), ["login", "status"], {- stdio: ["ignore", "pipe", "pipe"],- });- const finish = () => {- if (settled) return;- settled = true;- clearTimeout(timer);- resolve(parseCodexLoginStatus(output));- };- const timer = setTimeout(() => {- try {- child.kill("SIGTERM");- } catch {- // Ignore a process that already exited.- }- finish();- }, 3_000);- child.stdout.on("data", (chunk: Buffer) => (output += chunk.toString("utf8")));- child.stderr.on("data", (chunk: Buffer) => (output += chunk.toString("utf8")));- child.once("error", finish);- child.once("close", finish);- });-}--function inferAuthStatus(- authMode: string | undefined,- hasAccessToken: boolean,-): CodexAuthStatus {- if (!hasAccessToken) return "unknown";- if (authMode === "chatgpt") return "chatgpt";- if (authMode === "apikey" || authMode === "api-key") return "api-key";- return "unknown";-}--function readClaudeUsage(): HarnessUsage {- const file = path.join(os.homedir(), ".claude", "stats-cache.json");- if (!fs.existsSync(file)) {- return {- kind: "claude-code",- messagesToday: 0,- sessionsToday: 0,- tokensToday: 0,- stale: true,- lastComputedDate: null,- };- }- const stats = JSON.parse(fs.readFileSync(file, "utf-8")) as {- dailyActivity?: Array<{- date: string;- messageCount?: number;- sessionCount?: number;- }>;- dailyModelTokens?: Array<{- date: string;- tokensByModel?: Record<string, number>;- }>;- lastComputedDate?: string;- };- const today = new Date().toISOString().slice(0, 10);- const todayActivity = stats.dailyActivity?.find((d) => d.date === today);- const todayTokens = stats.dailyModelTokens?.find((d) => d.date === today);- const tokensSum = todayTokens- ? Object.values(todayTokens.tokensByModel ?? {}).reduce(- (sum, v) => sum + (typeof v === "number" ? v : 0),- 0,- )- : 0;- return {- kind: "claude-code",- messagesToday: todayActivity?.messageCount ?? 0,- sessionsToday: todayActivity?.sessionCount ?? 0,- tokensToday: tokensSum,- stale: stats.lastComputedDate !== today,- lastComputedDate: stats.lastComputedDate ?? null,- };-}diff --git a/notfair/src/server/live-events/emitter.test.ts b/notfair/src/server/live-events/emitter.test.tsdeleted file mode 100644index 88812347..00000000--- a/notfair/src/server/live-events/emitter.test.ts+++ /dev/null@@ -1,18 +0,0 @@-import { expect, it, vi } from "vitest";--import { publishSessionEvent, subscribeSessionEvents } from "./emitter";--it("publishes only to the matching session and unsubscribes", () => {- const one = vi.fn();- const two = vi.fn();- const offOne = subscribeSessionEvents("one", one);- const offTwo = subscribeSessionEvents("two", two);- const event = { id: "e", session_id: "one", seq: 1, kind: "user", payload_json: "{}", created_at: "now" } as const;- publishSessionEvent("one", event);- expect(one).toHaveBeenCalledWith(event);- expect(two).not.toHaveBeenCalled();- offOne();- publishSessionEvent("one", event);- expect(one).toHaveBeenCalledTimes(1);- offTwo();-});diff --git a/notfair/src/server/live-events/emitter.ts b/notfair/src/server/live-events/emitter.tsdeleted file mode 100644index 229f4087..00000000--- a/notfair/src/server/live-events/emitter.ts+++ /dev/null@@ -1,53 +0,0 @@-import { EventEmitter } from "node:events";-import type { TranscriptEvent } from "@/server/sessions";--/**- * In-process pub/sub for transcript events.- *- * Mirrors paperclip's live-events EventEmitter pattern: every time the- * dispatcher persists a row to `transcript_events`, it also publishes the- * event to subscribers keyed by `session_id`. SSE bridges open during a- * live turn receive the event in milliseconds instead of waiting for the- * next 500ms DB poll.- *- * Single-process only (NotFair is a local Next.js app). If we ever- * cluster, swap this for a Redis pub/sub or move events through the DB- * with NOTIFY/LISTEN — same subscriber API at the call site.- */-const emitter = new EventEmitter();-// Generous default — many tabs can attach to the same session on a single-// machine (user has multiple windows / agents page polls + chat tab open).-emitter.setMaxListeners(50);--export type SessionEventListener = (event: TranscriptEvent) => void;--/**- * Subscribe to all transcript events for one session. Returns an- * unsubscribe callback the caller MUST invoke when the consumer goes- * away (SSE client disconnect, route shutdown), otherwise we leak- * listeners.- */-export function subscribeSessionEvents(- session_id: string,- listener: SessionEventListener,-): () => void {- emitter.on(session_id, listener);- return () => {- emitter.off(session_id, listener);- };-}--/**- * Publish a transcript event to all live subscribers for a session.- *- * Called by `appendTranscriptEvent` immediately AFTER the SQLite INSERT- * commits — the DB write is the source of truth and the emit is a best-- * effort push notification. A late or missed listener can always- * recover by re-reading the table from the last-seen `seq`.- */-export function publishSessionEvent(- session_id: string,- event: TranscriptEvent,-): void {- emitter.emit(session_id, event);-}diff --git a/notfair/src/server/mcp-catalog.test.ts b/notfair/src/server/mcp-catalog.test.tsdeleted file mode 100644index e9e5dd6e..00000000--- a/notfair/src/server/mcp-catalog.test.ts+++ /dev/null@@ -1,118 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--import {- MCP_CATALOG_PRESETS,- getMcpCatalog,- getMcpPresets,- isPresetKey,- mcpSpecByKey,-} from "./mcp-catalog";-import { listUserMcpServers } from "@/server/db/user-mcp-servers";-import { getHiddenMcpPresetKeys } from "@/server/db/projects";-import type { UserMcpServer } from "@/server/db/user-mcp-servers";--vi.mock("@/server/db/user-mcp-servers", () => ({- listUserMcpServers: vi.fn(),-}));-vi.mock("@/server/db/projects", () => ({- getHiddenMcpPresetKeys: vi.fn(),-}));--const listUserMcpServersMock = vi.mocked(listUserMcpServers);-const getHiddenMcpPresetKeysMock = vi.mocked(getHiddenMcpPresetKeys);--function userRow(overrides: Partial<UserMcpServer> = {}): UserMcpServer {- return {- project_slug: "proj",- key: "custom-server",- display_name: "Custom",- description: "A user-added server",- resource_url: "https://mcp.custom.dev/v1",- discovery_url: "https://mcp.custom.dev/.well-known/oauth-protected-resource/v1",- created_at: "2026-01-01T00:00:00.000Z",- ...overrides,- } as UserMcpServer;-}--beforeEach(() => {- listUserMcpServersMock.mockReset().mockReturnValue([]);- getHiddenMcpPresetKeysMock.mockReset().mockReturnValue([]);-});--describe("isPresetKey / getMcpPresets", () => {- it("recognizes every shipped preset key", () => {- for (const preset of MCP_CATALOG_PRESETS) {- expect(isPresetKey(preset.key)).toBe(true);- }- expect(isPresetKey("custom-server")).toBe(false);- });-- it("getMcpPresets returns the static preset list", () => {- expect(getMcpPresets()).toBe(MCP_CATALOG_PRESETS);- expect(getMcpPresets().every((p) => p.source === "preset")).toBe(true);- });-- it("points every NotFair preset at the canonical MCP resource", () => {- expect(new Set(MCP_CATALOG_PRESETS.map((p) => p.resource_url))).toEqual(- new Set(["https://notfair.co/api/mcp/notfair"]),- );- expect(new Set(MCP_CATALOG_PRESETS.map((p) => p.discovery_url))).toEqual(- new Set([- "https://notfair.co/.well-known/oauth-protected-resource/api/mcp/notfair",- ]),- );- });-});--describe("getMcpCatalog", () => {- it("returns presets first, then user rows tagged source:'user'", () => {- listUserMcpServersMock.mockReturnValue([userRow()]);- const catalog = getMcpCatalog("proj");- expect(catalog.slice(0, MCP_CATALOG_PRESETS.length)).toEqual(MCP_CATALOG_PRESETS);- expect(catalog.at(-1)).toEqual({- key: "custom-server",- display_name: "Custom",- description: "A user-added server",- resource_url: "https://mcp.custom.dev/v1",- discovery_url: "https://mcp.custom.dev/.well-known/oauth-protected-resource/v1",- source: "user",- });- expect(listUserMcpServersMock).toHaveBeenCalledWith("proj");- expect(getHiddenMcpPresetKeysMock).toHaveBeenCalledWith("proj");- });-- it("a preset key shadows a colliding user row", () => {- listUserMcpServersMock.mockReturnValue([- userRow({ key: "notfair-googleads", display_name: "Impostor" }),- ]);- const catalog = getMcpCatalog("proj");- const ads = catalog.filter((m) => m.key === "notfair-googleads");- expect(ads).toHaveLength(1);- expect(ads[0]!.source).toBe("preset");- expect(ads[0]!.display_name).toBe("NotFair Google Ads");- });-- it("hidden presets are removed — and no longer shadow user rows", () => {- getHiddenMcpPresetKeysMock.mockReturnValue(["notfair-xads"]);- listUserMcpServersMock.mockReturnValue([- userRow({ key: "notfair-xads", display_name: "My own X server" }),- ]);- const catalog = getMcpCatalog("proj");- const xads = catalog.filter((m) => m.key === "notfair-xads");- expect(xads).toHaveLength(1);- expect(xads[0]!.source).toBe("user");- expect(xads[0]!.display_name).toBe("My own X server");- });-});--describe("mcpSpecByKey", () => {- it("finds presets and user rows", () => {- listUserMcpServersMock.mockReturnValue([userRow()]);- expect(mcpSpecByKey("proj", "notfair-metaads")?.display_name).toBe("NotFair Meta Ads");- expect(mcpSpecByKey("proj", "custom-server")?.source).toBe("user");- });-- it("returns undefined for unknown keys", () => {- expect(mcpSpecByKey("proj", "nope")).toBeUndefined();- });-});diff --git a/notfair/src/server/mcp-catalog.ts b/notfair/src/server/mcp-catalog.tsdeleted file mode 100644index a05c1e18..00000000--- a/notfair/src/server/mcp-catalog.ts+++ /dev/null@@ -1,129 +0,0 @@-/**- * Project-scoped catalog of MCP servers the NotFair UI knows about.- *- * Two sources merge into one list:- *- * - Static **presets** (this file): curated entries we ship with —- * server URL + OAuth discovery doc are stable, so the connect flow- * can drive end-to-end with zero LLM in the loop.- * - **User-added** servers (`user_mcp_servers` SQLite table): anything- * the user registers from the Connections page. Same `McpSpec` shape;- * distinguished by `source: 'user'` so the UI can offer a "Remove"- * action.- *- * Everything downstream of the catalog (OAuth callback, token storage in- * `mcp_tokens`, harness adapter `registerMcp`) is keyed off `spec.key`,- * which doubles as `mcp_tokens.server_name`. So both kinds of entries- * flow through the same code paths once registered.- */--import { listUserMcpServers } from "@/server/db/user-mcp-servers";-import { getHiddenMcpPresetKeys } from "@/server/db/projects";-import {- CANONICAL_MCP_DISCOVERY_URL,- CANONICAL_MCP_RESOURCE_URL,-} from "@/lib/canonical-mcp";--export {- CANONICAL_MCP_DISCOVERY_URL,- CANONICAL_MCP_RESOURCE_URL,-} from "@/lib/canonical-mcp";--export type McpSpec = {- /** Stable catalog identifier (used by the UI + mcp_tokens.server_name). */- key: string;- display_name: string;- description: string;- /** Resource URL the token authenticates against (RFC 8707 audience). */- resource_url: string;- /** RFC 9728 protected-resource discovery endpoint. */- discovery_url: string;- /** Where this entry came from — presets are immutable from the UI. */- source: "preset" | "user";-};--export const MCP_CATALOG_PRESETS: McpSpec[] = [- {- key: "notfair-googleads",- display_name: "NotFair Google Ads",- description:- "Live Google Ads operations: campaigns, bids, budgets, keywords, search terms, change history.",- resource_url: CANONICAL_MCP_RESOURCE_URL,- discovery_url: CANONICAL_MCP_DISCOVERY_URL,- source: "preset",- },- {- key: "notfair-metaads",- display_name: "NotFair Meta Ads",- description:- "Live Meta Ads (Facebook + Instagram) operations: campaigns, ad sets, ads, creatives, insights.",- resource_url: CANONICAL_MCP_RESOURCE_URL,- discovery_url: CANONICAL_MCP_DISCOVERY_URL,- source: "preset",- },- {- key: "notfair-googlesearchconsole",- display_name: "NotFair Google Search Console",- description:- "Organic search performance: queries, pages, impressions, clicks, indexing.",- resource_url: CANONICAL_MCP_RESOURCE_URL,- discovery_url: CANONICAL_MCP_DISCOVERY_URL,- source: "preset",- },- {- key: "notfair-googleanalytics",- display_name: "NotFair Google Analytics",- description:- "GA4 traffic and conversion analytics: sessions, channels, pages, events, audiences.",- resource_url: CANONICAL_MCP_RESOURCE_URL,- discovery_url: CANONICAL_MCP_DISCOVERY_URL,- source: "preset",- },- {- key: "notfair-xads",- display_name: "NotFair X Ads",- description:- "Live X (Twitter) Ads operations: campaigns, line items, promoted posts, analytics.",- resource_url: CANONICAL_MCP_RESOURCE_URL,- discovery_url: CANONICAL_MCP_DISCOVERY_URL,- source: "preset",- },-];--/** True if any preset reserves this key. Presets win over user rows. */-export function isPresetKey(key: string): boolean {- return MCP_CATALOG_PRESETS.some((p) => p.key === key);-}--export function getMcpPresets(): McpSpec[] {- return MCP_CATALOG_PRESETS;-}--/**- * Return the merged catalog for a project: presets first, then user-added- * rows. A preset key shadows any colliding user row (which the add-server- * action prevents at insert time, but we double-check on read too).- */-export function getMcpCatalog(project_slug: string): McpSpec[] {- const hidden = new Set(getHiddenMcpPresetKeys(project_slug));- const presets = MCP_CATALOG_PRESETS.filter((p) => !hidden.has(p.key));- const presetKeys = new Set(presets.map((p) => p.key));- const userRows = listUserMcpServers(project_slug)- .filter((row) => !presetKeys.has(row.key))- .map<McpSpec>((row) => ({- key: row.key,- display_name: row.display_name,- description: row.description,- resource_url: row.resource_url,- discovery_url: row.discovery_url,- source: "user",- }));- return [...presets, ...userRows];-}--export function mcpSpecByKey(- project_slug: string,- key: string,-): McpSpec | undefined {- return getMcpCatalog(project_slug).find((m) => m.key === key);-}diff --git a/notfair/src/server/mcp-pending.ts b/notfair/src/server/mcp-pending.tsdeleted file mode 100644index 92d5805c..00000000--- a/notfair/src/server/mcp-pending.ts+++ /dev/null@@ -1,68 +0,0 @@-/**- * In-process map of pending MCP OAuth flows. Keyed by `state` (the CSRF- * token in the authorize URL). Lives in the Next.js server process and is- * lost on restart — that's fine because the flow is short-lived: from- * "click Connect" to "back at callback" is seconds, not days.- *- * Keeping this in-memory (vs. SQLite) avoids a migration + cleanup job for- * what is otherwise transient data. Two entries with the same `state` is- * cryptographically improbable; we still use `consume` (pop, not peek) so- * a replayed callback can't reuse the same exchange context.- */--export type PendingMcpFlow = {- /** Catalog identifier (e.g. `notfair-googleads`) — what the UI shows. */- catalog_key: string;- /** Project-scoped display name; mirrors the catalog spec. */- display_name: string;- resource_url: string;- /** OAuth issuer (the protected resource's authorization server). */- issuer: string;- /** The token endpoint resolved during start. */- token_endpoint: string;- client_id: string;- /** May be undefined for public clients registered with auth_method=none. */- client_secret?: string;- code_verifier: string;- redirect_uri: string;- /** Project slug (the active project at the time the flow started). */- project_slug: string;- /**- * Local path to redirect to after the callback finishes (e.g. the chat- * URL the user started from). Validated to be same-origin/path-only when- * stashed. Falls back to /connections when absent.- */- return_to?: string;- created_at: number;-};--// In Next dev, edits to any file in the action's module graph trigger a-// recompile that re-evaluates this module — a fresh `Map()` drops every-// in-flight flow. Pinning to `globalThis` survives hot reloads because the-// global is not recreated. The single-process invariant still holds (the-// CLI launches one local Next.js server), so we don't need a real KV.-const GLOBAL_KEY = "__notfair_mcp_pending__";-type GlobalSlot = { store?: Map<string, PendingMcpFlow> };-const slot = globalThis as unknown as GlobalSlot;-const STORE: Map<string, PendingMcpFlow> = slot.store ?? (slot.store = new Map());-const TTL_MS = 10 * 60 * 1000;--function evictExpired() {- const cutoff = Date.now() - TTL_MS;- for (const [k, v] of STORE) {- if (v.created_at < cutoff) STORE.delete(k);- }-}--export function setPending(state: string, flow: PendingMcpFlow): void {- evictExpired();- STORE.set(state, flow);-}--export function consumePending(state: string): PendingMcpFlow | null {- evictExpired();- const hit = STORE.get(state);- if (!hit) return null;- STORE.delete(state);- return hit;-}diff --git a/notfair/src/server/mcp-server/browser-tools.test.ts b/notfair/src/server/mcp-server/browser-tools.test.tsdeleted file mode 100644index e5bd5f9b..00000000--- a/notfair/src/server/mcp-server/browser-tools.test.ts+++ /dev/null@@ -1,332 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--const actions = vi.hoisted(() => ({- back: vi.fn(),- click: vi.fn(),- navigate: vi.fn(),- press: vi.fn(),- scroll: vi.fn(),- snapshot: vi.fn(),- type: vi.fn(),-}));-const session = vi.hoisted(() => ({- getOrLaunchBrowser: vi.fn(),- getSessionStatus: vi.fn(),-}));-const tabs = vi.hoisted(() => ({- closeTab: vi.fn(),- getTab: vi.fn(),- listTabs: vi.fn(),- openTab: vi.fn(),-}));--vi.mock("@/server/browser/actions", () => actions);-vi.mock("@/server/browser/session", () => session);-vi.mock("@/server/browser/tabs", () => tabs);--import { BROWSER_TOOLS } from "./browser-tools";-import type { ToolResult } from "./tools";--const PAGE = { fake: "page" };-const BASE = { project_slug: "proj", target_id: "agent-1" };--async function call(name: string, input: unknown): Promise<ToolResult> {- const tool = BROWSER_TOOLS.find((t) => t.name === name);- if (!tool) throw new Error(`no tool ${name}`);- return tool.handler(input, {});-}--function text(result: ToolResult): string {- if (!result.ok) throw new Error(`expected ok result, got: ${result.error}`);- return result.content.map((c) => c.text).join("\n");-}--function errorOf(result: ToolResult): string {- if (result.ok) throw new Error("expected error result");- return result.error;-}--beforeEach(() => {- for (const group of [actions, session, tabs]) {- for (const fn of Object.values(group)) fn.mockReset();- }- tabs.getTab.mockResolvedValue(PAGE);-});--describe("registry", () => {- it("exposes the full browser surface and no shutdown primitive", () => {- expect(BROWSER_TOOLS.map((t) => t.name)).toEqual([- "browser_status",- "browser_tabs",- "browser_open",- "browser_close",- "browser_navigate",- "browser_snapshot",- "browser_click",- "browser_type",- "browser_press",- "browser_scroll",- "browser_back",- ]);- expect(BROWSER_TOOLS.some((t) => t.name.includes("shutdown"))).toBe(false);- });-- it("every tool rejects malformed args", async () => {- for (const tool of BROWSER_TOOLS) {- const r = await tool.handler({}, {});- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toMatch(/^Invalid arguments:/);- }- });-});--describe("browser_status", () => {- it("reports a running session", async () => {- session.getSessionStatus.mockReturnValue({- projectSlug: "proj",- running: true,- cdpPort: 19042,- userDataDir: "/tmp/x/user-data",- uptimeMs: 1234,- idleTimeoutMs: 300_000,- });- const r = await call("browser_status", { project_slug: "proj" });- const parsed = JSON.parse(text(r));- expect(parsed).toMatchObject({ running: true, cdpPort: 19042, uptimeMs: 1234 });- expect(parsed.note).toContain("is running");- expect(session.getSessionStatus).toHaveBeenCalledWith("proj");- });-- it("reports a stopped session with launch guidance", async () => {- session.getSessionStatus.mockReturnValue({- projectSlug: "proj",- running: false,- cdpPort: 19042,- userDataDir: "/tmp/x/user-data",- idleTimeoutMs: 300_000,- });- const r = await call("browser_status", { project_slug: "proj" });- expect(JSON.parse(text(r)).note).toContain("not running");- });-});--describe("browser_tabs", () => {- it("lists tabs as JSON", async () => {- tabs.listTabs.mockResolvedValue([{ id: "agent-1", label: "agent-1", url: "https://x", title: "X" }]);- const r = await call("browser_tabs", { project_slug: "proj" });- expect(JSON.parse(text(r))).toEqual([- { id: "agent-1", label: "agent-1", url: "https://x", title: "X" },- ]);- });-- it("wraps listing failures", async () => {- tabs.listTabs.mockRejectedValue(new Error("chrome died"));- const r = await call("browser_tabs", { project_slug: "proj" });- expect(errorOf(r)).toBe("browser_tabs failed: chrome died");- });-});--describe("browser_open", () => {- it("launches the session then opens the labeled tab", async () => {- session.getOrLaunchBrowser.mockResolvedValue({});- tabs.openTab.mockResolvedValue({ id: "agent-1", label: "agent-1", url: "https://x", title: "" });- const r = await call("browser_open", {- project_slug: "proj",- url: "https://x",- label: "agent-1",- });- expect(session.getOrLaunchBrowser).toHaveBeenCalledWith("proj");- expect(tabs.openTab).toHaveBeenCalledWith("proj", { label: "agent-1", url: "https://x" });- expect(JSON.parse(text(r)).id).toBe("agent-1");- });-- it("rejects a non-URL url and a malformed label", async () => {- expect((await call("browser_open", { project_slug: "proj", url: "not a url" })).ok).toBe(false);- expect(- (await call("browser_open", { project_slug: "proj", label: "-starts-with-dash" })).ok,- ).toBe(false);- expect(session.getOrLaunchBrowser).not.toHaveBeenCalled();- });-- it("wraps launch failures", async () => {- session.getOrLaunchBrowser.mockRejectedValue(new Error("no chrome binary"));- const r = await call("browser_open", { project_slug: "proj" });- expect(errorOf(r)).toBe("browser_open failed: no chrome binary");- });-});--describe("browser_close", () => {- it("reports both the closed and the not-found outcome", async () => {- tabs.closeTab.mockResolvedValueOnce(true).mockResolvedValueOnce(false);- expect(text(await call("browser_close", BASE))).toBe('Closed tab "agent-1".');- expect(text(await call("browser_close", BASE))).toBe('No tab "agent-1" to close.');- expect(tabs.closeTab).toHaveBeenCalledWith("proj", "agent-1");- });-- it("wraps close failures", async () => {- tabs.closeTab.mockRejectedValue(new Error("boom"));- expect(errorOf(await call("browser_close", BASE))).toBe("browser_close failed: boom");- });-});--describe("browser_navigate", () => {- it("navigates the resolved tab and returns url + title", async () => {- actions.navigate.mockResolvedValue({ url: "https://x/after", title: "After" });- const r = await call("browser_navigate", {- ...BASE,- url: "https://x/after",- wait_until: "domcontentloaded",- timeout_ms: 5000,- });- expect(tabs.getTab).toHaveBeenCalledWith("proj", "agent-1");- expect(actions.navigate).toHaveBeenCalledWith(PAGE, {- url: "https://x/after",- waitUntil: "domcontentloaded",- timeoutMs: 5000,- });- expect(JSON.parse(text(r))).toEqual({ url: "https://x/after", title: "After" });- });-- it("fails with guidance when the tab is unknown", async () => {- tabs.getTab.mockResolvedValue(null);- const r = await call("browser_navigate", { ...BASE, url: "https://x" });- expect(errorOf(r)).toContain('No tab "agent-1" in workspace "proj"');- expect(actions.navigate).not.toHaveBeenCalled();- });-- it("caps timeout_ms at 120s", async () => {- const r = await call("browser_navigate", { ...BASE, url: "https://x", timeout_ms: 500_000 });- expect(r.ok).toBe(false);- });-});--describe("browser_snapshot", () => {- const SNAP = {- url: "https://x",- title: "X",- elements: [- { ref: "e1", role: "button", name: "Save" },- { ref: "e2", role: "a", name: "Docs", href: "https://x/docs" },- ],- text: "page text",- };-- it("returns the full snapshot", async () => {- actions.snapshot.mockResolvedValue(SNAP);- const r = await call("browser_snapshot", BASE);- expect(JSON.parse(text(r))).toEqual(SNAP);- });-- it("truncates the element list to max_elements", async () => {- actions.snapshot.mockResolvedValue(SNAP);- const r = await call("browser_snapshot", { ...BASE, max_elements: 1 });- const parsed = JSON.parse(text(r));- expect(parsed.elements).toEqual([SNAP.elements[0]]);- expect(parsed.text).toBe("page text");- });-- it("fails when the tab is unknown", async () => {- tabs.getTab.mockResolvedValue(null);- expect(errorOf(await call("browser_snapshot", BASE))).toContain('No tab "agent-1"');- });-});--describe("browser_click", () => {- it("clicks the ref with the mapped options", async () => {- actions.click.mockResolvedValue(undefined);- const r = await call("browser_click", {- ...BASE,- ref: "e3",- button: "right",- modifiers: ["Meta"],- double_click: true,- timeout_ms: 2000,- });- expect(actions.click).toHaveBeenCalledWith(PAGE, {- ref: "e3",- button: "right",- modifiers: ["Meta"],- doubleClick: true,- timeoutMs: 2000,- });- expect(text(r)).toBe('Clicked e3 on tab "agent-1".');- });-- it("rejects refs that do not look like snapshot refs", async () => {- const r = await call("browser_click", { ...BASE, ref: "button#save" });- expect(r.ok).toBe(false);- expect(actions.click).not.toHaveBeenCalled();- });-});--describe("browser_type", () => {- it("types with mapped options and reports the char count", async () => {- actions.type.mockResolvedValue(undefined);- const r = await call("browser_type", {- ...BASE,- ref: "e2",- text: "hello",- submit: true,- clear_first: false,- });- expect(actions.type).toHaveBeenCalledWith(PAGE, {- ref: "e2",- text: "hello",- submit: true,- clearFirst: false,- timeoutMs: undefined,- });- expect(text(r)).toBe("Typed 5 chars into e2 and submitted.");- });-- it("omits the submit suffix by default", async () => {- actions.type.mockResolvedValue(undefined);- const r = await call("browser_type", { ...BASE, ref: "e2", text: "hi" });- expect(text(r)).toBe("Typed 2 chars into e2.");- });-});--describe("browser_press", () => {- it("presses at the page level without a ref", async () => {- actions.press.mockResolvedValue(undefined);- const r = await call("browser_press", { ...BASE, key: "Escape" });- expect(actions.press).toHaveBeenCalledWith(PAGE, { key: "Escape", ref: undefined });- expect(text(r)).toBe("Pressed Escape.");- });-- it("focuses the ref first when given", async () => {- actions.press.mockResolvedValue(undefined);- const r = await call("browser_press", { ...BASE, key: "Enter", ref: "e4" });- expect(actions.press).toHaveBeenCalledWith(PAGE, { key: "Enter", ref: "e4" });- expect(text(r)).toBe("Pressed Enter on e4.");- });-});--describe("browser_scroll", () => {- it("scrolls with an explicit amount", async () => {- actions.scroll.mockResolvedValue(undefined);- const r = await call("browser_scroll", { ...BASE, direction: "down", amount: 900 });- expect(actions.scroll).toHaveBeenCalledWith(PAGE, { direction: "down", amount: 900 });- expect(text(r)).toBe("Scrolled down by 900px.");- });-- it("omits the pixel clause when using the default amount", async () => {- actions.scroll.mockResolvedValue(undefined);- const r = await call("browser_scroll", { ...BASE, direction: "up" });- expect(text(r)).toBe("Scrolled up.");- });-});--describe("browser_back", () => {- it("navigates back on the tab", async () => {- actions.back.mockResolvedValue(undefined);- const r = await call("browser_back", BASE);- expect(actions.back).toHaveBeenCalledWith(PAGE);- expect(text(r)).toBe('Navigated back on tab "agent-1".');- });-- it("fails when the tab is unknown", async () => {- tabs.getTab.mockResolvedValue(null);- expect(errorOf(await call("browser_back", BASE))).toContain('No tab "agent-1"');- });-});diff --git a/notfair/src/server/mcp-server/browser-tools.ts b/notfair/src/server/mcp-server/browser-tools.tsdeleted file mode 100644index 07880752..00000000--- a/notfair/src/server/mcp-server/browser-tools.ts+++ /dev/null@@ -1,488 +0,0 @@-/**- * MCP tool definitions for the workspace browser.- *- * Agent-facing surface modeled on Hermes' tool shape: many small, typed- * tools rather than one mega-tool with an action discriminator. Each tool- * takes `project_slug` (from IDENTITY.md, used to pick the right workspace- * Chrome) plus the action-specific args. Stable `targetId` handles let- * agents thread state across calls without re-snapshotting tabs.- */-import { z } from "zod";--import {- back as actBack,- click as actClick,- navigate as actNavigate,- press as actPress,- scroll as actScroll,- snapshot as actSnapshot,- type as actType,- type SnapshotElement,-} from "@/server/browser/actions";-import { getOrLaunchBrowser, getSessionStatus } from "@/server/browser/session";-import { closeTab, getTab, listTabs, openTab } from "@/server/browser/tabs";--import type { ToolDefinition, ToolResult } from "./tools";--// ── Shared helpers ─────────────────────────────────────────────────────--const projectSlug = z- .string()- .min(1)- .describe("The project this browser belongs to. From your IDENTITY.md prompt header.");--const targetId = z- .string()- .min(1)- .describe(- "Tab handle from browser_open or browser_tabs. Use your agent_id as the label when opening, then reuse the same label in subsequent calls.",- );--const ref = z- .string()- .regex(/^e\d+$/, "ref must look like 'e1', 'e2', ... from the latest snapshot")- .describe("Element ref from the most recent browser_snapshot call.");--function invalid(err: z.ZodError): ToolResult {- return {- ok: false,- error: `Invalid arguments: ${err.issues- .map((i) => `${i.path.join(".")} ${i.message}`)- .join("; ")}`,- };-}--function txt(text: string): ToolResult {- return { ok: true, content: [{ type: "text", text }] };-}--function fail(message: string): ToolResult {- return { ok: false, error: message };-}--function safeMessage(err: unknown): string {- return err instanceof Error ? err.message : String(err);-}--async function withTab<T>(- project_slug: string,- target: string,- fn: (page: Awaited<ReturnType<typeof getTab>>) => Promise<T>,-): Promise<T | ToolResult> {- const page = await getTab(project_slug, target);- if (!page) {- return fail(- `No tab "${target}" in workspace "${project_slug}". Call browser_tabs to see what's open, or browser_open to create one.`,- );- }- return fn(page);-}--// ── browser_status ─────────────────────────────────────────────────────--const browserStatusInput = z.object({ project_slug: projectSlug });--async function handleBrowserStatus(input: unknown): Promise<ToolResult> {- const parsed = browserStatusInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const status = getSessionStatus(parsed.data.project_slug);- return txt(- JSON.stringify(- {- running: status.running,- cdpPort: status.cdpPort,- userDataDir: status.userDataDir,- uptimeMs: status.uptimeMs,- // V1 has no real signed-in check; surface the user-data-dir so- // agents/users know cookies persist across restarts.- note: status.running- ? "Workspace browser is running. Use browser_tabs to list windows."- : "Workspace browser is not running. The first browser_open will launch it.",- },- null,- 2,- ),- );-}--// ── browser_tabs ───────────────────────────────────────────────────────--const browserTabsInput = z.object({ project_slug: projectSlug });--async function handleBrowserTabs(input: unknown): Promise<ToolResult> {- const parsed = browserTabsInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- try {- const tabs = await listTabs(parsed.data.project_slug);- return txt(JSON.stringify(tabs, null, 2));- } catch (err) {- return fail(`browser_tabs failed: ${safeMessage(err)}`);- }-}--// ── browser_open ───────────────────────────────────────────────────────--const browserOpenInput = z.object({- project_slug: projectSlug,- url: z.string().url().optional().describe("Initial URL. Omit to open about:blank."),- label: z- .string()- .regex(/^[a-z0-9][a-z0-9_\-]{0,63}$/i)- .optional()- .describe(- "Stable handle for future calls. Recommended: your agent_id. Reusing an existing label navigates that tab instead of opening a duplicate.",- ),-});--async function handleBrowserOpen(input: unknown): Promise<ToolResult> {- const parsed = browserOpenInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, url, label } = parsed.data;- try {- // Ensure the session is up — first open triggers the Chrome launch.- await getOrLaunchBrowser(project_slug);- const handle = await openTab(project_slug, { label, url });- return txt(JSON.stringify(handle, null, 2));- } catch (err) {- return fail(`browser_open failed: ${safeMessage(err)}`);- }-}--// ── browser_close ──────────────────────────────────────────────────────--const browserCloseInput = z.object({- project_slug: projectSlug,- target_id: targetId,-});--async function handleBrowserClose(input: unknown): Promise<ToolResult> {- const parsed = browserCloseInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, target_id } = parsed.data;- try {- const ok = await closeTab(project_slug, target_id);- return txt(ok ? `Closed tab "${target_id}".` : `No tab "${target_id}" to close.`);- } catch (err) {- return fail(`browser_close failed: ${safeMessage(err)}`);- }-}--// ── browser_navigate ───────────────────────────────────────────────────--const browserNavigateInput = z.object({- project_slug: projectSlug,- target_id: targetId,- url: z.string().url(),- wait_until: z.enum(["load", "domcontentloaded", "networkidle", "commit"]).optional(),- timeout_ms: z.number().int().positive().max(120_000).optional(),-});--async function handleBrowserNavigate(input: unknown): Promise<ToolResult> {- const parsed = browserNavigateInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, target_id, url, wait_until, timeout_ms } = parsed.data;- const result = await withTab(project_slug, target_id, async (page) => {- const r = await actNavigate(page!, { url, waitUntil: wait_until, timeoutMs: timeout_ms });- return txt(JSON.stringify(r, null, 2));- });- if (isToolResult(result)) return result;- return result;-}--// ── browser_snapshot ───────────────────────────────────────────────────--const browserSnapshotInput = z.object({- project_slug: projectSlug,- target_id: targetId,- /** Truncate the element list shown to the model. Underlying snapshot may have more. */- max_elements: z.number().int().positive().max(200).optional(),-});--async function handleBrowserSnapshot(input: unknown): Promise<ToolResult> {- const parsed = browserSnapshotInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, target_id, max_elements } = parsed.data;- const result = await withTab(project_slug, target_id, async (page) => {- const snap = await actSnapshot(page!);- const elements: SnapshotElement[] = max_elements- ? snap.elements.slice(0, max_elements)- : snap.elements;- return txt(- JSON.stringify(- {- url: snap.url,- title: snap.title,- elements,- text: snap.text,- },- null,- 2,- ),- );- });- if (isToolResult(result)) return result;- return result;-}--// ── browser_click ──────────────────────────────────────────────────────--const browserClickInput = z.object({- project_slug: projectSlug,- target_id: targetId,- ref: ref,- button: z.enum(["left", "right", "middle"]).optional(),- modifiers: z.array(z.enum(["Alt", "Control", "Meta", "Shift"])).optional(),- double_click: z.boolean().optional(),- timeout_ms: z.number().int().positive().max(30_000).optional(),-});--async function handleBrowserClick(input: unknown): Promise<ToolResult> {- const parsed = browserClickInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, target_id, ref, button, modifiers, double_click, timeout_ms } = parsed.data;- const result = await withTab(project_slug, target_id, async (page) => {- await actClick(page!, {- ref,- button,- modifiers,- doubleClick: double_click,- timeoutMs: timeout_ms,- });- return txt(`Clicked ${ref} on tab "${target_id}".`);- });- if (isToolResult(result)) return result;- return result;-}--// ── browser_type ───────────────────────────────────────────────────────--const browserTypeInput = z.object({- project_slug: projectSlug,- target_id: targetId,- ref: ref,- text: z.string(),- submit: z.boolean().optional().describe("Press Enter after typing."),- clear_first: z.boolean().optional().describe("Clear the field before typing. Default true."),- timeout_ms: z.number().int().positive().max(30_000).optional(),-});--async function handleBrowserType(input: unknown): Promise<ToolResult> {- const parsed = browserTypeInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, target_id, ref, text, submit, clear_first, timeout_ms } = parsed.data;- const result = await withTab(project_slug, target_id, async (page) => {- await actType(page!, {- ref,- text,- submit,- clearFirst: clear_first,- timeoutMs: timeout_ms,- });- return txt(`Typed ${text.length} chars into ${ref}${submit ? " and submitted" : ""}.`);- });- if (isToolResult(result)) return result;- return result;-}--// ── browser_press ──────────────────────────────────────────────────────--const browserPressInput = z.object({- project_slug: projectSlug,- target_id: targetId,- key: z- .string()- .min(1)- .describe("Playwright key string, e.g. 'Enter', 'Tab', 'Control+a', 'ArrowDown'."),- ref: z- .string()- .regex(/^e\d+$/)- .optional()- .describe("Focus this element before pressing. Omit to press at the page/keyboard level."),-});--async function handleBrowserPress(input: unknown): Promise<ToolResult> {- const parsed = browserPressInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, target_id, key, ref } = parsed.data;- const result = await withTab(project_slug, target_id, async (page) => {- await actPress(page!, { key, ref });- return txt(`Pressed ${key}${ref ? ` on ${ref}` : ""}.`);- });- if (isToolResult(result)) return result;- return result;-}--// ── browser_scroll ─────────────────────────────────────────────────────--const browserScrollInput = z.object({- project_slug: projectSlug,- target_id: targetId,- direction: z.enum(["up", "down", "left", "right"]),- amount: z.number().int().positive().max(10_000).optional(),-});--async function handleBrowserScroll(input: unknown): Promise<ToolResult> {- const parsed = browserScrollInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, target_id, direction, amount } = parsed.data;- const result = await withTab(project_slug, target_id, async (page) => {- await actScroll(page!, { direction, amount });- return txt(`Scrolled ${direction}${amount ? ` by ${amount}px` : ""}.`);- });- if (isToolResult(result)) return result;- return result;-}--// ── browser_back ───────────────────────────────────────────────────────--const browserBackInput = z.object({- project_slug: projectSlug,- target_id: targetId,-});--async function handleBrowserBack(input: unknown): Promise<ToolResult> {- const parsed = browserBackInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, target_id } = parsed.data;- const result = await withTab(project_slug, target_id, async (page) => {- await actBack(page!);- return txt(`Navigated back on tab "${target_id}".`);- });- if (isToolResult(result)) return result;- return result;-}--// browser_shutdown is intentionally NOT exposed as an agent tool. With multiple-// agents sharing one workspace Chrome, any agent calling shutdown would kill-// the browser out from under the others mid-task. Browser lifecycle stays-// owned by the user (Settings → Workspace browser → Stop) and by process exit-// hooks. The /api/browser/shutdown route imports stopBrowser directly from-// session.ts; agents do not get this primitive.--// ── Helpers ────────────────────────────────────────────────────────────--function isToolResult(x: unknown): x is ToolResult {- return (- typeof x === "object" &&- x !== null &&- "ok" in x &&- (("content" in x && Array.isArray((x as ToolResult & { content?: unknown }).content)) ||- "error" in x)- );-}--// ── Registry export ────────────────────────────────────────────────────--// ─── Tool descriptions ───────────────────────────────────────────────────-// Following Hermes' convention (tools/browser_tool.py:1473), every browser-// tool description does explicit traffic control: when to use it, when-// something else is better, and (importantly) what NOT to fall back to.-// This matters because NotFair runs agents under Codex CLI / Claude-// Code, both of which may ship bundled "browser" plugins that compete-// for the same intent. Strong descriptions outcompete generic plugins by-// making the right tool obviously the right choice.--const ROUTING_PREAMBLE =- "This is the ONLY browser tool that drives the NotFair workspace browser " +- "(persistent profile at ~/.notfair/projects/<slug>/browser/, shared by " +- "every agent in the project, where the user has signed into Google/Meta/etc.). " +- "Do NOT use any other 'browser-use' plugin, `open -a 'Google Chrome'` shell " +- "commands, AppleScript, or similar — those launch a different Chrome with the " +- "user's personal profile and your work won't persist for other agents in this " +- "project.";--export const BROWSER_TOOLS: ToolDefinition[] = [- {- name: "browser_status",- description:- "Check whether the workspace browser is running, on which port, and where its profile lives. Cheap; safe to call any time. " +- ROUTING_PREAMBLE,- inputSchema: browserStatusInput,- handler: handleBrowserStatus,- },- {- name: "browser_tabs",- description:- "List every tab in the workspace browser with handle, URL, and title. Call before browser_open to find an existing tab you can reuse instead of duplicating. " +- ROUTING_PREAMBLE,- inputSchema: browserTabsInput,- handler: handleBrowserTabs,- },- {- name: "browser_open",- description:- "Open (or reuse) a tab in the workspace browser. THIS is the tool to call when the user says 'launch the browser', 'open a page', 'go to <URL>', etc. " +- "Pass your agent_id as `label` so future calls can target the tab by handle; reusing an existing label navigates that tab instead of duplicating it. " +- "Returns a TabHandle with `id` you pass as `target_id` to subsequent browser_* calls. " +- "For plain-text fetches (.json, .txt, .md, raw GitHub URLs, documented HTTP APIs) prefer curl via the shell — the browser stack is overkill. " +- "But for ANYTHING that needs a real browser (logged-in dashboards, dynamic pages, sign-in flows, Google Ads/Search Console/Meta UIs), use browser_open. " +- ROUTING_PREAMBLE,- inputSchema: browserOpenInput,- handler: handleBrowserOpen,- },- {- name: "browser_close",- description:- "Close a tab by handle. Safe no-op if the handle is unknown. Does NOT stop the workspace browser — only the user can do that via Settings.",- inputSchema: browserCloseInput,- handler: handleBrowserClose,- },- {- name: "browser_navigate",- description:- "Navigate an EXISTING tab (already opened via browser_open) to a new URL. Returns the loaded URL + title. " +- "For opening a brand-new tab, use browser_open instead. " +- ROUTING_PREAMBLE,- inputSchema: browserNavigateInput,- handler: handleBrowserNavigate,- },- {- name: "browser_snapshot",- description:- "Capture the page's interactable elements (buttons, links, inputs, etc.) with stable refs like e1/e2 plus a text excerpt. " +- "Snapshot the tab before EVERY click/type so refs are fresh — refs from a prior snapshot become stale after navigation, form submit, or DOM mutation, and stale refs fail with a clear error. " +- "If you ever see 'ref e3 not found', the answer is always: snapshot again, then retry with the new ref. Never blindly retry the same ref.",- inputSchema: browserSnapshotInput,- handler: handleBrowserSnapshot,- },- {- name: "browser_click",- description:- "Click an element by ref from the LATEST browser_snapshot on the same tab. Supports right/middle/double click and keyboard modifiers (Meta/Control/Alt/Shift). " +- "If the ref is stale, snapshot the tab again and retry with the new ref — don't keep clicking a missing ref.",- inputSchema: browserClickInput,- handler: handleBrowserClick,- },- {- name: "browser_type",- description:- "Type text into an input/textarea/contenteditable ref. By default clears the field first; pass clear_first=false to append. " +- "Set submit=true to press Enter when done (use this for search boxes, login forms). " +- "Ref must come from the most recent browser_snapshot — re-snapshot if the page has changed since.",- inputSchema: browserTypeInput,- handler: handleBrowserType,- },- {- name: "browser_press",- description:- "Press a single key or key combo (e.g. 'Enter', 'Tab', 'Escape', 'Control+a', 'ArrowDown'). " +- "With `ref` set, focuses that element first; without, presses at the page/keyboard level — use the ref-less form to dismiss modals (Escape) or trigger global shortcuts.",- inputSchema: browserPressInput,- handler: handleBrowserPress,- },- {- name: "browser_scroll",- description:- "Scroll the viewport up/down/left/right by `amount` pixels (default ~600, about one screen). " +- "Use when interactable elements you need aren't in the current snapshot — scroll, then snapshot again to discover newly-visible elements.",- inputSchema: browserScrollInput,- handler: handleBrowserScroll,- },- {- name: "browser_back",- description:- "Navigate back one entry in the tab's history. No-ops cleanly on the first page (no error). After navigating back, snapshot the tab again before clicking anything — the DOM changed.",- inputSchema: browserBackInput,- handler: handleBrowserBack,- },-];diff --git a/notfair/src/server/mcp-server/jsonrpc.test.ts b/notfair/src/server/mcp-server/jsonrpc.test.tsdeleted file mode 100644index 3684277f..00000000--- a/notfair/src/server/mcp-server/jsonrpc.test.ts+++ /dev/null@@ -1,178 +0,0 @@-import { describe, expect, it, vi } from "vitest";--import { handleJsonRpc, type McpServerInfo } from "./jsonrpc";-import type { ToolDefinition } from "./tools";-import { z } from "zod";--function makeTool(over: Partial<ToolDefinition> = {}): ToolDefinition {- return {- name: "echo",- description: "echoes",- inputSchema: z.object({ text: z.string() }),- handler: vi.fn(async () => ({- ok: true as const,- content: [{ type: "text" as const, text: "hi" }],- })),- ...over,- };-}--function server(tools: ToolDefinition[]): McpServerInfo {- return { name: "notfair-goals", version: "1.2.3", tools };-}--describe("handleJsonRpc", () => {- it("returns null for notifications (no id)", async () => {- const res = await handleJsonRpc(- { jsonrpc: "2.0", method: "notifications/initialized" },- server([]),- );- expect(res).toBeNull();- });-- it("returns null when id is explicitly null", async () => {- const res = await handleJsonRpc(- { jsonrpc: "2.0", id: null, method: "initialize" },- server([]),- );- expect(res).toBeNull();- });-- it("answers initialize with protocol + serverInfo", async () => {- const res = await handleJsonRpc(- { jsonrpc: "2.0", id: 1, method: "initialize" },- server([]),- );- expect(res).toMatchObject({- id: 1,- result: {- protocolVersion: "2025-06-18",- serverInfo: { name: "notfair-goals", version: "1.2.3" },- capabilities: { tools: {} },- },- });- });-- it("answers tools/list with described tools", async () => {- const res = await handleJsonRpc(- { jsonrpc: "2.0", id: "a", method: "tools/list" },- server([makeTool()]),- );- expect(res).toMatchObject({ id: "a" });- const result = (res as { result: { tools: { name: string }[] } }).result;- expect(result.tools[0]!.name).toBe("echo");- });-- it("answers ping with an empty result", async () => {- const res = await handleJsonRpc(- { jsonrpc: "2.0", id: 2, method: "ping" },- server([]),- );- expect(res).toMatchObject({ id: 2, result: {} });- });-- it("returns -32601 for an unknown method", async () => {- const res = await handleJsonRpc(- { jsonrpc: "2.0", id: 3, method: "does/not/exist" },- server([]),- );- expect(res).toMatchObject({ id: 3, error: { code: -32601 } });- });-- it("executes tools/call and wraps ok results", async () => {- const tool = makeTool();- const res = await handleJsonRpc(- {- jsonrpc: "2.0",- id: 4,- method: "tools/call",- params: { name: "echo", arguments: { text: "x" } },- },- server([tool]),- );- expect(tool.handler).toHaveBeenCalledWith({ text: "x" }, {});- expect(res).toMatchObject({- id: 4,- result: { isError: false, content: [{ type: "text", text: "hi" }] },- });- });-- it("defaults arguments to {} when omitted", async () => {- const tool = makeTool();- await handleJsonRpc(- { jsonrpc: "2.0", id: 5, method: "tools/call", params: { name: "echo" } },- server([tool]),- );- expect(tool.handler).toHaveBeenCalledWith({}, {});- });-- it("surfaces a failed tool result via isError:true", async () => {- const tool = makeTool({- handler: vi.fn(async () => ({ ok: false as const, error: "boom" })),- });- const res = await handleJsonRpc(- { jsonrpc: "2.0", id: 6, method: "tools/call", params: { name: "echo" } },- server([tool]),- );- expect(res).toMatchObject({- id: 6,- result: { isError: true, content: [{ type: "text", text: "boom" }] },- });- });-- it("returns -32602 when name is not a string", async () => {- const res = await handleJsonRpc(- { jsonrpc: "2.0", id: 7, method: "tools/call", params: { name: 123 } },- server([makeTool()]),- );- expect(res).toMatchObject({ id: 7, error: { code: -32602 } });- });-- it("returns -32601 for an unknown tool name", async () => {- const res = await handleJsonRpc(- {- jsonrpc: "2.0",- id: 8,- method: "tools/call",- params: { name: "nope" },- },- server([makeTool()]),- );- expect(res).toMatchObject({- id: 8,- error: { code: -32601, message: expect.stringContaining("Unknown tool") },- });- });-- it("maps a throwing handler to -32603 internal error", async () => {- const tool = makeTool({- handler: vi.fn(async () => {- throw new Error("kaboom");- }),- });- const res = await handleJsonRpc(- { jsonrpc: "2.0", id: 9, method: "tools/call", params: { name: "echo" } },- server([tool]),- );- expect(res).toMatchObject({- id: 9,- error: { code: -32603, message: expect.stringContaining("kaboom") },- });- });-- it("stringifies non-Error throws in the internal-error message", async () => {- const tool = makeTool({- handler: vi.fn(async () => {- throw "stringy";- }),- });- const res = await handleJsonRpc(- { jsonrpc: "2.0", id: 10, method: "tools/call", params: { name: "echo" } },- server([tool]),- );- expect(res).toMatchObject({- id: 10,- error: { code: -32603, message: expect.stringContaining("stringy") },- });- });-});diff --git a/notfair/src/server/mcp-server/jsonrpc.ts b/notfair/src/server/mcp-server/jsonrpc.tsdeleted file mode 100644index a8318e1d..00000000--- a/notfair/src/server/mcp-server/jsonrpc.ts+++ /dev/null@@ -1,129 +0,0 @@-import { describeTool, type ToolDefinition } from "./tools";--/**- * JSON-RPC 2.0 dispatcher for NotFair's outbound MCP servers.- *- * Each MCP server endpoint (e.g. /api/mcp/goals, /api/mcp/browser)- * passes its own tool registry to `handleJsonRpc`. Splitting the surface- * into multiple servers keeps related tools grouped, lets users- * enable/disable per-MCP, and makes "what is this MCP for?" obvious from- * the server name alone.- *- * MCP methods we implement:- * - initialize: handshake; reports protocol version + server info- * - tools/list: returns the available tool defs (name + JSON-schema)- * - tools/call: executes a named tool with arguments- *- * Notifications (no id) we no-op so older clients that send- * `notifications/initialized` don't error.- *- * Auth is upstream of this dispatcher (the route checks the Bearer first);- * callers reaching here are already authenticated.- */--export type JsonRpcRequest = {- jsonrpc: "2.0";- id?: string | number | null;- method: string;- params?: Record<string, unknown>;-};--export type JsonRpcResponse =- | {- jsonrpc: "2.0";- id: string | number | null;- result: unknown;- }- | {- jsonrpc: "2.0";- id: string | number | null;- error: { code: number; message: string; data?: unknown };- };--const PROTOCOL_VERSION = "2025-06-18";--export interface McpServerInfo {- /** Server name reported in `initialize`. Should match the MCP registration key (e.g. "notfair-goals"). */- name: string;- /** Server version string. Bump when wire-visible behavior changes. */- version: string;- /** Tool registry for this server. */- tools: ReadonlyArray<ToolDefinition>;-}--export async function handleJsonRpc(- req: JsonRpcRequest,- server: McpServerInfo,-): Promise<JsonRpcResponse | null> {- // Notifications (no id): handle the side-effecting ones but never reply.- if (req.id === undefined || req.id === null) {- return null;- }- const id = req.id;-- try {- switch (req.method) {- case "initialize":- return ok(id, {- protocolVersion: PROTOCOL_VERSION,- serverInfo: { name: server.name, version: server.version },- capabilities: { tools: {} },- });- case "tools/list":- return ok(id, { tools: server.tools.map(describeTool) });- case "tools/call":- return await handleToolsCall(id, req.params ?? {}, server.tools);- case "ping":- return ok(id, {});- default:- return err(id, -32601, `Method not found: ${req.method}`);- }- } catch (cause) {- return err(- id,- -32603,- `Internal error: ${cause instanceof Error ? cause.message : String(cause)}`,- );- }-}--async function handleToolsCall(- id: string | number,- params: Record<string, unknown>,- tools: ReadonlyArray<ToolDefinition>,-): Promise<JsonRpcResponse> {- const name = params.name;- const args = params.arguments ?? {};- if (typeof name !== "string") {- return err(id, -32602, "Invalid params: 'name' must be a string");- }- const tool = tools.find((t) => t.name === name);- if (!tool) {- return err(id, -32601, `Unknown tool: ${name}`);- }- // The handler does its own schema validation and returns a structured- // result. For MCP tools/call, we surface errors via `isError: true` on the- // result envelope (per spec) rather than as JSON-RPC errors, so the agent's- // model sees the failure as a tool-call response it can react to.- const result = await tool.handler(args, {});- if (!result.ok) {- return ok(id, {- isError: true,- content: [{ type: "text", text: result.error }],- });- }- return ok(id, { isError: false, content: result.content });-}--function ok(id: string | number, result: unknown): JsonRpcResponse {- return { jsonrpc: "2.0", id, result };-}--function err(- id: string | number,- code: number,- message: string,- data?: unknown,-): JsonRpcResponse {- return { jsonrpc: "2.0", id, error: { code, message, data } };-}diff --git a/notfair/src/server/mcp-server/registration.test.ts b/notfair/src/server/mcp-server/registration.test.tsdeleted file mode 100644index cbe68afa..00000000--- a/notfair/src/server/mcp-server/registration.test.ts+++ /dev/null@@ -1,190 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- requireAdapter: vi.fn(),- getProject: vi.fn(),- listProjectAgents: vi.fn(),- mcpSpecByKey: vi.fn(),- findMcpToken: vi.fn(),- getOrCreateMcpServerSecret: vi.fn(() => "shared-secret"),- registerMcp: vi.fn(async () => {}),-}));--vi.mock("@/server/adapters/registry", () => ({- requireAdapter: mocks.requireAdapter,-}));-vi.mock("@/server/db/projects", () => ({- getProject: mocks.getProject,-}));-vi.mock("@/server/agent-meta", () => ({- listProjectAgents: mocks.listProjectAgents,-}));-vi.mock("@/server/mcp-catalog", () => ({- mcpSpecByKey: mocks.mcpSpecByKey,-}));-vi.mock("@/server/mcp/tokens", () => ({- findMcpToken: mocks.findMcpToken,-}));-vi.mock("./secret", () => ({- getOrCreateMcpServerSecret: mocks.getOrCreateMcpServerSecret,-}));--import {- BROWSER_MCP_KEY,- GOALS_MCP_KEY,- registerBrowserMcpForAgent,- registerCatalogMcpForAgent,- registerCatalogMcpForProject,- registerGoalsMcpForAgent,-} from "./registration";--const PROJECT = { slug: "proj", harness_adapter: "claude-code-local" };-const SPEC = { key: "notfair-googleads", resource_url: "https://srv/mcp" };--beforeEach(() => {- vi.clearAllMocks();- delete process.env.NOTFAIR_MCP_URL;- delete process.env.NOTFAIR_BROWSER_MCP_URL;- delete process.env.NOTFAIR_PORT;- mocks.getProject.mockReturnValue(PROJECT);- mocks.requireAdapter.mockReturnValue({ registerMcp: mocks.registerMcp });- mocks.mcpSpecByKey.mockReturnValue(SPEC);- mocks.findMcpToken.mockReturnValue({ access_token_enc: "enc-token" });- mocks.getOrCreateMcpServerSecret.mockReturnValue("shared-secret");-});--describe("registerGoalsMcpForAgent", () => {- it("registers with default goals URL + bearer secret", async () => {- const r = await registerGoalsMcpForAgent("proj", "agent-1");- expect(r).toEqual({- ok: true,- key: GOALS_MCP_KEY,- url: "http://127.0.0.1:3326/api/mcp/goals",- });- expect(mocks.registerMcp).toHaveBeenCalledWith({- serverName: GOALS_MCP_KEY,- agentId: "agent-1",- projectSlug: "proj",- transport: {- type: "http",- url: "http://127.0.0.1:3326/api/mcp/goals",- headers: { Authorization: "Bearer shared-secret" },- },- });- });-- it("honors NOTFAIR_PORT and NOTFAIR_MCP_URL overrides", async () => {- process.env.NOTFAIR_PORT = "9999";- let r = await registerGoalsMcpForAgent("proj", "a");- expect(r.url).toBe("http://127.0.0.1:9999/api/mcp/goals");-- process.env.NOTFAIR_MCP_URL = "https://custom/mcp";- r = await registerGoalsMcpForAgent("proj", "a");- expect(r.url).toBe("https://custom/mcp");- });-- it("fails when the project is unknown", async () => {- mocks.getProject.mockReturnValue(null);- const r = await registerGoalsMcpForAgent("proj", "a");- expect(r).toMatchObject({ ok: false, error: expect.stringContaining("Unknown project") });- expect(mocks.registerMcp).not.toHaveBeenCalled();- });-- it("fails when the adapter throws", async () => {- mocks.requireAdapter.mockImplementation(() => {- throw new Error("no adapter");- });- const r = await registerGoalsMcpForAgent("proj", "a");- expect(r).toMatchObject({ ok: false, error: "no adapter" });- });-- it("stringifies non-Error throws from the adapter", async () => {- mocks.requireAdapter.mockImplementation(() => {- throw "weird";- });- const r = await registerGoalsMcpForAgent("proj", "a");- expect(r).toMatchObject({ ok: false, error: "weird" });- });-});--describe("registerBrowserMcpForAgent", () => {- it("registers with the default browser URL", async () => {- const r = await registerBrowserMcpForAgent("proj", "a");- expect(r).toEqual({- ok: true,- key: BROWSER_MCP_KEY,- url: "http://127.0.0.1:3326/api/mcp/browser",- });- });-- it("honors NOTFAIR_BROWSER_MCP_URL", async () => {- process.env.NOTFAIR_BROWSER_MCP_URL = "https://custom/browser";- const r = await registerBrowserMcpForAgent("proj", "a");- expect(r.url).toBe("https://custom/browser");- });-});--describe("registerCatalogMcpForAgent", () => {- it("registers using the catalog resource URL + token bearer", async () => {- const r = await registerCatalogMcpForAgent("proj", "notfair-googleads", "agent-1");- expect(r).toEqual({ ok: true, key: "notfair-googleads", url: SPEC.resource_url });- expect(mocks.registerMcp).toHaveBeenCalledWith(- expect.objectContaining({- serverName: "notfair-googleads",- transport: expect.objectContaining({- url: SPEC.resource_url,- headers: { Authorization: "Bearer enc-token" },- }),- }),- );- });-- it("fails on unknown catalog key", async () => {- mocks.mcpSpecByKey.mockReturnValue(undefined);- const r = await registerCatalogMcpForAgent("proj", "nope", "a");- expect(r).toMatchObject({ ok: false, url: "", error: expect.stringContaining("Unknown catalog key") });- });-- it("fails on unknown project (with spec url echoed)", async () => {- mocks.getProject.mockReturnValue(null);- const r = await registerCatalogMcpForAgent("proj", "notfair-googleads", "a");- expect(r).toMatchObject({ ok: false, url: SPEC.resource_url, error: expect.stringContaining("Unknown project") });- });-- it("fails when no token is stored", async () => {- mocks.findMcpToken.mockReturnValue(null);- const r = await registerCatalogMcpForAgent("proj", "notfair-googleads", "a");- expect(r).toMatchObject({ ok: false, error: expect.stringContaining("No token stored") });- });-- it("fails when the adapter throws", async () => {- mocks.registerMcp.mockRejectedValueOnce(new Error("register failed"));- const r = await registerCatalogMcpForAgent("proj", "notfair-googleads", "a");- expect(r).toMatchObject({ ok: false, error: "register failed" });- });-- it("stringifies non-Error throws", async () => {- mocks.registerMcp.mockRejectedValueOnce("boom");- const r = await registerCatalogMcpForAgent("proj", "notfair-googleads", "a");- expect(r).toMatchObject({ ok: false, error: "boom" });- });-});--describe("registerCatalogMcpForProject", () => {- it("registers for each agent and collects results", async () => {- mocks.listProjectAgents.mockResolvedValue([- { agent_id: "a1" },- { agent_id: "a2" },- ]);- const results = await registerCatalogMcpForProject("proj", "notfair-googleads");- expect(results).toHaveLength(2);- expect(results.every((r) => r.ok)).toBe(true);- expect(mocks.registerMcp).toHaveBeenCalledTimes(2);- });-- it("returns an empty array when the project has no agents", async () => {- mocks.listProjectAgents.mockResolvedValue([]);- const results = await registerCatalogMcpForProject("proj", "notfair-googleads");- expect(results).toEqual([]);- });-});diff --git a/notfair/src/server/mcp-server/registration.ts b/notfair/src/server/mcp-server/registration.tsdeleted file mode 100644index c66404ce..00000000--- a/notfair/src/server/mcp-server/registration.ts+++ /dev/null@@ -1,191 +0,0 @@-import { requireAdapter } from "@/server/adapters/registry";-import { getProject } from "@/server/db/projects";-import { listProjectAgents } from "@/server/agent-meta";-import { mcpSpecByKey } from "@/server/mcp-catalog";-import { findMcpToken } from "@/server/mcp/tokens";-import { getOrCreateMcpServerSecret } from "./secret";--/**- * Register NotFair's outbound MCP server (`notfair-goals`) with- * the project's harness adapter for a specific agent.- *- * The harness-adapter model writes MCP wiring into whichever config file- * the chosen harness expects (Claude Code's `.mcp.json`, Codex's- * `~/.codex/config.toml`); registration is per-agent.- *- * URL: `NOTFAIR_MCP_URL` if set, else- * `http://127.0.0.1:${NOTFAIR_PORT||3326}/api/mcp/goals`.- */--export const GOALS_MCP_KEY = "notfair-goals";-export const BROWSER_MCP_KEY = "notfair-browser";--function notfairOriginPort(): string {- return process.env.NOTFAIR_PORT?.trim() || "3326";-}--function defaultMcpUrl(): string {- if (process.env.NOTFAIR_MCP_URL?.trim()) {- return process.env.NOTFAIR_MCP_URL.trim();- }- return `http://127.0.0.1:${notfairOriginPort()}/api/mcp/goals`;-}--function defaultBrowserMcpUrl(): string {- if (process.env.NOTFAIR_BROWSER_MCP_URL?.trim()) {- return process.env.NOTFAIR_BROWSER_MCP_URL.trim();- }- return `http://127.0.0.1:${notfairOriginPort()}/api/mcp/browser`;-}--export type InstallResult =- | { ok: true; key: string; url: string }- | { ok: false; key: string; url: string; error: string };--export async function registerGoalsMcpForAgent(- project_slug: string,- agent_id: string,-): Promise<InstallResult> {- return registerInternalMcpForAgent({- project_slug,- agent_id,- key: GOALS_MCP_KEY,- url: defaultMcpUrl(),- });-}--/**- * Register the standalone browser MCP (notfair-browser) for an agent.- * Same shared-secret auth + same harness adapter glue as the goals server;- * separate URL + server name so agents see the surface as its own thing.- */-export async function registerBrowserMcpForAgent(- project_slug: string,- agent_id: string,-): Promise<InstallResult> {- return registerInternalMcpForAgent({- project_slug,- agent_id,- key: BROWSER_MCP_KEY,- url: defaultBrowserMcpUrl(),- });-}--async function registerInternalMcpForAgent(args: {- project_slug: string;- agent_id: string;- key: string;- url: string;-}): Promise<InstallResult> {- const { project_slug, agent_id, key, url } = args;- const project = getProject(project_slug);- if (!project) {- return { ok: false, key, url, error: `Unknown project ${project_slug}` };- }- try {- const adapter = requireAdapter(project.harness_adapter);- await adapter.registerMcp({- serverName: key,- agentId: agent_id,- projectSlug: project_slug,- transport: {- type: "http",- url,- headers: { Authorization: `Bearer ${getOrCreateMcpServerSecret()}` },- },- });- return { ok: true, key, url };- } catch (err) {- return {- ok: false,- key,- url,- error: err instanceof Error ? err.message : String(err),- };- }-}--/**- * Register an external catalog MCP server (Google Ads, GSC, etc.) with the- * project's harness adapter for a specific agent. Pulls the OAuth bearer- * from the `mcp_tokens` table and the resource URL from the catalog spec.- *- * Called after a successful OAuth callback so the bearer becomes visible- * to running agents without the user manually re-provisioning. Idempotent:- * the adapter `registerMcp` overwrites the prior entry on rewrite.- */-export async function registerCatalogMcpForAgent(- project_slug: string,- catalog_key: string,- agent_id: string,-): Promise<InstallResult> {- const spec = mcpSpecByKey(project_slug, catalog_key);- if (!spec) {- return {- ok: false,- key: catalog_key,- url: "",- error: `Unknown catalog key ${catalog_key}`,- };- }- const project = getProject(project_slug);- if (!project) {- return {- ok: false,- key: catalog_key,- url: spec.resource_url,- error: `Unknown project ${project_slug}`,- };- }- const token = findMcpToken(project_slug, catalog_key);- if (!token) {- return {- ok: false,- key: catalog_key,- url: spec.resource_url,- error: `No token stored for ${catalog_key} in project ${project_slug}`,- };- }- try {- const adapter = requireAdapter(project.harness_adapter);- await adapter.registerMcp({- serverName: catalog_key,- agentId: agent_id,- projectSlug: project_slug,- transport: {- type: "http",- url: spec.resource_url,- headers: { Authorization: `Bearer ${token.access_token_enc}` },- },- });- return { ok: true, key: catalog_key, url: spec.resource_url };- } catch (err) {- return {- ok: false,- key: catalog_key,- url: spec.resource_url,- error: err instanceof Error ? err.message : String(err),- };- }-}--/**- * Convenience: register an external catalog MCP with EVERY agent in the- * project. Called from the OAuth callback so a fresh token reaches all- * project agents without re-provisioning. Best-effort per agent — one- * failed registration doesn't abort the rest.- */-export async function registerCatalogMcpForProject(- project_slug: string,- catalog_key: string,-): Promise<InstallResult[]> {- const agents = await listProjectAgents(project_slug);- const results: InstallResult[] = [];- for (const agent of agents) {- results.push(- await registerCatalogMcpForAgent(project_slug, catalog_key, agent.agent_id),- );- }- return results;-}-diff --git a/notfair/src/server/mcp-server/secret.test.ts b/notfair/src/server/mcp-server/secret.test.tsdeleted file mode 100644index 13c42bb2..00000000--- a/notfair/src/server/mcp-server/secret.test.ts+++ /dev/null@@ -1,86 +0,0 @@-import { describe, expect, it, vi } from "vitest";-import { existsSync, rmSync, statSync, writeFileSync } from "node:fs";-import { join } from "node:path";--// Real fs against a tmpdir data dir, per repo test conventions.-// MUST be hoisted: secret.ts captures NOTFAIR_DATA_DIR at import time, so a-// plain assignment would point the suite at the developer's live ~/.notfair.-const h = vi.hoisted(() => {- const { mkdtempSync, rmSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- const dataDir = mkdtempSync(join(tmpdir(), "notfair-secret-"));- // The module mints the data dir itself when missing — exercise that path.- rmSync(dataDir, { recursive: true, force: true });- process.env.NOTFAIR_DATA_DIR = dataDir;- return { dataDir };-});--import {- getMcpServerSecretPath,- getOrCreateMcpServerSecret,- verifyMcpServerSecret,-} from "./secret";--describe("getOrCreateMcpServerSecret", () => {- it("mints a 32-byte hex secret and creates the data dir on first read", () => {- expect(existsSync(h.dataDir)).toBe(false);- const secret = getOrCreateMcpServerSecret();- expect(secret).toMatch(/^[0-9a-f]{64}$/);- expect(existsSync(h.dataDir)).toBe(true);- });-- it("persists with 0600 perms and a trailing newline", () => {- getOrCreateMcpServerSecret();- const mode = statSync(getMcpServerSecretPath()).mode & 0o777;- expect(mode).toBe(0o600);- });-- it("returns the same secret on subsequent reads", () => {- expect(getOrCreateMcpServerSecret()).toBe(getOrCreateMcpServerSecret());- });-- it("re-mints when the stored file is empty", () => {- const first = getOrCreateMcpServerSecret();- writeFileSync(getMcpServerSecretPath(), "\n", "utf8");- const second = getOrCreateMcpServerSecret();- expect(second).toMatch(/^[0-9a-f]{64}$/);- expect(second).not.toBe(first);- });-- it("re-mints after the file is deleted (manual rotation)", () => {- const first = getOrCreateMcpServerSecret();- rmSync(getMcpServerSecretPath());- expect(getOrCreateMcpServerSecret()).not.toBe(first);- });-});--describe("verifyMcpServerSecret", () => {- it("accepts the stored secret", () => {- const secret = getOrCreateMcpServerSecret();- expect(verifyMcpServerSecret(secret)).toBe(true);- });-- it("rejects null / undefined / empty without throwing", () => {- expect(verifyMcpServerSecret(null)).toBe(false);- expect(verifyMcpServerSecret(undefined)).toBe(false);- expect(verifyMcpServerSecret("")).toBe(false);- });-- it("rejects a length-mismatched bearer before the constant-time compare", () => {- expect(verifyMcpServerSecret("short")).toBe(false);- });-- it("rejects an equal-length wrong bearer", () => {- const secret = getOrCreateMcpServerSecret();- const wrong = secret.slice(0, -1) + (secret.endsWith("0") ? "1" : "0");- expect(wrong).toHaveLength(secret.length);- expect(verifyMcpServerSecret(wrong)).toBe(false);- });-});--describe("getMcpServerSecretPath", () => {- it("lives inside the data dir", () => {- expect(getMcpServerSecretPath()).toBe(join(h.dataDir, "mcp-server-secret"));- });-});diff --git a/notfair/src/server/mcp-server/secret.ts b/notfair/src/server/mcp-server/secret.tsdeleted file mode 100644index 15f99b23..00000000--- a/notfair/src/server/mcp-server/secret.ts+++ /dev/null@@ -1,53 +0,0 @@-import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";-import { homedir } from "node:os";-import { join } from "node:path";-import { randomBytes, timingSafeEqual } from "node:crypto";--/**- * Shared secret used to authenticate calls from harness-side agents into our- * outbound-facing MCP server. Lives in a file with 0600 perms inside the- * NotFair data dir (NOT the project SQLite DB — keeping it in a small- * dedicated file lets the file's own mode bits enforce single-user access- * and lets registration read it with a one-liner).- *- * Single-user local CLI: we mint one secret per install and reuse it across- * every project + every agent. No rotation in V1 — easy to add later by- * deleting the file and re-running `NotFair mcp register`.- */--const DATA_DIR = process.env.NOTFAIR_DATA_DIR ?? join(homedir(), ".notfair");-const SECRET_PATH = join(DATA_DIR, "mcp-server-secret");--/** Read the secret, minting + persisting one the first time. */-export function getOrCreateMcpServerSecret(): string {- if (!existsSync(DATA_DIR)) {- mkdirSync(DATA_DIR, { recursive: true, mode: 0o700 });- }- if (existsSync(SECRET_PATH)) {- const value = readFileSync(SECRET_PATH, "utf8").trim();- if (value) return value;- }- const minted = randomBytes(32).toString("hex");- writeFileSync(SECRET_PATH, `${minted}\n`, { mode: 0o600 });- return minted;-}--/**- * Constant-time compare of a presented bearer against the stored secret.- * Returns false rather than throwing when the input is malformed so callers- * can map all unauth paths to 401 without special-casing exceptions.- */-export function verifyMcpServerSecret(presented: string | null | undefined): boolean {- if (!presented) return false;- const expected = getOrCreateMcpServerSecret();- if (presented.length !== expected.length) return false;- return timingSafeEqual(- Buffer.from(presented, "utf8"),- Buffer.from(expected, "utf8"),- );-}--/** Where the secret lives on disk — surfaced for CLI registration helpers. */-export function getMcpServerSecretPath(): string {- return SECRET_PATH;-}diff --git a/notfair/src/server/mcp-server/tool-summaries.ts b/notfair/src/server/mcp-server/tool-summaries.tsdeleted file mode 100644index 36aa3c69..00000000--- a/notfair/src/server/mcp-server/tool-summaries.ts+++ /dev/null@@ -1,91 +0,0 @@-import { TOOLS, describeTool } from "./tools";--/**- * Client-safe summary of an MCP tool, suitable for rendering in the- * tools modal. We deliberately don't pass zod schemas (or full JSON- * Schema trees) across the server/client boundary — the modal cares- * about name + description + arg list, not validation.- *- * Same shape for built-in (notfair-goals) tools we own + for- * external (Google Ads etc.) tools we learn about via tools/list. The- * modal renders both identically.- */-export type ToolArgSummary = {- name: string;- /**- * One-token type hint: "string", "number", "boolean", `enum: a|b|c`,- * "array<string>", "object". Picked for human readability rather- * than schema fidelity.- */- type: string;- description: string;- required: boolean;-};--export type ToolSummary = {- name: string;- description: string;- args: ToolArgSummary[];-};--/**- * Walk TOOLS (server-side; the registry holds zod schemas + handlers)- * and produce a JSON-safe summary array for the connections-page- * built-in MCP card. We piggyback on describeTool() which already runs- * the zod → JSON Schema conversion this app needs for the MCP protocol- * surface, so the modal stays in lockstep with what agents actually see.- */-export function summarizeBuiltinTools(): ToolSummary[] {- return TOOLS.map((tool) => {- const desc = describeTool(tool);- return {- name: desc.name,- description: desc.description,- args: argsFromJsonSchema(desc.inputSchema),- };- });-}--type JsonSchemaProp = {- type?: string | string[];- description?: string;- enum?: unknown[];- items?: { type?: string };-};--type JsonSchemaObject = {- type?: string;- properties?: Record<string, JsonSchemaProp>;- required?: string[];-};--/**- * Map a JSON-Schema object (the shape describeTool produces) into the- * flat arg-summary list the UI renders. Unknown shapes degrade to- * "unknown" type without crashing — better to show a tool with a fuzzy- * arg row than to drop it.- */-export function argsFromJsonSchema(- schema: Record<string, unknown>,-): ToolArgSummary[] {- const obj = schema as JsonSchemaObject;- if (!obj.properties) return [];- const required = new Set(obj.required ?? []);- return Object.entries(obj.properties).map(([name, prop]) => ({- name,- type: typeHint(prop),- description: prop.description ?? "",- required: required.has(name),- }));-}--function typeHint(prop: JsonSchemaProp): string {- if (Array.isArray(prop.enum) && prop.enum.length > 0) {- return `enum: ${prop.enum.map(String).join(" | ")}`;- }- if (prop.type === "array") {- return `array<${prop.items?.type ?? "any"}>`;- }- if (Array.isArray(prop.type)) return prop.type.join(" | ");- return prop.type ?? "unknown";-}diff --git a/notfair/src/server/mcp-server/tools.test.ts b/notfair/src/server/mcp-server/tools.test.tsdeleted file mode 100644index 0fd9e624..00000000--- a/notfair/src/server/mcp-server/tools.test.ts+++ /dev/null@@ -1,515 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--const handlers = vi.hoisted(() => ({- handleAmendGoal: vi.fn(),- handleAddSupportMetric: vi.fn(),- handleBackfillHistory: vi.fn(),- handleDefineGoal: vi.fn(),- handleGetGoal: vi.fn(),- handleGetProject: vi.fn(),- handleLogGoalAction: vi.fn(),- handleLogLearning: vi.fn(),- handleProposeGoalMetric: vi.fn(),- handleProposeTarget: vi.fn(),- handleRegisterPullRequest: vi.fn(),- handleReviewGoalAction: vi.fn(),- handleSearchLearnings: vi.fn(),- handleSetProjectBrief: vi.fn(),- handleUpdateGoalStatus: vi.fn(),-}));--vi.mock("@/server/goals/handlers", () => handlers);--import { TOOLS, describeTool, findTool, type ToolResult } from "./tools";--const CTX = { project_slug: "proj", agent_id: "agent-1" };-const BASE = { project_slug: "proj", agent_id: "agent-1", goal_id: "goal-1" };--function ok<T>(data: T) {- return { ok: true as const, data };-}--async function call(name: string, input: unknown): Promise<ToolResult> {- const tool = findTool(name);- if (!tool) throw new Error(`no tool ${name}`);- return tool.handler(input, {});-}--function text(result: ToolResult): string {- if (!result.ok) throw new Error(`expected ok result, got: ${result.error}`);- return result.content.map((c) => c.text).join("\n");-}--beforeEach(() => {- for (const fn of Object.values(handlers)) fn.mockReset();-});--describe("registry", () => {- it("exposes the full goal-lifecycle surface", () => {- expect(TOOLS.map((t) => t.name)).toEqual([- "get_goal",- "define_goal",- "propose_goal_metric",- "backfill_metric_history",- "add_supporting_metric",- "propose_target",- "amend_goal",- "log_goal_action",- "register_pull_request",- "review_goal_action",- "log_learning",- "search_learnings",- "update_goal_status",- "get_project",- "set_shared_context",- ]);- for (const tool of TOOLS) {- expect(tool.description.length).toBeGreaterThan(20);- expect(typeof tool.handler).toBe("function");- }- });-- it("findTool resolves by name and misses cleanly", () => {- expect(findTool("get_goal")?.name).toBe("get_goal");- expect(findTool("no_such_tool")).toBeUndefined();- });-- it("every tool rejects malformed args without calling its handler", async () => {- for (const tool of TOOLS) {- const r = await tool.handler({ project_slug: 42 }, {});- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toMatch(/^Invalid arguments:/);- }- for (const fn of Object.values(handlers)) expect(fn).not.toHaveBeenCalled();- });-});--describe("describeTool JSON schema", () => {- it("maps enum/number/string/optionality for propose_goal_metric", () => {- const desc = describeTool(findTool("propose_goal_metric")!);- expect(desc.name).toBe("propose_goal_metric");- const schema = desc.inputSchema as {- type: string;- properties: Record<string, { type: string; enum?: string[]; description?: string }>;- required: string[];- additionalProperties: boolean;- };- expect(schema.type).toBe("object");- expect(schema.additionalProperties).toBe(false);- expect(schema.properties.metric_direction).toMatchObject({- type: "string",- enum: ["increase", "decrease"],- });- expect(schema.properties.project_slug).toMatchObject({- type: "string",- description: "From IDENTITY.md.",- });- expect(schema.required).toEqual([- "project_slug",- "agent_id",- "goal_id",- "metric_name",- "metric_source_key",- "metric_source_tool",- "metric_source_args_json",- "metric_direction",- ]);- });-- it("optional numbers and booleans keep their types but leave required", () => {- const define = describeTool(findTool("define_goal")!).inputSchema as {- properties: Record<string, { type: string }>;- required: string[];- };- expect(define.properties.spend_envelope_usd.type).toBe("number");- expect(define.required).not.toContain("spend_envelope_usd");- expect(define.required).not.toContain("deadline");-- const review = describeTool(findTool("review_goal_action")!).inputSchema as {- properties: Record<string, { type: string }>;- required: string[];- };- expect(review.properties.abandoned.type).toBe("boolean");- expect(review.required).not.toContain("abandoned");- });-});--describe("get_goal", () => {- it("dispatches and returns the goal state as JSON", async () => {- handlers.handleGetGoal.mockResolvedValueOnce(ok({ statement: "grow" }));- const r = await call("get_goal", BASE);- expect(handlers.handleGetGoal).toHaveBeenCalledWith({ goal_id: "goal-1" }, CTX);- expect(JSON.parse(text(r))).toEqual({ statement: "grow" });- });-- it("surfaces handler errors", async () => {- handlers.handleGetGoal.mockResolvedValueOnce({ ok: false, error: "Unknown goal_id 'goal-1'" });- const r = await call("get_goal", BASE);- expect(r).toEqual({ ok: false, error: "Unknown goal_id 'goal-1'" });- });-});--describe("define_goal", () => {- it("splits caller identity from the payload", async () => {- handlers.handleDefineGoal.mockReturnValueOnce(ok({ statement: "Cut CAC to $30" }));- const r = await call("define_goal", {- ...BASE,- statement: "Cut CAC to $30",- short_label: "CAC → $30",- deadline: "2026-09-01",- spend_envelope_usd: 500,- });- expect(handlers.handleDefineGoal).toHaveBeenCalledWith(- {- goal_id: "goal-1",- statement: "Cut CAC to $30",- short_label: "CAC → $30",- deadline: "2026-09-01",- spend_envelope_usd: 500,- },- CTX,- );- expect(text(r)).toContain('goal defined: "Cut CAC to $30"');- });-- it("enforces the 48-char short_label cap", async () => {- const r = await call("define_goal", {- ...BASE,- statement: "x",- short_label: "y".repeat(49),- });- expect(r.ok).toBe(false);- expect(handlers.handleDefineGoal).not.toHaveBeenCalled();- });-});--describe("propose_goal_metric", () => {- it("reports the verified baseline", async () => {- handlers.handleProposeGoalMetric.mockResolvedValueOnce(ok({ baseline_value: 42.5 }));- const r = await call("propose_goal_metric", {- ...BASE,- metric_name: "CAC (USD, trailing 30d)",- metric_source_key: "notfair-googleads",- metric_source_tool: "runScript",- metric_source_args_json: '{"script":"..."}',- metric_direction: "decrease",- });- expect(handlers.handleProposeGoalMetric).toHaveBeenCalledWith(- {- goal_id: "goal-1",- metric_name: "CAC (USD, trailing 30d)",- metric_source_key: "notfair-googleads",- metric_source_tool: "runScript",- metric_source_args_json: '{"script":"..."}',- metric_direction: "decrease",- },- CTX,- );- expect(text(r)).toContain("Baseline measured: 42.5");- });-- it("rejects an unknown metric_direction", async () => {- const r = await call("propose_goal_metric", {- ...BASE,- metric_name: "x",- metric_source_key: "k",- metric_source_tool: "t",- metric_source_args_json: "{}",- metric_direction: "sideways",- });- expect(r.ok).toBe(false);- });-});--describe("backfill_metric_history", () => {- it("summarizes the backfilled range", async () => {- handlers.handleBackfillHistory.mockResolvedValueOnce(- ok({ points: 30, from: "2026-06-01", to: "2026-06-30" }),- );- const r = await call("backfill_metric_history", {- ...BASE,- source_key: "notfair-googleads",- source_tool: "runScript",- source_args_json: "{}",- });- expect(text(r)).toBe(- "History backfilled: 30 daily points from 2026-06-01 to 2026-06-30. The progress chart now has context.",- );- });-- it("surfaces handler errors", async () => {- handlers.handleBackfillHistory.mockResolvedValueOnce({ ok: false, error: "query failed" });- const r = await call("backfill_metric_history", {- ...BASE,- source_key: "k",- source_tool: "t",- source_args_json: "{}",- });- expect(r).toEqual({ ok: false, error: "query failed" });- });-});--describe("add_supporting_metric", () => {- const args = {- ...BASE,- name: "PRs open (live)",- source_key: "local",- source_tool: "shell",- source_args_json: '{"command":"echo 3"}',- };-- it("mentions backfilled points when history was provided", async () => {- handlers.handleAddSupportMetric.mockResolvedValueOnce(- ok({ metric: { name: "PRs open (live)", current_value: 3 }, backfilled: 30 }),- );- const r = await call("add_supporting_metric", { ...args, history_args_json: "{}" });- expect(text(r)).toContain("current value 3, 30 history points backfilled");- });-- it("omits the backfill clause when nothing was backfilled", async () => {- handlers.handleAddSupportMetric.mockResolvedValueOnce(- ok({ metric: { name: "PRs open (live)", current_value: 3 }, backfilled: 0 }),- );- const r = await call("add_supporting_metric", args);- expect(text(r)).not.toContain("backfilled");- });-});--describe("propose_target", () => {- it("rejects an invalid cadence_cron before touching the handler", async () => {- const r = await call("propose_target", {- ...BASE,- target_value: 30,- cadence_cron: "not a cron",- });- expect(r).toEqual({- ok: false,- error: "Invalid cadence_cron 'not a cron' — must be a 5-field cron expression.",- });- expect(handlers.handleProposeTarget).not.toHaveBeenCalled();- });-- it("accepts a valid cron and starts the loop", async () => {- handlers.handleProposeTarget.mockReturnValueOnce(ok({}));- const r = await call("propose_target", {- ...BASE,- target_value: 30,- mode: "maintain",- cadence_cron: "0 16 * * 1-5",- });- expect(handlers.handleProposeTarget).toHaveBeenCalledWith(- { goal_id: "goal-1", target_value: 30, mode: "maintain", cadence_cron: "0 16 * * 1-5" },- CTX,- );- expect(text(r)).toContain("loop is LIVE");- });-- it("cadence_cron is optional", async () => {- handlers.handleProposeTarget.mockReturnValueOnce(ok({}));- const r = await call("propose_target", { ...BASE, target_value: 30 });- expect(r.ok).toBe(true);- });-});--describe("amend_goal", () => {- it("validates cadence_cron", async () => {- const r = await call("amend_goal", { ...BASE, cadence_cron: "99 99 * * *" });- expect(r.ok).toBe(false);- if (!r.ok) expect(r.error).toContain("Invalid cadence_cron");- expect(handlers.handleAmendGoal).not.toHaveBeenCalled();- });-- it("echoes the amended values, with placeholders for unset fields", async () => {- handlers.handleAmendGoal.mockReturnValueOnce(- ok({ target_value: null, deadline: null, spend_envelope_usd: null, cadence_cron: "0 16 * * *" }),- );- const r = await call("amend_goal", { ...BASE, cadence_cron: "0 16 * * *" });- expect(text(r)).toBe(- "Goal amended: target=—, deadline=none, envelope=none, cadence=0 16 * * *. Confirm the change back to the user.",- );- });-- it("formats set values", async () => {- handlers.handleAmendGoal.mockReturnValueOnce(- ok({- target_value: 25,- deadline: "2026-10-01",- spend_envelope_usd: 400,- cadence_cron: "0 16 * * 1",- }),- );- const r = await call("amend_goal", { ...BASE, target_value: 25 });- expect(text(r)).toContain("target=25, deadline=2026-10-01, envelope=$400, cadence=0 16 * * 1");- });-});--describe("log_goal_action", () => {- const args = {- ...BASE,- kind: "mutation",- description: "Lower tROAS to 220% on campaign 123",- expected_effect: "CPA -$3 within 7 days",- };-- it("splits resources_touched into a trimmed list", async () => {- handlers.handleLogGoalAction.mockReturnValueOnce(- ok({ action_id: "act-1", review_after: "2026-07-25T00:00:00.000Z" }),- );- const r = await call("log_goal_action", {- ...args,- resources_touched: " campaign:123 , adgroup:456,, ",- review_after_hours: 120,- });- expect(handlers.handleLogGoalAction).toHaveBeenCalledWith(- {- goal_id: "goal-1",- kind: "mutation",- description: "Lower tROAS to 220% on campaign 123",- expected_effect: "CPA -$3 within 7 days",- resources_touched: ["campaign:123", "adgroup:456"],- review_after_hours: 120,- },- CTX,- );- expect(text(r)).toBe(- "action act-1 logged. Review due 2026-07-25T00:00:00.000Z. Its resources are gated until then.",- );- });-- it("defaults resources to [] and omits the gate sentence without review_after", async () => {- handlers.handleLogGoalAction.mockReturnValueOnce(ok({ action_id: "act-2", review_after: null }));- const r = await call("log_goal_action", { ...args, kind: "research" });- expect(handlers.handleLogGoalAction).toHaveBeenCalledWith(- expect.objectContaining({ resources_touched: [] }),- CTX,- );- expect(text(r)).toBe("action act-2 logged.");- });-});--describe("register_pull_request", () => {- it("dispatches and reports the PR state", async () => {- handlers.handleRegisterPullRequest.mockResolvedValueOnce(ok({ state: "open" }));- const r = await call("register_pull_request", {- ...BASE,- url: "https://github.com/o/r/pull/7",- title: "feat: add landing page",- branch: "feat/landing",- action_id: "act-1",- });- expect(handlers.handleRegisterPullRequest).toHaveBeenCalledWith(- {- goal_id: "goal-1",- url: "https://github.com/o/r/pull/7",- title: "feat: add landing page",- branch: "feat/landing",- action_id: "act-1",- },- CTX,- );- expect(text(r)).toContain("PR registered (state: open)");- });-});--describe("review_goal_action", () => {- it("reports status and any recorded learning", async () => {- handlers.handleReviewGoalAction.mockReturnValueOnce(- ok({ action_id: "act-1", status: "reviewed", learning_id: "lrn-9" }),- );- const r = await call("review_goal_action", {- ...BASE,- action_id: "act-1",- observed_outcome: "CPA fell $2.10 vs the $3 predicted",- learning: "tROAS moves take ~5 days to settle",- });- expect(text(r)).toBe("action act-1 reviewed. Learning lrn-9 recorded.");- });-- it("omits the learning clause when none was recorded", async () => {- handlers.handleReviewGoalAction.mockReturnValueOnce(- ok({ action_id: "act-1", status: "abandoned", learning_id: null }),- );- const r = await call("review_goal_action", {- ...BASE,- action_id: "act-1",- observed_outcome: "reverted",- abandoned: true,- });- expect(text(r)).toBe("action act-1 abandoned.");- });-});--describe("log_learning / search_learnings", () => {- it("log_learning confirms the recorded id", async () => {- handlers.handleLogLearning.mockReturnValueOnce(ok({ learning_id: "lrn-1" }));- const r = await call("log_learning", {- ...BASE,- body: "Brand campaigns cap out at ~$40/day",- confidence: "high",- });- expect(handlers.handleLogLearning).toHaveBeenCalledWith(- { goal_id: "goal-1", body: "Brand campaigns cap out at ~$40/day", confidence: "high" },- CTX,- );- expect(text(r)).toBe("learning lrn-1 recorded.");- });-- it("search_learnings returns the matches as JSON", async () => {- handlers.handleSearchLearnings.mockReturnValueOnce(- ok({ learnings: [{ id: "lrn-1", body: "fact" }] }),- );- const r = await call("search_learnings", { ...BASE, query: "fact", limit: 5 });- expect(handlers.handleSearchLearnings).toHaveBeenCalledWith(- { goal_id: "goal-1", query: "fact", limit: 5 },- CTX,- );- expect(JSON.parse(text(r))).toEqual([{ id: "lrn-1", body: "fact" }]);- });-});--describe("update_goal_status", () => {- it("dispatches and confirms the new status", async () => {- handlers.handleUpdateGoalStatus.mockReturnValueOnce(- ok({ goal_id: "goal-1", status: "achieved" }),- );- const r = await call("update_goal_status", {- ...BASE,- status: "achieved",- reason: "CAC measured at $28.40, target $30",- });- expect(text(r)).toBe("goal goal-1 is now 'achieved'.");- });-- it("rejects statuses outside the enum", async () => {- const r = await call("update_goal_status", { ...BASE, status: "done", reason: "x" });- expect(r.ok).toBe(false);- });-});--describe("get_project / set_shared_context", () => {- it("get_project returns project metadata as JSON", async () => {- handlers.handleGetProject.mockReturnValueOnce(ok({ slug: "proj", website: "https://x.co" }));- const r = await call("get_project", { project_slug: "proj", agent_id: "agent-1" });- expect(handlers.handleGetProject).toHaveBeenCalledWith({}, CTX);- expect(JSON.parse(text(r))).toEqual({ slug: "proj", website: "https://x.co" });- });-- it("set_shared_context pluralizes the synced-agent count", async () => {- handlers.handleSetProjectBrief.mockResolvedValueOnce(ok({ bytes: 512, synced_agents: 2 }));- const two = await call("set_shared_context", {- project_slug: "proj",- agent_id: "agent-1",- content: "# Brief",- });- expect(handlers.handleSetProjectBrief).toHaveBeenCalledWith({ content: "# Brief" }, CTX);- expect(text(two)).toBe("shared context updated (512 bytes); 2 agent identities re-rendered.");-- handlers.handleSetProjectBrief.mockResolvedValueOnce(ok({ bytes: 64, synced_agents: 1 }));- const one = await call("set_shared_context", {- project_slug: "proj",- agent_id: "agent-1",- content: "# Brief",- });- expect(text(one)).toBe("shared context updated (64 bytes); 1 agent identity re-rendered.");- });-});diff --git a/notfair/src/server/mcp-server/tools.ts b/notfair/src/server/mcp-server/tools.tsdeleted file mode 100644index 88797fdb..00000000--- a/notfair/src/server/mcp-server/tools.ts+++ /dev/null@@ -1,703 +0,0 @@-import { z } from "zod";-import { CronExpressionParser } from "cron-parser";--import {- handleAmendGoal,- handleAddSupportMetric,- handleBackfillHistory,- handleDefineGoal,- handleGetGoal,- handleGetProject,- handleLogGoalAction,- handleLogLearning,- handleProposeGoalMetric,- handleProposeTarget,- handleRegisterPullRequest,- handleReviewGoalAction,- handleSearchLearnings,- handleSetProjectBrief,- handleUpdateGoalStatus,-} from "@/server/goals/handlers";--/**- * Tool definitions exposed by NotFair's MCP server to goal agents. The- * server is globally shared (one bearer for every project), so every tool- * takes required `project_slug` + `agent_id` args the caller fills from- * its IDENTITY.md — we never derive identity from the bearer.- *- * The surface is deliberately small: the goal lifecycle- * (define → propose metric → propose target on the user's confirm, which- * starts the loop), the loop's bookkeeping- * (actions, reviews, learnings, status), the shared workspace context,- * and auxiliary scheduling. There is no task board, no approvals, no- * delegation — one agent, one goal, one loop.- */--// ── Shared scaffolding ─────────────────────────────────────────────────--export type ToolHandlerContext = {- /** Reserved for future per-agent bearer scoping. Unused today. */- agentId?: string;-};--export type ToolResult =- | { ok: true; content: { type: "text"; text: string }[] }- | { ok: false; error: string };--export type ToolDefinition = {- name: string;- description: string;- inputSchema: z.ZodObject<z.ZodRawShape>;- handler: (input: unknown, ctx: ToolHandlerContext) => Promise<ToolResult>;-};--function invalid(err: z.ZodError): ToolResult {- return {- ok: false,- error: `Invalid arguments: ${err.issues.map((i) => `${i.path.join(".")} ${i.message}`).join("; ")}`,- };-}--function txt(text: string): ToolResult {- return { ok: true, content: [{ type: "text", text }] };-}--const callerFields = {- project_slug: z.string().min(1).describe("From IDENTITY.md."),- agent_id: z.string().min(1).describe("Your own agent_id, from IDENTITY.md."),-};--const goalIdFields = {- ...callerFields,- goal_id: z.string().min(1).describe("Your goal_id, from IDENTITY.md."),-};--// ── get_goal ───────────────────────────────────────────────────────────--const getGoalInput = z.object({ ...goalIdFields });--async function handleGetGoalTool(input: unknown): Promise<ToolResult> {- const parsed = getGoalInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, agent_id, goal_id } = parsed.data;- const r = await handleGetGoal({ goal_id }, { project_slug, agent_id });- if (!r.ok) return { ok: false, error: r.error };- return txt(JSON.stringify(r.data, null, 2));-}--// ── define_goal ────────────────────────────────────────────────────────--const defineGoalInput = z.object({- ...goalIdFields,- statement: z- .string()- .min(1)- .describe(- "The ambition, concrete enough to measure — e.g. 'Cut Google Ads CAC to ~$30 within 60 days'. Refine by calling again while still in intake.",- ),- short_label: z- .string()- .min(1)- .max(48)- .describe(- "Compact display label for the sidebar/dashboard, ≤ 5 words with the number — e.g. 'Wasted X spend → $0', 'CAC → $30'. This is how the user identifies the goal everywhere.",- ),- deadline: z- .string()- .optional()- .describe("ISO date the user stated, if any (e.g. 2026-09-01)."),- spend_envelope_usd: z- .number()- .optional()- .describe("Total incremental ad spend the user authorized, if stated."),-});--async function handleDefineGoalTool(input: unknown): Promise<ToolResult> {- const parsed = defineGoalInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, agent_id, ...rest } = parsed.data;- const r = handleDefineGoal(rest, { project_slug, agent_id });- if (!r.ok) return { ok: false, error: r.error };- return txt(`goal defined: "${r.data.statement}". Next: author + test the metric, then propose_goal_metric.`);-}--// ── propose_goal_metric ────────────────────────────────────────────────--const proposeGoalMetricInput = z.object({- ...goalIdFields,- metric_name: z- .string()- .min(1)- .describe("Human label incl. unit + window, e.g. 'CAC (USD, trailing 30d)'."),- metric_source_key: z- .string()- .min(1)- .describe(- "Connected catalog MCP key (e.g. 'notfair-googleads'), or 'local' to measure via a shell command the platform runs on this machine.",- ),- metric_source_tool: z- .string()- .min(1)- .describe("Tool to call on that server, usually 'runScript'. For the 'local' source: 'shell'."),- metric_source_args_json: z- .string()- .min(1)- .describe(- "JSON-encoded arguments object for the tool call. The call must return a single number (or {value: number}). For 'local': {\"command\": \"<sh command>\"} whose stdout is that number. You must have TESTED this exact call yourself first.",- ),- metric_direction: z- .enum(["increase", "decrease"])- .describe("Which way is progress: 'increase' (signups, ROAS) or 'decrease' (CAC, wasted spend)."),-});--async function handleProposeGoalMetricTool(input: unknown): Promise<ToolResult> {- const parsed = proposeGoalMetricInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, agent_id, ...rest } = parsed.data;- const r = await handleProposeGoalMetric(rest, { project_slug, agent_id });- if (!r.ok) return { ok: false, error: r.error };- return txt(- `Metric verified server-side. Baseline measured: ${r.data.baseline_value}. Report this to the user, suggest a target + cadence + spend envelope, and record it with propose_target once they agree — recording it starts the loop immediately.`,- );-}--// ── backfill_metric_history ────────────────────────────────────────────--const backfillHistoryInput = z.object({- ...goalIdFields,- source_key: z- .string()- .min(1)- .describe(- "Connected catalog MCP key (usually the same as the metric's), or 'local' for a shell command.",- ),- source_tool: z- .string()- .min(1)- .describe("Tool to call, usually 'runScript'. For the 'local' source: 'shell'."),- source_args_json: z- .string()- .min(1)- .describe(- "JSON-encoded arguments for a DATE-SEGMENTED query returning an array of {date: 'YYYY-MM-DD', value: number} — one point per day, ~30 days, same definition as the goal metric. For 'local': {\"command\": \"<sh command>\"} printing that array to stdout. TEST it yourself first.",- ),-});--async function handleBackfillHistoryTool(input: unknown): Promise<ToolResult> {- const parsed = backfillHistoryInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, agent_id, ...rest } = parsed.data;- const r = await handleBackfillHistory(rest, { project_slug, agent_id });- if (!r.ok) return { ok: false, error: r.error };- return txt(- `History backfilled: ${r.data.points} daily points from ${r.data.from} to ${r.data.to}. The progress chart now has context.`,- );-}--// ── add_supporting_metric ──────────────────────────────────────────────--const addSupportMetricInput = z.object({- ...goalIdFields,- name: z- .string()- .min(1)- .describe("Human label incl. unit + window, e.g. 'Listing PRs open (live)'. Re-using a name redefines that metric."),- source_key: z- .string()- .min(1)- .describe(- "Connected catalog MCP key (e.g. 'notfair-googleads'), or 'local' for a shell command.",- ),- source_tool: z- .string()- .min(1)- .describe("Tool to call on that server, usually 'runScript'. For the 'local' source: 'shell'."),- source_args_json: z- .string()- .min(1)- .describe(- "JSON-encoded arguments object for the tool call. Must return a single number (or {value: number}); for 'local': {\"command\": \"<sh command>\"} whose stdout is that number. TEST it yourself first.",- ),- direction: z- .enum(["increase", "decrease"])- .optional()- .describe("Which way is healthy, if there is one — context only, never judged."),- history_args_json: z- .string()- .optional()- .describe(- "Optional: DATE-SEGMENTED version of the same query (same source) returning an array of {date: 'YYYY-MM-DD', value: number}, ~30 days — gives the metric's chart a past from day one. Replaces any earlier backfill. TEST it yourself first.",- ),-});--async function handleAddSupportMetricTool(input: unknown): Promise<ToolResult> {- const parsed = addSupportMetricInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, agent_id, ...rest } = parsed.data;- const r = await handleAddSupportMetric(rest, { project_slug, agent_id });- if (!r.ok) return { ok: false, error: r.error };- return txt(- `Supporting metric '${r.data.metric.name}' verified — current value ${r.data.metric.current_value}${r.data.backfilled > 0 ? `, ${r.data.backfilled} history points backfilled` : ""}. The platform now measures it on every check; it appears on your Goal tab and in every tick brief. The goal is still judged on the primary metric only.`,- );-}--// ── propose_target / amend_goal ────────────────────────────────────────--const proposeTargetInput = z.object({- ...goalIdFields,- target_value: z- .number()- .describe("The number you and the user landed on in chat."),- mode: z- .enum(["achieve", "maintain"])- .optional()- .describe(- "achieve (default) = the goal completes when the target is reached. maintain = HOLD the number there indefinitely (\"keep waste at $0\") — the loop keeps watching and never self-completes.",- ),- deadline: z.string().optional().describe("ISO date, if agreed."),- spend_envelope_usd: z- .number()- .optional()- .describe("Total incremental spend ceiling, if agreed."),- cadence_cron: z- .string()- .optional()- .describe(- "5-field UTC cron for the heartbeat. Common: '0 16 * * *' daily 9am PT, '0 16 * * 1-5' weekdays, '0 16 * * 1' weekly Monday. Defaults to daily.",- ),-});--async function handleProposeTargetTool(input: unknown): Promise<ToolResult> {- const parsed = proposeTargetInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, agent_id, ...rest } = parsed.data;- if (rest.cadence_cron) {- try {- CronExpressionParser.parse(rest.cadence_cron, { tz: "UTC" });- } catch {- return { ok: false, error: `Invalid cadence_cron '${rest.cadence_cron}' — must be a 5-field cron expression.` };- }- }- const r = handleProposeTarget(rest, { project_slug, agent_id });- if (!r.ok) return { ok: false, error: r.error };- return txt(- "Target recorded — the loop is LIVE and the first check is running now. Tell the user the plan is locked in and they can watch the first check on their Goal tab.",- );-}--const amendGoalInput = z.object({- ...goalIdFields,- target_value: z.number().optional().describe("New target, if the user changed it."),- deadline: z.string().optional().describe("New ISO deadline."),- spend_envelope_usd: z.number().optional().describe("New total spend ceiling."),- cadence_cron: z.string().optional().describe("New 5-field UTC heartbeat cron."),-});--async function handleAmendGoalTool(input: unknown): Promise<ToolResult> {- const parsed = amendGoalInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, agent_id, ...rest } = parsed.data;- if (rest.cadence_cron) {- try {- CronExpressionParser.parse(rest.cadence_cron, { tz: "UTC" });- } catch {- return { ok: false, error: `Invalid cadence_cron '${rest.cadence_cron}' — must be a 5-field cron expression.` };- }- }- const r = handleAmendGoal(rest, { project_slug, agent_id });- if (!r.ok) return { ok: false, error: r.error };- const d = r.data;- return txt(- `Goal amended: target=${d.target_value ?? "—"}, deadline=${d.deadline ?? "none"}, envelope=${d.spend_envelope_usd !== null ? `$${d.spend_envelope_usd}` : "none"}, cadence=${d.cadence_cron}. Confirm the change back to the user.`,- );-}--// ── log_goal_action ────────────────────────────────────────────────────--const logGoalActionInput = z.object({- ...goalIdFields,- kind: z- .enum(["mutation", "research", "decision"])- .describe(- "mutation = a platform write (bid, budget, pause, creative). research = read-only investigation. decision = a strategic choice worth recording.",- ),- description: z- .string()- .min(1)- .describe("What you did / are about to do. Be specific — quote IDs and dollar amounts."),- resources_touched: z- .string()- .optional()- .describe(- "Comma-separated resource keys the action touches, e.g. 'campaign:123,adgroup:456'. Required for mutations.",- ),- expected_effect: z- .string()- .min(1)- .describe("The falsifiable prediction, e.g. 'CPA -$3 within 7 days'. You will be scored against this at review time."),- review_after_hours: z- .number()- .optional()- .describe(- "Observation window in hours before this action's resources may be touched again. REQUIRED for mutations. Derive it from your metric's latency, never a default: hourly server metrics 24–72h, waste pauses 72h+, bid/budget 120h+, creative/keywords/SEO 168h+. It is maximum patience — review_goal_action accepts a verdict early when post-change data is decisive.",- ),- spend_usd: z- .number()- .optional()- .describe(- "Estimated INCREMENTAL spend this action commits (e.g. a budget raise's expected extra cost until review). The platform sums these against the envelope and shows the total in every tick brief. Omit for spend-neutral actions.",- ),- action_badge: z- .string()- .max(60)- .optional()- .describe(- "2–4 word past-tense badge naming what changed, shown on this check's diary row (e.g. 'Budget updated', 'Keywords paused', 'Ad label updated'). REQUIRED for mutations, except pull-request changes — the PR badge is automatic, omit it there. Omit for research/decision actions.",- ),-});--async function handleLogGoalActionTool(input: unknown): Promise<ToolResult> {- const parsed = logGoalActionInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, agent_id, resources_touched, ...rest } = parsed.data;- const r = handleLogGoalAction(- {- ...rest,- resources_touched: resources_touched- ? resources_touched.split(",").map((s) => s.trim()).filter(Boolean)- : [],- },- { project_slug, agent_id },- );- if (!r.ok) return { ok: false, error: r.error };- return txt(- `action ${r.data.action_id} logged.${r.data.review_after ? ` Review due ${r.data.review_after}. Its resources are gated until then.` : ""}`,- );-}--// ── review_goal_action ─────────────────────────────────────────────────--const reviewGoalActionInput = z.object({- ...goalIdFields,- action_id: z.string().min(1).describe("The open action you're scoring."),- observed_outcome: z- .string()- .min(1)- .describe("What actually happened vs. expected_effect, with the numbers."),- abandoned: z- .boolean()- .optional()- .describe("true when the action was reverted/obsoleted rather than measured."),- learning: z- .string()- .optional()- .describe("Optional durable learning to record alongside the review."),-});--async function handleReviewGoalActionTool(input: unknown): Promise<ToolResult> {- const parsed = reviewGoalActionInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, agent_id, ...rest } = parsed.data;- const r = handleReviewGoalAction(rest, { project_slug, agent_id });- if (!r.ok) return { ok: false, error: r.error };- return txt(- `action ${r.data.action_id} ${r.data.status}.${r.data.learning_id ? ` Learning ${r.data.learning_id} recorded.` : ""}`,- );-}--// ── log_learning / search_learnings ────────────────────────────────────--const logLearningInput = z.object({- ...goalIdFields,- body: z- .string()- .min(1)- .describe("The durable fact, specific enough to act on later. Quote numbers."),- confidence: z.enum(["low", "medium", "high"]).optional().describe("Default medium."),- supersedes_id: z- .string()- .optional()- .describe("Learning this replaces — supersede stale facts instead of contradicting them."),-});--async function handleLogLearningTool(input: unknown): Promise<ToolResult> {- const parsed = logLearningInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, agent_id, ...rest } = parsed.data;- const r = handleLogLearning(rest, { project_slug, agent_id });- if (!r.ok) return { ok: false, error: r.error };- return txt(`learning ${r.data.learning_id} recorded.`);-}--const searchLearningsInput = z.object({- ...goalIdFields,- query: z- .string()- .optional()- .describe("Substring to search for. Omit to list the most recent learnings."),- limit: z.number().optional().describe("Max results (default 20, cap 50)."),-});--async function handleSearchLearningsTool(input: unknown): Promise<ToolResult> {- const parsed = searchLearningsInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, agent_id, ...rest } = parsed.data;- const r = handleSearchLearnings(rest, { project_slug, agent_id });- if (!r.ok) return { ok: false, error: r.error };- return txt(JSON.stringify(r.data.learnings, null, 2));-}--// ── update_goal_status ─────────────────────────────────────────────────--const updateGoalStatusInput = z.object({- ...goalIdFields,- status: z- .enum(["achieved", "failed", "paused"])- .describe(- "achieved = target met (verified against the measured metric). failed = can't be met (deadline/envelope/blocked). paused = needs the user before the loop can continue.",- ),- reason: z- .string()- .min(1)- .describe("Evidence-based reason, quoting the measured metric."),-});--async function handleUpdateGoalStatusTool(input: unknown): Promise<ToolResult> {- const parsed = updateGoalStatusInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, agent_id, ...rest } = parsed.data;- const r = handleUpdateGoalStatus(rest, { project_slug, agent_id });- if (!r.ok) return { ok: false, error: r.error };- return txt(`goal ${r.data.goal_id} is now '${r.data.status}'.`);-}--// ── get_project / set_shared_context ───────────────────────────────────--const getProjectInput = z.object({ ...callerFields });--async function handleGetProjectTool(input: unknown): Promise<ToolResult> {- const parsed = getProjectInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, agent_id } = parsed.data;- const r = handleGetProject({}, { project_slug, agent_id });- if (!r.ok) return { ok: false, error: r.error };- return txt(JSON.stringify(r.data, null, 2));-}--const setSharedContextInput = z.object({- ...callerFields,- content: z- .string()- .min(1)- .describe(- "The FULL new shared context (markdown). This replaces the previous version — read the current one first (get_goal returns it) and edit, don't blindly overwrite.",- ),-});--async function handleSetSharedContextTool(input: unknown): Promise<ToolResult> {- const parsed = setSharedContextInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, agent_id, content } = parsed.data;- const r = await handleSetProjectBrief({ content }, { project_slug, agent_id });- if (!r.ok) return { ok: false, error: r.error };- return txt(- `shared context updated (${r.data.bytes} bytes); ${r.data.synced_agents} agent identit${r.data.synced_agents === 1 ? "y" : "ies"} re-rendered.`,- );-}--// ── register_pull_request ──────────────────────────────────────────────--const registerPullRequestInput = z.object({- ...goalIdFields,- url: z- .string()- .min(1)- .describe(- "The GitHub pull-request URL you just opened, e.g. https://github.com/owner/repo/pull/123.",- ),- title: z.string().min(1).max(200).describe("The PR title."),- branch: z.string().optional().describe("The head branch name."),- action_id: z- .string()- .optional()- .describe(- "The log_goal_action id this PR executes — link them so the observation gate and the PR travel together.",- ),-});--async function handleRegisterPullRequestTool(- input: unknown,-): Promise<ToolResult> {- const parsed = registerPullRequestInput.safeParse(input);- if (!parsed.success) return invalid(parsed.error);- const { project_slug, agent_id, ...rest } = parsed.data;- const r = await handleRegisterPullRequest(rest, { project_slug, agent_id });- if (!r.ok) return { ok: false, error: r.error };- return txt(- `PR registered (state: ${r.data.state}). The user sees it on your Goal tab for review; every tick brief carries its live state (reviews, comments, merged/closed). Do NOT merge it yourself — the user does.`,- );-}--// ── Registry ───────────────────────────────────────────────────────────--export const TOOLS: ToolDefinition[] = [- {- name: "get_goal",- description:- "Fetch your goal's full state: spec, metric history, open actions (due-for-review vs still-gated), recent learnings and ticks, plus the shared workspace context. Call FIRST whenever you've lost context — this is the re-anchor tool.",- inputSchema: getGoalInput,- handler: handleGetGoalTool,- },- {- name: "define_goal",- description:- "Intake step 1: record the ambition the user articulated in chat (statement + any stated deadline/spend envelope). Repeatable while the goal is in intake — refine as the conversation sharpens.",- inputSchema: defineGoalInput,- handler: handleDefineGoalTool,- },- {- name: "propose_goal_metric",- description:- "Intake step 2: submit the metric definition you authored AND tested. The platform re-runs the exact tool call server-side; only a reproducible single number moves the goal to 'proposed' and records the baseline. Fails with the error if the query can't be verified — fix and propose again.",- inputSchema: proposeGoalMetricInput,- handler: handleProposeGoalMetricTool,- },- {- name: "backfill_metric_history",- description:- "Reconstruct the metric's past: run a date-segmented version of the metric query (per-day values, ~30 days) so the user's progress chart has history from day one. Platform-verified like the metric; replaces any earlier backfill. Call during intake right after propose_goal_metric.",- inputSchema: backfillHistoryInput,- handler: handleBackfillHistoryTool,- },- {- name: "add_supporting_metric",- description:- "Attach a SUPPORTING metric to your goal — a second number the platform measures on every check alongside the primary (leading indicators, diagnostics: 'PRs opened' while merges are the target). Platform-verified like the primary; re-using a name redefines that metric. No target semantics — the goal is judged on the primary metric only. Usable at any point in the goal's life.",- inputSchema: addSupportMetricInput,- handler: handleAddSupportMetricTool,- },- {- name: "propose_target",- description:- "Intake step 3: record the target/cadence/spend envelope the user agreed to in chat. Recording it STARTS the loop — the goal goes active and the first check fires immediately, so call this ONLY after the user has explicitly confirmed the plan. Rejects targets on the wrong side of the baseline.",- inputSchema: proposeTargetInput,- handler: handleProposeTargetTool,- },- {- name: "amend_goal",- description:- "Adjust a LIVE goal when the user asks: new target, deadline, spend envelope, or heartbeat cadence. Active/paused goals only; echo the change back to the user after. Never amend without the user having asked.",- inputSchema: amendGoalInput,- handler: handleAmendGoalTool,- },- {- name: "log_goal_action",- description:- "Record a move BEFORE executing it: what, which resources, the falsifiable expected effect, and the observation window (review_after_hours, required for mutations). Gated resources are untouchable until their review date. Unlogged mutations are invisible to future ticks — always log first.",- inputSchema: logGoalActionInput,- handler: handleLogGoalActionTool,- },- {- name: "register_pull_request",- description:- "Record a pull request you just opened against the workspace's codebase (gh pr create → register here). The PR is the approval gate for code changes: the user reviews and merges on GitHub, the platform syncs its state (review decision, comments, merged/closed) into every tick brief, and your Goal tab shows it for review. Never merge your own PR.",- inputSchema: registerPullRequestInput,- handler: handleRegisterPullRequestTool,- },- {- name: "review_goal_action",- description:- "Score an open action whose review date arrived: observed outcome vs. expected_effect, with numbers. Closes the measurement loop and (optionally) records a learning. Do this at the START of a tick, before any new move.",- inputSchema: reviewGoalActionInput,- handler: handleReviewGoalActionTool,- },- {- name: "log_learning",- description:- "Write a durable fact to your own memory (survives context rotation). Use for anything future ticks must know: platform quirks, what worked, decisions made in chat. Supersede stale learnings instead of contradicting them.",- inputSchema: logLearningInput,- handler: handleLogLearningTool,- },- {- name: "search_learnings",- description:- "Query your own memory. Call while orienting, before acting — check what you already know about a campaign/keyword/tactic before touching it.",- inputSchema: searchLearningsInput,- handler: handleSearchLearningsTool,- },- {- name: "update_goal_status",- description:- "Declare your goal achieved / failed, or pause it. Requires an evidence-based reason; 'achieved' is rejected unless the measured metric actually meets the target. Resume and close belong to the user in the UI.",- inputSchema: updateGoalStatusInput,- handler: handleUpdateGoalStatusTool,- },- {- name: "get_project",- description:- "Fetch project metadata: connected account ids (Google Ads / Meta / GSC), website, harness. Cheap re-anchor for platform facts.",- inputSchema: getProjectInput,- handler: handleGetProjectTool,- },- {- name: "set_shared_context",- description:- "Rewrite the shared workspace context (PROJECT.md) — the brief EVERY agent in this workspace sees in its identity: what the company sells, who buys, positioning, voice, global constraints. Update it when you learn something all agents should know. Full replacement: read the current version first (get_goal returns it) and edit.",- inputSchema: setSharedContextInput,- handler: handleSetSharedContextTool,- },-];--// Browser MCP tools live in their own server (notfair-browser) so this-// surface stays focused. See ./browser-tools.ts and the /api/mcp/browser-// route.--export function describeTool(tool: ToolDefinition): {- name: string;- description: string;- inputSchema: Record<string, unknown>;-} {- return {- name: tool.name,- description: tool.description,- inputSchema: zodObjectToJsonSchema(tool.inputSchema),- };-}--export function findTool(name: string): ToolDefinition | undefined {- return TOOLS.find((t) => t.name === name);-}--/**- * Minimal zod→JSON-schema conversion covering the shapes we use- * (string / number / boolean / enum, optional, describe). Anything more- * exotic falls back to `{type:"string"}` — the handler's safeParse is the- * real validation.- */-function zodObjectToJsonSchema(schema: z.ZodObject<z.ZodRawShape>): Record<string, unknown> {- const properties: Record<string, unknown> = {};- const required: string[] = [];- for (const [key, raw] of Object.entries(schema.shape)) {- let field = raw as z.ZodTypeAny;- let isOptional = false;- while (field instanceof z.ZodOptional || field instanceof z.ZodDefault) {- isOptional = true;- field = field._def.innerType as z.ZodTypeAny;- }- const description = (field as { description?: string }).description ?? (raw as { description?: string }).description;- let prop: Record<string, unknown>;- if (field instanceof z.ZodEnum) {- prop = { type: "string", enum: field.options };- } else if (field instanceof z.ZodNumber) {- prop = { type: "number" };- } else if (field instanceof z.ZodBoolean) {- prop = { type: "boolean" };- } else {- prop = { type: "string" };- }- if (description) prop.description = description;- properties[key] = prop;- if (!isOptional) required.push(key);- }- return { type: "object", properties, required, additionalProperties: false };-}diff --git a/notfair/src/server/mcp/account-selection.test.ts b/notfair/src/server/mcp/account-selection.test.tsdeleted file mode 100644index e888ca54..00000000--- a/notfair/src/server/mcp/account-selection.test.ts+++ /dev/null@@ -1,186 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--import {- resolvePostConnectSelection,- prefetchAccountChoice,-} from "@/server/mcp/account-selection";-import {- getProject,- setProjectGscProperty,- setProjectGoogleAdsAccount,-} from "@/server/db/projects";-import { listGscProperties } from "@/server/onboarding/accounts";-import type { Project } from "@/types";--// Mock at the platform-action + db layer so the real registry-// (mcp-account-pickers) is exercised as part of the resolution.-vi.mock("@/server/onboarding/accounts", () => ({- listGoogleAdsAccounts: vi.fn(),- setOnboardingAccountAction: vi.fn(),- listMetaAdsAccounts: vi.fn(),- setOnboardingMetaAdsAccountAction: vi.fn(),- listGscProperties: vi.fn(),- setOnboardingGscPropertyAction: vi.fn(),-}));-vi.mock("@/server/db/projects", () => ({- getProject: vi.fn(),- setProjectGoogleAdsAccount: vi.fn(),- setProjectMetaAdsAccount: vi.fn(),- setProjectGscProperty: vi.fn(),-}));--const GSC = "notfair-googlesearchconsole";--function makeProject(overrides: Partial<Project> = {}): Project {- return {- google_ads_account_id: null,- meta_ads_account_id: null,- gsc_property_id: null,- ...overrides,- } as Project;-}--function gscList(ids: string[]) {- vi.mocked(listGscProperties).mockResolvedValue({- ok: true,- properties: ids.map((id) => ({ id, name: id })),- });-}--beforeEach(() => {- vi.clearAllMocks();-});--describe("resolvePostConnectSelection", () => {- it("is not_pickable for MCPs without a picker (never lists)", async () => {- const r = await resolvePostConnectSelection("proj", "notfair-xads");- expect(r).toEqual({ kind: "not_pickable" });- expect(listGscProperties).not.toHaveBeenCalled();- });-- it("is not_pickable when the project row is gone", async () => {- vi.mocked(getProject).mockReturnValue(null);- const r = await resolvePostConnectSelection("proj", GSC);- expect(r).toEqual({ kind: "not_pickable" });- });-- it("keeps an existing selection the new bearer can still reach", async () => {- vi.mocked(getProject).mockReturnValue(- makeProject({ gsc_property_id: "sc-domain:a.com" }),- );- gscList(["sc-domain:a.com", "sc-domain:b.com"]);- const r = await resolvePostConnectSelection("proj", GSC);- expect(r).toEqual({ kind: "kept_existing" });- expect(setProjectGscProperty).not.toHaveBeenCalled();- });-- it("auto-persists the only reachable account", async () => {- vi.mocked(getProject).mockReturnValue(makeProject());- gscList(["sc-domain:only.com"]);- const r = await resolvePostConnectSelection("proj", GSC);- expect(r).toEqual({- kind: "auto_selected",- id: "sc-domain:only.com",- name: "sc-domain:only.com",- });- expect(setProjectGscProperty).toHaveBeenCalledWith(- "proj",- "sc-domain:only.com",- );- });-- it("requires a choice when the bearer reaches several accounts", async () => {- vi.mocked(getProject).mockReturnValue(makeProject());- gscList(["sc-domain:a.com", "sc-domain:b.com"]);- const r = await resolvePostConnectSelection("proj", GSC);- expect(r).toEqual({ kind: "choice_required" });- expect(setProjectGscProperty).not.toHaveBeenCalled();- });-- it("requires a choice when the old selection is no longer reachable", async () => {- vi.mocked(getProject).mockReturnValue(- makeProject({ gsc_property_id: "sc-domain:gone.com" }),- );- gscList(["sc-domain:a.com", "sc-domain:b.com"]);- const r = await resolvePostConnectSelection("proj", GSC);- expect(r).toEqual({ kind: "choice_required" });- });-- it("requires a choice (to surface the problem) when the list call fails", async () => {- vi.mocked(getProject).mockReturnValue(makeProject());- vi.mocked(listGscProperties).mockResolvedValue({- ok: false,- kind: "rpc",- error: "timeout",- });- const r = await resolvePostConnectSelection("proj", GSC);- expect(r).toEqual({ kind: "choice_required" });- });-- it("routes each platform to its own project column", async () => {- const { listGoogleAdsAccounts } = await import(- "@/server/onboarding/accounts"- );- vi.mocked(getProject).mockReturnValue(makeProject());- vi.mocked(listGoogleAdsAccounts).mockResolvedValue({- ok: true,- accounts: [{ id: "123", name: "Only" }],- });- await resolvePostConnectSelection("proj", "notfair-googleads");- expect(setProjectGoogleAdsAccount).toHaveBeenCalledWith("proj", "123");- expect(setProjectGscProperty).not.toHaveBeenCalled();- });-});--describe("prefetchAccountChoice", () => {- it("returns null for non-pickable MCPs", async () => {- const r = await prefetchAccountChoice(makeProject(), "stripe");- expect(r).toBeNull();- });-- it("returns null when the persisted selection is still reachable", async () => {- gscList(["sc-domain:a.com"]);- const r = await prefetchAccountChoice(- makeProject({ gsc_property_id: "sc-domain:a.com" }),- GSC,- );- expect(r).toBeNull();- });-- it("hands the list + current selection to the dialog when a choice is due", async () => {- gscList(["sc-domain:a.com", "sc-domain:b.com"]);- const r = await prefetchAccountChoice(- makeProject({ gsc_property_id: "sc-domain:gone.com" }),- GSC,- );- expect(r).toEqual({- prefetch: {- ok: true,- items: [- { id: "sc-domain:a.com", name: "sc-domain:a.com" },- { id: "sc-domain:b.com", name: "sc-domain:b.com" },- ],- },- selected_id: "sc-domain:gone.com",- });- });-- it("passes a list failure through so the dialog can show it", async () => {- vi.mocked(listGscProperties).mockResolvedValue({- ok: false,- kind: "rpc",- error: "HTTP 502",- });- const r = await prefetchAccountChoice(makeProject(), GSC);- expect(r).toEqual({- prefetch: { ok: false, error: "HTTP 502" },- selected_id: null,- });- });-- it("never writes — auto-selection is the OAuth callback's job", async () => {- gscList(["sc-domain:only.com"]);- await prefetchAccountChoice(makeProject(), GSC);- expect(setProjectGscProperty).not.toHaveBeenCalled();- });-});diff --git a/notfair/src/server/mcp/account-selection.ts b/notfair/src/server/mcp/account-selection.tsdeleted file mode 100644index c5064c0b..00000000--- a/notfair/src/server/mcp/account-selection.ts+++ /dev/null@@ -1,95 +0,0 @@-/**- * Server-side post-connect account/property resolution for multi-account- * MCPs (Google Ads, Meta Ads, Search Console).- *- * Runs inside the OAuth callback, before the redirect back to the app:- *- * - selection already set and still reachable by the new bearer → keep it;- * - the bearer reaches exactly one account/property → persist it (there is- * no real choice to offer);- * - otherwise → `choice_required`, and the callback appends `?mcp_key=` so- * the Connections page opens the picker dialog.- *- * Doing this server-side (rather than in a client effect after landing)- * matters: a mount-time server-action fetch races the flash banner's- * URL-cleanup navigation, which can strand the action's promise.- */--import { accountPickerFor } from "@/lib/mcp-account-pickers";-import {- getProject,- setProjectGoogleAdsAccount,- setProjectMetaAdsAccount,- setProjectGscProperty,-} from "@/server/db/projects";-import type { AccountPickerPrefetch } from "@/components/mcp-account-picker-dialog";-import type { Project } from "@/types";--const SETTERS: Record<- string,- (slug: string, id: string | null) => Project | null-> = {- "notfair-googleads": setProjectGoogleAdsAccount,- "notfair-metaads": setProjectMetaAdsAccount,- "notfair-googlesearchconsole": setProjectGscProperty,-};--export type PostConnectSelection =- | { kind: "not_pickable" }- | { kind: "kept_existing" }- | { kind: "auto_selected"; id: string; name: string }- | { kind: "choice_required" };--export async function resolvePostConnectSelection(- project_slug: string,- catalog_key: string,-): Promise<PostConnectSelection> {- const picker = accountPickerFor(catalog_key);- const setter = SETTERS[catalog_key];- if (!picker || !setter) return { kind: "not_pickable" };- const project = getProject(project_slug);- if (!project) return { kind: "not_pickable" };-- const list = await picker.list(project_slug);- // Can't reach the MCP right now — let the Connections page's picker- // surface the problem (it retries the list on render).- if (!list.ok) return { kind: "choice_required" };-- const selected = picker.selectedId(project);- if (selected && list.items.some((i) => i.id === selected)) {- return { kind: "kept_existing" };- }- if (list.items.length === 1) {- const only = list.items[0]!;- setter(project_slug, only.id);- return { kind: "auto_selected", id: only.id, name: only.name };- }- // Zero or many — the user has to look at it either way.- return { kind: "choice_required" };-}--/**- * Server-render-time prefetch for the account picker dialog. Pages that- * receive the post-OAuth `?mcp_key=` (Connections, onboarding connect- * step) call this during render and hand the result to the client, so- * the dialog opens with data instead of racing the flash banner's- * URL-cleanup navigation with a mount-time fetch.- *- * Returns null when no picker should open: unknown/non-pickable key, or- * the persisted selection is still reachable (covers stale URLs — the- * OAuth callback normally filters that case before appending the param).- * Read-only by design: auto-selecting a lone account is the callback's- * job; a GET render must not write.- */-export async function prefetchAccountChoice(- project: Project,- mcp_key: string,-): Promise<{ prefetch: AccountPickerPrefetch; selected_id: string | null } | null> {- const picker = accountPickerFor(mcp_key);- if (!picker) return null;- const selected_id = picker.selectedId(project);- const list = await picker.list(project.slug);- if (!list.ok) return { prefetch: { ok: false, error: list.error }, selected_id };- if (selected_id && list.items.some((i) => i.id === selected_id)) return null;- return { prefetch: { ok: true, items: list.items }, selected_id };-}diff --git a/notfair/src/server/mcp/catalog-token.test.ts b/notfair/src/server/mcp/catalog-token.test.tsdeleted file mode 100644index 01ea03e0..00000000--- a/notfair/src/server/mcp/catalog-token.test.ts+++ /dev/null@@ -1,73 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- getMcpCatalog: vi.fn(),- mcpSpecByKey: vi.fn(),- findMcpToken: vi.fn(),-}));--vi.mock("@/server/mcp-catalog", () => ({- getMcpCatalog: mocks.getMcpCatalog,- mcpSpecByKey: mocks.mcpSpecByKey,-}));-vi.mock("@/server/mcp/tokens", () => ({- findMcpToken: mocks.findMcpToken,-}));--import {- catalogKeysSharingResource,- findCatalogMcpToken,-} from "./catalog-token";--const CANONICAL = "https://notfair.co/api/mcp/notfair";-const STRIPE = "https://mcp.stripe.com/mcp";--beforeEach(() => {- vi.clearAllMocks();- mocks.getMcpCatalog.mockReturnValue([- { key: "notfair-googleads", resource_url: CANONICAL },- { key: "notfair-metaads", resource_url: CANONICAL },- { key: "stripe", resource_url: STRIPE },- ]);- mocks.mcpSpecByKey.mockImplementation((_slug: string, key: string) =>- mocks.getMcpCatalog().find((entry: { key: string }) => entry.key === key),- );- mocks.findMcpToken.mockReturnValue(null);-});--describe("findCatalogMcpToken", () => {- it("returns the direct token when present", () => {- mocks.findMcpToken.mockImplementation((_slug: string, key: string) =>- key === "notfair-metaads" ? { id: "tok-m" } : null,- );- expect(findCatalogMcpToken("proj", "notfair-metaads")).toEqual({ id: "tok-m" });- });-- it("falls back to a sibling catalog key with the same resource URL", () => {- mocks.findMcpToken.mockImplementation((_slug: string, key: string) =>- key === "notfair-googleads" ? { id: "tok-g" } : null,- );- expect(findCatalogMcpToken("proj", "notfair-metaads")).toEqual({ id: "tok-g" });- });-- it("does not reuse a token from a different resource URL", () => {- mocks.findMcpToken.mockImplementation((_slug: string, key: string) =>- key === "stripe" ? { id: "tok-s" } : null,- );- expect(findCatalogMcpToken("proj", "notfair-googleads")).toBeNull();- });-});--describe("catalogKeysSharingResource", () => {- it("returns every catalog key on the same resource, including itself", () => {- expect(catalogKeysSharingResource("proj", "notfair-googleads")).toEqual([- "notfair-googleads",- "notfair-metaads",- ]);- });-- it("returns the requested key when the spec is unknown", () => {- mocks.mcpSpecByKey.mockReturnValue(undefined);- expect(catalogKeysSharingResource("proj", "missing")).toEqual(["missing"]);- });-});diff --git a/notfair/src/server/mcp/catalog-token.ts b/notfair/src/server/mcp/catalog-token.tsdeleted file mode 100644index 7594606f..00000000--- a/notfair/src/server/mcp/catalog-token.ts+++ /dev/null@@ -1,42 +0,0 @@-import { getMcpCatalog, mcpSpecByKey } from "@/server/mcp-catalog";-import { findMcpToken, type McpToken } from "@/server/mcp/tokens";-import { normalizeResourceUrl } from "@/server/mcp/discovery-url";--/**- * Look up the stored token for a catalog key, then fall back to any other- * catalog entry that advertises the same resource URL.- *- * NotFair presets all point at `/api/mcp/notfair`, so one OAuth grant is- * enough for Google Ads, Meta Ads, Search Console, Analytics, and X Ads.- */-export function findCatalogMcpToken(- project_slug: string,- catalog_key: string,-): McpToken | null {- const direct = findMcpToken(project_slug, catalog_key);- if (direct) return direct;-- const spec = mcpSpecByKey(project_slug, catalog_key);- if (!spec) return null;- const target = normalizeResourceUrl(spec.resource_url);- for (const other of getMcpCatalog(project_slug)) {- if (other.key === catalog_key) continue;- if (normalizeResourceUrl(other.resource_url) !== target) continue;- const token = findMcpToken(project_slug, other.key);- if (token) return token;- }- return null;-}--/** Catalog keys that share this entry's resource URL, including itself. */-export function catalogKeysSharingResource(- project_slug: string,- catalog_key: string,-): string[] {- const spec = mcpSpecByKey(project_slug, catalog_key);- if (!spec) return [catalog_key];- const target = normalizeResourceUrl(spec.resource_url);- return getMcpCatalog(project_slug)- .filter((entry) => normalizeResourceUrl(entry.resource_url) === target)- .map((entry) => entry.key);-}diff --git a/notfair/src/server/mcp/discovery-url.test.ts b/notfair/src/server/mcp/discovery-url.test.tsdeleted file mode 100644index 9932cb61..00000000--- a/notfair/src/server/mcp/discovery-url.test.ts+++ /dev/null@@ -1,78 +0,0 @@-import { describe, expect, it } from "vitest";--import { deriveDiscoveryUrl, normalizeResourceUrl } from "./discovery-url";--describe("normalizeResourceUrl", () => {- it("lowercases scheme and host, preserves path case", () => {- expect(normalizeResourceUrl("HTTPS://NotFair.CO/Api/Mcp")).toBe(- "https://notfair.co/Api/Mcp",- );- });-- it("drops trailing slashes from the path", () => {- expect(normalizeResourceUrl("https://notfair.co/api/mcp///")).toBe(- "https://notfair.co/api/mcp",- );- });-- it("drops the default https port 443", () => {- expect(normalizeResourceUrl("https://notfair.co:443/api")).toBe(- "https://notfair.co/api",- );- });-- it("drops the default http port 80", () => {- expect(normalizeResourceUrl("http://notfair.co:80/api")).toBe(- "http://notfair.co/api",- );- });-- it("keeps a non-default port", () => {- expect(normalizeResourceUrl("http://127.0.0.1:3326/api/mcp/goals")).toBe(- "http://127.0.0.1:3326/api/mcp/goals",- );- });-- it("root-only URLs normalize to origin with no trailing slash", () => {- expect(normalizeResourceUrl("https://notfair.co/")).toBe("https://notfair.co");- });-- it("falls back to trim + lowercase + slash-strip for unparseable input", () => {- expect(normalizeResourceUrl(" Not A URL// ")).toBe("not a url");- });-});--describe("deriveDiscoveryUrl", () => {- it("inserts the well-known suffix between origin and path", () => {- expect(deriveDiscoveryUrl("https://notfair.co/api/mcp/notfair")).toBe(- "https://notfair.co/.well-known/oauth-protected-resource/api/mcp/notfair",- );- });-- it("root resources get the suffix with no trailing path", () => {- expect(deriveDiscoveryUrl("https://mcp.example.com/")).toBe(- "https://mcp.example.com/.well-known/oauth-protected-resource",- );- });-- it("strips trailing slashes from a non-root path", () => {- expect(deriveDiscoveryUrl("https://mcp.example.com/v1/")).toBe(- "https://mcp.example.com/.well-known/oauth-protected-resource/v1",- );- });-- it("supports plain http", () => {- expect(deriveDiscoveryUrl("http://127.0.0.1:9000/mcp")).toBe(- "http://127.0.0.1:9000/.well-known/oauth-protected-resource/mcp",- );- });-- it("returns null for malformed input", () => {- expect(deriveDiscoveryUrl("not a url")).toBeNull();- });-- it("returns null for non-HTTP(S) schemes", () => {- expect(deriveDiscoveryUrl("ftp://example.com/mcp")).toBeNull();- expect(deriveDiscoveryUrl("file:///tmp/mcp")).toBeNull();- });-});diff --git a/notfair/src/server/mcp/discovery-url.ts b/notfair/src/server/mcp/discovery-url.tsdeleted file mode 100644index 8f567418..00000000--- a/notfair/src/server/mcp/discovery-url.ts+++ /dev/null@@ -1,50 +0,0 @@-/**- * Normalize an MCP resource URL into a stable comparable form: lowercase- * scheme + host, preserve case-sensitive path, drop trailing slashes,- * and remove any default port. Used to detect "this server is already- * in the project" regardless of how the user typed the URL or how it- * was slugified into a key historically.- *- * Returns the input unchanged when it can't be parsed — better to miss- * a match than crash a render.- */-export function normalizeResourceUrl(url: string): string {- let u: URL;- try {- u = new URL(url);- } catch {- return url.trim().toLowerCase().replace(/\/+$/, "");- }- const scheme = u.protocol.toLowerCase();- const host = u.hostname.toLowerCase();- const port =- (scheme === "https:" && u.port === "443") ||- (scheme === "http:" && u.port === "80") ||- !u.port- ? ""- : `:${u.port}`;- const path = u.pathname.replace(/\/+$/, "");- return `${scheme}//${host}${port}${path}`;-}--/**- * Derive the RFC 9728 protected-resource discovery URL from a resource URL.- *- * Spec rule: the well-known suffix `.well-known/oauth-protected-resource`- * is inserted between the origin and the resource path. For root-only- * resources (path `/` or empty) the suffix sits directly under the origin- * with no trailing path.- *- * Returns `null` for malformed input or non-HTTP(S) schemes.- */-export function deriveDiscoveryUrl(resource_url: string): string | null {- let u: URL;- try {- u = new URL(resource_url);- } catch {- return null;- }- if (u.protocol !== "https:" && u.protocol !== "http:") return null;- const path = u.pathname === "/" ? "" : u.pathname.replace(/\/+$/, "");- return `${u.origin}/.well-known/oauth-protected-resource${path}`;-}diff --git a/notfair/src/server/mcp/probe-cache.test.ts b/notfair/src/server/mcp/probe-cache.test.tsdeleted file mode 100644index e1e30e89..00000000--- a/notfair/src/server/mcp/probe-cache.test.ts+++ /dev/null@@ -1,91 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--import {- _clearProbeCacheForTests,- getCachedProbe,- invalidateProbe,- setCachedProbe,-} from "./probe-cache";-import type { McpRuntimeStatus } from "./state";--const connected: McpRuntimeStatus = {- state: "connected",- url: "https://x",- tools_count: null,- last_checked_at: "now",-};-const unreachable: McpRuntimeStatus = {- state: "unreachable",- url: "https://x",- error: "down",- last_checked_at: "now",-};-const staleToken: McpRuntimeStatus = {- state: "stale_token",- url: "https://x",- http_status: 401,- last_checked_at: "now",-};--beforeEach(() => _clearProbeCacheForTests());-afterEach(() => {- vi.useRealTimers();- _clearProbeCacheForTests();-});--describe("probe-cache", () => {- it("misses on an empty cache", () => {- expect(getCachedProbe("p", "k")).toBeNull();- });-- it("caches connected results and reads them back", () => {- setCachedProbe("p", "k", connected);- expect(getCachedProbe("p", "k")).toEqual(connected);- });-- it("caches unreachable results", () => {- setCachedProbe("p", "k", unreachable);- expect(getCachedProbe("p", "k")).toEqual(unreachable);- });-- it("does not cache stale_token (ttl 0) and clears a prior entry", () => {- setCachedProbe("p", "k", connected);- setCachedProbe("p", "k", staleToken);- expect(getCachedProbe("p", "k")).toBeNull();- });-- it("does not cache not_configured", () => {- setCachedProbe("p", "k", { state: "not_configured" });- expect(getCachedProbe("p", "k")).toBeNull();- });-- it("keys entries by project + catalog", () => {- setCachedProbe("p1", "k", connected);- expect(getCachedProbe("p2", "k")).toBeNull();- expect(getCachedProbe("p1", "k2")).toBeNull();- });-- it("expires connected entries after 60s", () => {- vi.useFakeTimers();- vi.setSystemTime(0);- setCachedProbe("p", "k", connected);- vi.setSystemTime(59_999);- expect(getCachedProbe("p", "k")).toEqual(connected);- vi.setSystemTime(60_001);- expect(getCachedProbe("p", "k")).toBeNull();- });-- it("expires unreachable entries after 10s", () => {- vi.useFakeTimers();- vi.setSystemTime(0);- setCachedProbe("p", "k", unreachable);- vi.setSystemTime(10_001);- expect(getCachedProbe("p", "k")).toBeNull();- });-- it("invalidateProbe drops the entry", () => {- setCachedProbe("p", "k", connected);- invalidateProbe("p", "k");- expect(getCachedProbe("p", "k")).toBeNull();- });-});diff --git a/notfair/src/server/mcp/probe-cache.ts b/notfair/src/server/mcp/probe-cache.tsdeleted file mode 100644index e77d7b70..00000000--- a/notfair/src/server/mcp/probe-cache.ts+++ /dev/null@@ -1,99 +0,0 @@-import type { McpRuntimeStatus } from "./state";--/**- * In-process TTL cache for `getMcpStatus` probe results.- *- * Every server render of the Connections page (and the chat thread page,- * which checks notfair-googleads liveness for its banner) fans out one- * `initialize` JSON-RPC call per connector. Without a cache, navigating to- * `/connections` thirty times in five minutes means thirty round-trips per- * provider — fine for one user dogfooding, rude to upstreams long-term.- *- * The cache wraps just the RPC-bearing states. Stable "I have a token and- * the server answered" results live for 60s (access tokens last hours, so- * staleness here is invisible). "Provider is sick" results live for 10s so- * we recover quickly when the provider comes back. "Token is stale" and- * "nothing configured" are not cached — both are user-actionable states- * where instant feedback matters after a reconnect or a fresh setup.- *- * Pinned to `globalThis` so Next.js HMR doesn't drop the cache on every- * code edit (same pattern as `mcp-pending.ts`).- */--type CacheEntry = { result: McpRuntimeStatus; expiresAt: number };--const GLOBAL_KEY = "__notfair_probe_cache__";-type GlobalSlot = { [GLOBAL_KEY]?: Map<string, CacheEntry> };-const slot = globalThis as unknown as GlobalSlot;-const STORE: Map<string, CacheEntry> =- slot[GLOBAL_KEY] ?? (slot[GLOBAL_KEY] = new Map());--const TTL_CONNECTED_MS = 60_000;-const TTL_UNREACHABLE_MS = 10_000;--function cacheKey(project_slug: string, catalog_key: string): string {- return `${project_slug}|${catalog_key}`;-}--/**- * TTL (ms) for a given probe result. Returns 0 when the result should not- * be cached at all — `stale_token` (user just needs to reconnect, instant- * feedback wins), `not_configured` / `configured_no_token` (cheap DB-only- * derivations, no upstream RPC to amortize).- */-function ttlFor(state: McpRuntimeStatus["state"]): number {- switch (state) {- case "connected":- return TTL_CONNECTED_MS;- case "unreachable":- return TTL_UNREACHABLE_MS;- default:- return 0;- }-}--/** Read the cache. Returns null on miss or expired entry (and evicts the latter). */-export function getCachedProbe(- project_slug: string,- catalog_key: string,-): McpRuntimeStatus | null {- const key = cacheKey(project_slug, catalog_key);- const entry = STORE.get(key);- if (!entry) return null;- if (entry.expiresAt <= Date.now()) {- STORE.delete(key);- return null;- }- return entry.result;-}--/** Populate the cache, or clear any prior entry when the new state is not cacheable. */-export function setCachedProbe(- project_slug: string,- catalog_key: string,- result: McpRuntimeStatus,-): void {- const key = cacheKey(project_slug, catalog_key);- const ttl = ttlFor(result.state);- if (ttl <= 0) {- // A previously-cached "connected" entry is now wrong; drop it so the- // next read doesn't serve a stale-positive.- STORE.delete(key);- return;- }- STORE.set(key, { result, expiresAt: Date.now() + ttl });-}--/**- * Drop the cached entry. Called from `setMcpBearer` (right after a fresh- * OAuth callback writes new credentials — the badge should update on the- * next render, not 60s later) and from `disconnectMcp`.- */-export function invalidateProbe(project_slug: string, catalog_key: string): void {- STORE.delete(cacheKey(project_slug, catalog_key));-}--/** Test-only escape hatch. */-export function _clearProbeCacheForTests(): void {- STORE.clear();-}diff --git a/notfair/src/server/mcp/refresh.test.ts b/notfair/src/server/mcp/refresh.test.tsdeleted file mode 100644index cc3e9a4d..00000000--- a/notfair/src/server/mcp/refresh.test.ts+++ /dev/null@@ -1,172 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--// Real better-sqlite3 against a tmpdir DB, per repo test conventions.-// MUST be hoisted: static imports evaluate before module-level statements,-// and db.ts captures NOTFAIR_DATA_DIR at import time — a plain assignment-// here would silently point the suite at the developer's live ~/.notfair.-vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-refresh-"));-});--import { getDb } from "@/server/db/db";-import { isExpiringSoon, refreshMcpToken } from "./refresh";-import { getMcpToken, upsertMcpToken, type McpToken } from "./tokens";--const fetchMock = vi.fn();--beforeEach(() => {- fetchMock.mockReset();- vi.stubGlobal("fetch", fetchMock);- vi.spyOn(console, "warn").mockImplementation(() => {});- // mcp_tokens.project_slug FKs to projects(slug).- getDb()- .prepare(- "INSERT OR IGNORE INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES ('proj', 'proj', 'proj', ?, 'claude-code-local')",- )- .run(new Date().toISOString());-});--afterEach(() => {- vi.unstubAllGlobals();- vi.restoreAllMocks();-});--let counter = 0;-function makeToken(overrides: Partial<Parameters<typeof upsertMcpToken>[0]> = {}): McpToken {- return upsertMcpToken({- project_slug: "proj",- server_name: `srv-${++counter}`,- access_token: "old-at",- refresh_token: "rt-1",- token_endpoint: "https://oauth.example.com/token",- client_id: "cid",- ...overrides,- });-}--function jsonResponse(body: unknown, status = 200): Response {- return new Response(JSON.stringify(body), {- status,- headers: { "Content-Type": "application/json" },- });-}--describe("refreshMcpToken", () => {- it("returns null without fetching when refresh fields are missing", async () => {- const noRefresh = makeToken({ refresh_token: undefined });- const noEndpoint = makeToken({ token_endpoint: undefined });- const noClient = makeToken({ client_id: undefined });- expect(await refreshMcpToken(noRefresh)).toBeNull();- expect(await refreshMcpToken(noEndpoint)).toBeNull();- expect(await refreshMcpToken(noClient)).toBeNull();- expect(fetchMock).not.toHaveBeenCalled();- });-- it("posts a urlencoded refresh_token grant and persists the rotated pair", async () => {- const token = makeToken();- fetchMock.mockResolvedValueOnce(- jsonResponse({ access_token: "new-at", refresh_token: "rt-2", expires_in: 3600 }),- );-- const before = Date.now();- const refreshed = await refreshMcpToken(token);- const after = Date.now();-- expect(fetchMock).toHaveBeenCalledTimes(1);- const [url, init] = fetchMock.mock.calls[0]! as [string, RequestInit];- expect(url).toBe("https://oauth.example.com/token");- expect(init.method).toBe("POST");- expect((init.headers as Record<string, string>)["Content-Type"]).toBe(- "application/x-www-form-urlencoded",- );- const params = new URLSearchParams(init.body as string);- expect(params.get("grant_type")).toBe("refresh_token");- expect(params.get("refresh_token")).toBe("rt-1");- expect(params.get("client_id")).toBe("cid");- expect(params.get("client_secret")).toBeNull();-- expect(refreshed).not.toBeNull();- expect(refreshed!.access_token_enc).toBe("new-at");- expect(refreshed!.refresh_token_enc).toBe("rt-2");- const expiresMs = Date.parse(refreshed!.expires_at!);- expect(expiresMs).toBeGreaterThanOrEqual(before + 3600 * 1000);- expect(expiresMs).toBeLessThanOrEqual(after + 3600 * 1000);-- // Persisted, not just returned.- expect(getMcpToken(token.id)!.access_token_enc).toBe("new-at");- });-- it("includes client_secret when stored", async () => {- const token = makeToken({ client_secret: "shh" });- fetchMock.mockResolvedValueOnce(jsonResponse({ access_token: "new-at" }));- await refreshMcpToken(token);- const params = new URLSearchParams(fetchMock.mock.calls[0]![1].body as string);- expect(params.get("client_secret")).toBe("shh");- });-- it("keeps the existing refresh token when the response omits one", async () => {- const token = makeToken();- fetchMock.mockResolvedValueOnce(jsonResponse({ access_token: "new-at" }));- const refreshed = await refreshMcpToken(token);- expect(refreshed!.refresh_token_enc).toBe("rt-1");- expect(refreshed!.expires_at).toBeNull();- });-- it("returns null and leaves the row alone on network error", async () => {- const token = makeToken();- fetchMock.mockRejectedValueOnce(new Error("ECONNREFUSED"));- expect(await refreshMcpToken(token)).toBeNull();- expect(getMcpToken(token.id)!.access_token_enc).toBe("old-at");- });-- it("returns null on a non-2xx response", async () => {- const token = makeToken();- fetchMock.mockResolvedValueOnce(jsonResponse({ error: "invalid_grant" }, 400));- expect(await refreshMcpToken(token)).toBeNull();- expect(getMcpToken(token.id)!.access_token_enc).toBe("old-at");- });-- it("returns null on a non-JSON body", async () => {- const token = makeToken();- fetchMock.mockResolvedValueOnce(new Response("<html>oops</html>", { status: 200 }));- expect(await refreshMcpToken(token)).toBeNull();- });-- it("returns null when the response has no access_token", async () => {- const token = makeToken();- fetchMock.mockResolvedValueOnce(jsonResponse({ token_type: "Bearer" }));- expect(await refreshMcpToken(token)).toBeNull();- });-});--describe("isExpiringSoon", () => {- function tokenWithExpiry(expires_at: string | null): McpToken {- return { expires_at } as McpToken;- }-- it("false when expires_at is missing (legacy rows)", () => {- expect(isExpiringSoon(tokenWithExpiry(null))).toBe(false);- });-- it("false when expires_at is unparseable", () => {- expect(isExpiringSoon(tokenWithExpiry("not-a-date"))).toBe(false);- });-- it("true when already expired", () => {- expect(- isExpiringSoon(tokenWithExpiry(new Date(Date.now() - 1000).toISOString())),- ).toBe(true);- });-- it("true inside the skew window, false outside it", () => {- const in30s = new Date(Date.now() + 30_000).toISOString();- const in10m = new Date(Date.now() + 600_000).toISOString();- expect(isExpiringSoon(tokenWithExpiry(in30s))).toBe(true);- expect(isExpiringSoon(tokenWithExpiry(in10m))).toBe(false);- // Custom skew widens the window.- expect(isExpiringSoon(tokenWithExpiry(in10m), 700_000)).toBe(true);- });-});diff --git a/notfair/src/server/mcp/refresh.ts b/notfair/src/server/mcp/refresh.tsdeleted file mode 100644index f2711135..00000000--- a/notfair/src/server/mcp/refresh.ts+++ /dev/null@@ -1,108 +0,0 @@-import { updateMcpTokenSecrets, type McpToken } from "./tokens";--/**- * Exchange a stored refresh_token for a fresh access_token at the upstream- * OAuth token endpoint, persist the rotated pair, and return the updated row.- *- * Returns `null` (and leaves the row alone) when:- * - the row has no refresh_token / token_endpoint / client_id stored- * (rows written before refresh support), OR- * - the token endpoint rejects the refresh (revoked, expired, scope drift).- *- * Callers should treat `null` as "the user must reconnect" and surface the- * existing stale-token UX. We deliberately don't delete the row on a failed- * refresh — the user might be offline, and a transient 5xx shouldn't nuke- * their connection.- */-export async function refreshMcpToken(token: McpToken): Promise<McpToken | null> {- if (!token.refresh_token_enc || !token.token_endpoint || !token.client_id) {- return null;- }-- const body = new URLSearchParams({- grant_type: "refresh_token",- refresh_token: token.refresh_token_enc,- client_id: token.client_id,- });- if (token.client_secret) body.set("client_secret", token.client_secret);-- let res: Response;- try {- res = await fetch(token.token_endpoint, {- method: "POST",- headers: {- "Content-Type": "application/x-www-form-urlencoded",- Accept: "application/json",- },- body: body.toString(),- });- } catch (err) {- console.warn(- `[mcp-refresh] network error refreshing ${token.server_name}:`,- err instanceof Error ? err.message : String(err),- );- return null;- }-- if (!res.ok) {- // Don't log the body — refresh failures from some providers echo the- // refresh token verbatim in the error payload. Status is enough to- // distinguish "token revoked" (4xx) from "provider hiccup" (5xx).- console.warn(- `[mcp-refresh] ${token.server_name} refresh failed: HTTP ${res.status}`,- );- return null;- }-- let parsed: {- access_token?: string;- refresh_token?: string;- expires_in?: number;- };- try {- parsed = (await res.json()) as typeof parsed;- } catch (err) {- console.warn(- `[mcp-refresh] ${token.server_name} returned non-JSON body:`,- err instanceof Error ? err.message : String(err),- );- return null;- }-- if (!parsed.access_token) {- console.warn(`[mcp-refresh] ${token.server_name} response missing access_token`);- return null;- }-- const expires_at =- typeof parsed.expires_in === "number"- ? new Date(Date.now() + parsed.expires_in * 1000).toISOString()- : null;-- return updateMcpTokenSecrets(token.id, {- access_token: parsed.access_token,- // Per RFC 6749 §6, the response MAY include a new refresh_token. When- // present, providers expect us to replace the old one (Stripe rotates,- // Google doesn't). When absent, COALESCE in updateMcpTokenSecrets keeps- // the existing one.- refresh_token: parsed.refresh_token ?? null,- expires_at,- });-}--/**- * True iff the access token is either expired or within `skewMs` of expiry.- * Used to decide whether to refresh proactively before an MCP RPC. We keep- * the skew tight (default 60s) so we don't refresh every single call — only- * when we're actually close to a 401.- *- * Rows with no `expires_at` (legacy or providers that omit `expires_in`)- * return `false`: we can't tell if they're expiring, so we let the call- * proceed and rely on the 401 reactive path.- */-export function isExpiringSoon(token: McpToken, skewMs = 60_000): boolean {- if (!token.expires_at) return false;- const expiresMs = Date.parse(token.expires_at);- if (Number.isNaN(expiresMs)) return false;- return expiresMs - Date.now() < skewMs;-}diff --git a/notfair/src/server/mcp/rpc.test.ts b/notfair/src/server/mcp/rpc.test.tsdeleted file mode 100644index 4cbe3dcf..00000000--- a/notfair/src/server/mcp/rpc.test.ts+++ /dev/null@@ -1,397 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";--// Real better-sqlite3 against a tmpdir DB, per repo test conventions.-// MUST be hoisted: static imports evaluate before module-level statements,-// and db.ts captures NOTFAIR_DATA_DIR at import time — a plain assignment-// here would silently point the suite at the developer's live ~/.notfair.-vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-rpc-"));-});--const refreshMocks = vi.hoisted(() => ({- refreshMcpToken: vi.fn(),- isExpiringSoon: vi.fn(),-}));--vi.mock("./refresh", () => refreshMocks);--import {- bearerFromHeaders,- getMcpConfig,- mcpRpc,- mcpRpcAutoRefresh,- readMcpConfigRow,-} from "./rpc";-import { upsertMcpToken, type McpToken } from "./tokens";-import { getDb } from "@/server/db/db";--const ADS = "notfair-googleads";-const ADS_URL = "https://notfair.co/api/mcp/notfair";--const fetchMock = vi.fn();--beforeEach(() => {- fetchMock.mockReset();- vi.stubGlobal("fetch", fetchMock);- refreshMocks.refreshMcpToken.mockReset();- refreshMocks.isExpiringSoon.mockReset().mockReturnValue(false);-});--afterEach(() => {- vi.unstubAllGlobals();-});--let projCounter = 0;-function freshProject(): string {- const slug = `proj-${++projCounter}`;- // mcp_tokens.project_slug FKs to projects(slug).- getDb()- .prepare(- "INSERT OR IGNORE INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES (?, ?, ?, ?, 'claude-code-local')",- )- .run(slug, slug, slug, new Date().toISOString());- return slug;-}--function storeToken(project_slug: string, access_token = "tok"): McpToken {- return upsertMcpToken({ project_slug, server_name: ADS, access_token });-}--/** Age the row's updated_at past the 5s "just refreshed" reactive-skip window. */-function ageToken(token: McpToken): McpToken {- const old = new Date(Date.now() - 60_000).toISOString();- getDb().prepare("UPDATE mcp_tokens SET updated_at = ? WHERE id = ?").run(old, token.id);- return { ...token, updated_at: old };-}--function rpcSuccess(result: unknown): Response {- return new Response(JSON.stringify({ jsonrpc: "2.0", id: 1, result }), {- status: 200,- headers: { "Content-Type": "application/json" },- });-}--describe("readMcpConfigRow / getMcpConfig", () => {- it("returns null for an unknown catalog key", () => {- expect(readMcpConfigRow(freshProject(), "no-such-server")).toBeNull();- expect(getMcpConfig(freshProject(), "no-such-server")).toBeNull();- });-- it("returns url-only when no token is stored", () => {- const slug = freshProject();- expect(readMcpConfigRow(slug, ADS)).toEqual({ url: ADS_URL });- // No bearer → no usable config.- expect(getMcpConfig(slug, ADS)).toBeNull();- });-- it("returns url + bearer header when a token exists", () => {- const slug = freshProject();- storeToken(slug, "secret-bearer");- expect(readMcpConfigRow(slug, ADS)).toEqual({- url: ADS_URL,- headers: { Authorization: "Bearer secret-bearer" },- });- expect(getMcpConfig(slug, ADS)).toEqual({ url: ADS_URL, token: "secret-bearer" });- });-- it("reuses a token stored under another catalog key that shares the resource URL", () => {- const slug = freshProject();- upsertMcpToken({- project_slug: slug,- server_name: "notfair-metaads",- access_token: "shared-bearer",- });- expect(getMcpConfig(slug, ADS)).toEqual({- url: ADS_URL,- token: "shared-bearer",- });- });-});--describe("bearerFromHeaders", () => {- it("returns null for missing headers or missing Authorization", () => {- expect(bearerFromHeaders(undefined)).toBeNull();- expect(bearerFromHeaders({})).toBeNull();- });-- it("extracts the bearer, case-insensitively", () => {- expect(bearerFromHeaders({ Authorization: "Bearer abc" })).toBe("abc");- expect(bearerFromHeaders({ authorization: "bearer xyz " })).toBe("xyz");- });-- it("rejects non-bearer schemes", () => {- expect(bearerFromHeaders({ Authorization: "Basic dXNlcg==" })).toBeNull();- });-});--describe("mcpRpc", () => {- it("POSTs a JSON-RPC envelope with auth + protocol headers and parses the result", async () => {- fetchMock.mockResolvedValueOnce(rpcSuccess({ tools: [] }));- const r = await mcpRpc("https://mcp.example.com/x", "tok-1", "tools/list", { a: 1 });- expect(r).toEqual({ ok: true, result: { tools: [] } });-- const [url, init] = fetchMock.mock.calls[0]! as [string, RequestInit];- expect(url).toBe("https://mcp.example.com/x");- expect(init.method).toBe("POST");- const headers = init.headers as Record<string, string>;- expect(headers.Authorization).toBe("Bearer tok-1");- expect(headers["MCP-Protocol-Version"]).toBe("2025-06-18");- expect(headers.Accept).toBe("application/json, text/event-stream");- expect(JSON.parse(init.body as string)).toEqual({- jsonrpc: "2.0",- id: 1,- method: "tools/list",- params: { a: 1 },- });- });-- it("parses an SSE body, taking the last data frame", async () => {- const sse =- 'event: message\ndata: {"jsonrpc":"2.0","id":1,"result":"first"}\n\n' +- 'event: message\ndata: {"jsonrpc":"2.0",\ndata: "id":1,"result":"last"}\n\n';- fetchMock.mockResolvedValueOnce(new Response(sse, { status: 200 }));- const r = await mcpRpc("https://x", "t", "m");- expect(r).toEqual({ ok: true, result: "last" });- });-- it("SSE body with no data lines is malformed", async () => {- fetchMock.mockResolvedValueOnce(new Response("event: ping\n\n", { status: 200 }));- const r = await mcpRpc("https://x", "t", "m");- expect(r).toMatchObject({ ok: false, kind: "malformed_response", message: "empty body" });- });-- it("surfaces HTTP errors with the (truncated) body", async () => {- fetchMock.mockResolvedValueOnce(- new Response("must initialize first", { status: 400 }),- );- const r = await mcpRpc("https://x", "t", "m");- expect(r).toEqual({- ok: false,- kind: "http_error",- status: 400,- body: "must initialize first",- });- });-- it("HTTP error with a blank body reports body: undefined", async () => {- fetchMock.mockResolvedValueOnce(new Response(" ", { status: 503 }));- const r = await mcpRpc("https://x", "t", "m");- expect(r).toEqual({ ok: false, kind: "http_error", status: 503, body: undefined });- });-- it("HTTP error where the body read throws still reports the status", async () => {- fetchMock.mockResolvedValueOnce({- ok: false,- status: 502,- text: () => Promise.reject(new Error("read failed")),- });- const r = await mcpRpc("https://x", "t", "m");- expect(r).toEqual({ ok: false, kind: "http_error", status: 502, body: undefined });- });-- it("maps a JSON-RPC error envelope to rpc_error", async () => {- fetchMock.mockResolvedValueOnce(- new Response(- JSON.stringify({ jsonrpc: "2.0", id: 1, error: { code: -32601, message: "no such method" } }),- { status: 200 },- ),- );- const r = await mcpRpc("https://x", "t", "m");- expect(r).toEqual({ ok: false, kind: "rpc_error", code: -32601, message: "no such method" });- });-- it("flags malformed bodies: empty, unparseable, and result-less envelopes", async () => {- fetchMock.mockResolvedValueOnce(new Response("", { status: 200 }));- expect(await mcpRpc("https://x", "t", "m")).toMatchObject({- ok: false,- kind: "malformed_response",- message: "empty body",- });-- fetchMock.mockResolvedValueOnce(new Response("{nope", { status: 200 }));- expect(await mcpRpc("https://x", "t", "m")).toMatchObject({- ok: false,- kind: "malformed_response",- });-- fetchMock.mockResolvedValueOnce(new Response('{"jsonrpc":"2.0","id":1}', { status: 200 }));- expect(await mcpRpc("https://x", "t", "m")).toMatchObject({- ok: false,- kind: "malformed_response",- message: "envelope has neither result nor error",- });- });-- it("maps fetch rejection to network_error", async () => {- fetchMock.mockRejectedValueOnce(new Error("ECONNREFUSED"));- const r = await mcpRpc("https://x", "t", "m");- expect(r).toEqual({ ok: false, kind: "network_error", message: "ECONNREFUSED" });- });-- it("maps a body read failure on a 200 to network_error", async () => {- fetchMock.mockResolvedValueOnce({- ok: true,- status: 200,- text: () => Promise.reject(new Error("stream reset")),- });- const r = await mcpRpc("https://x", "t", "m");- expect(r).toEqual({ ok: false, kind: "network_error", message: "stream reset" });- });-- it("returns timeout when the deadline fires before the response", async () => {- fetchMock.mockImplementationOnce(- (_url: string, init: RequestInit) =>- new Promise((_, reject) => {- (init.signal as AbortSignal).addEventListener("abort", () =>- reject(new DOMException("The operation was aborted.", "AbortError")),- );- }),- );- const r = await mcpRpc("https://x", "t", "m", {}, { timeoutMs: 10 });- expect(r).toEqual({ ok: false, kind: "timeout" });- });-- it("returns aborted when the caller's signal fires", async () => {- const controller = new AbortController();- fetchMock.mockImplementationOnce(- (_url: string, init: RequestInit) =>- new Promise((_, reject) => {- (init.signal as AbortSignal).addEventListener("abort", () =>- reject(new DOMException("The operation was aborted.", "AbortError")),- );- }),- );- const pending = mcpRpc("https://x", "t", "m", {}, { signal: controller.signal });- controller.abort();- expect(await pending).toEqual({ ok: false, kind: "aborted" });- });-- it("returns aborted when the caller's signal is already aborted", async () => {- const controller = new AbortController();- controller.abort();- fetchMock.mockImplementationOnce((_url: string, init: RequestInit) => {- const signal = init.signal as AbortSignal;- return signal.aborted- ? Promise.reject(new DOMException("The operation was aborted.", "AbortError"))- : Promise.resolve(rpcSuccess("nope"));- });- const r = await mcpRpc("https://x", "t", "m", {}, { signal: controller.signal });- expect(r).toEqual({ ok: false, kind: "aborted" });- });-});--describe("mcpRpcAutoRefresh", () => {- it("404s on an unknown catalog key", async () => {- const r = await mcpRpcAutoRefresh(freshProject(), "no-such-server", "tools/list");- expect(r).toEqual({- ok: false,- kind: "http_error",- status: 404,- body: "unknown mcp catalog key",- });- expect(fetchMock).not.toHaveBeenCalled();- });-- it("401s when no token is stored", async () => {- const r = await mcpRpcAutoRefresh(freshProject(), ADS, "tools/list");- expect(r).toEqual({ ok: false, kind: "http_error", status: 401, body: "no token stored" });- expect(fetchMock).not.toHaveBeenCalled();- });-- it("uses the stored token when it is not expiring", async () => {- const slug = freshProject();- storeToken(slug, "stored-tok");- fetchMock.mockResolvedValueOnce(rpcSuccess("fine"));-- const r = await mcpRpcAutoRefresh(slug, ADS, "tools/list");- expect(r).toEqual({ ok: true, result: "fine" });- expect(refreshMocks.refreshMcpToken).not.toHaveBeenCalled();- const headers = fetchMock.mock.calls[0]![1].headers as Record<string, string>;- expect(headers.Authorization).toBe("Bearer stored-tok");- expect(fetchMock.mock.calls[0]![0]).toBe(ADS_URL);- });-- it("proactively refreshes an expiring token before the call", async () => {- const slug = freshProject();- const token = storeToken(slug, "stale-tok");- refreshMocks.isExpiringSoon.mockReturnValue(true);- refreshMocks.refreshMcpToken.mockResolvedValueOnce({- ...token,- access_token_enc: "fresh-tok",- });- fetchMock.mockResolvedValueOnce(rpcSuccess("ok"));-- const r = await mcpRpcAutoRefresh(slug, ADS, "tools/list");- expect(r).toEqual({ ok: true, result: "ok" });- expect(refreshMocks.refreshMcpToken).toHaveBeenCalledTimes(1);- const headers = fetchMock.mock.calls[0]![1].headers as Record<string, string>;- expect(headers.Authorization).toBe("Bearer fresh-tok");- });-- it("falls back to the stored token when the proactive refresh fails", async () => {- const slug = freshProject();- ageToken(storeToken(slug, "stale-tok"));- refreshMocks.isExpiringSoon.mockReturnValue(true);- refreshMocks.refreshMcpToken.mockResolvedValueOnce(null);- fetchMock.mockResolvedValueOnce(rpcSuccess("still ok"));-- const r = await mcpRpcAutoRefresh(slug, ADS, "tools/list");- expect(r).toEqual({ ok: true, result: "still ok" });- const headers = fetchMock.mock.calls[0]![1].headers as Record<string, string>;- expect(headers.Authorization).toBe("Bearer stale-tok");- });-- it("on 401, refreshes once and retries with the new token", async () => {- const slug = freshProject();- const token = ageToken(storeToken(slug, "revoked-tok"));- refreshMocks.refreshMcpToken.mockResolvedValueOnce({- ...token,- access_token_enc: "rotated-tok",- });- fetchMock- .mockResolvedValueOnce(new Response("unauthorized", { status: 401 }))- .mockResolvedValueOnce(rpcSuccess("recovered"));-- const r = await mcpRpcAutoRefresh(slug, ADS, "tools/list");- expect(r).toEqual({ ok: true, result: "recovered" });- expect(fetchMock).toHaveBeenCalledTimes(2);- const retryHeaders = fetchMock.mock.calls[1]![1].headers as Record<string, string>;- expect(retryHeaders.Authorization).toBe("Bearer rotated-tok");- });-- it("returns the original 401 when the reactive refresh fails", async () => {- const slug = freshProject();- ageToken(storeToken(slug));- refreshMocks.refreshMcpToken.mockResolvedValueOnce(null);- fetchMock.mockResolvedValueOnce(new Response("unauthorized", { status: 401 }));-- const r = await mcpRpcAutoRefresh(slug, ADS, "tools/list");- expect(r).toMatchObject({ ok: false, kind: "http_error", status: 401 });- expect(fetchMock).toHaveBeenCalledTimes(1);- });-- it("skips the reactive refresh when the token was refreshed within this call", async () => {- const slug = freshProject();- // Freshly upserted row → updated_at is now, inside the 5s skip window.- storeToken(slug);- fetchMock.mockResolvedValueOnce(new Response("unauthorized", { status: 401 }));-- const r = await mcpRpcAutoRefresh(slug, ADS, "tools/list");- expect(r).toMatchObject({ ok: false, kind: "http_error", status: 401 });- expect(refreshMocks.refreshMcpToken).not.toHaveBeenCalled();- expect(fetchMock).toHaveBeenCalledTimes(1);- });-- it("passes through non-401 failures without refreshing", async () => {- const slug = freshProject();- ageToken(storeToken(slug));- fetchMock.mockRejectedValueOnce(new Error("down"));-- const r = await mcpRpcAutoRefresh(slug, ADS, "tools/list");- expect(r).toEqual({ ok: false, kind: "network_error", message: "down" });- expect(refreshMocks.refreshMcpToken).not.toHaveBeenCalled();- });-});diff --git a/notfair/src/server/mcp/rpc.ts b/notfair/src/server/mcp/rpc.tsdeleted file mode 100644index e1ed318e..00000000--- a/notfair/src/server/mcp/rpc.ts+++ /dev/null@@ -1,267 +0,0 @@-import { findCatalogMcpToken } from "@/server/mcp/catalog-token";-import { mcpSpecByKey } from "@/server/mcp-catalog";-import { refreshMcpToken, isExpiringSoon } from "./refresh";--/**- * Shared MCP HTTP plumbing. Two callers use this today:- * - `mcp/state.ts:probe()` (liveness check via tools/list)- * - `onboarding/audit.ts` (real audit via tools/call runScript)- *- * Single source of truth for: token lookup (from NotFair SQLite), bearer- * extraction, JSON-RPC envelope construction, SSE-vs-JSON response parsing,- * error shapes.- *- * Security: never log the bearer. Token is held in memory only for the- * duration of one RPC call.- */--export interface McpConfigRow {- url?: string;- headers?: Record<string, string>;-}--export interface McpConfig {- url: string;- token: string;-}--export type RpcResult<T> =- | { ok: true; result: T }- | { ok: false; kind: "http_error"; status: number; body?: string }- | { ok: false; kind: "timeout" }- | { ok: false; kind: "aborted" }- | { ok: false; kind: "network_error"; message: string }- | { ok: false; kind: "rpc_error"; code: number; message: string }- | { ok: false; kind: "malformed_response"; message: string };--/**- * Look up an MCP config row by (project_slug, catalog_key). Returns null when- * no token is stored or the catalog entry is unknown. Replaces the legacy- * subprocess call that backed the same surface.- */-export function readMcpConfigRow(- project_slug: string,- catalog_key: string,-): McpConfigRow | null {- const spec = mcpSpecByKey(project_slug, catalog_key);- if (!spec) return null;- const token = findCatalogMcpToken(project_slug, catalog_key);- if (!token) return { url: spec.resource_url };- return {- url: spec.resource_url,- headers: { Authorization: `Bearer ${token.access_token_enc}` },- };-}--export function bearerFromHeaders(- headers: Record<string, string> | undefined,-): string | null {- if (!headers) return null;- const raw = headers.Authorization ?? headers.authorization;- if (!raw) return null;- const m = raw.match(/^Bearer\s+(.+)$/i);- return m ? m[1].trim() : null;-}--export function getMcpConfig(project_slug: string, catalog_key: string): McpConfig | null {- const row = readMcpConfigRow(project_slug, catalog_key);- if (!row || !row.url) return null;- const token = bearerFromHeaders(row.headers);- if (!token) return null;- return { url: row.url, token };-}--export interface McpRpcOpts {- timeoutMs?: number;- signal?: AbortSignal;-}--export async function mcpRpc<T = unknown>(- url: string,- token: string,- method: string,- params: Record<string, unknown> = {},- opts: McpRpcOpts = {},-): Promise<RpcResult<T>> {- const timeoutMs = opts.timeoutMs ?? 10_000;- const controller = new AbortController();- let timerFired = false;- const timer = setTimeout(() => {- timerFired = true;- controller.abort();- }, timeoutMs);-- const onCallerAbort = () => controller.abort();- if (opts.signal) {- if (opts.signal.aborted) controller.abort();- else opts.signal.addEventListener("abort", onCallerAbort, { once: true });- }-- const cleanup = () => {- clearTimeout(timer);- opts.signal?.removeEventListener("abort", onCallerAbort);- };-- let res: Response;- try {- res = await fetch(url, {- method: "POST",- headers: {- "Content-Type": "application/json",- Accept: "application/json, text/event-stream",- Authorization: `Bearer ${token}`,- // MCP Streamable-HTTP 2025-06-18 §3.3: clients SHOULD declare- // the intended protocol version on every request, and strict- // servers (Supabase, etc.) return HTTP 400 when it's absent.- // Lenient servers (Stripe, NotFair) ignore it. Safe to send- // unconditionally.- "MCP-Protocol-Version": "2025-06-18",- },- body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),- signal: controller.signal,- });- } catch (err) {- cleanup();- if (timerFired) return { ok: false, kind: "timeout" };- if (opts.signal?.aborted) return { ok: false, kind: "aborted" };- return {- ok: false,- kind: "network_error",- message: err instanceof Error ? err.message : String(err),- };- }-- if (!res.ok) {- // Try to capture the body so callers can surface the real upstream- // error (e.g. Supabase's "must initialize first" or a missing-scope- // message). Best-effort: if the read fails or the body is huge, fall- // back to just the status.- let errBody: string | undefined;- try {- const raw = await res.text();- errBody = raw.trim() ? raw.slice(0, 500) : undefined;- } catch {- // ignore- }- cleanup();- return { ok: false, kind: "http_error", status: res.status, body: errBody };- }-- let body: string;- try {- body = await res.text();- } catch (err) {- cleanup();- if (timerFired) return { ok: false, kind: "timeout" };- if (opts.signal?.aborted) return { ok: false, kind: "aborted" };- return {- ok: false,- kind: "network_error",- message: err instanceof Error ? err.message : String(err),- };- }- cleanup();-- return parseRpcBody<T>(body);-}--/**- * `mcpRpc` with silent refresh-token handling. Looks up the token row by- * (project_slug, catalog_key), proactively refreshes when the access token- * is within ~60s of expiry, calls `mcpRpc`, and on HTTP 401 attempts a- * single refresh + retry before giving up.- *- * Returns the same `RpcResult<T>` shape as `mcpRpc` so callers don't need a- * new error branch. When refresh isn't possible (legacy rows without- * refresh_token, or upstream rejects the refresh), the original 401 result- * is returned and the caller's existing stale-token UX kicks in.- */-export async function mcpRpcAutoRefresh<T = unknown>(- project_slug: string,- catalog_key: string,- method: string,- params: Record<string, unknown> = {},- opts: McpRpcOpts = {},-): Promise<RpcResult<T>> {- const spec = mcpSpecByKey(project_slug, catalog_key);- if (!spec) {- return { ok: false, kind: "http_error", status: 404, body: "unknown mcp catalog key" };- }- let token = findCatalogMcpToken(project_slug, catalog_key);- if (!token) {- return { ok: false, kind: "http_error", status: 401, body: "no token stored" };- }-- if (isExpiringSoon(token)) {- const refreshed = await refreshMcpToken(token);- if (refreshed) token = refreshed;- }-- const first = await mcpRpc<T>(- spec.resource_url,- token.access_token_enc,- method,- params,- opts,- );- if (first.ok) return first;- if (first.kind !== "http_error" || first.status !== 401) return first;-- // Reactive refresh. Skip if we just refreshed proactively — the upstream- // is telling us our fresh token is bad, and looping would burn cycles.- // `updated_at` is bumped by updateMcpTokenSecrets, so we can detect a- // refresh that happened within this same call.- if (Date.parse(token.updated_at) > Date.now() - 5_000) return first;-- const refreshed = await refreshMcpToken(token);- if (!refreshed) return first;- return mcpRpc<T>(spec.resource_url, refreshed.access_token_enc, method, params, opts);-}--function parseRpcBody<T>(body: string): RpcResult<T> {- const envelope = pickRpcEnvelope(body);- if (envelope === null) {- return { ok: false, kind: "malformed_response", message: "empty body" };- }- let parsed: { result?: T; error?: { code: number; message: string } };- try {- parsed = JSON.parse(envelope) as typeof parsed;- } catch (err) {- return {- ok: false,- kind: "malformed_response",- message: err instanceof Error ? err.message : "JSON parse failed",- };- }- if (parsed.error) {- return { ok: false, kind: "rpc_error", code: parsed.error.code, message: parsed.error.message };- }- if (parsed.result === undefined) {- return {- ok: false,- kind: "malformed_response",- message: "envelope has neither result nor error",- };- }- return { ok: true, result: parsed.result };-}--function pickRpcEnvelope(body: string): string | null {- const trimmed = body.trim();- if (!trimmed) return null;- if (!trimmed.startsWith("data:") && !trimmed.startsWith("event:")) {- return trimmed;- }- const frames = trimmed- .split(/\n\n+/)- .map((frame) =>- frame- .split("\n")- .filter((line) => line.startsWith("data:"))- .map((line) => line.slice("data:".length).trim())- .join(""),- )- .filter((s) => s.length > 0);- if (frames.length === 0) return null;- return frames[frames.length - 1] ?? null;-}diff --git a/notfair/src/server/mcp/state.test.ts b/notfair/src/server/mcp/state.test.tsdeleted file mode 100644index 6f0f0046..00000000--- a/notfair/src/server/mcp/state.test.ts+++ /dev/null@@ -1,193 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- findMcpToken: vi.fn(),- upsertMcpToken: vi.fn(),- deleteMcpToken: vi.fn(),- mcpSpecByKey: vi.fn(),- mcpRpcAutoRefresh: vi.fn(),- getCachedProbe: vi.fn(),- setCachedProbe: vi.fn(),- invalidateProbe: vi.fn(),- findCatalogMcpToken: vi.fn(),- catalogKeysSharingResource: vi.fn(),-}));--vi.mock("./tokens", () => ({- findMcpToken: mocks.findMcpToken,- upsertMcpToken: mocks.upsertMcpToken,- deleteMcpToken: mocks.deleteMcpToken,-}));-vi.mock("@/server/mcp-catalog", () => ({- mcpSpecByKey: mocks.mcpSpecByKey,-}));-vi.mock("./catalog-token", () => ({- findCatalogMcpToken: mocks.findCatalogMcpToken,- catalogKeysSharingResource: mocks.catalogKeysSharingResource,-}));-vi.mock("./rpc", () => ({- mcpRpcAutoRefresh: mocks.mcpRpcAutoRefresh,-}));-vi.mock("./probe-cache", () => ({- getCachedProbe: mocks.getCachedProbe,- setCachedProbe: mocks.setCachedProbe,- invalidateProbe: mocks.invalidateProbe,-}));--import { disconnectMcp, getMcpStatus, setMcpBearer } from "./state";--const SPEC = { resource_url: "https://srv/mcp", key: "notfair-googleads" };--beforeEach(() => {- vi.clearAllMocks();- mocks.mcpSpecByKey.mockReturnValue(SPEC);- mocks.findMcpToken.mockReturnValue({ id: "tok-1" });- mocks.findCatalogMcpToken.mockReturnValue({ id: "tok-1" });- mocks.catalogKeysSharingResource.mockImplementation((_slug: string, key: string) => [key]);- mocks.getCachedProbe.mockReturnValue(null);-});--describe("getMcpStatus short-circuits", () => {- it("returns not_configured when no spec", async () => {- mocks.mcpSpecByKey.mockReturnValue(undefined);- expect(await getMcpStatus("p", "k")).toEqual({ state: "not_configured" });- });-- it("returns not_configured when no token", async () => {- mocks.findCatalogMcpToken.mockReturnValue(null);- expect(await getMcpStatus("p", "k")).toEqual({ state: "not_configured" });- });-- it("returns the cached probe without hitting rpc", async () => {- const cached = { state: "connected" as const, url: "u", tools_count: null, last_checked_at: "t" };- mocks.getCachedProbe.mockReturnValue(cached);- expect(await getMcpStatus("p", "k")).toBe(cached);- expect(mocks.mcpRpcAutoRefresh).not.toHaveBeenCalled();- });-});--describe("getMcpStatus probe outcomes", () => {- it("connected on rpc ok, and caches the result", async () => {- mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: true, result: {} });- const r = await getMcpStatus("p", "k");- expect(r).toMatchObject({ state: "connected", url: SPEC.resource_url, tools_count: null });- expect(mocks.setCachedProbe).toHaveBeenCalledWith("p", "k", r);- });-- it("stale_token on 401", async () => {- mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, kind: "http_error", status: 401 });- expect(await getMcpStatus("p", "k")).toMatchObject({ state: "stale_token", http_status: 401 });- });-- it("stale_token on 403", async () => {- mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, kind: "http_error", status: 403 });- expect(await getMcpStatus("p", "k")).toMatchObject({ state: "stale_token", http_status: 403 });- });-- it("unreachable on other http_error with body", async () => {- mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, kind: "http_error", status: 500, body: "oops" });- expect(await getMcpStatus("p", "k")).toMatchObject({- state: "unreachable",- error: "HTTP 500: oops",- });- });-- it("unreachable on http_error without body", async () => {- mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, kind: "http_error", status: 502 });- expect(await getMcpStatus("p", "k")).toMatchObject({ state: "unreachable", error: "HTTP 502" });- });-- it("unreachable on timeout", async () => {- mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, kind: "timeout" });- expect(await getMcpStatus("p", "k")).toMatchObject({ state: "unreachable", error: "timed out" });- });-- it("unreachable on aborted", async () => {- mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, kind: "aborted" });- expect(await getMcpStatus("p", "k")).toMatchObject({ state: "unreachable", error: "aborted" });- });-- it("unreachable on rpc_error", async () => {- mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, kind: "rpc_error", code: -1, message: "bad" });- expect(await getMcpStatus("p", "k")).toMatchObject({- state: "unreachable",- error: "rpc error -1: bad",- });- });-- it("unreachable on malformed_response", async () => {- mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, kind: "malformed_response", message: "junk" });- expect(await getMcpStatus("p", "k")).toMatchObject({- state: "unreachable",- error: "malformed response: junk",- });- });-- it("unreachable fallthrough on network_error", async () => {- mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, kind: "network_error", message: "econnrefused" });- expect(await getMcpStatus("p", "k")).toMatchObject({- state: "unreachable",- error: "econnrefused",- });- });-});--describe("disconnectMcp", () => {- it("deletes the token and invalidates the probe when a token exists", async () => {- mocks.findMcpToken.mockReturnValue({ id: "tok-9" });- await disconnectMcp("p", "k");- expect(mocks.deleteMcpToken).toHaveBeenCalledWith("tok-9");- expect(mocks.invalidateProbe).toHaveBeenCalledWith("p", "k");- });-- it("only invalidates when there is no token", async () => {- mocks.findMcpToken.mockReturnValue(null);- await disconnectMcp("p", "k");- expect(mocks.deleteMcpToken).not.toHaveBeenCalled();- expect(mocks.invalidateProbe).toHaveBeenCalledWith("p", "k");- });-- it("disconnects every catalog key that shares the same resource URL", async () => {- mocks.catalogKeysSharingResource.mockReturnValue(["notfair-googleads", "notfair-metaads"]);- mocks.findMcpToken.mockImplementation((_slug: string, key: string) =>- key === "notfair-googleads" ? { id: "tok-g" } : { id: "tok-m" },- );- await disconnectMcp("p", "notfair-googleads");- expect(mocks.deleteMcpToken).toHaveBeenCalledWith("tok-g");- expect(mocks.deleteMcpToken).toHaveBeenCalledWith("tok-m");- expect(mocks.invalidateProbe).toHaveBeenCalledWith("p", "notfair-googleads");- expect(mocks.invalidateProbe).toHaveBeenCalledWith("p", "notfair-metaads");- });-});--describe("setMcpBearer", () => {- it("upserts with all fields and invalidates the probe", async () => {- await setMcpBearer("p", "k", "secret", {- scope: "s",- expires_at: "later",- refresh_token: "r",- token_endpoint: "te",- client_id: "ci",- client_secret: "cs",- });- expect(mocks.upsertMcpToken).toHaveBeenCalledWith({- project_slug: "p",- server_name: "k",- access_token: "secret",- scope: "s",- expires_at: "later",- refresh_token: "r",- token_endpoint: "te",- client_id: "ci",- client_secret: "cs",- });- expect(mocks.invalidateProbe).toHaveBeenCalledWith("p", "k");- });-- it("works with default (empty) options", async () => {- await setMcpBearer("p", "k", "secret");- expect(mocks.upsertMcpToken).toHaveBeenCalledWith(- expect.objectContaining({ access_token: "secret", scope: undefined }),- );- });-});diff --git a/notfair/src/server/mcp/state.ts b/notfair/src/server/mcp/state.tsdeleted file mode 100644index dc6814a5..00000000--- a/notfair/src/server/mcp/state.ts+++ /dev/null@@ -1,182 +0,0 @@-import { findMcpToken, upsertMcpToken, deleteMcpToken } from "./tokens";-import { mcpSpecByKey } from "@/server/mcp-catalog";-import {- catalogKeysSharingResource,- findCatalogMcpToken,-} from "./catalog-token";-import { mcpRpcAutoRefresh } from "./rpc";-import {- getCachedProbe,- invalidateProbe,- setCachedProbe,-} from "./probe-cache";--/**- * Status surface for the Connections page + dashboard banners.- *- * - "not_configured": no row in mcp_tokens- * - "configured_no_token": (legacy compat — pre-OAuth half-config rows)- * - "connected": token present and probe succeeded- * - "stale_token": probe came back 401/403- * - "unreachable": probe failed (network/timeout/5xx)- */-export type McpRuntimeStatus =- | { state: "not_configured" }- | { state: "configured_no_token"; url: string }- | {- state: "connected";- url: string;- tools_count: number | null;- last_checked_at: string;- }- | {- state: "stale_token";- url: string;- http_status: number;- last_checked_at: string;- }- | {- state: "unreachable";- url: string;- error: string;- last_checked_at: string;- };--export async function getMcpStatus(- project_slug: string,- catalog_key: string,-): Promise<McpRuntimeStatus> {- const spec = mcpSpecByKey(project_slug, catalog_key);- if (!spec) return { state: "not_configured" };- const token = findCatalogMcpToken(project_slug, catalog_key);- if (!token) return { state: "not_configured" };-- // Cache short-circuit: only `connected` (60s) and `unreachable` (10s)- // results live in the cache. `stale_token` is deliberately uncached so- // a reconnect surfaces fresh state on the very next render. See- // probe-cache.ts for the rationale.- const cached = getCachedProbe(project_slug, catalog_key);- if (cached) return cached;-- const fresh = await probe(project_slug, catalog_key, spec.resource_url);- setCachedProbe(project_slug, catalog_key, fresh);- return fresh;-}--async function probe(- project_slug: string,- catalog_key: string,- url: string,-): Promise<McpRuntimeStatus> {- const last_checked_at = new Date().toISOString();- // Use `initialize` — the spec-mandated first call — as the liveness- // probe. Some MCP servers (Supabase) reject `tools/list` with HTTP 400- // when no prior initialize has happened; `initialize` is universally- // accepted as the opening message. We don't track the session ID since- // we're not following up with another call in the probe; tool count- // gets surfaced on demand via the View tools dialog (its own RPC).- //- // Goes through `mcpRpcAutoRefresh` so an expired access token gets- // silently swapped for a fresh one instead of flapping the status to- // "stale_token" on every page load.- //- // 6s budget: an OAuth-validated `initialize` across the public internet- // typically lands in 0.3–1.5s, but cold serverless starts, SSE buffering- // (the parser drains the full body before extracting the JSON-RPC frame),- // and an upstream introspection RTT can stack. 2s was too tight and made- // healthy connectors flap to "unreachable: timed out". 6s still bounds- // page render at ~6s worst-case via Promise.all in the page component.- const r = await mcpRpcAutoRefresh<unknown>(- project_slug,- catalog_key,- "initialize",- {- protocolVersion: "2025-06-18",- capabilities: {},- clientInfo: { name: "NotFair", version: "0.3.1" },- },- { timeoutMs: 6000 },- );- if (r.ok) {- return {- state: "connected",- url,- tools_count: null,- last_checked_at,- };- }- if (r.kind === "http_error" && (r.status === 401 || r.status === 403)) {- return { state: "stale_token", url, http_status: r.status, last_checked_at };- }- if (r.kind === "http_error") {- return {- state: "unreachable",- url,- error: r.body ? `HTTP ${r.status}: ${r.body}` : `HTTP ${r.status}`,- last_checked_at,- };- }- if (r.kind === "timeout") {- return { state: "unreachable", url, error: "timed out", last_checked_at };- }- if (r.kind === "aborted") {- return { state: "unreachable", url, error: "aborted", last_checked_at };- }- if (r.kind === "rpc_error") {- return {- state: "unreachable",- url,- error: `rpc error ${r.code}: ${r.message}`,- last_checked_at,- };- }- if (r.kind === "malformed_response") {- return {- state: "unreachable",- url,- error: `malformed response: ${r.message}`,- last_checked_at,- };- }- return { state: "unreachable", url, error: r.message, last_checked_at };-}--export async function disconnectMcp(project_slug: string, catalog_key: string): Promise<void> {- const keys = catalogKeysSharingResource(project_slug, catalog_key);- const tokenIds = new Set<string>();- for (const key of keys) {- const token = findMcpToken(project_slug, key);- if (token) tokenIds.add(token.id);- invalidateProbe(project_slug, key);- }- for (const id of tokenIds) deleteMcpToken(id);-}--export async function setMcpBearer(- project_slug: string,- catalog_key: string,- token: string,- options: {- scope?: string;- expires_at?: string;- refresh_token?: string;- token_endpoint?: string;- client_id?: string;- client_secret?: string;- } = {},-): Promise<void> {- upsertMcpToken({- project_slug,- server_name: catalog_key,- access_token: token,- scope: options.scope,- expires_at: options.expires_at,- refresh_token: options.refresh_token,- token_endpoint: options.token_endpoint,- client_id: options.client_id,- client_secret: options.client_secret,- });- // Drop any cached probe result so the badge reflects the new credentials- // on the very next render instead of waiting out the TTL.- invalidateProbe(project_slug, catalog_key);-}diff --git a/notfair/src/server/mcp/tokens.test.ts b/notfair/src/server/mcp/tokens.test.tsdeleted file mode 100644index c8737a77..00000000--- a/notfair/src/server/mcp/tokens.test.ts+++ /dev/null@@ -1,213 +0,0 @@-import { beforeAll, describe, expect, it, vi } from "vitest";--// Real better-sqlite3 against a tmpdir DB, per repo test conventions.-// MUST be hoisted: static imports evaluate before module-level statements,-// and db.ts captures NOTFAIR_DATA_DIR at import time — a plain assignment-// here would silently point the suite at the developer's live ~/.notfair.-vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- process.env.NOTFAIR_DATA_DIR = mkdtempSync(join(tmpdir(), "notfair-tokens-"));-});--import { getDb } from "@/server/db/db";-import {- deleteMcpToken,- deleteProjectMcpTokens,- findMcpToken,- getMcpToken,- listProjectMcpTokens,- updateMcpTokenSecrets,- upsertMcpToken,-} from "./tokens";--// mcp_tokens.project_slug FKs to projects(slug); seed the parent rows the-// cases reference before any upsert runs.-beforeAll(() => {- const db = getDb();- const insert = db.prepare(- "INSERT OR IGNORE INTO projects (id, slug, display_name, created_at, harness_adapter) VALUES (?, ?, ?, ?, 'claude-code-local')",- );- for (const slug of [- "proj-a", "proj-b", "proj-c", "proj-d", "proj-e",- "proj-f", "proj-g", "proj-h", "proj-i",- ]) {- insert.run(slug, slug, slug, new Date().toISOString());- }-});--describe("upsertMcpToken", () => {- it("inserts a new row with defaults applied", () => {- const token = upsertMcpToken({- project_slug: "proj-a",- server_name: "notfair-googleads",- access_token: "at-1",- });- expect(token.id).toBeTruthy();- expect(token.account_label).toBe("");- expect(token.access_token_enc).toBe("at-1");- expect(token.refresh_token_enc).toBeNull();- expect(token.expires_at).toBeNull();- expect(token.scope).toBeNull();- expect(token.metadata_json).toBeNull();- expect(token.token_endpoint).toBeNull();- expect(token.client_id).toBeNull();- expect(token.client_secret).toBeNull();-- // Round-trips through the DB identically.- expect(getMcpToken(token.id)).toEqual(token);- });-- it("updates in place on (project_slug, server_name, account_label) collision", () => {- const first = upsertMcpToken({- project_slug: "proj-b",- server_name: "notfair-metaads",- access_token: "old",- refresh_token: "old-rt",- });- const second = upsertMcpToken({- project_slug: "proj-b",- server_name: "notfair-metaads",- access_token: "new",- expires_at: "2027-01-01T00:00:00.000Z",- scope: "ads.read",- metadata: { account: "123" },- token_endpoint: "https://oauth.example.com/token",- client_id: "cid",- client_secret: "csec",- });- expect(second.id).toBe(first.id);- expect(second.access_token_enc).toBe("new");- // Update overwrites every secret column — omitted refresh_token becomes null.- expect(second.refresh_token_enc).toBeNull();- expect(second.expires_at).toBe("2027-01-01T00:00:00.000Z");- expect(second.scope).toBe("ads.read");- expect(second.metadata_json).toBe(JSON.stringify({ account: "123" }));- expect(second.token_endpoint).toBe("https://oauth.example.com/token");- expect(second.client_id).toBe("cid");- expect(second.client_secret).toBe("csec");- expect(listProjectMcpTokens("proj-b")).toHaveLength(1);- });-- it("treats different account_labels as distinct rows", () => {- upsertMcpToken({- project_slug: "proj-c",- server_name: "notfair-googleads",- account_label: "acct-1",- access_token: "a",- });- upsertMcpToken({- project_slug: "proj-c",- server_name: "notfair-googleads",- account_label: "acct-2",- access_token: "b",- });- expect(listProjectMcpTokens("proj-c")).toHaveLength(2);- });-});--describe("updateMcpTokenSecrets", () => {- it("rotates the access token and keeps the refresh token via COALESCE", () => {- const token = upsertMcpToken({- project_slug: "proj-d",- server_name: "srv",- access_token: "at",- refresh_token: "rt-keep",- expires_at: "2026-01-01T00:00:00.000Z",- });- const updated = updateMcpTokenSecrets(token.id, {- access_token: "at-2",- refresh_token: null,- expires_at: "2026-02-01T00:00:00.000Z",- });- expect(updated).not.toBeNull();- expect(updated!.access_token_enc).toBe("at-2");- expect(updated!.refresh_token_enc).toBe("rt-keep");- expect(updated!.expires_at).toBe("2026-02-01T00:00:00.000Z");- });-- it("replaces the refresh token when the provider rotates it", () => {- const token = upsertMcpToken({- project_slug: "proj-d",- server_name: "srv-rotate",- access_token: "at",- refresh_token: "rt-old",- });- const updated = updateMcpTokenSecrets(token.id, {- access_token: "at-2",- refresh_token: "rt-new",- });- expect(updated!.refresh_token_enc).toBe("rt-new");- // Omitted expires_at nulls the column.- expect(updated!.expires_at).toBeNull();- });-- it("returns null when the row was deleted mid-refresh", () => {- expect(- updateMcpTokenSecrets("nope", { access_token: "x" }),- ).toBeNull();- });-});--describe("lookups and deletes", () => {- it("getMcpToken returns null for unknown id", () => {- expect(getMcpToken("missing")).toBeNull();- });-- it("findMcpToken matches (project, server, label) and defaults label to ''", () => {- const token = upsertMcpToken({- project_slug: "proj-e",- server_name: "srv",- access_token: "at",- });- expect(findMcpToken("proj-e", "srv")).toEqual(token);- expect(findMcpToken("proj-e", "srv", "other-label")).toBeNull();- expect(findMcpToken("other-proj", "srv")).toBeNull();- });-- it("listProjectMcpTokens orders by server_name then account_label", () => {- upsertMcpToken({ project_slug: "proj-f", server_name: "zeta", access_token: "1" });- upsertMcpToken({- project_slug: "proj-f",- server_name: "alpha",- account_label: "b",- access_token: "2",- });- upsertMcpToken({- project_slug: "proj-f",- server_name: "alpha",- account_label: "a",- access_token: "3",- });- const rows = listProjectMcpTokens("proj-f");- expect(rows.map((r) => [r.server_name, r.account_label])).toEqual([- ["alpha", "a"],- ["alpha", "b"],- ["zeta", ""],- ]);- });-- it("deleteMcpToken removes one row", () => {- const token = upsertMcpToken({- project_slug: "proj-g",- server_name: "srv",- access_token: "at",- });- deleteMcpToken(token.id);- expect(getMcpToken(token.id)).toBeNull();- });-- it("deleteProjectMcpTokens clears the whole project without touching others", () => {- upsertMcpToken({ project_slug: "proj-h", server_name: "one", access_token: "1" });- upsertMcpToken({ project_slug: "proj-h", server_name: "two", access_token: "2" });- const other = upsertMcpToken({- project_slug: "proj-i",- server_name: "one",- access_token: "3",- });- deleteProjectMcpTokens("proj-h");- expect(listProjectMcpTokens("proj-h")).toEqual([]);- expect(getMcpToken(other.id)).toEqual(other);- });-});diff --git a/notfair/src/server/mcp/tokens.ts b/notfair/src/server/mcp/tokens.tsdeleted file mode 100644index ff1bac50..00000000--- a/notfair/src/server/mcp/tokens.ts+++ /dev/null@@ -1,200 +0,0 @@-import { randomUUID } from "node:crypto";-import { getDb } from "@/server/db/db";--/**- * MCP token storage for NotFair.- *- * Tokens- * are project-scoped — one project's notfair-googleads connection never bleeds- * into another's.- *- * `access_token_enc` / `refresh_token_enc` columns are encrypted-at-rest- * placeholders today (we store the raw JSON envelope from the OAuth callback)- * but the schema is ready for a keytar-backed encryption pass.- *- * `token_endpoint`, `client_id`, `client_secret` support refresh- * so the refresh helper (`mcp/refresh.ts`) can rotate access tokens without- * sending the user back through consent. They are nullable: pre-013 rows- * have them as NULL and stay on the legacy reconnect-on-401 path.- */-export interface McpToken {- id: string;- project_slug: string;- server_name: string;- account_label: string;- access_token_enc: string;- refresh_token_enc: string | null;- expires_at: string | null;- scope: string | null;- metadata_json: string | null;- token_endpoint: string | null;- client_id: string | null;- client_secret: string | null;- created_at: string;- updated_at: string;-}--export interface UpsertMcpTokenInput {- project_slug: string;- server_name: string;- account_label?: string;- access_token: string;- refresh_token?: string;- expires_at?: string;- scope?: string;- metadata?: Record<string, unknown>;- token_endpoint?: string;- client_id?: string;- client_secret?: string;-}--export function upsertMcpToken(input: UpsertMcpTokenInput): McpToken {- const db = getDb();- const account_label = input.account_label ?? "";- const now = new Date().toISOString();- const existing = db- .prepare(- "SELECT * FROM mcp_tokens WHERE project_slug = ? AND server_name = ? AND account_label = ?",- )- .get(input.project_slug, input.server_name, account_label) as McpToken | undefined;-- if (existing) {- db.prepare(- `UPDATE mcp_tokens SET- access_token_enc = ?,- refresh_token_enc = ?,- expires_at = ?,- scope = ?,- metadata_json = ?,- token_endpoint = ?,- client_id = ?,- client_secret = ?,- updated_at = ?- WHERE id = ?`,- ).run(- input.access_token,- input.refresh_token ?? null,- input.expires_at ?? null,- input.scope ?? null,- input.metadata ? JSON.stringify(input.metadata) : null,- input.token_endpoint ?? null,- input.client_id ?? null,- input.client_secret ?? null,- now,- existing.id,- );- return getMcpToken(existing.id)!;- }-- const token: McpToken = {- id: randomUUID(),- project_slug: input.project_slug,- server_name: input.server_name,- account_label,- access_token_enc: input.access_token,- refresh_token_enc: input.refresh_token ?? null,- expires_at: input.expires_at ?? null,- scope: input.scope ?? null,- metadata_json: input.metadata ? JSON.stringify(input.metadata) : null,- token_endpoint: input.token_endpoint ?? null,- client_id: input.client_id ?? null,- client_secret: input.client_secret ?? null,- created_at: now,- updated_at: now,- };- db.prepare(- `INSERT INTO mcp_tokens (- id, project_slug, server_name, account_label,- access_token_enc, refresh_token_enc, expires_at, scope, metadata_json,- token_endpoint, client_id, client_secret,- created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,- ).run(- token.id,- token.project_slug,- token.server_name,- token.account_label,- token.access_token_enc,- token.refresh_token_enc,- token.expires_at,- token.scope,- token.metadata_json,- token.token_endpoint,- token.client_id,- token.client_secret,- token.created_at,- token.updated_at,- );- return token;-}--/**- * In-place rotation of the access token (and optionally the refresh token —- * some providers rotate it on every refresh). Used by `mcp/refresh.ts` after- * a successful `grant_type=refresh_token` exchange. Leaves the OAuth client- * fields untouched so the next refresh has what it needs.- *- * Returns the updated row, or null if `id` no longer exists (deleted between- * lookup and refresh — race that's possible if the user disconnects mid-call).- */-export function updateMcpTokenSecrets(- id: string,- patch: { access_token: string; refresh_token?: string | null; expires_at?: string | null },-): McpToken | null {- const db = getDb();- const now = new Date().toISOString();- const result = db- .prepare(- `UPDATE mcp_tokens SET- access_token_enc = ?,- refresh_token_enc = COALESCE(?, refresh_token_enc),- expires_at = ?,- updated_at = ?- WHERE id = ?`,- )- .run(- patch.access_token,- patch.refresh_token ?? null,- patch.expires_at ?? null,- now,- id,- );- if (result.changes === 0) return null;- return getMcpToken(id);-}--export function getMcpToken(id: string): McpToken | null {- return (- (getDb()- .prepare("SELECT * FROM mcp_tokens WHERE id = ?")- .get(id) as McpToken | undefined) ?? null- );-}--export function findMcpToken(- project_slug: string,- server_name: string,- account_label = "",-): McpToken | null {- return (- (getDb()- .prepare(- "SELECT * FROM mcp_tokens WHERE project_slug = ? AND server_name = ? AND account_label = ?",- )- .get(project_slug, server_name, account_label) as McpToken | undefined) ?? null- );-}--export function listProjectMcpTokens(project_slug: string): McpToken[] {- return getDb()- .prepare("SELECT * FROM mcp_tokens WHERE project_slug = ? ORDER BY server_name, account_label")- .all(project_slug) as McpToken[];-}--export function deleteMcpToken(id: string): void {- getDb().prepare("DELETE FROM mcp_tokens WHERE id = ?").run(id);-}--export function deleteProjectMcpTokens(project_slug: string): void {- getDb().prepare("DELETE FROM mcp_tokens WHERE project_slug = ?").run(project_slug);-}diff --git a/notfair/src/server/native-bindings.test.ts b/notfair/src/server/native-bindings.test.tsdeleted file mode 100644index 3a331a7e..00000000--- a/notfair/src/server/native-bindings.test.ts+++ /dev/null@@ -1,164 +0,0 @@-import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";-import { tmpdir } from "node:os";-import { dirname, join } from "node:path";-import { describe, expect, it } from "vitest";--import {- resolveCompatibleNodeRuntime,- syncStandaloneNativeBindings,-} from "../../bin/native-bindings.mjs";--describe("syncStandaloneNativeBindings", () => {- it("refreshes release-built bindings before a fresh CLI start", async () => {- const packageRoot = await mkdtemp(join(tmpdir(), "notfair-cli-bindings-"));- const runtimeDir = join(packageRoot, "node_modules", "better-sqlite3", "build", "Release");- const tracedDir = join(- packageRoot,- ".next",- "standalone",- ".next",- "node_modules",- "better-sqlite3-traced",- "build",- "Release",- );-- try {- await Promise.all([- mkdir(runtimeDir, { recursive: true }),- mkdir(tracedDir, { recursive: true }),- ]);- await writeFile(join(runtimeDir, "better_sqlite3.node"), "local-node-binding");- await writeFile(join(tracedDir, "better_sqlite3.node"), "release-node-binding");-- expect(syncStandaloneNativeBindings(packageRoot)).toBe(1);- await expect(readFile(join(tracedDir, "better_sqlite3.node"), "utf8")).resolves.toBe(- "local-node-binding",- );- } finally {- await rm(packageRoot, { recursive: true, force: true });- }- });-- it("is a no-op when npm did not install a runtime binding", async () => {- const packageRoot = await mkdtemp(join(tmpdir(), "notfair-cli-bindings-"));- try {- expect(syncStandaloneNativeBindings(packageRoot)).toBe(0);- } finally {- await rm(packageRoot, { recursive: true, force: true });- }- });-- it("uses the package prefix Node when the shell Node cannot load the installed binding", async () => {- const prefix = await mkdtemp(join(tmpdir(), "notfair-cli-runtime-"));- const packageRoot = join(prefix, "lib", "node_modules", "notfair");- const binding = join(- packageRoot,- "node_modules",- "better-sqlite3",- "build",- "Release",- "better_sqlite3.node",- );- const shellNode = join(prefix, "shell", "node");- const installedNode = join(prefix, "bin", "node");-- try {- await Promise.all([- mkdir(dirname(binding), { recursive: true }),- mkdir(dirname(shellNode), { recursive: true }),- mkdir(dirname(installedNode), { recursive: true }),- ]);- await Promise.all([- writeFile(binding, "node-25-binding"),- writeFile(shellNode, "node-24"),- writeFile(installedNode, "node-25"),- ]);-- expect(- resolveCompatibleNodeRuntime(packageRoot, {- execPath: shellNode,- probe: (candidate: string) => candidate === installedNode,- }),- ).toBe(installedNode);- } finally {- await rm(prefix, { recursive: true, force: true });- }- });-- it("keeps the active Node when it can load the installed binding", async () => {- const prefix = await mkdtemp(join(tmpdir(), "notfair-cli-runtime-"));- const packageRoot = join(prefix, "lib", "node_modules", "notfair");- const binding = join(- packageRoot,- "node_modules",- "better-sqlite3",- "build",- "Release",- "better_sqlite3.node",- );- const shellNode = join(prefix, "shell", "node");- const probed: string[] = [];-- try {- await Promise.all([- mkdir(dirname(binding), { recursive: true }),- mkdir(dirname(shellNode), { recursive: true }),- ]);- await Promise.all([- writeFile(binding, "node-25-binding"),- writeFile(shellNode, "node-25"),- ]);-- expect(- resolveCompatibleNodeRuntime(packageRoot, {- execPath: shellNode,- probe: (candidate: string) => {- probed.push(candidate);- return candidate === shellNode;- },- }),- ).toBe(shellNode);- expect(probed).toEqual([shellNode]);- } finally {- await rm(prefix, { recursive: true, force: true });- }- });-- it("fails with reinstall guidance when no available Node can load the binding", async () => {- const prefix = await mkdtemp(join(tmpdir(), "notfair-cli-runtime-"));- const packageRoot = join(prefix, "lib", "node_modules", "notfair");- const binding = join(- packageRoot,- "node_modules",- "better-sqlite3",- "build",- "Release",- "better_sqlite3.node",- );- const shellNode = join(prefix, "shell", "node");- const installedNode = join(prefix, "bin", "node");-- try {- await Promise.all([- mkdir(dirname(binding), { recursive: true }),- mkdir(dirname(shellNode), { recursive: true }),- mkdir(dirname(installedNode), { recursive: true }),- ]);- await Promise.all([- writeFile(binding, "node-25-binding"),- writeFile(shellNode, "node-24"),- writeFile(installedNode, "node-23"),- ]);-- expect(() =>- resolveCompatibleNodeRuntime(packageRoot, {- execPath: shellNode,- probe: () => false,- }),- ).toThrow("npm install -g notfair@latest");- } finally {- await rm(prefix, { recursive: true, force: true });- }- });-});diff --git a/notfair/src/server/onboarding/accounts.test.ts b/notfair/src/server/onboarding/accounts.test.tsdeleted file mode 100644index 9d8b266a..00000000--- a/notfair/src/server/onboarding/accounts.test.ts+++ /dev/null@@ -1,367 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- revalidatePath: vi.fn(),- getMcpConfig: vi.fn(),- mcpRpcAutoRefresh: vi.fn(),- getProject: vi.fn(),- setGoogle: vi.fn(),- setMeta: vi.fn(),- setGsc: vi.fn(),- getMcpCatalog: vi.fn(),- getMcpStatus: vi.fn(),- accountPickerFor: vi.fn(),-}));--vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));-vi.mock("@/server/mcp/rpc", () => ({- getMcpConfig: mocks.getMcpConfig,- mcpRpcAutoRefresh: mocks.mcpRpcAutoRefresh,-}));-vi.mock("@/server/db/projects", () => ({- getProject: mocks.getProject,- setProjectGoogleAdsAccount: mocks.setGoogle,- setProjectMetaAdsAccount: mocks.setMeta,- setProjectGscProperty: mocks.setGsc,-}));-vi.mock("@/server/mcp-catalog", () => ({- getMcpCatalog: mocks.getMcpCatalog,-}));-vi.mock("@/server/mcp/state", () => ({ getMcpStatus: mocks.getMcpStatus }));-vi.mock("@/lib/mcp-account-pickers", () => ({- accountPickerFor: mocks.accountPickerFor,-}));--import {- getOnboardingConnectCardsAction,- listGoogleAdsAccounts,- listGscProperties,- listMetaAdsAccounts,- setOnboardingAccountAction,- setOnboardingGscPropertyAction,- setOnboardingMetaAdsAccountAction,-} from "./accounts";--const project = {- slug: "acme",- google_ads_account_id: "g-selected",- meta_ads_account_id: "m-selected",- gsc_property_url: "https://selected.example/",-};--function toolResult(body: unknown) {- return {- ok: true,- result: { content: [{ type: "text", text: JSON.stringify(body) }] },- };-}--beforeEach(() => {- vi.clearAllMocks();- mocks.getMcpConfig.mockReturnValue({ url: "https://mcp.example" });- mocks.getProject.mockReturnValue(project);- mocks.setGoogle.mockReturnValue(project);- mocks.setMeta.mockReturnValue(project);- mocks.setGsc.mockReturnValue(project);-});--describe("listGoogleAdsAccounts", () => {- it("reports a missing MCP configuration without making an RPC", async () => {- mocks.getMcpConfig.mockReturnValue(null);- await expect(listGoogleAdsAccounts("acme")).resolves.toMatchObject({- ok: false,- kind: "mcp_not_configured",- });- expect(mocks.mcpRpcAutoRefresh).not.toHaveBeenCalled();- });-- it("normalizes accounts, names, and ids", async () => {- mocks.mcpRpcAutoRefresh.mockResolvedValue(- toolResult({- accounts: [- { id: 123, name: " Main " },- { id: "fallback", name: "" },- { id: "", name: "ignored" },- null,- ],- defaultAccountId: 123,- }),- );- await expect(listGoogleAdsAccounts("acme")).resolves.toEqual({- ok: true,- accounts: [- { id: "123", name: "Main" },- { id: "fallback", name: "fallback" },- ],- });- expect(mocks.mcpRpcAutoRefresh).toHaveBeenCalledWith(- "acme",- "notfair-googleads",- "tools/call",- { name: "executeRead", arguments: { capabilityId: "google_ads_listConnectedAccounts", arguments: {} } },- { timeoutMs: 8_000 },- );- });-- it.each([- [{ kind: "http_error", status: 503 }, "HTTP 503"],- [{ kind: "rpc_error", code: -1, message: "bad" }, "RPC -1: bad"],- [{ kind: "timeout" }, "MCP call timed out"],- [{ kind: "aborted" }, "MCP call aborted"],- [{ kind: "malformed_response", message: "junk" }, "junk"],- [{ kind: "network_error", message: "offline" }, "offline"],- ])("formats RPC failure %o", async (failure, message) => {- mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, ...failure });- await expect(listGoogleAdsAccounts("acme")).resolves.toEqual({- ok: false,- kind: "rpc",- error: message,- });- });-- it.each([- null,- { isError: true, content: [{ text: "{}" }] },- { content: [] },- { content: [{ text: "not json" }] },- { content: [{ text: "{}" }] },- ])("rejects malformed tool result %#", async (result) => {- mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: true, result });- await expect(listGoogleAdsAccounts("acme")).resolves.toMatchObject({- ok: false,- kind: "shape",- });- });-});--describe("setOnboardingAccountAction", () => {- it("validates required input and project existence", async () => {- await expect(setOnboardingAccountAction(" ", "id")).resolves.toMatchObject({ ok: false });- await expect(setOnboardingAccountAction("acme", " ")).resolves.toMatchObject({ ok: false });- mocks.getProject.mockReturnValue(null);- await expect(setOnboardingAccountAction("acme", "id")).resolves.toEqual({- ok: false,- error: "Project not found.",- });- });-- it("rejects failed verification and unreachable account ids", async () => {- mocks.getMcpConfig.mockReturnValue(null);- await expect(setOnboardingAccountAction("acme", "id")).resolves.toMatchObject({- ok: false,- error: expect.stringContaining("Couldn't verify account"),- });-- mocks.getMcpConfig.mockReturnValue({});- mocks.mcpRpcAutoRefresh.mockResolvedValue(toolResult({ accounts: [{ id: "other" }] }));- await expect(setOnboardingAccountAction("acme", "id")).resolves.toMatchObject({- ok: false,- error: expect.stringContaining("isn't in"),- });- });-- it("persists a verified account and revalidates the layout", async () => {- mocks.mcpRpcAutoRefresh.mockResolvedValue(toolResult({ accounts: [{ id: "id", name: "A" }] }));- await expect(setOnboardingAccountAction("acme", "id")).resolves.toEqual({- ok: true,- project,- });- expect(mocks.setGoogle).toHaveBeenCalledWith("acme", "id");- expect(mocks.revalidatePath).toHaveBeenCalledWith("/", "layout");- });-- it("handles a project disappearing during the write", async () => {- mocks.mcpRpcAutoRefresh.mockResolvedValue(toolResult({ accounts: [{ id: "id" }] }));- mocks.setGoogle.mockReturnValue(null);- await expect(setOnboardingAccountAction("acme", "id")).resolves.toEqual({- ok: false,- error: "Project not found.",- });- });-});--describe("Meta Ads account onboarding", () => {- it("supports Graph data and fallback accounts shapes", async () => {- mocks.mcpRpcAutoRefresh.mockResolvedValue(- toolResult({ data: [{ id: "act_1", name: " Primary " }, { id: "act_2" }, null] }),- );- await expect(listMetaAdsAccounts("acme")).resolves.toMatchObject({- ok: true,- accounts: [- { id: "act_1", name: "Primary" },- { id: "act_2", name: "act_2" },- ],- });- mocks.mcpRpcAutoRefresh.mockResolvedValue(- toolResult({ accounts: [{ id: "act_3", name: "Third" }], defaultAccountId: "act_3" }),- );- await expect(listMetaAdsAccounts("acme")).resolves.toMatchObject({- ok: true,- accounts: [{ id: "act_3", name: "Third" }],- });- expect(await listMetaAdsAccounts("acme")).not.toHaveProperty("default_account_id");- expect(mocks.mcpRpcAutoRefresh).toHaveBeenCalledWith(- "acme",- "notfair-metaads",- "tools/call",- {- name: "executeRead",- arguments: { capabilityId: "meta_ads_listAdAccounts", arguments: {} },- },- { timeoutMs: 8_000 },- );- });-- it("handles missing config, RPC failure, and malformed payloads", async () => {- mocks.getMcpConfig.mockReturnValue(null);- await expect(listMetaAdsAccounts("acme")).resolves.toMatchObject({ kind: "mcp_not_configured" });- mocks.getMcpConfig.mockReturnValue({});- mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, kind: "timeout" });- await expect(listMetaAdsAccounts("acme")).resolves.toMatchObject({ kind: "rpc" });- mocks.mcpRpcAutoRefresh.mockResolvedValue(toolResult({ nope: [] }));- await expect(listMetaAdsAccounts("acme")).resolves.toMatchObject({ kind: "shape" });- });-- it("validates and persists the selected Meta account", async () => {- await expect(setOnboardingMetaAdsAccountAction("", "act_1")).resolves.toMatchObject({ ok: false });- mocks.getProject.mockReturnValue(null);- await expect(setOnboardingMetaAdsAccountAction("acme", "act_1")).resolves.toMatchObject({ ok: false });- mocks.getProject.mockReturnValue(project);- mocks.mcpRpcAutoRefresh.mockResolvedValue(toolResult({ data: [{ id: "act_1" }] }));- await expect(setOnboardingMetaAdsAccountAction("acme", "missing")).resolves.toMatchObject({ ok: false });- await expect(setOnboardingMetaAdsAccountAction("acme", "act_1")).resolves.toEqual({ ok: true, project });- expect(mocks.setMeta).toHaveBeenCalledWith("acme", "act_1");- });-- it("surfaces verification and disappearing-project failures", async () => {- mocks.getMcpConfig.mockReturnValue(null);- await expect(setOnboardingMetaAdsAccountAction("acme", "act_1")).resolves.toMatchObject({- error: expect.stringContaining("Meta Ads MCP"),- });- mocks.getMcpConfig.mockReturnValue({});- mocks.mcpRpcAutoRefresh.mockResolvedValue(toolResult({ data: [{ id: "act_1" }] }));- mocks.setMeta.mockReturnValue(null);- await expect(setOnboardingMetaAdsAccountAction("acme", "act_1")).resolves.toEqual({- ok: false,- error: "Project not found.",- });- });-});--describe("Search Console property onboarding", () => {- it("normalizes bare, siteEntry, and sites payloads with readable labels", async () => {- mocks.mcpRpcAutoRefresh.mockResolvedValue(- toolResult([- { siteUrl: "sc-domain:example.com", permissionLevel: "siteOwner" },- { siteUrl: "https://example.com/blog/" },- { id: "not a url", name: " Custom " },- { siteUrl: "" },- null,- ]),- );- await expect(listGscProperties("acme")).resolves.toMatchObject({- ok: true,- properties: [- { id: "sc-domain:example.com", name: "example.com", permission: "siteOwner" },- { id: "https://example.com/blog/", name: "example.com/blog/" },- { id: "not a url", name: "Custom" },- ],- });- expect(mocks.mcpRpcAutoRefresh).toHaveBeenCalledWith(- "acme",- "notfair-googlesearchconsole",- "tools/call",- {- name: "executeRead",- arguments: {- capabilityId: "search_console_listProperties",- arguments: {},- },- },- { timeoutMs: 8_000 },- );- mocks.mcpRpcAutoRefresh.mockResolvedValue(- toolResult({ siteEntry: [{ siteUrl: "https://one.example/" }], defaultPropertyId: "one" }),- );- await expect(listGscProperties("acme")).resolves.toMatchObject({- ok: true,- properties: [{ id: "https://one.example/", name: "one.example" }],- });- expect(await listGscProperties("acme")).not.toHaveProperty("default_property_id");- mocks.mcpRpcAutoRefresh.mockResolvedValue(toolResult({ sites: [] }));- await expect(listGscProperties("acme")).resolves.toMatchObject({ ok: true, properties: [] });- });-- it("handles missing config, RPC errors, and malformed object payloads", async () => {- mocks.getMcpConfig.mockReturnValue(null);- await expect(listGscProperties("acme")).resolves.toMatchObject({ kind: "mcp_not_configured" });- mocks.getMcpConfig.mockReturnValue({});- mocks.mcpRpcAutoRefresh.mockResolvedValue({ ok: false, kind: "aborted" });- await expect(listGscProperties("acme")).resolves.toMatchObject({ kind: "rpc", error: "MCP call aborted" });- mocks.mcpRpcAutoRefresh.mockResolvedValue(toolResult({ unknown: [] }));- await expect(listGscProperties("acme")).resolves.toMatchObject({ kind: "shape" });- });-- it("validates and persists a selected property", async () => {- await expect(setOnboardingGscPropertyAction("acme", " ")).resolves.toMatchObject({ ok: false });- mocks.getProject.mockReturnValue(null);- await expect(setOnboardingGscPropertyAction("acme", "x")).resolves.toMatchObject({ ok: false });- mocks.getProject.mockReturnValue(project);- mocks.mcpRpcAutoRefresh.mockResolvedValue(toolResult([{ siteUrl: "https://example.com/" }]));- await expect(setOnboardingGscPropertyAction("acme", "missing")).resolves.toMatchObject({ ok: false });- await expect(setOnboardingGscPropertyAction("acme", "https://example.com/")).resolves.toEqual({ ok: true, project });- expect(mocks.setGsc).toHaveBeenCalledWith("acme", "https://example.com/");- });-- it("surfaces verification and disappearing-project failures", async () => {- mocks.getMcpConfig.mockReturnValue(null);- await expect(setOnboardingGscPropertyAction("acme", "x")).resolves.toMatchObject({- error: expect.stringContaining("GSC MCP"),- });- mocks.getMcpConfig.mockReturnValue({});- mocks.mcpRpcAutoRefresh.mockResolvedValue(toolResult([{ siteUrl: "x" }]));- mocks.setGsc.mockReturnValue(null);- await expect(setOnboardingGscPropertyAction("acme", "x")).resolves.toEqual({- ok: false,- error: "Project not found.",- });- });-});--describe("getOnboardingConnectCardsAction", () => {- it("validates the project", async () => {- await expect(getOnboardingConnectCardsAction(" ")).resolves.toMatchObject({ ok: false });- mocks.getProject.mockReturnValue(null);- await expect(getOnboardingConnectCardsAction("acme")).resolves.toEqual({- ok: false,- error: "Project not found.",- });- });-- it("keeps recommended cards plus connected extras and derives selections", async () => {- const catalog = [- { key: "notfair-googleads" },- { key: "custom-connected" },- { key: "custom-idle" },- ];- mocks.getMcpCatalog.mockReturnValue(catalog);- mocks.getMcpStatus- .mockResolvedValueOnce({ state: "not_configured" })- .mockResolvedValueOnce({ state: "connected" })- .mockResolvedValueOnce({ state: "unreachable" });- mocks.accountPickerFor.mockImplementation((key: string) =>- key === "notfair-googleads"- ? { selectedId: (p: typeof project) => p.google_ads_account_id }- : null,- );- const result = await getOnboardingConnectCardsAction("acme");- expect(result).toMatchObject({ ok: true, any_connected: true });- if (!result.ok) throw new Error("expected cards");- expect(result.cards.map((card) => card.spec.key)).toEqual([- "notfair-googleads",- "custom-connected",- ]);- expect(result.cards[0]!.selected_id).toBe("g-selected");- expect(result.cards[1]!.selected_id).toBeNull();- });-});diff --git a/notfair/src/server/onboarding/accounts.ts b/notfair/src/server/onboarding/accounts.tsdeleted file mode 100644index f2ab04fd..00000000--- a/notfair/src/server/onboarding/accounts.ts+++ /dev/null@@ -1,530 +0,0 @@-"use server";--import { revalidatePath } from "next/cache";--import { getMcpConfig, mcpRpcAutoRefresh } from "@/server/mcp/rpc";-import {- getProject,- setProjectGoogleAdsAccount,- setProjectMetaAdsAccount,- setProjectGscProperty,-} from "@/server/db/projects";-import type { Project } from "@/types";--/**- * Google Ads account picker for onboarding step=account.- *- * notfair.co's MCP bearer can grant access to multiple customer accounts- * (Demo2 case: 5 accounts under one bearer). The onboarding flow asks the- * user to pick one and we persist the choice on `projects.google_ads_account_id`- * so the audit + later automation target the right account.- *- * Single source of truth for the account ID is the DB column. MCP listings- * return accounts equally; we never treat one as the default.- */--export type GoogleAdsAccount = { id: string; name: string };--export type ListAccountsResult =- | { ok: true; accounts: GoogleAdsAccount[] }- | { ok: false; error: string; kind: "mcp_not_configured" | "rpc" | "shape" };--type ListAccountsToolResult = {- content?: Array<{ type?: string; text?: string }>;- isError?: boolean;-};--type AccountsPayload = {- accounts?: Array<{ id?: unknown; name?: unknown }>;- totalAccounts?: unknown;-};--const MCP_CATALOG_KEY = "notfair-googleads";-const LIST_TIMEOUT_MS = 8_000;-const GOOGLE_ADS_LIST_CAPABILITY = "google_ads_listConnectedAccounts";--function compactExecuteRead(capabilityId: string) {- return {- name: "executeRead" as const,- arguments: { capabilityId, arguments: {} },- };-}--/**- * Call compact `executeRead` for Google Ads accounts with the project's stored bearer.- * Returns the account list (id + name).- */-export async function listGoogleAdsAccounts(- project_slug: string,-): Promise<ListAccountsResult> {- const cfg = getMcpConfig(project_slug, MCP_CATALOG_KEY);- if (!cfg) {- return {- ok: false,- kind: "mcp_not_configured",- error: "Google Ads MCP is not configured for this project.",- };- }-- const rpcResult = await mcpRpcAutoRefresh<ListAccountsToolResult>(- project_slug,- MCP_CATALOG_KEY,- "tools/call",- compactExecuteRead(GOOGLE_ADS_LIST_CAPABILITY),- { timeoutMs: LIST_TIMEOUT_MS },- );-- if (!rpcResult.ok) {- const message =- rpcResult.kind === "http_error"- ? `HTTP ${rpcResult.status}`- : rpcResult.kind === "rpc_error"- ? `RPC ${rpcResult.code}: ${rpcResult.message}`- : rpcResult.kind === "timeout"- ? "MCP call timed out"- : rpcResult.kind === "aborted"- ? "MCP call aborted"- : rpcResult.kind === "malformed_response"- ? rpcResult.message- : rpcResult.message;- return { ok: false, kind: "rpc", error: message };- }-- const parsed = parseAccountsPayload(rpcResult.result);- if (!parsed) {- return {- ok: false,- kind: "shape",- error: "MCP listConnectedAccounts returned an unexpected shape.",- };- }- return { ok: true, ...parsed };-}--function parseAccountsPayload(- result: ListAccountsToolResult,-): { accounts: GoogleAdsAccount[] } | null {- if (!result || typeof result !== "object") return null;- if (result.isError) return null;- const text = result.content?.[0]?.text;- if (typeof text !== "string") return null;- let body: AccountsPayload;- try {- body = JSON.parse(text) as AccountsPayload;- } catch {- return null;- }- if (!body || typeof body !== "object" || !Array.isArray(body.accounts)) {- return null;- }- const accounts: GoogleAdsAccount[] = [];- for (const a of body.accounts) {- if (!a || typeof a !== "object") continue;- const id = String(a.id ?? "").trim();- const name = String(a.name ?? "").trim() || id;- if (id) accounts.push({ id, name });- }- return { accounts };-}--export type SetAccountResult =- | { ok: true; project: Project }- | { ok: false; error: string };--/**- * Persist the chosen Google Ads account on the project row. Validates the- * account_id against the MCP's reachable list (anti-tamper for the form- * submit). Goal agents pick this up via get_project / their identity.- */-export async function setOnboardingAccountAction(- project_slug: string,- account_id: string,-): Promise<SetAccountResult> {- if (!project_slug.trim() || !account_id.trim()) {- return { ok: false, error: "Missing project slug or account id." };- }- const project = getProject(project_slug);- if (!project) return { ok: false, error: "Project not found." };-- // Validate the account exists for this bearer. Defends against URL/form- // tampering that would otherwise let a user persist any string here.- const list = await listGoogleAdsAccounts(project_slug);- if (!list.ok) {- return {- ok: false,- error: `Couldn't verify account against MCP: ${list.error}`,- };- }- const match = list.accounts.find((a) => a.id === account_id);- if (!match) {- return {- ok: false,- error: `Account ${account_id} isn't in this bearer's reachable accounts.`,- };- }-- const updated = setProjectGoogleAdsAccount(project_slug, match.id);- if (!updated) return { ok: false, error: "Project not found." };-- revalidatePath("/", "layout");- return { ok: true, project: updated };-}--const META_ADS_MCP_KEY = "notfair-metaads";-const META_ADS_LIST_CAPABILITY = "meta_ads_listAdAccounts";--export type MetaAdsAccount = {- /** Numeric ad-account id with the `act_` prefix (e.g. `act_123456`). */- id: string;- /** Display name pulled from the Meta Graph payload. Falls back to id. */- name: string;-};--export type ListMetaAdsAccountsResult =- | { ok: true; accounts: MetaAdsAccount[] }- | { ok: false; error: string; kind: "mcp_not_configured" | "rpc" | "shape" };--export async function listMetaAdsAccounts(- project_slug: string,-): Promise<ListMetaAdsAccountsResult> {- const cfg = getMcpConfig(project_slug, META_ADS_MCP_KEY);- if (!cfg) {- return {- ok: false,- kind: "mcp_not_configured",- error: "Meta Ads MCP is not configured for this project.",- };- }-- const rpcResult = await mcpRpcAutoRefresh<ListAccountsToolResult>(- project_slug,- META_ADS_MCP_KEY,- "tools/call",- compactExecuteRead(META_ADS_LIST_CAPABILITY),- { timeoutMs: LIST_TIMEOUT_MS },- );- if (!rpcResult.ok) {- return { ok: false, kind: "rpc", error: rpcErrorMessage(rpcResult) };- }-- const parsed = parseMetaAccountsPayload(rpcResult.result);- if (!parsed) {- return {- ok: false,- kind: "shape",- error: `MCP ${META_ADS_LIST_CAPABILITY} returned an unexpected shape.`,- };- }- return { ok: true, ...parsed };-}--type MetaAccountsPayload = {- // The Meta MCP wraps Graph API responses, which use `data` for the- // collection. We also accept the Google-Ads-style `accounts` key- // defensively in case the MCP normalizes the shape upstream.- data?: Array<{ id?: unknown; name?: unknown; account_id?: unknown }>;- accounts?: Array<{ id?: unknown; name?: unknown }>;-};--function parseMetaAccountsPayload(- result: ListAccountsToolResult,-): { accounts: MetaAdsAccount[] } | null {- if (!result || typeof result !== "object") return null;- if (result.isError) return null;- const text = result.content?.[0]?.text;- if (typeof text !== "string") return null;- let body: MetaAccountsPayload;- try {- body = JSON.parse(text) as MetaAccountsPayload;- } catch {- return null;- }- const raw = Array.isArray(body.data)- ? body.data- : Array.isArray(body.accounts)- ? body.accounts- : null;- if (!raw) return null;- const accounts: MetaAdsAccount[] = [];- for (const a of raw) {- if (!a || typeof a !== "object") continue;- const id = String(a.id ?? "").trim();- const name = String(a.name ?? "").trim() || id;- if (id) accounts.push({ id, name });- }- return { accounts };-}--export type SetMetaAdsAccountResult =- | { ok: true; project: Project }- | { ok: false; error: string };--export async function setOnboardingMetaAdsAccountAction(- project_slug: string,- account_id: string,-): Promise<SetMetaAdsAccountResult> {- if (!project_slug.trim() || !account_id.trim()) {- return { ok: false, error: "Missing project slug or account id." };- }- if (!getProject(project_slug)) return { ok: false, error: "Project not found." };-- const list = await listMetaAdsAccounts(project_slug);- if (!list.ok) {- return {- ok: false,- error: `Couldn't verify account against Meta Ads MCP: ${list.error}`,- };- }- const match = list.accounts.find((a) => a.id === account_id);- if (!match) {- return {- ok: false,- error: `Account ${account_id} isn't in this bearer's reachable accounts.`,- };- }- const updated = setProjectMetaAdsAccount(project_slug, match.id);- if (!updated) return { ok: false, error: "Project not found." };- revalidatePath("/", "layout");- return { ok: true, project: updated };-}--// ── Google Search Console property picker ──────────────────────────-//-// Mirrors the Google Ads pattern. Per the GSC REST API the unit is a-// "site" (e.g. `https://example.com/` or `sc-domain:example.com`); we-// surface them as "properties" in the UI to match what users see in-// Search Console.-//-// The compact NotFair MCP exposes `search_console_listProperties` via-// executeRead (verified against the live server) which returns a bare JSON-// array of `{ siteUrl, permissionLevel }`. We also accept the spec-shaped-// `{ siteEntry: [...] }` wrap and a defensive `{ sites: [...] }` so a-// future server-side change doesn't break the picker.--const GSC_MCP_KEY = "notfair-googlesearchconsole";-const GSC_LIST_CAPABILITY = "search_console_listProperties";--export type GscProperty = {- /** Site URL exactly as Search Console uses it. */- id: string;- /** Display label — typically equals id but trimmed of the scheme. */- name: string;- /** Permission level the bearer has on this property (owner / full / …). */- permission?: string;-};--export type ListGscPropertiesResult =- | { ok: true; properties: GscProperty[] }- | { ok: false; error: string; kind: "mcp_not_configured" | "rpc" | "shape" };--export async function listGscProperties(- project_slug: string,-): Promise<ListGscPropertiesResult> {- const cfg = getMcpConfig(project_slug, GSC_MCP_KEY);- if (!cfg) {- return {- ok: false,- kind: "mcp_not_configured",- error: "Google Search Console MCP is not configured for this project.",- };- }-- const rpcResult = await mcpRpcAutoRefresh<ListAccountsToolResult>(- project_slug,- GSC_MCP_KEY,- "tools/call",- compactExecuteRead(GSC_LIST_CAPABILITY),- { timeoutMs: LIST_TIMEOUT_MS },- );- if (!rpcResult.ok) {- return { ok: false, kind: "rpc", error: rpcErrorMessage(rpcResult) };- }-- const parsed = parseGscPropertiesPayload(rpcResult.result);- if (!parsed) {- return {- ok: false,- kind: "shape",- error: `MCP ${GSC_LIST_CAPABILITY} returned an unexpected shape.`,- };- }- return { ok: true, ...parsed };-}--type GscSiteRow = {- siteUrl?: unknown;- permissionLevel?: unknown;- id?: unknown;- name?: unknown;-};--type GscPropertiesPayload =- // The actual notfair-googlesearchconsole MCP returns a bare array.- | GscSiteRow[]- // Spec shape per the Search Console REST API.- | { siteEntry?: GscSiteRow[]; sites?: GscSiteRow[] };--function parseGscPropertiesPayload(- result: ListAccountsToolResult,-): { properties: GscProperty[] } | null {- if (!result || typeof result !== "object") return null;- if (result.isError) return null;- const text = result.content?.[0]?.text;- if (typeof text !== "string") return null;- let body: GscPropertiesPayload;- try {- body = JSON.parse(text) as GscPropertiesPayload;- } catch {- return null;- }-- // Normalize all three accepted shapes down to a single row list.- const rows: GscSiteRow[] | null = Array.isArray(body)- ? body- : Array.isArray(body?.siteEntry)- ? body.siteEntry- : Array.isArray(body?.sites)- ? body.sites- : null;- // Empty arrays are valid: a connected bearer can legitimately have no- // reachable properties. Only reject objects with neither supported key.- if (!rows) return null;-- const properties: GscProperty[] = [];- for (const s of rows) {- if (!s || typeof s !== "object") continue;- const id = String(s.siteUrl ?? s.id ?? "").trim();- if (!id) continue;- const customName = typeof s.name === "string" ? s.name.trim() : "";- properties.push({- id,- name: customName || prettyGscName(id),- permission:- typeof s.permissionLevel === "string" ? s.permissionLevel : undefined,- });- }- return { properties };-}--function prettyGscName(siteUrl: string): string {- // `sc-domain:example.com` → `example.com`- // `https://example.com/` → `example.com`- if (siteUrl.startsWith("sc-domain:")) return siteUrl.slice("sc-domain:".length);- try {- const u = new URL(siteUrl);- return u.host + (u.pathname === "/" ? "" : u.pathname);- } catch {- return siteUrl;- }-}--export type SetGscPropertyResult =- | { ok: true; project: Project }- | { ok: false; error: string };--export async function setOnboardingGscPropertyAction(- project_slug: string,- property_id: string,-): Promise<SetGscPropertyResult> {- if (!project_slug.trim() || !property_id.trim()) {- return { ok: false, error: "Missing project slug or property id." };- }- if (!getProject(project_slug)) return { ok: false, error: "Project not found." };-- const list = await listGscProperties(project_slug);- if (!list.ok) {- return {- ok: false,- error: `Couldn't verify property against GSC MCP: ${list.error}`,- };- }- const match = list.properties.find((p) => p.id === property_id);- if (!match) {- return {- ok: false,- error: `Property ${property_id} isn't in this bearer's reachable properties.`,- };- }- const updated = setProjectGscProperty(project_slug, match.id);- if (!updated) return { ok: false, error: "Project not found." };- revalidatePath("/", "layout");- return { ok: true, project: updated };-}--// ── Onboarding connect-step cards ──────────────────────────────────-//-// The connect step renders the exact `McpCard` rows the Connections page-// uses — one shared component, one lifecycle (Connect → Choose → Switch),-// zero drift between the two surfaces. This action assembles the card-// inputs client-side onboarding can't compute itself: the catalog spec,-// the live runtime status, and the persisted account/property selection.-//-// The list is curated for the wizard: the recommended MCPs (the ones-// goal agents most commonly measure) always show; anything else from the-// catalog (Google Analytics, Stripe, user-pasted servers) appears only-// once connected — until then it lives in the "More tools" browse menu.--const RECOMMENDED_MCP_KEYS = new Set([- "notfair-googleads",- "notfair-metaads",- "notfair-googlesearchconsole",- "notfair-xads",-]);--export type ConnectCard = {- spec: import("@/server/mcp-catalog").McpSpec;- status: import("@/server/mcp/state").McpRuntimeStatus;- /** Persisted account/property selection — null when unset/not pickable. */- selected_id: string | null;-};--export type GetConnectCardsResult =- | { ok: true; cards: ConnectCard[]; any_connected: boolean }- | { ok: false; error: string };--export async function getOnboardingConnectCardsAction(- project_slug: string,-): Promise<GetConnectCardsResult> {- if (!project_slug.trim()) return { ok: false, error: "Missing project slug." };- const project = getProject(project_slug);- if (!project) return { ok: false, error: "Project not found." };-- const { getMcpCatalog } = await import("@/server/mcp-catalog");- const { getMcpStatus } = await import("@/server/mcp/state");- const { accountPickerFor } = await import("@/lib/mcp-account-pickers");-- const catalog = getMcpCatalog(project_slug);- const statuses = await Promise.all(- catalog.map((s) => getMcpStatus(project_slug, s.key)),- );- const all = catalog.map((spec, i) => ({- spec,- status: statuses[i]!,- selected_id: accountPickerFor(spec.key)?.selectedId(project) ?? null,- }));- return {- ok: true,- cards: all.filter(- (c) =>- RECOMMENDED_MCP_KEYS.has(c.spec.key) || c.status.state === "connected",- ),- any_connected: all.some((c) => c.status.state === "connected"),- };-}--// ── Shared RPC error formatter ─────────────────────────────────────--function rpcErrorMessage(- rpcResult: Extract<- Awaited<ReturnType<typeof mcpRpcAutoRefresh>>,- { ok: false }- >,-): string {- if (rpcResult.kind === "http_error") return `HTTP ${rpcResult.status}`;- if (rpcResult.kind === "rpc_error")- return `RPC ${rpcResult.code}: ${rpcResult.message}`;- if (rpcResult.kind === "timeout") return "MCP call timed out";- if (rpcResult.kind === "aborted") return "MCP call aborted";- if (rpcResult.kind === "malformed_response") return rpcResult.message;- return rpcResult.message;-}diff --git a/notfair/src/server/onboarding/project-brief.test.ts b/notfair/src/server/onboarding/project-brief.test.tsdeleted file mode 100644index 03832283..00000000--- a/notfair/src/server/onboarding/project-brief.test.ts+++ /dev/null@@ -1,115 +0,0 @@-import { describe, expect, it, vi } from "vitest";-import { existsSync } from "node:fs";-import { mkdir, writeFile } from "node:fs/promises";-import { join } from "node:path";--// Real fs against a tmpdir data dir, per repo test conventions.-// MUST be hoisted: static imports evaluate before module-level statements,-// so a plain assignment would point the suite at the developer's ~/.notfair.-const h = vi.hoisted(() => {- const { mkdtempSync } = require("node:fs") as typeof import("node:fs");- const { tmpdir } = require("node:os") as typeof import("node:os");- const { join } = require("node:path") as typeof import("node:path");- const dataDir = mkdtempSync(join(tmpdir(), "notfair-brief-"));- process.env.NOTFAIR_DATA_DIR = dataDir;- return { dataDir };-});--import {- PROJECT_BRIEF_MAX_BYTES,- deleteProjectBriefDir,- projectBriefDir,- projectBriefPath,- readProjectBrief,- renameProjectBriefDir,- writeProjectBrief,-} from "./project-brief";--describe("project brief paths", () => {- it("lives under <data dir>/projects/<slug>/PROJECT.md", () => {- expect(projectBriefDir("acme")).toBe(join(h.dataDir, "projects", "acme"));- expect(projectBriefPath("acme")).toBe(- join(h.dataDir, "projects", "acme", "PROJECT.md"),- );- });-- it("exposes the documented size cap", () => {- expect(PROJECT_BRIEF_MAX_BYTES).toBe(64 * 1024);- });-});--describe("read / write round trip", () => {- it("returns null before any brief has been written", async () => {- await expect(readProjectBrief("never-written")).resolves.toBeNull();- });-- it("writes and reads back the exact body", async () => {- await writeProjectBrief("acme", "# Acme\n\nWe sell anvils.\n");- await expect(readProjectBrief("acme")).resolves.toBe(- "# Acme\n\nWe sell anvils.\n",- );- });-- it("overwrites idempotently on rewrite", async () => {- await writeProjectBrief("acme", "v1");- await writeProjectBrief("acme", "v2");- await expect(readProjectBrief("acme")).resolves.toBe("v2");- });-- it("propagates non-ENOENT fs errors instead of masking them as null", async () => {- // Make PROJECT.md a *directory* — readFile then fails with EISDIR,- // which must bubble (only ENOENT means "no brief yet").- await mkdir(projectBriefPath("dir-not-file"), { recursive: true });- await expect(readProjectBrief("dir-not-file")).rejects.toThrow();- });-});--describe("deleteProjectBriefDir", () => {- it("removes the canonical dir so a recreated slug starts clean", async () => {- await writeProjectBrief("doomed", "secret prior-tenant brief");- await deleteProjectBriefDir("doomed");- expect(existsSync(projectBriefDir("doomed"))).toBe(false);- await expect(readProjectBrief("doomed")).resolves.toBeNull();- });-- it("is a no-op when the dir never existed", async () => {- await expect(deleteProjectBriefDir("never-existed")).resolves.toBeUndefined();- });-});--describe("renameProjectBriefDir", () => {- it("moves the brief to the new slug's dir", async () => {- await writeProjectBrief("old-slug", "the brief");- await renameProjectBriefDir("old-slug", "new-slug");- expect(existsSync(projectBriefDir("old-slug"))).toBe(false);- await expect(readProjectBrief("new-slug")).resolves.toBe("the brief");- });-- it("no-ops when old and new slug are identical", async () => {- await expect(renameProjectBriefDir("same", "same")).resolves.toBeUndefined();- });-- it("no-ops when the source dir doesn't exist", async () => {- await renameProjectBriefDir("ghost", "ghost-dest");- expect(existsSync(projectBriefDir("ghost-dest"))).toBe(false);- });-- it("throws on a slug collision with a non-empty destination", async () => {- await writeProjectBrief("col-src", "src brief");- await writeProjectBrief("col-dst", "dst brief");- await expect(renameProjectBriefDir("col-src", "col-dst")).rejects.toThrow();- // Neither side was clobbered.- await expect(readProjectBrief("col-dst")).resolves.toBe("dst brief");- await expect(readProjectBrief("col-src")).resolves.toBe("src brief");- });-- it("propagates non-ENOENT stat errors", async () => {- // A file where the *parent dir path component* should be a directory- // makes stat fail with ENOTDIR, which must bubble.- await mkdir(join(h.dataDir, "projects"), { recursive: true });- await writeFile(join(h.dataDir, "projects", "plainfile"), "x", "utf8");- await expect(- renameProjectBriefDir("plainfile/child", "elsewhere"),- ).rejects.toThrow();- });-});diff --git a/notfair/src/server/onboarding/project-brief.ts b/notfair/src/server/onboarding/project-brief.tsdeleted file mode 100644index 28d0885b..00000000--- a/notfair/src/server/onboarding/project-brief.ts+++ /dev/null@@ -1,104 +0,0 @@-import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";-import { homedir } from "node:os";-import { dirname, join } from "node:path";--/**- * PROJECT.md — the shared workspace context: "what is this project / who- * is the company". Any goal agent can update it via the- * `set_shared_context` tool; it propagates into every agent's IDENTITY.md- * so all goals share the same picture.- *- * Path layout (relative to the data dir, default ~/.notfair):- *- * projects/<slug>/PROJECT.md — canonical shared copy- *- * Per-agent copies live in each agent's workspace and are written by- * `writeIdentityFile` so a human inspecting the workspace can see what the- * agent actually has. The IDENTITY.md prompt inlines the same content- * under a `## Project context` heading so it lands in the system prompt- * regardless of which files the harness chooses to load.- */--/** Hard cap on PROJECT.md body size — keeps system prompts bounded. */-export const PROJECT_BRIEF_MAX_BYTES = 64 * 1024;--function dataDir(): string {- return process.env.NOTFAIR_DATA_DIR ?? join(homedir(), ".notfair");-}--export function projectBriefDir(project_slug: string): string {- return join(dataDir(), "projects", project_slug);-}--export function projectBriefPath(project_slug: string): string {- return join(projectBriefDir(project_slug), "PROJECT.md");-}--/**- * Return the current PROJECT.md body for a project, or null when none has- * been written yet. Errors (other than ENOENT) bubble up so callers can- * surface fs problems instead of silently treating them as "no brief".- */-export async function readProjectBrief(- project_slug: string,-): Promise<string | null> {- try {- return await readFile(projectBriefPath(project_slug), "utf8");- } catch (err) {- if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;- throw err;- }-}--/**- * Persist a new PROJECT.md body to the canonical path. Idempotent — calling- * with the same body is a no-op rewrite. Does NOT propagate to agent- * workspaces; that's the caller's job (see set_project_brief handler).- */-export async function writeProjectBrief(- project_slug: string,- body: string,-): Promise<void> {- const path = projectBriefPath(project_slug);- await mkdir(dirname(path), { recursive: true });- await writeFile(path, body, "utf8");-}--/**- * Remove the canonical PROJECT.md directory for a project — called from- * the project-delete cascade so we don't orphan briefs on disk. Without- * this, recreating a project with the same slug would inherit the prior- * tenant's brief (writeIdentityFile reads PROJECT.md if it exists).- *- * Best-effort: missing dir is a no-op, other fs errors propagate so the- * caller can decide whether to surface them.- */-export async function deleteProjectBriefDir(- project_slug: string,-): Promise<void> {- await rm(projectBriefDir(project_slug), { recursive: true, force: true });-}--/**- * Move the canonical PROJECT.md directory when a project's slug changes.- * Called by the rename cascade in changeProjectSlug. No-op when the- * source dir doesn't exist (project never had a brief written). Throws- * if the destination already exists — that would be a slug-collision- * higher up the call chain that we should not silently paper over.- */-export async function renameProjectBriefDir(- old_slug: string,- new_slug: string,-): Promise<void> {- if (old_slug === new_slug) return;- const from = projectBriefDir(old_slug);- try {- await stat(from);- } catch (err) {- if ((err as NodeJS.ErrnoException).code === "ENOENT") return;- throw err;- }- const to = projectBriefDir(new_slug);- await mkdir(dirname(to), { recursive: true });- await rename(from, to);-}diff --git a/notfair/src/server/remote-control.test.ts b/notfair/src/server/remote-control.test.tsdeleted file mode 100644index bd1e5d52..00000000--- a/notfair/src/server/remote-control.test.ts+++ /dev/null@@ -1,92 +0,0 @@-import { createServer, type Server } from "node:http";-import { afterEach, describe, expect, it } from "vitest";--import {- createRemoteProxyServer,- remoteBootstrapHtml,-} from "@/server/remote-control";--const servers: Server[] = [];--afterEach(async () => {- await Promise.all(- servers.splice(0).map(- (server) =>- new Promise<void>((resolve) => server.close(() => resolve())),- ),- );-});--describe("remote-control authentication proxy", () => {- it("keeps the token in the URL fragment and claims an HttpOnly session", async () => {- const token = "phone-only-secret";- const target = createServer((req, res) => {- res.writeHead(200, { "content-type": "application/json" });- res.end(JSON.stringify({ path: req.url, host: req.headers.host }));- });- servers.push(target);- const targetPort = await listen(target);-- const proxy = createRemoteProxyServer({- token,- target: `http://127.0.0.1:${targetPort}`,- });- servers.push(proxy);- const proxyPort = await listen(proxy);- const origin = `http://127.0.0.1:${proxyPort}`;-- const locked = await fetch(origin);- expect(locked.status).toBe(401);- expect(locked.headers.get("content-security-policy")).toContain(- "connect-src 'self'",- );- expect(await locked.text()).toContain("Securing this device");-- const rejected = await fetch(`${origin}/.notfair-remote/claim`, {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify({ token: "wrong" }),- });- expect(rejected.status).toBe(401);-- const claimed = await fetch(`${origin}/.notfair-remote/claim`, {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify({ token }),- });- expect(claimed.status).toBe(204);- const cookie = claimed.headers.get("set-cookie");- expect(cookie).toContain("__Host-notfair_remote=phone-only-secret");- expect(cookie).toContain("HttpOnly");- expect(cookie).toContain("Secure");- expect(cookie).toContain("SameSite=Strict");-- const allowed = await fetch(`${origin}/phone-view?tab=goals`, {- headers: { cookie: cookie!.split(";")[0] },- });- expect(allowed.status).toBe(200);- await expect(allowed.json()).resolves.toEqual({- path: "/phone-view?tab=goals",- host: `127.0.0.1:${proxyPort}`,- });- });-- it("bootstraps from a fragment rather than putting the secret in a request", () => {- const html = remoteBootstrapHtml();- expect(html).toContain('location.hash.slice(1)');- expect(html).toContain('params.get("notfair-remote")');- expect(html).not.toContain("phone-only-secret");- });-});--function listen(server: Server): Promise<number> {- return new Promise((resolve) => {- server.listen(0, "127.0.0.1", () => {- const address = server.address();- if (!address || typeof address === "string") {- throw new Error("Expected TCP address");- }- resolve(address.port);- });- });-}diff --git a/notfair/src/server/remote-control.ts b/notfair/src/server/remote-control.tsdeleted file mode 100644index d1cf8aae..00000000--- a/notfair/src/server/remote-control.ts+++ /dev/null@@ -1,529 +0,0 @@-import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";-import { createHash, randomBytes, timingSafeEqual } from "node:crypto";-import { existsSync } from "node:fs";-import {- createServer,- type IncomingMessage,- type Server,- type ServerResponse,-} from "node:http";-import { homedir } from "node:os";-import { delimiter, join } from "node:path";-import { Socket } from "node:net";-import type { Duplex } from "node:stream";--const COOKIE_NAME = "__Host-notfair_remote";-const CLAIM_PATH = "/.notfair-remote/claim";-const START_TIMEOUT_MS = 30_000;-const MAX_CLAIM_BYTES = 4_096;--export type RemoteControlStatus =- | { status: "inactive" }- | { status: "starting" }- | {- status: "active";- public_url: string;- access_url: string;- started_at: string;- }- | { status: "error"; error: string };--type RemoteRuntime = {- state: RemoteControlStatus;- token: string | null;- proxy: Server | null;- tunnel: ChildProcessWithoutNullStreams | null;- startPromise: Promise<RemoteControlStatus> | null;- stopping: boolean;- hooksRegistered: boolean;-};--declare global {- // eslint-disable-next-line no-var- var __notfairRemoteControlRuntime: RemoteRuntime | undefined;-}--function runtime(): RemoteRuntime {- if (!globalThis.__notfairRemoteControlRuntime) {- globalThis.__notfairRemoteControlRuntime = {- state: { status: "inactive" },- token: null,- proxy: null,- tunnel: null,- startPromise: null,- stopping: false,- hooksRegistered: false,- };- }- return globalThis.__notfairRemoteControlRuntime;-}--/**- * Start an authenticated Cloudflare Quick Tunnel to this NotFair process.- *- * The access token lives in the URL fragment, so browsers never send it to- * Cloudflare. A tiny local reverse proxy exchanges it for a secure HttpOnly- * cookie before forwarding any NotFair request.- */-export async function startRemoteControl(): Promise<RemoteControlStatus> {- const rt = runtime();- if (rt.state.status === "active") return rt.state;- if (rt.startPromise) return rt.startPromise;-- rt.state = { status: "starting" };- rt.startPromise = startRuntime(rt).finally(() => {- rt.startPromise = null;- });- return rt.startPromise;-}--export function getRemoteControlStatus(): RemoteControlStatus {- const rt = runtime();- if (- rt.state.status === "active" &&- (!rt.tunnel || rt.tunnel.exitCode !== null)- ) {- rt.state = {- status: "error",- error: "The remote tunnel stopped unexpectedly. Activate it again.",- };- }- return rt.state;-}--export async function stopRemoteControl(): Promise<RemoteControlStatus> {- const rt = runtime();- rt.stopping = true;- const tunnel = rt.tunnel;- const proxy = rt.proxy;- rt.tunnel = null;- rt.proxy = null;- rt.token = null;-- if (tunnel && tunnel.exitCode === null) {- tunnel.kill("SIGTERM");- const exited = await waitForExit(tunnel, 3_000);- if (!exited && tunnel.exitCode === null) tunnel.kill("SIGKILL");- }- if (proxy) {- await new Promise<void>((resolve) => proxy.close(() => resolve()));- }-- rt.stopping = false;- rt.state = { status: "inactive" };- return rt.state;-}--async function startRuntime(rt: RemoteRuntime): Promise<RemoteControlStatus> {- const cloudflared = findCloudflaredBinary();- if (!cloudflared) {- return setError(- rt,- "Cloudflare Tunnel is required. Install it with `brew install cloudflared`, then try again.",- );- }-- registerShutdownHooks(rt);- rt.token = randomBytes(32).toString("base64url");-- try {- const targetPort = process.env.PORT?.trim() || "3326";- rt.proxy = createRemoteProxyServer({- token: rt.token,- target: `http://127.0.0.1:${targetPort}`,- });- const proxyPort = await listenOnLoopback(rt.proxy);-- const tunnel = spawn(- cloudflared,- [- "tunnel",- "--no-autoupdate",- "--url",- `http://127.0.0.1:${proxyPort}`,- ],- {- cwd: homedir(),- env: process.env,- stdio: ["pipe", "pipe", "pipe"],- },- );- tunnel.stdin.end();- rt.tunnel = tunnel;- tunnel.on("exit", () => {- if (rt.tunnel !== tunnel || rt.stopping) return;- rt.tunnel = null;- rt.token = null;- const proxy = rt.proxy;- rt.proxy = null;- proxy?.close();- rt.state = {- status: "error",- error: "The remote tunnel stopped unexpectedly. Activate it again.",- };- });-- const publicUrl = await waitForQuickTunnelUrl(tunnel);- const startedAt = new Date().toISOString();- rt.state = {- status: "active",- public_url: publicUrl,- access_url: `${publicUrl}/#notfair-remote=${encodeURIComponent(rt.token)}`,- started_at: startedAt,- };- return rt.state;- } catch (error) {- if (rt.tunnel?.exitCode === null) rt.tunnel.kill("SIGTERM");- rt.tunnel = null;- rt.token = null;- const proxy = rt.proxy;- rt.proxy = null;- proxy?.close();- return setError(rt, error instanceof Error ? error.message : String(error));- }-}--function setError(rt: RemoteRuntime, error: string): RemoteControlStatus {- rt.state = { status: "error", error };- return rt.state;-}--export function createRemoteProxyServer(args: {- token: string;- target: string;-}): Server {- const target = new URL(args.target);- const tokenDigest = digest(args.token);-- const server = createServer((req, res) => {- void handleProxyRequest(req, res, target, tokenDigest);- });-- server.on("upgrade", (req, socket, head) => {- if (!authorized(req, tokenDigest)) {- socket.write("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");- socket.destroy();- return;- }- proxyUpgrade(req, socket, head, target);- });-- return server;-}--async function handleProxyRequest(- req: IncomingMessage,- res: ServerResponse,- target: URL,- tokenDigest: Buffer,-): Promise<void> {- if (req.url?.split("?")[0] === CLAIM_PATH && req.method === "POST") {- await claimRemoteSession(req, res, tokenDigest);- return;- }-- if (!authorized(req, tokenDigest)) {- if (req.method === "GET" || req.method === "HEAD") {- const html = remoteBootstrapHtml();- res.writeHead(401, {- "content-type": "text/html; charset=utf-8",- "content-length": Buffer.byteLength(html),- "cache-control": "no-store",- "content-security-policy":- "default-src 'none'; connect-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'",- "referrer-policy": "no-referrer",- "x-content-type-options": "nosniff",- });- res.end(req.method === "HEAD" ? undefined : html);- } else {- res.writeHead(401, {- "content-type": "application/json; charset=utf-8",- "cache-control": "no-store",- });- res.end(JSON.stringify({ error: "Remote control authorization required" }));- }- return;- }-- const upstream = await import("node:http");- const proxyReq = upstream.request(- {- protocol: target.protocol,- hostname: target.hostname,- port: target.port,- method: req.method,- path: req.url,- headers: forwardedHeaders(req),- },- (proxyRes) => {- res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers);- proxyRes.pipe(res);- },- );- proxyReq.on("error", (error) => {- if (!res.headersSent) {- res.writeHead(502, { "content-type": "text/plain; charset=utf-8" });- }- res.end(`NotFair is not available: ${error.message}`);- });- req.pipe(proxyReq);-}--async function claimRemoteSession(- req: IncomingMessage,- res: ServerResponse,- tokenDigest: Buffer,-): Promise<void> {- try {- const body = await readSmallBody(req);- const parsed = JSON.parse(body) as { token?: unknown };- if (- typeof parsed.token !== "string" ||- !safeEqual(digest(parsed.token), tokenDigest)- ) {- res.writeHead(401, {- "content-type": "application/json; charset=utf-8",- "cache-control": "no-store",- });- res.end(JSON.stringify({ ok: false }));- return;- }- res.writeHead(204, {- "set-cookie": `${COOKIE_NAME}=${parsed.token}; Path=/; HttpOnly; Secure; SameSite=Strict`,- "cache-control": "no-store",- "referrer-policy": "no-referrer",- });- res.end();- } catch {- res.writeHead(400, {- "content-type": "application/json; charset=utf-8",- "cache-control": "no-store",- });- res.end(JSON.stringify({ ok: false }));- }-}--function proxyUpgrade(- req: IncomingMessage,- socket: Duplex,- head: Buffer,- target: URL,-): void {- const upstream = new Socket();- upstream.connect(Number(target.port || 80), target.hostname, () => {- const requestLine = `${req.method ?? "GET"} ${req.url ?? "/"} HTTP/${req.httpVersion}\r\n`;- const headers = Object.entries(forwardedHeaders(req))- .flatMap(([name, value]) =>- Array.isArray(value)- ? value.map((entry) => `${name}: ${entry}\r\n`)- : value === undefined- ? []- : [`${name}: ${value}\r\n`],- )- .join("");- upstream.write(`${requestLine}${headers}\r\n`);- if (head.length > 0) upstream.write(head);- socket.pipe(upstream).pipe(socket);- });- upstream.on("error", () => socket.destroy());- socket.on("error", () => upstream.destroy());-}--function forwardedHeaders(req: IncomingMessage): IncomingMessage["headers"] {- const headers = { ...req.headers };- const remoteAddress = req.socket.remoteAddress;- if (remoteAddress) {- headers["x-forwarded-for"] = headers["x-forwarded-for"]- ? `${headers["x-forwarded-for"]}, ${remoteAddress}`- : remoteAddress;- }- headers["x-forwarded-proto"] = "https";- return headers;-}--function authorized(req: IncomingMessage, tokenDigest: Buffer): boolean {- const value = parseCookies(req.headers.cookie ?? "")[COOKIE_NAME];- return typeof value === "string" && safeEqual(digest(value), tokenDigest);-}--function parseCookies(header: string): Record<string, string> {- const cookies: Record<string, string> = {};- for (const pair of header.split(";")) {- const separator = pair.indexOf("=");- if (separator < 1) continue;- const name = pair.slice(0, separator).trim();- const value = pair.slice(separator + 1).trim();- cookies[name] = value;- }- return cookies;-}--function digest(value: string): Buffer {- return createHash("sha256").update(value).digest();-}--function safeEqual(left: Buffer, right: Buffer): boolean {- return left.length === right.length && timingSafeEqual(left, right);-}--async function readSmallBody(req: IncomingMessage): Promise<string> {- const chunks: Buffer[] = [];- let size = 0;- for await (const chunk of req) {- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);- size += buffer.length;- if (size > MAX_CLAIM_BYTES) throw new Error("Claim body too large");- chunks.push(buffer);- }- return Buffer.concat(chunks).toString("utf8");-}--export function remoteBootstrapHtml(): string {- return `<!doctype html>-<html lang="en">-<head>- <meta charset="utf-8">- <meta name="viewport" content="width=device-width,initial-scale=1">- <meta name="referrer" content="no-referrer">- <title>NotFair Remote Control</title>- <style>- :root{color-scheme:light dark;font-family:-apple-system,BlinkMacSystemFont,"SF Pro Text",system-ui,sans-serif}- body{margin:0;min-height:100vh;display:grid;place-items:center;background:#101012;color:#ececee}- main{width:min(360px,calc(100% - 40px));padding:28px;border-radius:16px;background:#202024;box-shadow:0 24px 70px #0008}- h1{font-size:20px;margin:0 0 10px}p{font-size:14px;line-height:1.5;color:#a6a6ad;margin:0}- .dot{display:inline-block;width:9px;height:9px;margin-right:8px;border-radius:50%;background:#4caf6e}- .error{color:#f87171}- </style>-</head>-<body>- <main>- <h1><span class="dot"></span>NotFair Remote Control</h1>- <p id="status">Securing this device…</p>- </main>- <script>- (() => {- const status = document.getElementById("status");- const params = new URLSearchParams(location.hash.slice(1));- const token = params.get("notfair-remote");- if (!token) {- status.textContent = "This link is incomplete. Copy a fresh access link from NotFair on your Mac.";- status.className = "error";- return;- }- fetch("${CLAIM_PATH}", {- method: "POST",- headers: {"content-type": "application/json"},- body: JSON.stringify({token})- }).then((response) => {- if (!response.ok) throw new Error("expired");- history.replaceState(null, "", location.pathname + location.search);- location.reload();- }).catch(() => {- status.textContent = "This remote link has expired. Activate Remote control again on your Mac.";- status.className = "error";- });- })();- </script>-</body>-</html>`;-}--function findCloudflaredBinary(): string | null {- const explicit = process.env.NOTFAIR_CLOUDFLARED_BIN?.trim();- if (explicit) return existsSync(explicit) ? explicit : null;-- const candidates = [- ...(process.env.PATH ?? "")- .split(delimiter)- .filter(Boolean)- .map((dir) => join(dir, "cloudflared")),- "/opt/homebrew/bin/cloudflared",- "/usr/local/bin/cloudflared",- ];- return candidates.find((candidate) => existsSync(candidate)) ?? null;-}--function listenOnLoopback(server: Server): Promise<number> {- return new Promise((resolve, reject) => {- server.once("error", reject);- server.listen(0, "127.0.0.1", () => {- server.off("error", reject);- const address = server.address();- if (!address || typeof address === "string") {- reject(new Error("Could not open the remote-control proxy."));- return;- }- resolve(address.port);- });- });-}--function waitForQuickTunnelUrl(- child: ChildProcessWithoutNullStreams,-): Promise<string> {- return new Promise((resolve, reject) => {- let settled = false;- let output = "";- const finish = (error: Error | null, url?: string) => {- if (settled) return;- settled = true;- clearTimeout(timer);- child.off("error", onError);- child.off("exit", onExit);- if (error) reject(error);- else resolve(url!);- };- const consume = (chunk: Buffer | string) => {- output = (output + chunk.toString()).slice(-16_384);- const match = output.match(/https:\/\/[a-z0-9-]+\.trycloudflare\.com/i);- if (match) finish(null, match[0]);- };- const onError = (error: Error) => finish(error);- const onExit = (code: number | null) =>- finish(- new Error(- `Cloudflare Tunnel exited before it created a URL (code ${code ?? "unknown"}).`,- ),- );- child.stdout.on("data", consume);- child.stderr.on("data", consume);- child.once("error", onError);- child.once("exit", onExit);- const timer = setTimeout(() => {- finish(- new Error(- "Cloudflare Tunnel did not create a public URL within 30 seconds. Check your network and try again.",- ),- );- }, START_TIMEOUT_MS);- timer.unref();- });-}--function waitForExit(- child: ChildProcessWithoutNullStreams,- timeoutMs: number,-): Promise<boolean> {- if (child.exitCode !== null) return Promise.resolve(true);- return new Promise((resolve) => {- const timer = setTimeout(() => resolve(false), timeoutMs);- timer.unref();- child.once("exit", () => {- clearTimeout(timer);- resolve(true);- });- });-}--function registerShutdownHooks(rt: RemoteRuntime): void {- if (rt.hooksRegistered) return;- rt.hooksRegistered = true;- const shutdown = () => {- rt.stopping = true;- if (rt.tunnel?.exitCode === null) rt.tunnel.kill("SIGTERM");- rt.proxy?.close();- };- process.once("SIGINT", shutdown);- process.once("SIGTERM", shutdown);- process.once("exit", shutdown);-}diff --git a/notfair/src/server/scheduler/tick.test.ts b/notfair/src/server/scheduler/tick.test.tsdeleted file mode 100644index 9afe5619..00000000--- a/notfair/src/server/scheduler/tick.test.ts+++ /dev/null@@ -1,86 +0,0 @@-import { afterEach, beforeEach, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- recoverTicks: vi.fn(),- runTicks: vi.fn(),- syncPrs: vi.fn(),-}));-vi.mock("@/server/goals/tick", () => ({ runDueGoalTicks: mocks.runTicks }));-vi.mock("@/server/goals/pr-sync", () => ({ syncDueGoalPrs: mocks.syncPrs }));-vi.mock("@/server/goals/recovery", () => ({- recoverInterruptedGoalTicks: mocks.recoverTicks,-}));--import { ensureSchedulerRunning, stopScheduler } from "./tick";--beforeEach(() => {- vi.useFakeTimers();- vi.clearAllMocks();- mocks.recoverTicks.mockReturnValue({- recovered: 0,- completed: 0,- failed: 0,- active: 0,- });- mocks.runTicks.mockResolvedValue(undefined);- mocks.syncPrs.mockResolvedValue(undefined);- vi.spyOn(console, "error").mockImplementation(() => {});- vi.spyOn(console, "warn").mockImplementation(() => {});- stopScheduler();-});--afterEach(() => {- stopScheduler();- vi.useRealTimers();- vi.restoreAllMocks();-});--it("runs immediately, repeats every 30s, and starts only once", async () => {- ensureSchedulerRunning();- ensureSchedulerRunning();- expect(mocks.recoverTicks).toHaveBeenCalledTimes(1);- await vi.advanceTimersByTimeAsync(0);- expect(mocks.runTicks).toHaveBeenCalledTimes(1);- expect(mocks.syncPrs).toHaveBeenCalledTimes(1);- await vi.advanceTimersByTimeAsync(30_000);- expect(mocks.runTicks).toHaveBeenCalledTimes(2);- stopScheduler();- await vi.advanceTimersByTimeAsync(30_000);- expect(mocks.runTicks).toHaveBeenCalledTimes(2);-});--it("logs recovery failures but still starts the scheduler", async () => {- mocks.recoverTicks.mockImplementationOnce(() => {- throw new Error("recovery failed");- });- ensureSchedulerRunning();- await vi.advanceTimersByTimeAsync(0);- expect(console.error).toHaveBeenCalledWith(- "[scheduler] interrupted tick recovery failed:",- expect.any(Error),- );- expect(mocks.runTicks).toHaveBeenCalledTimes(1);-});--it("reports interrupted ticks recovered during startup", () => {- mocks.recoverTicks.mockReturnValueOnce({- recovered: 3,- completed: 1,- failed: 2,- active: 0,- });- ensureSchedulerRunning();- expect(console.warn).toHaveBeenCalledWith(- "[scheduler] recovered 3 interrupted goal tick(s): 1 completed, 2 failed",- );-});--it("logs independent tick and PR sweep failures", async () => {- mocks.runTicks.mockRejectedValue(new Error("tick failed"));- mocks.syncPrs.mockRejectedValue(new Error("pr failed"));- ensureSchedulerRunning();- await vi.advanceTimersByTimeAsync(0);- await Promise.resolve();- expect(console.error).toHaveBeenCalledWith("[scheduler] goal tick sweep failed:", expect.any(Error));- expect(console.error).toHaveBeenCalledWith("[scheduler] PR freshness sweep failed:", expect.any(Error));-});diff --git a/notfair/src/server/scheduler/tick.ts b/notfair/src/server/scheduler/tick.tsdeleted file mode 100644index 48ae52bd..00000000--- a/notfair/src/server/scheduler/tick.ts+++ /dev/null@@ -1,57 +0,0 @@-import { runDueGoalTicks } from "@/server/goals/tick";-import { syncDueGoalPrs } from "@/server/goals/pr-sync";-import { recoverInterruptedGoalTicks } from "@/server/goals/recovery";--/**- * The heartbeat loop. Started once on boot (src/instrumentation.ts); a- * 30s interval runs two due-work checks — both cheap local SQL reads- * that only spawn real work when a per-row timestamp has arrived:- *- * - goal ticks (goals.next_tick_at — the goal's agreed cadence)- * - open-PR freshness (goal_prs.next_sync_at — the adaptive poll- * schedule from pr-poll-policy; GitHub is only called for due PRs)- *- * This is the ONLY scheduler in the product.- */-let started = false;-let timer: NodeJS.Timeout | null = null;-const TICK_INTERVAL_MS = 30_000;--function sweep(): void {- runDueGoalTicks().catch((err) =>- console.error("[scheduler] goal tick sweep failed:", err),- );- syncDueGoalPrs().catch((err) =>- console.error("[scheduler] PR freshness sweep failed:", err),- );-}--export function ensureSchedulerRunning(): void {- if (started) return;- started = true;- try {- const recovered = recoverInterruptedGoalTicks();- if (recovered.recovered > 0) {- console.warn(- `[scheduler] recovered ${recovered.recovered} interrupted goal tick(s): ` +- `${recovered.completed} completed, ${recovered.failed} failed` +- (recovered.active > 0- ? `; left ${recovered.active} owned by a live process`- : ""),- );- }- } catch (err) {- // Recovery must never prevent future heartbeats from starting. Any- // untouched rows remain "running" and will be retried at next boot.- console.error("[scheduler] interrupted tick recovery failed:", err);- }- timer = setInterval(sweep, TICK_INTERVAL_MS);- // First sweep on the next event-loop turn so callers return immediately.- setImmediate(sweep);-}--export function stopScheduler(): void {- if (timer) clearInterval(timer);- timer = null;- started = false;-}diff --git a/notfair/src/server/secrets/cipher.test.ts b/notfair/src/server/secrets/cipher.test.tsdeleted file mode 100644index 79d2fbee..00000000--- a/notfair/src/server/secrets/cipher.test.ts+++ /dev/null@@ -1,62 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- // Fixed 32-byte AES-256 key so the round-trip is deterministic.- getMasterKey: vi.fn(async () => Buffer.alloc(32, 7)),-}));--vi.mock("./master-key", () => ({ getMasterKey: mocks.getMasterKey }));--import { decrypt, encrypt } from "./cipher";--beforeEach(() => vi.clearAllMocks());--describe("encrypt / decrypt round-trip", () => {- it("recovers the original plaintext", async () => {- const secret = "hello world 🌍 token=abc123";- const blob = await encrypt(secret);- expect(blob).not.toContain(secret);- expect(await decrypt(blob)).toBe(secret);- });-- it("recovers an empty string", async () => {- const blob = await encrypt("");- expect(await decrypt(blob)).toBe("");- });-- it("produces a distinct ciphertext each time (random IV)", async () => {- const a = await encrypt("same");- const b = await encrypt("same");- expect(a).not.toBe(b);- expect(await decrypt(a)).toBe("same");- expect(await decrypt(b)).toBe("same");- });-- it("outputs valid base64 wrapping iv|ciphertext|tag", async () => {- const blob = await encrypt("x");- const buf = Buffer.from(blob, "base64");- // 12-byte IV + 16-byte tag + >=1 ciphertext byte- expect(buf.length).toBeGreaterThanOrEqual(12 + 16 + 1);- });-});--describe("decrypt error handling", () => {- it("throws on a blob too short to hold iv+tag", async () => {- await expect(decrypt(Buffer.alloc(5).toString("base64"))).rejects.toThrow(- /malformed/,- );- });-- it("throws when the auth tag does not verify (tampered ciphertext)", async () => {- const blob = await encrypt("tamper me");- const buf = Buffer.from(blob, "base64");- buf[13] = buf[13]! ^ 0xff; // flip a ciphertext byte- await expect(decrypt(buf.toString("base64"))).rejects.toThrow();- });-- it("throws when decrypted with a different key", async () => {- const blob = await encrypt("wrong key");- mocks.getMasterKey.mockResolvedValueOnce(Buffer.alloc(32, 9));- await expect(decrypt(blob)).rejects.toThrow();- });-});diff --git a/notfair/src/server/secrets/cipher.ts b/notfair/src/server/secrets/cipher.tsdeleted file mode 100644index 86b77f88..00000000--- a/notfair/src/server/secrets/cipher.ts+++ /dev/null@@ -1,32 +0,0 @@-import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";-import { getMasterKey } from "./master-key";--const ALGORITHM = "aes-256-gcm";-const IV_LEN = 12;-const TAG_LEN = 16;--/**- * Encrypt a plaintext string with AES-256-GCM using the project master key- * (loaded from OS keychain). Output format: base64(iv | ciphertext | tag).- */-export async function encrypt(plaintext: string): Promise<string> {- const key = await getMasterKey();- const iv = randomBytes(IV_LEN);- const cipher = createCipheriv(ALGORITHM, key, iv);- const encrypted = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);- const tag = cipher.getAuthTag();- return Buffer.concat([iv, encrypted, tag]).toString("base64");-}--export async function decrypt(blob: string): Promise<string> {- const key = await getMasterKey();- const buf = Buffer.from(blob, "base64");- if (buf.length < IV_LEN + TAG_LEN) throw new Error("Encrypted blob is malformed");- const iv = buf.subarray(0, IV_LEN);- const tag = buf.subarray(buf.length - TAG_LEN);- const ciphertext = buf.subarray(IV_LEN, buf.length - TAG_LEN);- const decipher = createDecipheriv(ALGORITHM, key, iv);- decipher.setAuthTag(tag);- const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);- return decrypted.toString("utf8");-}diff --git a/notfair/src/server/secrets/master-key.ts b/notfair/src/server/secrets/master-key.tsdeleted file mode 100644index 54032e10..00000000--- a/notfair/src/server/secrets/master-key.ts+++ /dev/null@@ -1,50 +0,0 @@-import { randomBytes } from "node:crypto";--const KEYTAR_SERVICE = "NotFair";-const KEYTAR_ACCOUNT = "master-key";--type Keytar = {- getPassword: (service: string, account: string) => Promise<string | null>;- setPassword: (service: string, account: string, password: string) => Promise<void>;-};--let cachedKey: Buffer | null = null;-let loadAttempted = false;--async function loadKeytar(): Promise<Keytar | null> {- try {- const mod = (await import("keytar")) as unknown as { default?: Keytar } & Keytar;- return mod.default ?? mod;- } catch {- return null;- }-}--/**- * Get or create the project's master encryption key.- * Returns a 32-byte (256-bit) Buffer suitable for AES-256-GCM.- *- * V1: stored in OS keychain via keytar. If keytar is unavailable, throws.- * Future: file-based fallback with prompt-based password unlock.- */-export async function getMasterKey(): Promise<Buffer> {- if (cachedKey) return cachedKey;- if (loadAttempted) throw new Error("Master key unavailable (keytar not loadable)");- loadAttempted = true;-- const keytar = await loadKeytar();- if (!keytar) {- throw new Error(- "OS keychain (keytar) not available on this platform. OAuth credentials cannot be stored securely.",- );- }-- let stored = await keytar.getPassword(KEYTAR_SERVICE, KEYTAR_ACCOUNT);- if (!stored) {- const fresh = randomBytes(32).toString("base64");- await keytar.setPassword(KEYTAR_SERVICE, KEYTAR_ACCOUNT, fresh);- stored = fresh;- }- cachedKey = Buffer.from(stored, "base64");- return cachedKey;-}diff --git a/notfair/src/server/sessions/index.ts b/notfair/src/server/sessions/index.tsdeleted file mode 100644index c92f5312..00000000--- a/notfair/src/server/sessions/index.ts+++ /dev/null@@ -1,209 +0,0 @@-import { randomUUID } from "node:crypto";-import { getDb } from "@/server/db/db";-import type { HarnessAdapterId } from "@/server/adapters/types";--/**- * Session / thread management.- *- * A "session" is one chat thread between the user and an agent. Each agent- * can have many sessions (named "main", "Q4 audit", etc.). The session id- * is a stable NotFair UUID; we also store the adapter's own session id- * (e.g. Claude Code's session UUID for resumption) when known.- */-export interface Session {- id: string;- project_slug: string;- agent_id: string;- label: string;- harness_adapter: HarnessAdapterId;- harness_session_id: string | null;- /** User-set display title (thread rename). Null = derive from content. */- title: string | null;- /** Set when the user pins the thread; doubles as pin-order tiebreaker. */- pinned_at: string | null;- created_at: string;- updated_at: string;-}--export interface TranscriptEvent {- id: string;- session_id: string;- seq: number;- kind: "user" | "delta" | "tool" | "lifecycle" | "final" | "error";- payload_json: string;- created_at: string;-}--interface SessionRow {- id: string;- project_slug: string;- agent_id: string;- label: string;- harness_adapter: string;- harness_session_id: string | null;- title: string | null;- pinned_at: string | null;- created_at: string;- updated_at: string;-}--function rowToSession(row: SessionRow): Session {- return { ...row, harness_adapter: row.harness_adapter as HarnessAdapterId };-}--export function getOrCreateSession(input: {- project_slug: string;- agent_id: string;- label: string;- harness_adapter: HarnessAdapterId;-}): Session {- const db = getDb();- const existing = db- .prepare(- "SELECT * FROM sessions WHERE project_slug = ? AND agent_id = ? AND label = ?",- )- .get(input.project_slug, input.agent_id, input.label) as SessionRow | undefined;- if (existing) return rowToSession(existing);-- const session: Session = {- id: randomUUID(),- project_slug: input.project_slug,- agent_id: input.agent_id,- label: input.label,- harness_adapter: input.harness_adapter,- harness_session_id: null,- title: null,- pinned_at: null,- created_at: new Date().toISOString(),- updated_at: new Date().toISOString(),- };-- db.prepare(- "INSERT INTO sessions (id, project_slug, agent_id, label, harness_adapter, harness_session_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, NULL, ?, ?)",- ).run(- session.id,- session.project_slug,- session.agent_id,- session.label,- session.harness_adapter,- session.created_at,- session.updated_at,- );- return session;-}--/** Set / clear the user-facing display title (thread rename). */-export function setSessionTitle(id: string, title: string | null): void {- getDb()- .prepare("UPDATE sessions SET title = ? WHERE id = ?")- .run(title?.trim() || null, id);-}--/** Pin or unpin a thread. */-export function setSessionPinned(id: string, pinned: boolean): void {- getDb()- .prepare("UPDATE sessions SET pinned_at = ? WHERE id = ?")- .run(pinned ? new Date().toISOString() : null, id);-}--/**- * Permanently delete a thread. transcript_events cascades on the FK, so- * the whole conversation history goes with it.- */-export function deleteSession(id: string): void {- getDb().prepare("DELETE FROM sessions WHERE id = ?").run(id);-}--/** The session for a (project, agent, label) triple, if one exists. */-export function findSession(- project_slug: string,- agent_id: string,- label: string,-): Session | null {- const row = getDb()- .prepare(- "SELECT * FROM sessions WHERE project_slug = ? AND agent_id = ? AND label = ?",- )- .get(project_slug, agent_id, label) as SessionRow | undefined;- return row ? rowToSession(row) : null;-}--export function getSession(id: string): Session | null {- const row = getDb()- .prepare("SELECT * FROM sessions WHERE id = ?")- .get(id) as SessionRow | undefined;- return row ? rowToSession(row) : null;-}--export function listAgentSessions(project_slug: string, agent_id: string): Session[] {- const rows = getDb()- .prepare(- // Pinned threads first (most recently pinned on top), then by- // recency — the thread rail renders this order verbatim.- "SELECT * FROM sessions WHERE project_slug = ? AND agent_id = ? ORDER BY (pinned_at IS NULL) ASC, pinned_at DESC, updated_at DESC",- )- .all(project_slug, agent_id) as SessionRow[];- return rows.map(rowToSession);-}--export function touchSession(id: string, harness_session_id?: string): void {- const now = new Date().toISOString();- if (harness_session_id) {- getDb()- .prepare(- "UPDATE sessions SET updated_at = ?, harness_session_id = COALESCE(harness_session_id, ?) WHERE id = ?",- )- .run(now, harness_session_id, id);- } else {- getDb().prepare("UPDATE sessions SET updated_at = ? WHERE id = ?").run(now, id);- }-}--export function appendTranscriptEvent(- session_id: string,- kind: TranscriptEvent["kind"],- payload: unknown,-): void {- const db = getDb();- const seqRow = db- .prepare("SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM transcript_events WHERE session_id = ?")- .get(session_id) as { next: number };- const id = randomUUID();- const seq = seqRow.next;- const created_at = new Date().toISOString();- const payload_json = JSON.stringify(payload);- db.prepare(- "INSERT INTO transcript_events (id, session_id, seq, kind, payload_json, created_at) VALUES (?, ?, ?, ?, ?, ?)",- ).run(id, session_id, seq, kind, payload_json, created_at);- // Push to live subscribers AFTER the INSERT commits. Best-effort: the- // row is already persisted, so a publish failure must not throw into- // the caller's adapter-event loop.- try {- // eslint-disable-next-line @typescript-eslint/no-require-imports- const { publishSessionEvent } =- require("@/server/live-events/emitter") as typeof import("@/server/live-events/emitter");- publishSessionEvent(session_id, {- id,- session_id,- seq,- kind,- payload_json,- created_at,- });- } catch {- // Live subscribers miss this event; the poll fallback still sees it.- }-}--export function listTranscriptEvents(- session_id: string,- opts: { sinceSeq?: number; limit?: number } = {},-): TranscriptEvent[] {- const limit = opts.limit ?? 1000;- const since = opts.sinceSeq ?? 0;- return getDb()- .prepare(- "SELECT * FROM transcript_events WHERE session_id = ? AND seq > ? ORDER BY seq ASC LIMIT ?",- )- .all(session_id, since, limit) as TranscriptEvent[];-}diff --git a/notfair/src/server/sessions/live-turns.test.ts b/notfair/src/server/sessions/live-turns.test.tsdeleted file mode 100644index 4a3c3f78..00000000--- a/notfair/src/server/sessions/live-turns.test.ts+++ /dev/null@@ -1,36 +0,0 @@-import { describe, expect, it } from "vitest";-import {- registerLiveTurn,- releaseLiveTurn,- stopLiveTurn,-} from "./live-turns";--describe("live chat turn registry", () => {- it("stops a registered turn by aborting its controller", () => {- const ctrl = registerLiveTurn("s1");- expect(ctrl.signal.aborted).toBe(false);- expect(stopLiveTurn("s1")).toBe(true);- expect(ctrl.signal.aborted).toBe(true);- releaseLiveTurn("s1", ctrl);- });-- it("reports nothing to stop for an idle session", () => {- expect(stopLiveTurn("nope")).toBe(false);- });-- it("release is a no-op after the slot was re-registered by a newer turn", () => {- const old = registerLiveTurn("s2");- const fresh = registerLiveTurn("s2");- releaseLiveTurn("s2", old); // stale release must not evict the live turn- expect(stopLiveTurn("s2")).toBe(true);- expect(fresh.signal.aborted).toBe(true);- expect(old.signal.aborted).toBe(false);- releaseLiveTurn("s2", fresh);- });-- it("a released turn can no longer be stopped", () => {- const ctrl = registerLiveTurn("s3");- releaseLiveTurn("s3", ctrl);- expect(stopLiveTurn("s3")).toBe(false);- });-});diff --git a/notfair/src/server/sessions/live-turns.ts b/notfair/src/server/sessions/live-turns.tsdeleted file mode 100644index 560e5cfb..00000000--- a/notfair/src/server/sessions/live-turns.ts+++ /dev/null@@ -1,29 +0,0 @@-/**- * In-process registry of live chat turns, keyed by session id. The chat- * route registers each turn's AbortController here so the stop endpoint- * can kill the harness subprocess on the user's explicit request —- * distinct from a mere client disconnect, which never cancels the turn.- * Single-process local app: module state is the source of truth (same- * pattern as the tick runner's re-entrancy guard).- */--const liveTurns = new Map<string, AbortController>();--export function registerLiveTurn(sessionId: string): AbortController {- const ctrl = new AbortController();- liveTurns.set(sessionId, ctrl);- return ctrl;-}--/** Release only if this controller still owns the slot (races are benign). */-export function releaseLiveTurn(sessionId: string, ctrl: AbortController): void {- if (liveTurns.get(sessionId) === ctrl) liveTurns.delete(sessionId);-}--/** Abort a session's live turn. Returns whether one was running. */-export function stopLiveTurn(sessionId: string): boolean {- const ctrl = liveTurns.get(sessionId);- if (!ctrl) return false;- ctrl.abort();- return true;-}diff --git a/notfair/src/server/sessions/transcript-tail.test.ts b/notfair/src/server/sessions/transcript-tail.test.tsdeleted file mode 100644index b96142c3..00000000--- a/notfair/src/server/sessions/transcript-tail.test.ts+++ /dev/null@@ -1,76 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({ getDb: vi.fn() }));-vi.mock("@/server/db/db", () => ({ getDb: mocks.getDb }));--import { readTranscriptTail, resolveSessionForThread } from "./transcript-tail";--const session = { id: "session-1", project_slug: "acme", agent_id: "agent-1", label: "main" };--function dbWith(rows: Array<Record<string, unknown>>, found: unknown = session) {- return {- prepare: vi.fn((sql: string) => ({- get: vi.fn(() => found),- all: vi.fn(() => sql.includes("transcript_events") ? rows : []),- })),- };-}--beforeEach(() => vi.clearAllMocks());--it("resolves sessions with all ownership keys and returns null when absent", () => {- let db = dbWith([], session);- mocks.getDb.mockReturnValue(db);- expect(resolveSessionForThread("acme", "agent-1", "main")).toBe(session);- expect(db.prepare.mock.results[0]!.value.get).toHaveBeenCalledWith("acme", "agent-1", "main");- mocks.getDb.mockReturnValue(dbWith([], null));- expect(resolveSessionForThread("acme", "agent-1", "missing")).toBeNull();-});--it("returns the incoming cursor when no session exists", () => {- mocks.getDb.mockReturnValue(dbWith([], null));- expect(readTranscriptTail("p", "a", "t", 7)).toEqual({ events: [], cursor: 7 });-});--it("normalizes every transcript event kind and advances the cursor", () => {- const rows = [- { id: "u1", seq: 1, kind: "user", payload_json: '{"text":"hello","source":"human"}', created_at: "2026-01-01T00:00:00Z" },- { id: "u2", seq: 2, kind: "user", payload_json: '{"text":"brief","source":"goal-tick"}', created_at: "bad" },- { id: "d", seq: 3, kind: "delta", payload_json: '{"text":42}', created_at: "2026-01-01" },- { id: "tc", seq: 4, kind: "tool", payload_json: '{"phase":"start","toolCallId":"c1","name":"search","label":"Searching"}', created_at: "2026-01-01" },- { id: "tc2", seq: 5, kind: "tool", payload_json: '{}', created_at: "2026-01-01" },- { id: "tr", seq: 6, kind: "tool", payload_json: '{"phase":"result","toolCallId":"c1","name":"search"}', created_at: "2026-01-01" },- { id: "life", seq: 7, kind: "lifecycle", payload_json: '{}', created_at: "2026-01-01" },- { id: "fin", seq: 8, kind: "final", payload_json: '{}', created_at: "2026-01-01" },- { id: "err", seq: 9, kind: "error", payload_json: '{"message":"boom"}', created_at: "2026-01-01" },- { id: "err2", seq: 10, kind: "error", payload_json: 'null', created_at: "2026-01-01" },- { id: "x", seq: 11, kind: "other", payload_json: 'not json', created_at: "2026-01-01" },- ];- mocks.getDb.mockReturnValue(dbWith(rows));- const result = readTranscriptTail("p", "a", "t", 0);- expect(result.cursor).toBe(11);- expect(result.events).toEqual(expect.arrayContaining([- expect.objectContaining({ kind: "user_message", id: "u1", body: "hello", system: false }),- expect.objectContaining({ kind: "user_message", id: "u2", system: true }),- expect.objectContaining({ kind: "assistant_text", id: "d", body: "" }),- expect.objectContaining({ kind: "tool_call", id: "tc", tool_call_id: "c1", label: "Searching" }),- expect.objectContaining({ kind: "tool_call", id: "tc2", name: "tool", label: null }),- expect.objectContaining({ kind: "tool_result", id: "tr", ok: true, summary: null }),- expect.objectContaining({ kind: "lifecycle", id: "life", phase: "unknown" }),- expect.objectContaining({- kind: "lifecycle",- id: "fin",- phase: "done",- ok: true,- }),- expect.objectContaining({ kind: "assistant_text", id: "err", body: "⚠ boom" }),- expect.objectContaining({- kind: "lifecycle",- id: "err:done",- phase: "done",- ok: false,- }),- expect.objectContaining({ kind: "unknown", id: "x", raw_type: "other" }),- ]));- expect(result.events).toHaveLength(13);-});diff --git a/notfair/src/server/sessions/transcript-tail.ts b/notfair/src/server/sessions/transcript-tail.tsdeleted file mode 100644index 6b37def0..00000000--- a/notfair/src/server/sessions/transcript-tail.ts+++ /dev/null@@ -1,156 +0,0 @@-import { getDb } from "@/server/db/db";-import type { TranscriptEvent as RawEvent, Session } from "./index";--/**- * UI-facing transcript event shape. The chat polling endpoint returns a- * flat array of these so the live-transcript component can replay events- * on re-attach.- */-export type TranscriptEvent =- | { kind: "user_message"; id: string; ts: number; body: string; system?: boolean }- | { kind: "assistant_text"; id: string; ts: number; body: string }- | {- kind: "tool_call";- id: string;- ts: number;- tool_call_id: string;- name: string;- label: string | null;- }- | {- kind: "tool_result";- id: string;- ts: number;- tool_call_id: string;- name: string;- summary: string | null;- ok: boolean;- }- | { kind: "lifecycle"; id: string; ts: number; phase: string; ok?: boolean }- | { kind: "unknown"; id: string; ts: number; raw_type: string };--/**- * Resolve a URL thread id to a NotFair `sessions` row by label.- * Returns null when no session has been created yet (e.g., the user just- * clicked New and hasn't sent a turn).- */-export function resolveSessionForThread(- project_slug: string,- agent_id: string,- thread: string,-): Session | null {- const row = getDb()- .prepare(- "SELECT * FROM sessions WHERE project_slug = ? AND agent_id = ? AND label = ?",- )- .get(project_slug, agent_id, thread) as- | (Session & { harness_adapter: string })- | undefined;- if (!row) return null;- return row as Session;-}--/**- * Read transcript events for a thread after `cursor`. We expose the same- * cursor shape across polls (a `cursor` integer the client carries- * across polls) — only here it indexes the monotonically-increasing `seq`- * column on `transcript_events`. Callers don't care what backs the cursor;- * they just hand back what they received.- */-export function readTranscriptTail(- project_slug: string,- agent_id: string,- thread: string,- cursor: number,-): { events: TranscriptEvent[]; cursor: number } {- const session = resolveSessionForThread(project_slug, agent_id, thread);- if (!session) return { events: [], cursor };-- const rows = getDb()- .prepare(- "SELECT * FROM transcript_events WHERE session_id = ? AND seq > ? ORDER BY seq ASC",- )- .all(session.id, cursor) as RawEvent[];-- const events: TranscriptEvent[] = [];- let last = cursor;- for (const row of rows) {- last = row.seq;- const ts = Date.parse(row.created_at) || Date.now();- const payload = safeParse(row.payload_json);- const id = row.id;- if (row.kind === "user") {- const text = typeof payload.text === "string" ? payload.text : "";- // Platform-generated turns (goal intake kickoff, tick briefs) are- // not something the user typed — the UI renders them as a compact- // system line instead of a user bubble.- const source = typeof payload.source === "string" ? payload.source : "";- const system = source.startsWith("goal-");- events.push({ kind: "user_message", id, ts, body: text, system });- } else if (row.kind === "delta") {- const text = typeof payload.text === "string" ? payload.text : "";- events.push({ kind: "assistant_text", id, ts, body: text });- } else if (row.kind === "tool") {- const phase = typeof payload.phase === "string" ? payload.phase : "start";- const tool_call_id =- typeof payload.toolCallId === "string" ? payload.toolCallId : "";- const name = typeof payload.name === "string" ? payload.name : "tool";- if (phase === "result") {- events.push({- kind: "tool_result",- id,- ts,- tool_call_id,- name,- summary: null,- ok: true,- });- } else {- const label = typeof payload.label === "string" ? payload.label : null;- events.push({- kind: "tool_call",- id,- ts,- tool_call_id,- name,- label,- });- }- } else if (row.kind === "lifecycle") {- const phase = typeof payload.phase === "string" ? payload.phase : "unknown";- const ok = typeof payload.ok === "boolean" ? payload.ok : undefined;- events.push({ kind: "lifecycle", id, ts, phase, ok });- } else if (row.kind === "final") {- // Already covered by the accumulated delta stream; surface as a no-op- // lifecycle so clients can show "done" if they want.- events.push({ kind: "lifecycle", id, ts, phase: "done", ok: true });- } else if (row.kind === "error") {- const text = typeof payload.message === "string" ? payload.message : "";- events.push({ kind: "assistant_text", id, ts, body: `⚠ ${text}` });- // An error IS the end of the turn: the harness died without writing- // its final, so no lifecycle "done" will ever come. Emit a synthetic- // boundary so the client's open-turn detection closes immediately- // instead of showing "still working" until the staleness cutoff.- events.push({- kind: "lifecycle",- id: `${id}:done`,- ts,- phase: "done",- ok: false,- });- } else {- events.push({ kind: "unknown", id, ts, raw_type: row.kind });- }- }-- return { events, cursor: last };-}--function safeParse(json: string): Record<string, unknown> {- try {- const v = JSON.parse(json);- return v && typeof v === "object" ? (v as Record<string, unknown>) : {};- } catch {- return {};- }-}diff --git a/notfair/src/server/sessions/view.test.ts b/notfair/src/server/sessions/view.test.tsdeleted file mode 100644index ce82a7f5..00000000--- a/notfair/src/server/sessions/view.test.ts+++ /dev/null@@ -1,100 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";--const mocks = vi.hoisted(() => ({- getDb: vi.fn(),- getProject: vi.fn(),- getOrCreateSession: vi.fn(),- listAgentSessions: vi.fn(),-}));-vi.mock("@/server/db/db", () => ({ getDb: mocks.getDb }));-vi.mock("@/server/db/projects", () => ({ getProject: mocks.getProject }));-vi.mock("./index", () => ({- getOrCreateSession: mocks.getOrCreateSession,- listAgentSessions: mocks.listAgentSessions,-}));--import {- classifySessions,- findSessionBySessionId,- isSystemSession,- listSessionsForAgent,- materializeSession,- newSessionId,- pickLatestChatSession,- type SessionView,-} from "./view";--const row = {- id: "s1", label: "main", updated_at: "2026-01-02T00:00:00Z", title: "Title", pinned_at: "2026-01-01",-};--beforeEach(() => vi.clearAllMocks());--it("maps DB sessions to UI views", () => {- mocks.listAgentSessions.mockReturnValue([row, { ...row, id: "s2", label: "other", updated_at: "bad", title: null, pinned_at: null }]);- expect(listSessionsForAgent("p", "a")).toEqual([- expect.objectContaining({ sessionId: "main", sessionKey: "s1", pending: false, pinned: true, title: "Title" }),- expect.objectContaining({ sessionId: "other", lastInteractionAt: 0, pinned: false }),- ]);- expect(newSessionId()).toMatch(/^[0-9a-f-]{36}$/);-});--it("finds an owned session and handles missing rows", () => {- const get = vi.fn().mockReturnValueOnce(row).mockReturnValueOnce(undefined);- mocks.getDb.mockReturnValue({ prepare: vi.fn(() => ({ get })) });- expect(findSessionBySessionId("p", "a", "main")).toMatchObject({ sessionKey: "s1" });- expect(findSessionBySessionId("p", "a", "missing")).toBeNull();- expect(get).toHaveBeenCalledWith("p", "a", "main");-});--it("materializes with the project harness or the default", () => {- mocks.getOrCreateSession.mockReturnValue(row);- mocks.getProject.mockReturnValue({ harness_adapter: "codex-local" });- expect(materializeSession({ project_slug: "p", agent_id: "a", label: "main" })).toBe(row);- expect(mocks.getOrCreateSession).toHaveBeenLastCalledWith(expect.objectContaining({ harness_adapter: "codex-local" }));- mocks.getProject.mockReturnValue(null);- materializeSession({ project_slug: "p", agent_id: "a", label: "other" });- expect(mocks.getOrCreateSession).toHaveBeenLastCalledWith(expect.objectContaining({ harness_adapter: "claude-code-local" }));-});--it("detects tick sessions and picks the latest chat", () => {- expect(isSystemSession("tick-12")).toBe(true);- expect(isSystemSession("tick-x")).toBe(false);- expect(pickLatestChatSession([{ label: "tick-2" }, { label: "main" }, { label: "other" }])).toEqual({ label: "main" });- expect(pickLatestChatSession([{ label: "tick-2" }])).toBeUndefined();-});--it("classifies tick, pending, kickoff, normal, long, and malformed chats", async () => {- const sessions: SessionView[] = [- { sessionId: "tick-4", label: "tick-4", sessionKey: "1", lastInteractionAt: 0, pending: false, title: null, pinned: false },- { sessionId: "pending", label: "pending", sessionKey: "2", lastInteractionAt: 0, pending: true, title: null, pinned: false },- { sessionId: "kick", label: "kick", sessionKey: "3", lastInteractionAt: 0, pending: false, title: null, pinned: false },- { sessionId: "chat", label: "chat", sessionKey: "4", lastInteractionAt: 0, pending: false, title: null, pinned: false },- { sessionId: "long", label: "long", sessionKey: "5", lastInteractionAt: 0, pending: false, title: null, pinned: false },- { sessionId: "missing", label: "missing", sessionKey: "6", lastInteractionAt: 0, pending: false, title: null, pinned: false },- { sessionId: "bad", label: "bad", sessionKey: "7", lastInteractionAt: 0, pending: false, title: null, pinned: false },- ];- const payloadBySession: Record<string, unknown> = {- kick: { payload_json: JSON.stringify({ text: "[INTAKE] begin" }) },- chat: { payload_json: JSON.stringify({ text: " Hello\n world " }) },- long: { payload_json: JSON.stringify({ text: "x".repeat(150) }) },- bad: { payload_json: "not-json" },- };- mocks.getDb.mockReturnValue({- prepare: vi.fn((sql: string) => ({- get: vi.fn((...args: string[]) => {- if (sql.includes("SELECT id FROM")) return args[2] === "missing" ? undefined : { id: args[2] };- return payloadBySession[args[0]!];- }),- })),- });- const result = await classifySessions("a", "p", sessions);- expect(result.get("tick-4")).toEqual({ kind: "tick", tick_number: 4 });- expect(result.has("pending")).toBe(false);- expect(result.get("kick")).toEqual({ kind: "chat", preview: "Goal kickoff" });- expect(result.get("chat")).toEqual({ kind: "chat", preview: "Hello world" });- expect((result.get("long") as { preview: string }).preview).toHaveLength(140);- expect(result.get("missing")).toEqual({ kind: "chat", preview: "" });- expect(result.get("bad")).toEqual({ kind: "chat", preview: "" });- expect(await classifySessions("a", "p", [])).toEqual(new Map());-});diff --git a/notfair/src/server/sessions/view.ts b/notfair/src/server/sessions/view.tsdeleted file mode 100644index 5378a737..00000000--- a/notfair/src/server/sessions/view.ts+++ /dev/null@@ -1,172 +0,0 @@-import { randomUUID } from "node:crypto";-import { getDb } from "@/server/db/db";-import { getProject } from "@/server/db/projects";-import { DEFAULT_HARNESS_ADAPTER } from "@/server/adapters/registry";-import type { Session } from "./index";-import { getOrCreateSession, listAgentSessions } from "./index";--/** UI-facing session shape for the goal page's thread views. */-export interface SessionView {- /** Stable thread label used in URLs. */- sessionId: string;- /** Short label shown in thread lists. */- label: string;- /** The sessions row's DB primary key. */- sessionKey: string;- /** Last interaction (ms epoch). 0 when freshly minted. */- lastInteractionAt: number;- /** True when the row exists only in our cookie (no turns yet). */- pending: boolean;- /** User-set display title (thread rename). Null = derive from content. */- title: string | null;- /** True when the user pinned this thread to the top of the rail. */- pinned: boolean;-}--function sessionRowToView(s: Session): SessionView {- return {- sessionId: s.label,- label: s.label,- sessionKey: s.id,- lastInteractionAt: Date.parse(s.updated_at) || 0,- pending: false,- title: s.title,- pinned: s.pinned_at !== null,- };-}--export function listSessionsForAgent(- project_slug: string,- agent_id: string,-): SessionView[] {- const rows = listAgentSessions(project_slug, agent_id);- return rows.map(sessionRowToView);-}--export function newSessionId(): string {- return randomUUID();-}--export function findSessionBySessionId(- project_slug: string,- agent_id: string,- label: string,-): SessionView | null {- // Always scope by project_slug — even though agent_id encodes the slug,- // a project whose slug is a prefix of another's (e.g. "acme" vs "acme-q4")- // can produce overlapping agent_id patterns. Querying by project_slug- // closes that hole.- const row = getDb()- .prepare(- "SELECT * FROM sessions WHERE project_slug = ? AND agent_id = ? AND label = ? LIMIT 1",- )- .get(project_slug, agent_id, label) as Session | undefined;- return row ? sessionRowToView(row) : null;-}--/**- * Materialize a session row immediately (used when the first chat turn is- * about to fire and the caller wants the session UUID to exist). Falls back- * to the project's chosen harness adapter when one isn't passed.- */-export function materializeSession(input: {- project_slug: string;- agent_id: string;- label: string;-}): Session {- const project = getProject(input.project_slug);- const harness = project?.harness_adapter ?? DEFAULT_HARNESS_ADAPTER;- return getOrCreateSession({- project_slug: input.project_slug,- agent_id: input.agent_id,- label: input.label,- harness_adapter: harness,- });-}--// ── Thread origins ──────────────────────────────────────────────────--export type SessionOrigin =- | { kind: "tick"; tick_number: number }- | { kind: "chat"; preview: string };--const TICK_LABEL_RE = /^tick-(\d+)$/;--/** Tick-originated sessions (not user-initiated chats). */-export function isSystemSession(label: string): boolean {- return TICK_LABEL_RE.test(label);-}--export function pickLatestChatSession<S extends { label: string }>(- sessions: readonly S[],-): S | undefined {- return sessions.find((s) => !isSystemSession(s.label));-}--// Generous cap: the rail shows ~40 chars at rest and reveals the rest by-// scrolling the text horizontally on hover — a 40-char preview would give-// the marquee nothing to reveal.-const PREVIEW_MAX_CHARS = 140;--/**- * Classify each session by origin so the thread rail can show meaningful- * labels. Goal-loop ticks use a `tick-<n>` label; free chats fall back to- * a preview of the first user message.- */-export async function classifySessions(- agent_id: string,- project_slug: string,- sessions: SessionView[],-): Promise<Map<string, SessionOrigin>> {- const out = new Map<string, SessionOrigin>();- if (sessions.length === 0) return out;-- for (const s of sessions) {- if (s.pending) continue;- const tickMatch = s.label.match(TICK_LABEL_RE);- if (tickMatch) {- out.set(s.label, { kind: "tick", tick_number: Number(tickMatch[1]) });- continue;- }- const preview = readFirstUserMessagePreview(project_slug, agent_id, s.label);- out.set(s.label, {- kind: "chat",- // The intake kickoff is platform-generated — label the thread by- // what it is rather than the raw brief text.- preview: preview.startsWith("[INTAKE]") ? "Goal kickoff" : preview,- });- }- return out;-}--function readFirstUserMessagePreview(- project_slug: string,- agent_id: string,- label: string,-): string {- const session = getDb()- .prepare(- "SELECT id FROM sessions WHERE project_slug = ? AND agent_id = ? AND label = ?",- )- .get(project_slug, agent_id, label) as { id: string } | undefined;- if (!session) return "";- const row = getDb()- .prepare(- "SELECT payload_json FROM transcript_events WHERE session_id = ? AND kind = 'user' ORDER BY seq ASC LIMIT 1",- )- .get(session.id) as { payload_json: string } | undefined;- if (!row) return "";- try {- const payload = JSON.parse(row.payload_json) as { text?: string };- if (typeof payload.text !== "string") return "";- return shorten(payload.text);- } catch {- return "";- }-}--function shorten(s: string): string {- const flat = s.replace(/\s+/g, " ").trim();- if (flat.length <= PREVIEW_MAX_CHARS) return flat;- return flat.slice(0, PREVIEW_MAX_CHARS - 1) + "…";-}diff --git a/notfair/src/server/skills/browser-skill.ts b/notfair/src/server/skills/browser-skill.tsdeleted file mode 100644index b4d4967b..00000000--- a/notfair/src/server/skills/browser-skill.ts+++ /dev/null@@ -1,94 +0,0 @@-/**- * Workspace-browser guidance included in every goal agent's skill (see- * src/server/goals/identity.ts). The workspace has ONE shared Chrome with- * persistent cookies, so the rules here — labeled tabs, snapshot → act →- * snapshot, honest blocker reporting — are what keep multiple agents from- * stepping on each other.- */-export const BROWSER_SKILL = `## Workspace browser tools--The workspace has a single shared Chrome instance with persistent cookies.-The user has signed in there during onboarding — so login state for Google,-Meta, Search Console, etc. is already available to you. Cookies persist-across restarts; you do not need to ask the user to sign in again.--### CRITICAL: which "browser" tool to use--The notfair-browser MCP exposes \`browser_open\`, \`browser_snapshot\`,-\`browser_click\`, etc. **These are the ONLY tools that touch the workspace-browser.** When the user says "launch the browser", "open a page", "go to-<URL>", "snapshot the page", or anything in that family, the answer is-ALWAYS one of the \`browser_*\` MCP tools below.--Do **not**:-- Use any bundled or third-party "browser-use" plugin your host runtime- might ship (e.g. OpenAI's bundled \`browser-use\` plugin in Codex CLI).- Those open a different Chrome with a different profile — your work- won't persist for other agents in this project.-- Shell out to \`open -a "Google Chrome"\`, \`open <url>\`, AppleScript- \`tell application "Google Chrome"\`, \`xdg-open\`, \`start chrome\`,- or similar. Same problem: wrong profile, no shared cookies.-- "Initialize" or "launch" the browser as a separate step. \`browser_open\`- starts the workspace Chrome on its first call automatically.--If you're unsure whether the workspace browser is running, call-\`browser_status\` first — it's cheap and tells you everything.--### One labeled tab per agent--Every agent shares the same Chrome, so coordinate via tab labels.-**Always pass \`label\` equal to your \`agent_id\` when calling-\`browser_open\`.** That reserves a stable tab for your work and prevents-you (or a retry) from racing other agents.--\`\`\`-browser_open({ project_slug, label: "<your agent_id>", url: "..." })-\`\`\`--If a labeled tab already exists, \`browser_open\` reuses it (navigates-that tab instead of duplicating). Subsequent calls target it as-\`target_id: "<your agent_id>"\`.--Before opening, call \`browser_tabs\` if you suspect a prior turn left-state you can reuse — it lists every tab in the workspace with handle,-URL, and title.--### Snapshot → act → snapshot--Refs in a snapshot (\`e1\`, \`e2\`, ...) are valid ONLY until the DOM-changes. Discipline:--1. \`browser_snapshot\` to learn what's on the page (returns elements- with stable refs + a text excerpt).-2. \`browser_click\`/\`browser_type\`/\`browser_press\` using a ref from- that snapshot.-3. After any navigation, form submit, or modal change, snapshot AGAIN- before the next action. Stale refs fail loudly — recover with a- fresh snapshot, never a blind retry.--\`browser_navigate\` triggers a navigation; \`browser_scroll\` does not-invalidate refs but may reveal new ones (re-snapshot if you need them).--### Reporting blockers honestly--If the page surfaces a login wall, captcha, 2FA prompt, permission-dialog, or any state that needs the human, STOP. Do not loop. Use-\`submit_task_status\` with \`status: "blocked"\` and a summary that-quotes the exact UI ("Google asks for SMS verification on-+1•••••5309"). Do not claim "not logged in" just because the current-page shows an onboarding splash — snapshot first and read the visible-UI.--Do not try to bypass interstitials by reloading or clicking around. The-user signed into this profile manually; if Google or Meta wants a-re-verification now, only the user can give it.--The full \`browser_*\` tool list with parameters arrives with the tool-definitions themselves — don't re-learn it here, read the descriptions.--You CANNOT stop the workspace browser. Browser lifecycle belongs to the-user (Settings → Workspace browser → Stop). This is deliberate: every-agent in this workspace shares one Chrome, so stopping it would interrupt-your teammates mid-task.--`;diff --git a/notfair/src/server/suggestions/engine.test.ts b/notfair/src/server/suggestions/engine.test.tsdeleted file mode 100644index fa67ac7c..00000000--- a/notfair/src/server/suggestions/engine.test.ts+++ /dev/null@@ -1,182 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest";-import type { SuggestionDraft } from "@/server/db/suggestions";--// Mock at the db-module / analyzer boundary: the engine's own logic is the-// run-state machine, not the X Ads audit or the SQLite writes.-const mocks = vi.hoisted(() => ({- hasSuggestionsForSource: vi.fn<(slug: string, key: string) => boolean>(),- replaceOpenSuggestions: vi.fn(),- listLiveGoals: vi.fn<(slug: string) => Array<{ statement: string }>>(() => []),- listProjectMcpTokens: vi.fn<(slug: string) => Array<{ server_name: string }>>(- () => [],- ),- auditXadsAccount: vi.fn(),- xadsSuggestionsFromSnapshot: vi.fn<() => SuggestionDraft[]>(() => []),-}));--vi.mock("@/server/db/suggestions", () => ({- hasSuggestionsForSource: mocks.hasSuggestionsForSource,- replaceOpenSuggestions: mocks.replaceOpenSuggestions,-}));-vi.mock("@/server/db/goals", () => ({- listLiveGoals: mocks.listLiveGoals,-}));-vi.mock("@/server/mcp/tokens", () => ({- listProjectMcpTokens: mocks.listProjectMcpTokens,-}));-vi.mock("./xads", () => ({- XADS_SOURCE_KEY: "notfair-xads",- auditXadsAccount: mocks.auditXadsAccount,- xadsSuggestionsFromSnapshot: mocks.xadsSuggestionsFromSnapshot,-}));--import {- analyzableSources,- anySuggestionRunActive,- generateSuggestionsForSource,- listSuggestionRuns,- maybeAutoGenerate,- suggestionSourceLabel,-} from "./engine";--// The engine keeps per-project run state in module memory for the process-// lifetime — every test uses a distinct project slug for isolation.-let seq = 0;-const freshSlug = () => `proj-${++seq}`;--beforeEach(() => {- vi.clearAllMocks();- mocks.listLiveGoals.mockReturnValue([]);- mocks.listProjectMcpTokens.mockReturnValue([]);- mocks.xadsSuggestionsFromSnapshot.mockReturnValue([]);-});--describe("suggestionSourceLabel", () => {- it("labels known analyzers and returns null otherwise", () => {- expect(suggestionSourceLabel("notfair-xads")).toBe("X Ads");- expect(suggestionSourceLabel("notfair-googleads")).toBeNull();- });-});--describe("generateSuggestionsForSource", () => {- it("no-ops for a source without an analyzer", async () => {- const slug = freshSlug();- await generateSuggestionsForSource(slug, "notfair-googleads");- expect(listSuggestionRuns(slug)).toEqual([]);- expect(mocks.replaceOpenSuggestions).not.toHaveBeenCalled();- });-- it("runs the analyzer, refreshes open suggestions, and records done", async () => {- const slug = freshSlug();- const drafts = [{ title: "Fix wasted spend" }] as unknown as SuggestionDraft[];- mocks.listLiveGoals.mockReturnValue([{ statement: "Grow clicks" }]);- mocks.auditXadsAccount.mockResolvedValue({ ok: true });- mocks.xadsSuggestionsFromSnapshot.mockReturnValue(drafts);-- await generateSuggestionsForSource(slug, "notfair-xads");-- expect(mocks.auditXadsAccount).toHaveBeenCalledWith(slug);- expect(mocks.xadsSuggestionsFromSnapshot).toHaveBeenCalledWith(- { ok: true },- ["Grow clicks"],- );- expect(mocks.replaceOpenSuggestions).toHaveBeenCalledWith(- slug,- "notfair-xads",- drafts,- );- const runs = listSuggestionRuns(slug);- expect(runs).toHaveLength(1);- expect(runs[0]).toMatchObject({- source_key: "notfair-xads",- label: "X Ads",- status: "done",- });- expect(runs[0]!.finished_at).toBeTypeOf("number");- expect(anySuggestionRunActive(slug)).toBe(false);- });-- it("records a failed run with the error message instead of throwing", async () => {- const slug = freshSlug();- const consoleError = vi- .spyOn(console, "error")- .mockImplementation(() => {});- mocks.auditXadsAccount.mockRejectedValue(new Error("bearer expired"));-- await generateSuggestionsForSource(slug, "notfair-xads");-- expect(listSuggestionRuns(slug)[0]).toMatchObject({- status: "failed",- error: "bearer expired",- });- expect(mocks.replaceOpenSuggestions).not.toHaveBeenCalled();- consoleError.mockRestore();- });-- it("ignores a second trigger while a run is live", async () => {- const slug = freshSlug();- let finish!: (v: unknown) => void;- mocks.auditXadsAccount.mockReturnValue(new Promise((r) => (finish = r)));-- const first = generateSuggestionsForSource(slug, "notfair-xads");- expect(anySuggestionRunActive(slug)).toBe(true);-- // Re-trigger mid-flight: must not start a second audit.- await generateSuggestionsForSource(slug, "notfair-xads");- expect(mocks.auditXadsAccount).toHaveBeenCalledTimes(1);-- finish({});- await first;- expect(listSuggestionRuns(slug)[0]!.status).toBe("done");- });-});--describe("analyzableSources", () => {- it("keeps only connected sources that have an analyzer", () => {- const slug = freshSlug();- mocks.listProjectMcpTokens.mockReturnValue([- { server_name: "notfair-xads" },- { server_name: "notfair-googleads" },- ]);- expect(analyzableSources(slug)).toEqual(["notfair-xads"]);- });-});--describe("maybeAutoGenerate", () => {- it("kicks off analysis for a connected source with no prior suggestions", async () => {- const slug = freshSlug();- mocks.listProjectMcpTokens.mockReturnValue([{ server_name: "notfair-xads" }]);- mocks.hasSuggestionsForSource.mockReturnValue(false);- mocks.auditXadsAccount.mockResolvedValue({});-- maybeAutoGenerate(slug);- // Fire-and-forget: wait for the promise chain to settle.- await vi.waitFor(() =>- expect(listSuggestionRuns(slug)[0]?.status).toBe("done"),- );- expect(mocks.auditXadsAccount).toHaveBeenCalledTimes(1);- });-- it("skips sources that already have suggestion rows", () => {- const slug = freshSlug();- mocks.listProjectMcpTokens.mockReturnValue([{ server_name: "notfair-xads" }]);- mocks.hasSuggestionsForSource.mockReturnValue(true);-- maybeAutoGenerate(slug);- expect(mocks.auditXadsAccount).not.toHaveBeenCalled();- expect(listSuggestionRuns(slug)).toEqual([]);- });-- it("skips sources already attempted this process lifetime", async () => {- const slug = freshSlug();- mocks.listProjectMcpTokens.mockReturnValue([{ server_name: "notfair-xads" }]);- mocks.hasSuggestionsForSource.mockReturnValue(false);- mocks.auditXadsAccount.mockResolvedValue({});-- await generateSuggestionsForSource(slug, "notfair-xads");- mocks.auditXadsAccount.mockClear();-- maybeAutoGenerate(slug);- expect(mocks.auditXadsAccount).not.toHaveBeenCalled();- });-});diff --git a/notfair/src/server/suggestions/engine.ts b/notfair/src/server/suggestions/engine.tsdeleted file mode 100644index abe6b557..00000000--- a/notfair/src/server/suggestions/engine.ts+++ /dev/null@@ -1,131 +0,0 @@-import {- hasSuggestionsForSource,- replaceOpenSuggestions,- type SuggestionDraft,-} from "@/server/db/suggestions";-import { listLiveGoals } from "@/server/db/goals";-import { listProjectMcpTokens } from "@/server/mcp/tokens";-import {- auditXadsAccount,- xadsSuggestionsFromSnapshot,- XADS_SOURCE_KEY,-} from "./xads";--/**- * Suggestion generation: after a user connects an ads account, NotFair- * audits it mechanically and proposes goals. One analyzer per platform;- * X Ads is the first. Generation is idempotent per (project, source) —- * open rows refresh, accepted/dismissed rows are left alone.- */--type Analyzer = (- project_slug: string,- liveGoalStatements: string[],-) => Promise<SuggestionDraft[]>;--const ANALYZERS: Record<string, { label: string; run: Analyzer }> = {- [XADS_SOURCE_KEY]: {- label: "X Ads",- run: async (project_slug, liveGoals) => {- const snapshot = await auditXadsAccount(project_slug);- return xadsSuggestionsFromSnapshot(snapshot, liveGoals);- },- },-};--export function suggestionSourceLabel(source_key: string): string | null {- return ANALYZERS[source_key]?.label ?? null;-}--export type SuggestionRun = {- source_key: string;- label: string;- status: "running" | "done" | "failed";- error?: string;- finished_at?: number;-};--// Per-project run state. In-memory is enough for a single-user local-// process: the UI polls it while a run is live, and a lost run after a-// restart just means the user re-triggers from the index page.-const runs = new Map<string, Map<string, SuggestionRun>>();--function projectRuns(project_slug: string): Map<string, SuggestionRun> {- let m = runs.get(project_slug);- if (!m) {- m = new Map();- runs.set(project_slug, m);- }- return m;-}--export function listSuggestionRuns(project_slug: string): SuggestionRun[] {- return Array.from(projectRuns(project_slug).values());-}--export function anySuggestionRunActive(project_slug: string): boolean {- return listSuggestionRuns(project_slug).some((r) => r.status === "running");-}--/**- * Analyze one connected source and refresh its open suggestions.- * No-ops when the source has no analyzer or a run is already live.- */-export async function generateSuggestionsForSource(- project_slug: string,- source_key: string,-): Promise<void> {- const analyzer = ANALYZERS[source_key];- if (!analyzer) return;- const state = projectRuns(project_slug);- if (state.get(source_key)?.status === "running") return;-- state.set(source_key, {- source_key,- label: analyzer.label,- status: "running",- });- try {- const liveStatements = listLiveGoals(project_slug).map((g) => g.statement);- const drafts = await analyzer.run(project_slug, liveStatements);- replaceOpenSuggestions(project_slug, source_key, drafts);- state.set(source_key, {- source_key,- label: analyzer.label,- status: "done",- finished_at: Date.now(),- });- } catch (err) {- const message = err instanceof Error ? err.message : String(err);- console.error(`[suggestions] ${source_key} analysis failed:`, message);- state.set(source_key, {- source_key,- label: analyzer.label,- status: "failed",- error: message,- finished_at: Date.now(),- });- }-}--/** Every connected source that has an analyzer. */-export function analyzableSources(project_slug: string): string[] {- return listProjectMcpTokens(project_slug)- .map((t) => t.server_name)- .filter((key) => key in ANALYZERS);-}--/**- * First-visit hook for the goals index: kick off analysis for any- * connected source that has never produced suggestions (covers accounts- * connected before this feature existed, and dropped runs after a- * restart). Fire-and-forget; failures land in the run state.- */-export function maybeAutoGenerate(project_slug: string): void {- for (const key of analyzableSources(project_slug)) {- const run = projectRuns(project_slug).get(key);- if (run) continue; // already attempted this process lifetime- if (hasSuggestionsForSource(project_slug, key)) continue;- void generateSuggestionsForSource(project_slug, key);- }-}diff --git a/notfair/src/server/suggestions/xads.ts b/notfair/src/server/suggestions/xads.tsdeleted file mode 100644index c64425d6..00000000--- a/notfair/src/server/suggestions/xads.ts+++ /dev/null@@ -1,245 +0,0 @@-import { mcpRpcAutoRefresh } from "@/server/mcp/rpc";-import type { SuggestionDraft } from "@/server/db/suggestions";--/**- * Mechanical X Ads account audit → grounded goal suggestions.- *- * Same trust model as goal metrics: the platform runs the queries itself- * (no agent self-reporting), so every number in a suggestion's rationale- * is real account data. The audit is one `runScript` call against the- * notfair-xads MCP; the heuristics below turn its snapshot into at most- * three proposals. The goal agent re-verifies everything at intake, so- * suggestions only need to be directionally right.- */--export const XADS_SOURCE_KEY = "notfair-xads";--type ToolCallResult = {- content?: Array<{ type?: string; text?: string }>;- isError?: boolean;-};--export type XadsSnapshot = {- account: { name: string; currency: string };- counts: {- campaigns: number;- activeCampaigns: number;- lineItems: number;- activeLineItems: number;- };- activeDailyBudget: number;- /** Trailing-30-day totals across all line items. */- last30d: {- spend: number;- impressions: number;- engagements: number;- linkClicks: number;- conversions: number;- /** Spend on line items that took budget but produced zero engagement. */- wastedSpend: number;- };- /** Trailing-7-day totals (the most recent stats chunk). */- last7d: { spend: number; impressions: number };- topSpenders: Array<{ name: string; spend: number; conversions: number }>;-};--/**- * The audit script. X Ads sync stats allow at most 7 days + 1 hour per- * request, so the 30-day window runs as five sequential chunks; line- * items batch 20 ids per stats call (API limit).- */-const AUDIT_SCRIPT = `-const r = await ads.getParallel([- { name: 'account', path: 'accounts/{accountId}' },- { name: 'campaigns', path: 'accounts/{accountId}/campaigns', paged: true },- { name: 'lineItems', path: 'accounts/{accountId}/line_items', paged: true },-]);-for (const k of ['account', 'campaigns', 'lineItems']) {- if (!r[k] || !r[k].ok) throw new Error('X Ads audit: ' + k + ' fetch failed: ' + JSON.stringify(r[k] && r[k].error));-}-// Unpaged gets keep the raw response envelope; the entity is one level down.-const account = (r.account.data && r.account.data.data) || r.account.data || {};-const campaigns = r.campaigns.data || [];-const lineItems = r.lineItems.data || [];-const activeLineItems = lineItems.filter(li => li.entity_status === 'ACTIVE');--const ENGAGEMENT_KEYS = ['follows','app_clicks','retweets','likes','engagements','clicks','card_engagements','replies','link_clicks','billed_engagements','carousel_swipes'];-const CONVERSION_KEYS = ['conversion_purchases','conversion_sign_ups','conversion_site_visits','conversion_downloads','conversion_custom'];-// Metric values vary by group: ENGAGEMENT/BILLING come back as plain-// arrays ([574452]), WEB_CONVERSION as {metric: [...]} objects. Read both.-const sum = (m, k) => {- const v = m[k];- const arr = Array.isArray(v) ? v : (v && Array.isArray(v.metric) ? v.metric : []);- return arr.reduce((a, b) => a + Number(b || 0), 0);-};--// Per-line-item accumulators over 30 days.-const acc = {};-for (const li of lineItems) acc[li.id] = { spendMicros: 0, impressions: 0, engagements: 0, linkClicks: 0, conversions: 0 };--const end = new Date(); end.setUTCMinutes(0, 0, 0);-// 30 days as hour-aligned chunks inside the 7d+1h API limit: the first-// chunk is exactly the trailing 7 days (168h), the rest split the-// remaining 23 days into 138h slices. 168 + 4*138 = 720h = 30 days.-const HOUR = 3600000;-const bounds = [0, 168, 306, 444, 582, 720];-let spend7dMicros = 0, impressions7d = 0;-for (let chunk = 0; chunk < bounds.length - 1; chunk++) {- const chunkEnd = new Date(end.getTime() - bounds[chunk] * HOUR);- const chunkStart = new Date(end.getTime() - bounds[chunk + 1] * HOUR);- const win = { start_time: ads.helpers.formatHourIso(chunkStart), end_time: ads.helpers.formatHourIso(chunkEnd) };- for (let i = 0; i < lineItems.length; i += 20) {- const ids = lineItems.slice(i, i + 20).map(li => li.id);- const stats = await ads.stats({- entity: 'LINE_ITEM', entity_ids: ids,- metric_groups: ['BILLING', 'ENGAGEMENT', 'WEB_CONVERSION'],- granularity: 'TOTAL', ...win,- });- for (const row of (stats.data || [])) {- const m = (row.id_data && row.id_data[0] && row.id_data[0].metrics) || {};- const a = acc[row.id]; if (!a) continue;- const spendMicros = sum(m, 'billed_charge_local_micro');- a.spendMicros += spendMicros;- a.impressions += sum(m, 'impressions');- a.engagements += ENGAGEMENT_KEYS.reduce((t, k) => t + sum(m, k), 0);- a.linkClicks += sum(m, 'link_clicks');- a.conversions += CONVERSION_KEYS.reduce((t, k) => t + sum(m, k), 0);- if (chunk === 0) { spend7dMicros += spendMicros; impressions7d += sum(m, 'impressions'); }- }- }-}--const usd = micros => Number(ads.helpers.microsToMajor(micros).toFixed(2));-let spendMicros = 0, impressions = 0, engagements = 0, linkClicks = 0, conversions = 0, wastedMicros = 0;-const spenders = [];-for (const li of lineItems) {- const a = acc[li.id];- spendMicros += a.spendMicros; impressions += a.impressions;- engagements += a.engagements; linkClicks += a.linkClicks; conversions += a.conversions;- if (a.spendMicros > 0 && a.engagements === 0) wastedMicros += a.spendMicros;- if (a.spendMicros > 0) spenders.push({ name: li.name, spend: usd(a.spendMicros), conversions: a.conversions });-}-spenders.sort((a, b) => b.spend - a.spend);--return {- account: { name: account.name || 'your X Ads account', currency: 'USD' },- counts: {- campaigns: campaigns.length,- activeCampaigns: campaigns.filter(c => c.entity_status === 'ACTIVE').length,- lineItems: lineItems.length,- activeLineItems: activeLineItems.length,- },- activeDailyBudget: usd(activeLineItems.reduce((t, li) => t + (li.daily_budget_amount_local_micro || 0), 0)),- last30d: {- spend: usd(spendMicros), impressions, engagements, linkClicks, conversions,- wastedSpend: usd(wastedMicros),- },- last7d: { spend: usd(spend7dMicros), impressions: impressions7d },- topSpenders: spenders.slice(0, 3),-};-`;--export async function auditXadsAccount(project_slug: string): Promise<XadsSnapshot> {- const rpc = await mcpRpcAutoRefresh<ToolCallResult>(- project_slug,- XADS_SOURCE_KEY,- "tools/call",- { name: "runScript", arguments: { timeoutMs: 45_000, code: AUDIT_SCRIPT } },- { timeoutMs: 60_000 },- );- if (!rpc.ok) {- const detail = "message" in rpc && rpc.message ? `: ${rpc.message}` : "";- throw new Error(`X Ads audit failed (${rpc.kind}${detail})`);- }- const text = rpc.result?.content?.find((c) => c.type === "text")?.text ?? "";- if (rpc.result?.isError) {- throw new Error(`X Ads audit script errored: ${text.slice(0, 400)}`);- }- const envelope = JSON.parse(text) as { ok?: boolean; result?: XadsSnapshot; error?: { message?: string } };- if (!envelope.ok || !envelope.result) {- throw new Error(`X Ads audit script failed: ${envelope.error?.message ?? text.slice(0, 400)}`);- }- return envelope.result;-}--const money = (n: number) => `$${n % 1 === 0 ? n : n.toFixed(2)}`;--/**- * Snapshot → at most three proposals, priority-ordered. `liveGoalStatements`- * lets each heuristic skip territory an existing goal already owns (the- * user may have stated it by hand — don't pitch them their own goal).- */-export function xadsSuggestionsFromSnapshot(- s: XadsSnapshot,- liveGoalStatements: string[],-): SuggestionDraft[] {- const overlaps = (re: RegExp) => liveGoalStatements.some((st) => re.test(st));- const out: SuggestionDraft[] = [];- const d = s.last30d;-- // Nothing in the account yet → one bootstrap proposal and stop.- if (s.counts.lineItems === 0) {- if (!overlaps(/launch|first campaign/i)) {- out.push({- kind: "xads-bootstrap",- title: "Launch your first X Ads campaign",- statement:- "Launch our first X Ads campaign and get it delivering — reaching real impressions within a week.",- mode: "achieve",- rationale: `The connected X Ads account (${s.account.name}) has no campaigns or ad groups yet.`,- });- }- return out;- }-- // Spending but some of it buys zero engagement → cut the waste.- if (d.wastedSpend > 0 && !overlaps(/wast\w* spend|no.engagement/i)) {- out.push({- kind: "xads-wasted-spend",- title: "Cut wasted X Ads spend to $0",- statement: `Cut X Ads wasted spend to $0 and keep it there — pause line items that spend without producing a single engagement.`,- mode: "maintain",- rationale: `${money(d.wastedSpend)} of the last 30 days' ${money(d.spend)} X Ads spend went to line items with zero engagements.`,- });- }-- // Active entities but the account isn't actually delivering.- if (- s.counts.activeLineItems > 0 &&- s.last7d.impressions === 0 &&- !overlaps(/deliver|impression|reviv/i)- ) {- out.push({- kind: "xads-dormant",- title: "Get X Ads delivering again",- statement: `Revive the X Ads account: get the active campaigns actually serving, with steady daily impressions.`,- mode: "achieve",- rationale: `${s.counts.activeLineItems} of ${s.counts.lineItems} line items are ACTIVE with ${money(s.activeDailyBudget)}/day of budget, but the account served 0 impressions in the last 7 days.`,- });- }-- // Converting → push cost per conversion down.- if (d.conversions > 0 && d.spend > 0 && !overlaps(/cost per|cpa|per conversion/i)) {- const cpa = d.spend / d.conversions;- out.push({- kind: "xads-cpa",- title: "Lower X Ads cost per conversion",- statement: `Lower our X Ads cost per conversion below ${money(Math.floor(cpa * 0.8))} (currently ${money(Number(cpa.toFixed(2)))}).`,- mode: "achieve",- rationale: `Last 30 days: ${money(d.spend)} spend for ${d.conversions} conversions = ${money(Number(cpa.toFixed(2)))} per conversion.`,- });- }-- // Spending and getting clicks but conversions never report → tracking gap.- if (d.spend > 0 && d.linkClicks > 0 && d.conversions === 0 && !overlaps(/conversion|tracking/i)) {- out.push({- kind: "xads-no-conversions",- title: "Get X Ads conversions reporting",- statement: `Get X Ads conversion tracking working end to end — the account should report at least one conversion from paid traffic.`,- mode: "achieve",- rationale: `${money(d.spend)} spend and ${d.linkClicks} link clicks in 30 days, but 0 conversions recorded — either tracking is broken or the funnel is.`,- });- }-- return out.slice(0, 3);-}diff --git a/notfair/src/server/trusted-connectors.ts b/notfair/src/server/trusted-connectors.tsdeleted file mode 100644index 823aaca9..00000000--- a/notfair/src/server/trusted-connectors.ts+++ /dev/null@@ -1,88 +0,0 @@-import { CANONICAL_MCP_RESOURCE_URL } from "@/lib/canonical-mcp";--/**- * Browseable directory of trusted MCP servers shown in the "Browse- * connectors" dialog. Distinct from `MCP_CATALOG_PRESETS` (which is- * always-visible per project): these are opt-in. Picking one writes a- * row to `user_mcp_servers` via `addUserMcpServerAction` and triggers- * the usual OAuth probe before persisting.- *- * The `resource_url`s here are the ones the providers publish; if a- * vendor moves their MCP, the probe will surface the error and the- * user can paste the correct URL via "Add custom connector" until we- * update this list.- *- * **Why Vercel isn't here:**- *- * Vercel's DCR endpoint silently returns a single fixed `client_id`- * (`cl_WbdtcToDrMR4ZHvXLGAmbfoYCsQjMeS8`) regardless of the request body,- * and that client's pre-approved redirect-URI allowlist excludes every- * loopback URI — verified with multiple `redirect_uri` shapes. Vercel's- * MCP is wired only for their first-party integrations (Claude Desktop,- * Cursor, etc., each with hardcoded redirect URIs Vercel approved out- * of band); arbitrary OAuth-2.1 + DCR clients can't complete the flow- * until Vercel opens up DCR or adds an allowlist entry for us.- *- * Users can still try via "Add custom connector"; presenting Vercel in- * the curated grid would just produce a guaranteed failure toast.- */--export type TrustedConnector = {- /** Used purely for React keys + stable slugs in tests. */- id: string;- display_name: string;- description: string;- /** HTTPS resource URL the OAuth flow targets. */- resource_url: string;-};--export const TRUSTED_CONNECTORS: TrustedConnector[] = [- {- id: "notfair-googleads",- display_name: "NotFair Google Ads",- description: "Campaigns, bids, keywords, search terms.",- resource_url: CANONICAL_MCP_RESOURCE_URL,- },- {- id: "notfair-metaads",- display_name: "NotFair Meta Ads",- description: "Facebook + Instagram campaigns, ad sets, budgets.",- resource_url: CANONICAL_MCP_RESOURCE_URL,- },- {- id: "notfair-googlesearchconsole",- display_name: "NotFair Google Search Console",- description: "Organic search performance, queries, pages, indexing.",- resource_url: CANONICAL_MCP_RESOURCE_URL,- },- {- id: "notfair-googleanalytics",- display_name: "NotFair Google Analytics",- description: "GA4 traffic, channels, conversions, audiences.",- resource_url: CANONICAL_MCP_RESOURCE_URL,- },- {- id: "stripe",- display_name: "Stripe",- description: "Payments, customers, subscriptions, invoices.",- resource_url: "https://mcp.stripe.com/",- },- {- id: "supabase",- display_name: "Supabase",- description: "Postgres, auth, storage, edge functions.",- resource_url: "https://mcp.supabase.com/mcp",- },- {- id: "posthog",- display_name: "PostHog",- description: "Product analytics, funnels, feature flags.",- resource_url: "https://mcp.posthog.com/mcp",- },- {- id: "mixpanel",- display_name: "Mixpanel",- description: "Event analytics, cohorts, retention.",- resource_url: "https://mcp.mixpanel.com/mcp",- },-];diff --git a/notfair/src/server/version.test.ts b/notfair/src/server/version.test.tsdeleted file mode 100644index 58b6fcb7..00000000--- a/notfair/src/server/version.test.ts+++ /dev/null@@ -1,42 +0,0 @@-import { afterEach, describe, expect, it, vi } from "vitest";--import {- _resetLatestCache,- getLatestVersion,- isSemverGreater,-} from "@/server/version";--afterEach(() => {- _resetLatestCache();- vi.unstubAllGlobals();-});--describe("getLatestVersion", () => {- it("queries the lowercase npm package name (the registry is case-sensitive)", async () => {- const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>- new Response(JSON.stringify({ version: "9.9.9" }), { status: 200 }),- );- vi.stubGlobal("fetch", fetchMock);- const latest = await getLatestVersion(true);- expect(latest).toBe("9.9.9");- expect(String(fetchMock.mock.calls[0]![0])).toBe(- "https://registry.npmjs.org/notfair/latest",- );- });-- it("returns null on registry errors instead of throwing", async () => {- vi.stubGlobal("fetch", vi.fn(async () => new Response("nope", { status: 404 })));- expect(await getLatestVersion(true)).toBeNull();- });-});--describe("isSemverGreater", () => {- it("orders by major.minor.patch and ignores pre-release suffixes", () => {- expect(isSemverGreater("0.9.7", "0.9.6")).toBe(true);- expect(isSemverGreater("0.10.0", "0.9.9")).toBe(true);- expect(isSemverGreater("1.0.0", "0.99.99")).toBe(true);- expect(isSemverGreater("0.9.6", "0.9.6")).toBe(false);- expect(isSemverGreater("0.9.5", "0.9.6")).toBe(false);- expect(isSemverGreater("0.9.7-beta.1", "0.9.6")).toBe(true);- });-});diff --git a/notfair/src/server/version.ts b/notfair/src/server/version.tsdeleted file mode 100644index abf9a9cc..00000000--- a/notfair/src/server/version.ts+++ /dev/null@@ -1,97 +0,0 @@-/**- * NotFair version helpers.- *- * Reads the current version from package.json (JSON import is statically- * resolved by Next.js so it works in dev, prod standalone, and tests).- * Probes the npm registry for the latest published version with a 1-hour- * cache so the UI doesn't pound registry.npmjs.org on every refresh.- */-import pkg from "../../package.json";--// npm package names are lowercase and the registry is case-sensitive —-// "NotFair" 404s and silently kills the update check.-const PACKAGE_NAME = "notfair";-const NPM_REGISTRY_LATEST = `https://registry.npmjs.org/${PACKAGE_NAME}/latest`;-const NPM_FETCH_TIMEOUT_MS = 5_000;-const LATEST_CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour--let _cachedLatest: { version: string; checkedAt: number } | null = null;--export function getCurrentVersion(): string {- return (pkg as { version?: string }).version ?? "0.0.0";-}--/**- * Fetch the latest published version from npm. Cached in-process for- * 1 hour; pass `force` to bypass after a successful upgrade.- *- * Returns null when the registry is unreachable (offline, network down,- * registry 5xx). Callers should treat null as "no update info" rather- * than "no update available."- */-export async function getLatestVersion(- force = false,- now: number = Date.now(),-): Promise<string | null> {- if (- !force &&- _cachedLatest &&- now - _cachedLatest.checkedAt < LATEST_CACHE_TTL_MS- ) {- return _cachedLatest.version;- }- try {- const res = await fetch(NPM_REGISTRY_LATEST, {- signal: AbortSignal.timeout(NPM_FETCH_TIMEOUT_MS),- headers: { accept: "application/json" },- });- if (!res.ok) return null;- const data = (await res.json()) as { version?: unknown };- if (typeof data.version !== "string") return null;- _cachedLatest = { version: data.version, checkedAt: now };- return data.version;- } catch {- return null;- }-}--/** True when `a` is strictly newer than `b` by major.minor.patch ordering. */-export function isSemverGreater(a: string, b: string): boolean {- const pa = parseSemver(a);- const pb = parseSemver(b);- if (pa.major !== pb.major) return pa.major > pb.major;- if (pa.minor !== pb.minor) return pa.minor > pb.minor;- return pa.patch > pb.patch;-}--function parseSemver(v: string): { major: number; minor: number; patch: number } {- // Strip any pre-release / build suffix; we only compare the numeric core.- const core = v.split(/[-+]/)[0]!;- const parts = core.split(".");- return {- major: Number(parts[0] ?? 0) || 0,- minor: Number(parts[1] ?? 0) || 0,- patch: Number(parts[2] ?? 0) || 0,- };-}--export interface VersionStatus {- current: string;- latest: string | null;- has_update: boolean;-}--export async function getVersionStatus(): Promise<VersionStatus> {- const current = getCurrentVersion();- const latest = await getLatestVersion();- return {- current,- latest,- has_update: latest !== null && isSemverGreater(latest, current),- };-}--/** Test-only: forget the cached registry response. */-export function _resetLatestCache(): void {- _cachedLatest = null;-}diff --git a/notfair/src/types/index.ts b/notfair/src/types/index.tsdeleted file mode 100644index 9f38f512..00000000--- a/notfair/src/types/index.ts+++ /dev/null@@ -1,58 +0,0 @@-// Shared types. Imported by both server (Next.js API + MCP) and client (React).--export type Project = {- id: string;- slug: string;- display_name: string;- created_at: string;- archived_at: string | null;- /**- * Selected Google Ads customer ID for this project. Bearers from- * notfair.co/api/mcp/notfair can grant access to multiple customer- * accounts; the onboarding flow asks the user to pick one and persists- * it here so the audit + later automation target the right account.- * Null until the user picks (or until /onboarding gets re-run).- */- google_ads_account_id: string | null;- /**- * Selected Meta Ads ad-account id (e.g. "act_123456"). Same pattern as- * google_ads_account_id: the notfair-metaads bearer may grant access- * to multiple ad accounts, and onboarding asks the user to pick the- * one this project should target. Null until picked.- */- meta_ads_account_id: string | null;- /**- * Selected Google Search Console property id (e.g. "sc-domain:example.com"- * or "https://example.com/"). Same idea as the ad-account fields: the- * notfair-googlesearchconsole bearer may cover multiple verified- * properties, and we persist the chosen one. Null until picked.- */- gsc_property_id: string | null;- /**- * Optional inputs the user provided at onboarding — starting points- * for agents exploring what the project is. Both are free-text.- */- website_url: string | null;- codebase_path: string | null;- /**- * Which harness adapter runs this project's agents. Picked at- * onboarding. "codex-local" is the recommended default; "claude-code-local"- * runs through Anthropic's Claude Code CLI instead.- */- harness_adapter: "claude-code-local" | "codex-local";-};--export type ToolErrorEnvelope = {- ok: false;- error_code: string;- message: string;- retryable: boolean;- user_message: string;-};--export type ToolSuccessEnvelope<T> = {- ok: true;- data: T;-};--export type ToolResult<T> = ToolSuccessEnvelope<T> | ToolErrorEnvelope;diff --git a/notfair/tsconfig.json b/notfair/tsconfig.jsondeleted file mode 100644index 43d82906..00000000--- a/notfair/tsconfig.json+++ /dev/null@@ -1,42 +0,0 @@-{- "compilerOptions": {- "target": "ES2022",- "lib": [- "dom",- "dom.iterable",- "ES2022"- ],- "allowJs": true,- "skipLibCheck": true,- "strict": true,- "noEmit": true,- "esModuleInterop": true,- "module": "esnext",- "moduleResolution": "bundler",- "resolveJsonModule": true,- "isolatedModules": true,- "jsx": "react-jsx",- "incremental": true,- "plugins": [- {- "name": "next"- }- ],- "paths": {- "@/*": [- "./src/*"- ]- }- },- "include": [- "next-env.d.ts",- "**/*.ts",- "**/*.tsx",- ".next/types/**/*.ts",- ".next/dev/types/**/*.ts"- ],- "exclude": [- "node_modules",- ".next/standalone"- ]-}diff --git a/notfair/vitest.config.ts b/notfair/vitest.config.tsdeleted file mode 100644index d9c0c165..00000000--- a/notfair/vitest.config.ts+++ /dev/null@@ -1,41 +0,0 @@-import path from "node:path";-import { defineConfig } from "vitest/config";-import react from "@vitejs/plugin-react";--export default defineConfig({- plugins: [react()],- resolve: {- alias: { "@": path.resolve(__dirname, "src") },- },- test: {- // Testing-library auto-cleanup registers on the global afterEach.- globals: true,- // Only first-party tests — `next build` copies src (tests included)- // into .next/standalone, which vitest must not collect.- include: ["src/**/*.test.{ts,tsx}"],- setupFiles: ["./vitest.setup.ts"],- // Server modules and libs run in node. Component tests opt into a DOM- // per-file via `// @vitest-environment jsdom` (vitest 4 removed the- // environmentMatchGlobs shorthand).- environment: "node",- coverage: {- provider: "v8",- // The denominator is everything we unit-test by convention. Excluded- // per CLAUDE.md: Next.js pages/layouts/route handlers (live smoke- // covers those), vendored shadcn primitives, and the boot hook.- include: ["src/**/*.{ts,tsx}"],- exclude: [- "src/app/**",- "src/components/ui/**",- "src/instrumentation.ts",- "src/**/*.test.{ts,tsx}",- "src/**/*.d.ts",- "src/types.ts",- ],- thresholds: {- statements: 80,- lines: 80,- },- },- },-});diff --git a/notfair/vitest.setup.ts b/notfair/vitest.setup.tsdeleted file mode 100644index 1cac1383..00000000--- a/notfair/vitest.setup.ts+++ /dev/null@@ -1,34 +0,0 @@-import "@testing-library/jest-dom/vitest";--// Node 25 exposes an experimental, path-dependent global localStorage that can-// shadow jsdom's implementation. Keep component tests independent of the Node-// invocation flags by installing the small, standards-compatible subset they-// need in every DOM test environment.-if (typeof window !== "undefined") {- const values = new Map<string, string>();- const localStorage: Storage = {- get length() {- return values.size;- },- clear() {- values.clear();- },- getItem(key) {- return values.get(String(key)) ?? null;- },- key(index) {- return [...values.keys()][index] ?? null;- },- removeItem(key) {- values.delete(String(key));- },- setItem(key, value) {- values.set(String(key), String(value));- },- };-- Object.defineProperty(window, "localStorage", {- configurable: true,- value: localStorage,- });-}diff --git a/paid-ads/paid-ads-amazon/SKILL.md b/paid-ads/paid-ads-amazon/WORKFLOW.mdsimilarity index 100%rename from paid-ads/paid-ads-amazon/SKILL.mdrename to paid-ads/paid-ads-amazon/WORKFLOW.mddiff --git a/paid-ads/paid-ads-chatgpt/SKILL.md b/paid-ads/paid-ads-chatgpt/WORKFLOW.mdsimilarity index 100%rename from paid-ads/paid-ads-chatgpt/SKILL.mdrename to paid-ads/paid-ads-chatgpt/WORKFLOW.mddiff --git a/paid-ads/paid-ads-creative/SKILL.md b/paid-ads/paid-ads-creative/WORKFLOW.mdsimilarity index 100%rename from paid-ads/paid-ads-creative/SKILL.mdrename to paid-ads/paid-ads-creative/WORKFLOW.mddiff --git a/paid-ads/paid-ads-guide/SKILL.md b/paid-ads/paid-ads-guide/WORKFLOW.mdsimilarity index 87%rename from paid-ads/paid-ads-guide/SKILL.mdrename to paid-ads/paid-ads-guide/WORKFLOW.mdindex 92bfec30..f85b0879 100644--- a/paid-ads/paid-ads-guide/SKILL.md+++ b/paid-ads/paid-ads-guide/WORKFLOW.md@@ -21,6 +21,6 @@ Answer NotFair product questions from the repository documentation or current ofNotFair supplies host-agnostic skills plus one OAuth-connected MCP operating surface for Google Ads, Meta Ads, X Ads, LinkedIn Ads, Reddit Ads, TikTok Ads, Google Analytics, Search Console, WordPress, and GoHighLevel. Each platform keeps its dedicated workflow; the agent chooses tools from the live connection rather than a fixed skill-level tool list. Read [`../../docs/mcp-connection.md`](../../docs/mcp-connection.md) for capability discovery and connection upgrades. Amazon and ChatGPT Ads remain planning/review-first until the session has a verified connector; those skills are not a claim of publication access. Live WordPress work uses `/notfair:wordpress`; `/notfair:setup-cms` is only the local SEO-script CMS wizard. GoHighLevel CRM work uses `/notfair:gohighlevel`.-The goal-loop app makes an outcome measurable, verifies the baseline at the source, and revisits the metric on an approved cadence. The plugin is the hands-on companion for audits, briefs, and supported account operations. Explain the safety boundary plainly: an approved plan is not a live campaign, and a brief is not a published asset.+The plugin supplies audits, briefs, and supported account operations. Explain the safety boundary plainly: an approved plan is not a live campaign, and a brief is not a published asset.When installation is requested, direct the user to the README's plugin install steps. When a connector is missing or unauthorized, use the appropriate platform preamble and stop at the connection CTA rather than inventing a workaround.diff --git a/paid-ads/paid-ads-integrations/SKILL.md b/paid-ads/paid-ads-integrations/WORKFLOW.mdsimilarity index 100%rename from paid-ads/paid-ads-integrations/SKILL.mdrename to paid-ads/paid-ads-integrations/WORKFLOW.mddiff --git a/paid-ads/paid-ads-launch/SKILL.md b/paid-ads/paid-ads-launch/WORKFLOW.mdsimilarity index 100%rename from paid-ads/paid-ads-launch/SKILL.mdrename to paid-ads/paid-ads-launch/WORKFLOW.mddiff --git a/paid-ads/paid-ads-linkedin/SKILL.md b/paid-ads/paid-ads-linkedin/WORKFLOW.mdsimilarity index 100%rename from paid-ads/paid-ads-linkedin/SKILL.mdrename to paid-ads/paid-ads-linkedin/WORKFLOW.mddiff --git a/paid-ads/paid-ads-optimize/SKILL.md b/paid-ads/paid-ads-optimize/WORKFLOW.mdsimilarity index 100%rename from paid-ads/paid-ads-optimize/SKILL.mdrename to paid-ads/paid-ads-optimize/WORKFLOW.mddiff --git a/paid-ads/paid-ads-reddit/SKILL.md b/paid-ads/paid-ads-reddit/WORKFLOW.mdsimilarity index 100%rename from paid-ads/paid-ads-reddit/SKILL.mdrename to paid-ads/paid-ads-reddit/WORKFLOW.mddiff --git a/paid-ads/paid-ads-review/SKILL.md b/paid-ads/paid-ads-review/WORKFLOW.mdsimilarity index 100%rename from paid-ads/paid-ads-review/SKILL.mdrename to paid-ads/paid-ads-review/WORKFLOW.mddiff --git a/paid-ads/paid-ads-setup/SKILL.md b/paid-ads/paid-ads-setup/WORKFLOW.mdsimilarity index 100%rename from paid-ads/paid-ads-setup/SKILL.mdrename to paid-ads/paid-ads-setup/WORKFLOW.mddiff --git a/paid-ads/paid-ads-tiktok/SKILL.md b/paid-ads/paid-ads-tiktok/WORKFLOW.mdsimilarity index 100%rename from paid-ads/paid-ads-tiktok/SKILL.mdrename to paid-ads/paid-ads-tiktok/WORKFLOW.mddiff --git a/paid-ads/paid-ads-x/SKILL.md b/paid-ads/paid-ads-x/WORKFLOW.mdsimilarity index 100%rename from paid-ads/paid-ads-x/SKILL.mdrename to paid-ads/paid-ads-x/WORKFLOW.mddiff --git a/paid-ads/paid-ads/SKILL.md b/paid-ads/paid-ads/WORKFLOW.mdsimilarity index 100%rename from paid-ads/paid-ads/SKILL.mdrename to paid-ads/paid-ads/WORKFLOW.mddiff --git a/plugin.json b/plugin.jsonindex ea8aefea..0de4cf41 100644--- a/plugin.json+++ b/plugin.json@@ -1,7 +1,7 @@{"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","name": "notfair",- "version": "0.27.15",+ "version": "0.27.16","description": "Operate Google, Meta, X, LinkedIn, Reddit, and TikTok Ads plus GA4, Search Console, GoHighLevel, and WordPress through one OAuth MCP, and run open-source SEO, GEO, and content workflows.","author": {"name": "NotFair",@@ -47,7 +47,8 @@],"brandColor": "#111827","logo": "./assets/notfair-icon.png",- "composerIcon": "./assets/notfair-icon.png"+ "composerIcon": "./assets/notfair-icon.png",+ "supportURL": "https://notfair.co/contact"}}}diff --git a/bin/notfair-change-watch b/scripts/notfair-change-watch.shold mode 100755new mode 100644similarity index 100%rename from bin/notfair-change-watchrename to scripts/notfair-change-watch.shdiff --git a/bin/notfair-config b/scripts/notfair-config.shold mode 100755new mode 100644similarity index 100%rename from bin/notfair-configrename to scripts/notfair-config.shdiff --git a/bin/notfair-content-calendar b/scripts/notfair-content-calendar.pyold mode 100755new mode 100644similarity index 100%rename from bin/notfair-content-calendarrename to scripts/notfair-content-calendar.pydiff --git a/bin/notfair-update-check b/scripts/notfair-update-check.shold mode 100755new mode 100644similarity index 98%rename from bin/notfair-update-checkrename to scripts/notfair-update-check.shindex e38e7419..8e7aa19f--- a/bin/notfair-update-check+++ b/scripts/notfair-update-check.sh@@ -19,7 +19,7 @@ MARKER_FILE="$STATE_DIR/just-upgraded-from"SNOOZE_FILE="$STATE_DIR/update-snoozed"VERSION_FILE="$TOPRANK_DIR/VERSION"REMOTE_URL="${TOPRANK_REMOTE_URL:-https://raw.githubusercontent.com/nowork-studio/notfair-plugin/main/VERSION}"-CONFIG_BIN="$TOPRANK_DIR/bin/notfair-config"+CONFIG_BIN="$TOPRANK_DIR/scripts/notfair-config.sh"VERSION_RE='^[0-9]+(\.[0-9]+)+$'# State dir must exist early so any writes below succeed.@@ -40,7 +40,7 @@ if [ "${1:-}" = "--force" ]; thenfi# ─── Step 0: Check if updates are disabled ────────────────────-_UC=$("$CONFIG_BIN" get update_check 2>/dev/null || true)+_UC=$(bash "$CONFIG_BIN" get update_check 2>/dev/null || true)if [ "$_UC" = "false" ]; thenexit 0fidiff --git a/scripts/preamble.md b/scripts/preamble.mdnew file mode 100644index 00000000..a892886b--- /dev/null+++ b/scripts/preamble.md@@ -0,0 +1,13 @@+## Preamble (run first)++```bash+_UPD_BIN=$(ls ~/.claude/plugins/cache/nowork-studio/notfair/*/scripts/notfair-update-check.sh 2>/dev/null | head -1)+[ -n "$_UPD_BIN" ] && _UPD=$(bash "$_UPD_BIN" 2>/dev/null || true) || _UPD=""+[ -n "$_UPD" ] && echo "$_UPD" || true+```++If the output contains `UPGRADE_AVAILABLE <old> <new>`: report the available source version. Follow `/notfair:upgrade` when the user requests an update; the host's plugin manager determines which published version is available.++If the output contains `JUST_UPGRADED <old> <new>`: mention "NotFair upgraded from v{old} to v{new}" briefly, then continue.++---diff --git a/seo/backlink-audit/SKILL.md b/seo/backlink-audit/WORKFLOW.mdsimilarity index 100%rename from seo/backlink-audit/SKILL.mdrename to seo/backlink-audit/WORKFLOW.mddiff --git a/seo/broken-link-checker/SKILL.md b/seo/broken-link-checker/WORKFLOW.mdsimilarity index 100%rename from seo/broken-link-checker/SKILL.mdrename to seo/broken-link-checker/WORKFLOW.mddiff --git a/seo/competitor-pages/SKILL.md b/seo/competitor-pages/WORKFLOW.mdsimilarity index 100%rename from seo/competitor-pages/SKILL.mdrename to seo/competitor-pages/WORKFLOW.mddiff --git a/seo/content-planner/SKILL.md b/seo/content-planner/WORKFLOW.mdsimilarity index 94%rename from seo/content-planner/SKILL.mdrename to seo/content-planner/WORKFLOW.mdindex 26d7d323..c0c0330f 100644--- a/seo/content-planner/SKILL.md+++ b/seo/content-planner/WORKFLOW.md@@ -33,7 +33,7 @@ renders the calendar in the browser).## Step 1 — Setup (config + GSC)-Read and follow `../seo-analysis/SKILL.md` Step 1 for GSC connection. The+Read and follow `../seo-analysis/WORKFLOW.md` Step 1 for GSC connection. Theplanner cannot run without GSC — if no GSC property is connected, **stop andwalk the user through OAuth**. Don't invent data.@@ -195,6 +195,10 @@ Merge with an existing calendar instead of overwriting:## Step 6 — Present + offer the viewer+Resolve `<plugin-root>` from the location of this workflow and substitute its+absolute path in helper commands. Do not rely on `CLAUDE_PLUGIN_ROOT` being+exported by the host; these instructions also run on other agents.+Print:1. A Markdown summary table (top 12 topics by click potential), with columns:@@ -203,16 +207,16 @@ Print:3. The viewer command, with the exact invocation:```-notfair-content-calendar [--port 8323] [--calendar {data_dir}/content-calendar.json]+python3 "<plugin-root>/scripts/notfair-content-calendar.py" [--port 8323] [--calendar {data_dir}/content-calendar.json]```> Open the calendar in your browser:>> ```bash-> ~/.claude/plugins/cache/nowork-studio/notfair/<version>/bin/notfair-content-calendar+> python3 "<plugin-root>/scripts/notfair-content-calendar.py"> ```>-> (or run it from a clone of the notfair repo: `bin/notfair-content-calendar`.)+> (or run it from a clone of the notfair repo: `python3 scripts/notfair-content-calendar.py`.)> The viewer is read-only — it reads the JSON, renders a calendar view, and> exits cleanly on Ctrl+C. Edit the JSON to change scheduling; reload to see> updates.diff --git a/seo/content-writer/SKILL.md b/seo/content-writer/WORKFLOW.mdsimilarity index 100%rename from seo/content-writer/SKILL.mdrename to seo/content-writer/WORKFLOW.mddiff --git a/seo/ecommerce-seo/SKILL.md b/seo/ecommerce-seo/WORKFLOW.mdsimilarity index 100%rename from seo/ecommerce-seo/SKILL.mdrename to seo/ecommerce-seo/WORKFLOW.mddiff --git a/seo/geo-optimizer/SKILL.md b/seo/geo-optimizer/WORKFLOW.mdsimilarity index 100%rename from seo/geo-optimizer/SKILL.mdrename to seo/geo-optimizer/WORKFLOW.mddiff --git a/seo/hreflang-international/SKILL.md b/seo/hreflang-international/WORKFLOW.mdsimilarity index 100%rename from seo/hreflang-international/SKILL.mdrename to seo/hreflang-international/WORKFLOW.mddiff --git a/seo/image-seo/SKILL.md b/seo/image-seo/WORKFLOW.mdsimilarity index 100%rename from seo/image-seo/SKILL.mdrename to seo/image-seo/WORKFLOW.mddiff --git a/seo/keyword-research/SKILL.md b/seo/keyword-research/WORKFLOW.mdsimilarity index 98%rename from seo/keyword-research/SKILL.mdrename to seo/keyword-research/WORKFLOW.mdindex c408170b..1033a292 100644--- a/seo/keyword-research/SKILL.md+++ b/seo/keyword-research/WORKFLOW.md@@ -300,4 +300,4 @@ When a user requests keyword research:## Next Best Skill-- **Primary**: [content-writer](../content-writer/SKILL.md) — turn keyword opportunities into optimized content.+- **Primary**: [content-writer](../content-writer/WORKFLOW.md) — turn keyword opportunities into optimized content.diff --git a/seo/local-seo/SKILL.md b/seo/local-seo/WORKFLOW.mdsimilarity index 100%rename from seo/local-seo/SKILL.mdrename to seo/local-seo/WORKFLOW.mddiff --git a/seo/meta-tags-optimizer/SKILL.md b/seo/meta-tags-optimizer/WORKFLOW.mdsimilarity index 99%rename from seo/meta-tags-optimizer/SKILL.mdrename to seo/meta-tags-optimizer/WORKFLOW.mdindex d74e3c56..ce292a59 100644--- a/seo/meta-tags-optimizer/SKILL.md+++ b/seo/meta-tags-optimizer/WORKFLOW.md@@ -310,4 +310,4 @@ _Complete meta tag block (with OG, Twitter, Article tags) generated using templa## Next Best Skill-- **Primary**: [schema-markup-generator](../schema-markup-generator/SKILL.md) — complete the SERP packaging with structured data.+- **Primary**: [schema-markup-generator](../schema-markup-generator/WORKFLOW.md) — complete the SERP packaging with structured data.diff --git a/seo/programmatic-seo/SKILL.md b/seo/programmatic-seo/WORKFLOW.mdsimilarity index 100%rename from seo/programmatic-seo/SKILL.mdrename to seo/programmatic-seo/WORKFLOW.mddiff --git a/seo/schema-markup-generator/SKILL.md b/seo/schema-markup-generator/WORKFLOW.mdsimilarity index 99%rename from seo/schema-markup-generator/SKILL.mdrename to seo/schema-markup-generator/WORKFLOW.mdindex eab47eaf..85661569 100644--- a/seo/schema-markup-generator/SKILL.md+++ b/seo/schema-markup-generator/WORKFLOW.md@@ -306,4 +306,4 @@ Learn SEO from scratch with our comprehensive guide...## Next Best Skill-- **Primary**: [seo-analysis](../seo-analysis/SKILL.md) — verify implementation with a technical SEO audit.+- **Primary**: [seo-analysis](../seo-analysis/WORKFLOW.md) — verify implementation with a technical SEO audit.diff --git a/seo/seo-analysis/SKILL.md b/seo/seo-analysis/WORKFLOW.mdsimilarity index 100%rename from seo/seo-analysis/SKILL.mdrename to seo/seo-analysis/WORKFLOW.mddiff --git a/seo/seo-drift/SKILL.md b/seo/seo-drift/WORKFLOW.mdsimilarity index 100%rename from seo/seo-drift/SKILL.mdrename to seo/seo-drift/WORKFLOW.mddiff --git a/seo/seo-page/SKILL.md b/seo/seo-page/WORKFLOW.mdsimilarity index 100%rename from seo/seo-page/SKILL.mdrename to seo/seo-page/WORKFLOW.mddiff --git a/seo/setup-cms/SKILL.md b/seo/setup-cms/WORKFLOW.mdsimilarity index 99%rename from seo/setup-cms/SKILL.mdrename to seo/setup-cms/WORKFLOW.mdindex 1d1142f3..8b8d98b9 100644--- a/seo/setup-cms/SKILL.md+++ b/seo/setup-cms/WORKFLOW.md@@ -9,11 +9,6 @@ description: >user says "connect my CMS", "set up WordPress", "configure Strapi", "addContentful", "connect Ghost", or "CMS setup". Also trigger if the user askswhy no CMS data appears in a seo-analysis report.-allowed-tools:- - Bash- - Read- - Write- - AskUserQuestion---# /setup-cmsdiff --git a/seo/sitemap-audit/SKILL.md b/seo/sitemap-audit/WORKFLOW.mdsimilarity index 100%rename from seo/sitemap-audit/SKILL.mdrename to seo/sitemap-audit/WORKFLOW.mddiff --git a/seo/sxo/SKILL.md b/seo/sxo/WORKFLOW.mdsimilarity index 100%rename from seo/sxo/SKILL.mdrename to seo/sxo/WORKFLOW.mddiff --git a/server.json b/server.jsonindex 26041c7e..2e0b6e4e 100644--- a/server.json+++ b/server.json@@ -8,7 +8,7 @@"url": "https://github.com/nowork-studio/notfair-plugin","source": "github"},- "version": "0.27.15",+ "version": "0.27.16","remotes": [{"type": "streamable-http",diff --git a/skills/backlink-audit/SKILL.md b/skills/backlink-audit/SKILL.mdindex 62e5de4a..1c27566b 100644--- a/skills/backlink-audit/SKILL.md+++ b/skills/backlink-audit/SKILL.md@@ -19,4 +19,4 @@ description: ># Canonical NotFair workflow-Read [`../../seo/backlink-audit/SKILL.md`](../../seo/backlink-audit/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/backlink-audit/`.+Read [`../../seo/backlink-audit/WORKFLOW.md`](../../seo/backlink-audit/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/backlink-audit/`.diff --git a/skills/broken-link-checker/SKILL.md b/skills/broken-link-checker/SKILL.mdindex 6559cbc5..99b16d9f 100644--- a/skills/broken-link-checker/SKILL.md+++ b/skills/broken-link-checker/SKILL.md@@ -10,4 +10,4 @@ description: ># Canonical NotFair workflow-Read [`../../seo/broken-link-checker/SKILL.md`](../../seo/broken-link-checker/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/broken-link-checker/`.+Read [`../../seo/broken-link-checker/WORKFLOW.md`](../../seo/broken-link-checker/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/broken-link-checker/`.diff --git a/skills/competitor-pages/SKILL.md b/skills/competitor-pages/SKILL.mdindex 2266456b..28039e6b 100644--- a/skills/competitor-pages/SKILL.md+++ b/skills/competitor-pages/SKILL.md@@ -20,4 +20,4 @@ description: ># Canonical NotFair workflow-Read [`../../seo/competitor-pages/SKILL.md`](../../seo/competitor-pages/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/competitor-pages/`.+Read [`../../seo/competitor-pages/WORKFLOW.md`](../../seo/competitor-pages/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/competitor-pages/`.diff --git a/skills/content-planner/SKILL.md b/skills/content-planner/SKILL.mdindex 449b86ff..f4fee447 100644--- a/skills/content-planner/SKILL.md+++ b/skills/content-planner/SKILL.md@@ -14,4 +14,4 @@ description: ># Canonical NotFair workflow-Read [`../../seo/content-planner/SKILL.md`](../../seo/content-planner/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/content-planner/`.+Read [`../../seo/content-planner/WORKFLOW.md`](../../seo/content-planner/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/content-planner/`.diff --git a/skills/content-writer/SKILL.md b/skills/content-writer/SKILL.mdindex 37d574c6..bcaf844d 100644--- a/skills/content-writer/SKILL.md+++ b/skills/content-writer/SKILL.md@@ -14,4 +14,4 @@ description: ># Canonical NotFair workflow-Read [`../../seo/content-writer/SKILL.md`](../../seo/content-writer/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/content-writer/`.+Read [`../../seo/content-writer/WORKFLOW.md`](../../seo/content-writer/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/content-writer/`.diff --git a/skills/ecommerce-seo/SKILL.md b/skills/ecommerce-seo/SKILL.mdindex 0f054bf8..ef7cd0a7 100644--- a/skills/ecommerce-seo/SKILL.md+++ b/skills/ecommerce-seo/SKILL.md@@ -18,4 +18,4 @@ description: ># Canonical NotFair workflow-Read [`../../seo/ecommerce-seo/SKILL.md`](../../seo/ecommerce-seo/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/ecommerce-seo/`.+Read [`../../seo/ecommerce-seo/WORKFLOW.md`](../../seo/ecommerce-seo/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/ecommerce-seo/`.diff --git a/skills/gemini/SKILL.md b/skills/gemini/SKILL.mdindex 1bad80a2..0f1f87d1 100644--- a/skills/gemini/SKILL.md+++ b/skills/gemini/SKILL.md@@ -28,4 +28,4 @@ triggers:# Canonical NotFair workflow-Read [`../../gemini/SKILL.md`](../../gemini/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../gemini/`.+Read [`../../gemini/WORKFLOW.md`](../../gemini/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../gemini/`.diff --git a/skills/geo-optimizer/SKILL.md b/skills/geo-optimizer/SKILL.mdindex 633957d8..3259cce4 100644--- a/skills/geo-optimizer/SKILL.md+++ b/skills/geo-optimizer/SKILL.md@@ -17,4 +17,4 @@ description: ># Canonical NotFair workflow-Read [`../../seo/geo-optimizer/SKILL.md`](../../seo/geo-optimizer/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/geo-optimizer/`.+Read [`../../seo/geo-optimizer/WORKFLOW.md`](../../seo/geo-optimizer/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/geo-optimizer/`.diff --git a/skills/gohighlevel/SKILL.md b/skills/gohighlevel/SKILL.mdindex 9c76eb48..51812cc6 100644--- a/skills/gohighlevel/SKILL.md+++ b/skills/gohighlevel/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<location, contact, opportunity, or GHL question>"# Canonical NotFair workflow-Read [`../../gohighlevel/SKILL.md`](../../gohighlevel/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/gohighlevel/SKILL.md`, not `<plugin-root>/skills/gohighlevel/gohighlevel/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/gohighlevel/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../gohighlevel/WORKFLOW.md`](../../gohighlevel/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/gohighlevel/WORKFLOW.md`, not `<plugin-root>/skills/gohighlevel/gohighlevel/WORKFLOW.md`. Resolve every relative reference from the canonical file against `<plugin-root>/gohighlevel/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/google-ads-assets/SKILL.md b/skills/google-ads-assets/SKILL.mdindex bd978db5..9086311c 100644--- a/skills/google-ads-assets/SKILL.md+++ b/skills/google-ads-assets/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<campaign, asset group, or 'build an asset brief'>"# Canonical NotFair workflow-Read [`../../google-ads/assets/SKILL.md`](../../google-ads/assets/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/google-ads/assets/SKILL.md`, not `<plugin-root>/skills/google-ads-assets/assets/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/google-ads/assets/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../google-ads/assets/WORKFLOW.md`](../../google-ads/assets/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/google-ads/assets/WORKFLOW.md`, not `<plugin-root>/skills/google-ads-assets/assets/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/google-ads/assets/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/google-ads-audit/SKILL.md b/skills/google-ads-audit/SKILL.mdindex 43f8ec02..d2d25916 100644--- a/skills/google-ads-audit/SKILL.md+++ b/skills/google-ads-audit/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<account name or 'audit my ads'>"# Canonical NotFair workflow-Read [`../../google-ads/audit/SKILL.md`](../../google-ads/audit/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/google-ads/audit/SKILL.md`, not `<plugin-root>/skills/google-ads-audit/audit/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/google-ads/audit/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../google-ads/audit/WORKFLOW.md`](../../google-ads/audit/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/google-ads/audit/WORKFLOW.md`, not `<plugin-root>/skills/google-ads-audit/audit/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/google-ads/audit/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/google-ads-copy/SKILL.md b/skills/google-ads-copy/SKILL.mdindex a6ce268f..90549aee 100644--- a/skills/google-ads-copy/SKILL.md+++ b/skills/google-ads-copy/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<ad group name, keyword theme, or 'write new ads'>"# Canonical NotFair workflow-Read [`../../google-ads/copy/SKILL.md`](../../google-ads/copy/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/google-ads/copy/SKILL.md`, not `<plugin-root>/skills/google-ads-copy/copy/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/google-ads/copy/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../google-ads/copy/WORKFLOW.md`](../../google-ads/copy/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/google-ads/copy/WORKFLOW.md`, not `<plugin-root>/skills/google-ads-copy/copy/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/google-ads/copy/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/google-ads-landing/SKILL.md b/skills/google-ads-landing/SKILL.mdindex e857f204..606d0ce5 100644--- a/skills/google-ads-landing/SKILL.md+++ b/skills/google-ads-landing/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<landing page URL or ad group name>"# Canonical NotFair workflow-Read [`../../google-ads/landing/SKILL.md`](../../google-ads/landing/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/google-ads/landing/SKILL.md`, not `<plugin-root>/skills/google-ads-landing/landing/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/google-ads/landing/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../google-ads/landing/WORKFLOW.md`](../../google-ads/landing/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/google-ads/landing/WORKFLOW.md`, not `<plugin-root>/skills/google-ads-landing/landing/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/google-ads/landing/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/google-ads/SKILL.md b/skills/google-ads/SKILL.mdindex 1504df18..b4c7b006 100644--- a/skills/google-ads/SKILL.md+++ b/skills/google-ads/SKILL.md@@ -37,4 +37,4 @@ triggers:# Canonical NotFair workflow-Read [`../../google-ads/manage/SKILL.md`](../../google-ads/manage/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/google-ads/manage/SKILL.md`, not `<plugin-root>/skills/google-ads/manage/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/google-ads/manage/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../google-ads/manage/WORKFLOW.md`](../../google-ads/manage/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/google-ads/manage/WORKFLOW.md`, not `<plugin-root>/skills/google-ads/manage/WORKFLOW.md`. Resolve every relative reference from the canonical file against `<plugin-root>/google-ads/manage/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/google-analytics/SKILL.md b/skills/google-analytics/SKILL.mdindex aeaa7fa8..cba61716 100644--- a/skills/google-analytics/SKILL.md+++ b/skills/google-analytics/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<property, date range, metric, or GA4 question>"# Canonical NotFair workflow-Read [`../../analytics/google-analytics/SKILL.md`](../../analytics/google-analytics/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../analytics/google-analytics/`.+Read [`../../analytics/google-analytics/WORKFLOW.md`](../../analytics/google-analytics/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../analytics/google-analytics/`.diff --git a/skills/hreflang-international/SKILL.md b/skills/hreflang-international/SKILL.mdindex fcebfce7..94a051af 100644--- a/skills/hreflang-international/SKILL.md+++ b/skills/hreflang-international/SKILL.md@@ -19,4 +19,4 @@ description: ># Canonical NotFair workflow-Read [`../../seo/hreflang-international/SKILL.md`](../../seo/hreflang-international/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/hreflang-international/`.+Read [`../../seo/hreflang-international/WORKFLOW.md`](../../seo/hreflang-international/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/hreflang-international/`.diff --git a/skills/image-seo/SKILL.md b/skills/image-seo/SKILL.mdindex f16d34fd..a19d8ad4 100644--- a/skills/image-seo/SKILL.md+++ b/skills/image-seo/SKILL.md@@ -18,4 +18,4 @@ description: ># Canonical NotFair workflow-Read [`../../seo/image-seo/SKILL.md`](../../seo/image-seo/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/image-seo/`.+Read [`../../seo/image-seo/WORKFLOW.md`](../../seo/image-seo/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/image-seo/`.diff --git a/skills/keyword-research/SKILL.md b/skills/keyword-research/SKILL.mdindex db882cf6..ae3b3542 100644--- a/skills/keyword-research/SKILL.md+++ b/skills/keyword-research/SKILL.md@@ -14,4 +14,4 @@ description: ># Canonical NotFair workflow-Read [`../../seo/keyword-research/SKILL.md`](../../seo/keyword-research/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/keyword-research/`.+Read [`../../seo/keyword-research/WORKFLOW.md`](../../seo/keyword-research/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/keyword-research/`.diff --git a/skills/local-seo/SKILL.md b/skills/local-seo/SKILL.mdindex 14c6f90d..0d15650c 100644--- a/skills/local-seo/SKILL.md+++ b/skills/local-seo/SKILL.md@@ -18,4 +18,4 @@ description: ># Canonical NotFair workflow-Read [`../../seo/local-seo/SKILL.md`](../../seo/local-seo/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/local-seo/`.+Read [`../../seo/local-seo/WORKFLOW.md`](../../seo/local-seo/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/local-seo/`.diff --git a/skills/meta-ads-audit/SKILL.md b/skills/meta-ads-audit/SKILL.mdindex fbcd9eff..8d165ef0 100644--- a/skills/meta-ads-audit/SKILL.md+++ b/skills/meta-ads-audit/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<account name or 'audit my Meta ads'>"# Canonical NotFair workflow-Read [`../../meta-ads/audit/SKILL.md`](../../meta-ads/audit/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/meta-ads/audit/SKILL.md`, not `<plugin-root>/skills/meta-ads-audit/audit/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/meta-ads/audit/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../meta-ads/audit/WORKFLOW.md`](../../meta-ads/audit/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/meta-ads/audit/WORKFLOW.md`, not `<plugin-root>/skills/meta-ads-audit/audit/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/meta-ads/audit/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/meta-ads-creative/SKILL.md b/skills/meta-ads-creative/SKILL.mdindex 3853476e..024d2402 100644--- a/skills/meta-ads-creative/SKILL.md+++ b/skills/meta-ads-creative/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<campaign, audience, or 'build a creative slate'>"# Canonical NotFair workflow-Read [`../../meta-ads/creative/SKILL.md`](../../meta-ads/creative/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/meta-ads/creative/SKILL.md`, not `<plugin-root>/skills/meta-ads-creative/creative/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/meta-ads/creative/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../meta-ads/creative/WORKFLOW.md`](../../meta-ads/creative/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/meta-ads/creative/WORKFLOW.md`, not `<plugin-root>/skills/meta-ads-creative/creative/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/meta-ads/creative/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/meta-ads/SKILL.md b/skills/meta-ads/SKILL.mdindex 9f4d5c55..de415ca6 100644--- a/skills/meta-ads/SKILL.md+++ b/skills/meta-ads/SKILL.md@@ -29,4 +29,4 @@ triggers:# Canonical NotFair workflow-Read [`../../meta-ads/manage/SKILL.md`](../../meta-ads/manage/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/meta-ads/manage/SKILL.md`, not `<plugin-root>/skills/meta-ads/manage/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/meta-ads/manage/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../meta-ads/manage/WORKFLOW.md`](../../meta-ads/manage/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/meta-ads/manage/WORKFLOW.md`, not `<plugin-root>/skills/meta-ads/manage/WORKFLOW.md`. Resolve every relative reference from the canonical file against `<plugin-root>/meta-ads/manage/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/meta-tags-optimizer/SKILL.md b/skills/meta-tags-optimizer/SKILL.mdindex 9d1ee9a6..81ea6c81 100644--- a/skills/meta-tags-optimizer/SKILL.md+++ b/skills/meta-tags-optimizer/SKILL.md@@ -12,4 +12,4 @@ description: ># Canonical NotFair workflow-Read [`../../seo/meta-tags-optimizer/SKILL.md`](../../seo/meta-tags-optimizer/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/meta-tags-optimizer/`.+Read [`../../seo/meta-tags-optimizer/WORKFLOW.md`](../../seo/meta-tags-optimizer/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/meta-tags-optimizer/`.diff --git a/skills/paid-ads-amazon/SKILL.md b/skills/paid-ads-amazon/SKILL.mdindex 14fb75ee..6385df8c 100644--- a/skills/paid-ads-amazon/SKILL.md+++ b/skills/paid-ads-amazon/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<ASIN, product line, target ACoS, or Amazon export>"# Canonical NotFair workflow-Read [`../../paid-ads/paid-ads-amazon/SKILL.md`](../../paid-ads/paid-ads-amazon/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-amazon/SKILL.md`, not `<plugin-root>/skills/paid-ads-amazon/paid-ads-amazon/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-amazon/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../paid-ads/paid-ads-amazon/WORKFLOW.md`](../../paid-ads/paid-ads-amazon/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-amazon/WORKFLOW.md`, not `<plugin-root>/skills/paid-ads-amazon/paid-ads-amazon/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-amazon/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/paid-ads-chatgpt/SKILL.md b/skills/paid-ads-chatgpt/SKILL.mdindex 2c17e709..7219c16b 100644--- a/skills/paid-ads-chatgpt/SKILL.md+++ b/skills/paid-ads-chatgpt/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<objective, audience, or verified ChatGPT Ads export>"# Canonical NotFair workflow-Read [`../../paid-ads/paid-ads-chatgpt/SKILL.md`](../../paid-ads/paid-ads-chatgpt/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-chatgpt/SKILL.md`, not `<plugin-root>/skills/paid-ads-chatgpt/paid-ads-chatgpt/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-chatgpt/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../paid-ads/paid-ads-chatgpt/WORKFLOW.md`](../../paid-ads/paid-ads-chatgpt/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-chatgpt/WORKFLOW.md`, not `<plugin-root>/skills/paid-ads-chatgpt/paid-ads-chatgpt/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-chatgpt/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/paid-ads-creative/SKILL.md b/skills/paid-ads-creative/SKILL.mdindex 15b3bfde..e5b91bcd 100644--- a/skills/paid-ads-creative/SKILL.md+++ b/skills/paid-ads-creative/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<platform, audience, or campaign>"# Canonical NotFair workflow-Read [`../../paid-ads/paid-ads-creative/SKILL.md`](../../paid-ads/paid-ads-creative/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-creative/SKILL.md`, not `<plugin-root>/skills/paid-ads-creative/paid-ads-creative/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-creative/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../paid-ads/paid-ads-creative/WORKFLOW.md`](../../paid-ads/paid-ads-creative/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-creative/WORKFLOW.md`, not `<plugin-root>/skills/paid-ads-creative/paid-ads-creative/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-creative/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/paid-ads-guide/SKILL.md b/skills/paid-ads-guide/SKILL.mdindex 48adc287..5416b8ae 100644--- a/skills/paid-ads-guide/SKILL.md+++ b/skills/paid-ads-guide/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<installation, capability, connection, or product question>"# Canonical NotFair workflow-Read [`../../paid-ads/paid-ads-guide/SKILL.md`](../../paid-ads/paid-ads-guide/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-guide/SKILL.md`, not `<plugin-root>/skills/paid-ads-guide/paid-ads-guide/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-guide/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../paid-ads/paid-ads-guide/WORKFLOW.md`](../../paid-ads/paid-ads-guide/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-guide/WORKFLOW.md`, not `<plugin-root>/skills/paid-ads-guide/paid-ads-guide/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-guide/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/paid-ads-integrations/SKILL.md b/skills/paid-ads-integrations/SKILL.mdindex 76e5ec61..7da7651b 100644--- a/skills/paid-ads-integrations/SKILL.md+++ b/skills/paid-ads-integrations/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<platform or connection issue>"# Canonical NotFair workflow-Read [`../../paid-ads/paid-ads-integrations/SKILL.md`](../../paid-ads/paid-ads-integrations/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-integrations/SKILL.md`, not `<plugin-root>/skills/paid-ads-integrations/paid-ads-integrations/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-integrations/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../paid-ads/paid-ads-integrations/WORKFLOW.md`](../../paid-ads/paid-ads-integrations/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-integrations/WORKFLOW.md`, not `<plugin-root>/skills/paid-ads-integrations/paid-ads-integrations/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-integrations/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/paid-ads-launch/SKILL.md b/skills/paid-ads-launch/SKILL.mdindex d0081d2b..d2399a40 100644--- a/skills/paid-ads-launch/SKILL.md+++ b/skills/paid-ads-launch/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<business goal, budget, and target platform>"# Canonical NotFair workflow-Read [`../../paid-ads/paid-ads-launch/SKILL.md`](../../paid-ads/paid-ads-launch/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-launch/SKILL.md`, not `<plugin-root>/skills/paid-ads-launch/paid-ads-launch/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-launch/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../paid-ads/paid-ads-launch/WORKFLOW.md`](../../paid-ads/paid-ads-launch/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-launch/WORKFLOW.md`, not `<plugin-root>/skills/paid-ads-launch/paid-ads-launch/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-launch/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/paid-ads-linkedin/SKILL.md b/skills/paid-ads-linkedin/SKILL.mdindex 9e6e830a..708de1ce 100644--- a/skills/paid-ads-linkedin/SKILL.md+++ b/skills/paid-ads-linkedin/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<B2B goal, audience, account, or date range>"# Canonical NotFair workflow-Read [`../../paid-ads/paid-ads-linkedin/SKILL.md`](../../paid-ads/paid-ads-linkedin/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-linkedin/SKILL.md`, not `<plugin-root>/skills/paid-ads-linkedin/paid-ads-linkedin/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-linkedin/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../paid-ads/paid-ads-linkedin/WORKFLOW.md`](../../paid-ads/paid-ads-linkedin/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-linkedin/WORKFLOW.md`, not `<plugin-root>/skills/paid-ads-linkedin/paid-ads-linkedin/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-linkedin/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/paid-ads-optimize/SKILL.md b/skills/paid-ads-optimize/SKILL.mdindex ab2ea7fd..cf2f08c4 100644--- a/skills/paid-ads-optimize/SKILL.md+++ b/skills/paid-ads-optimize/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<campaign, target CPA/ROAS, or 'find waste'>"# Canonical NotFair workflow-Read [`../../paid-ads/paid-ads-optimize/SKILL.md`](../../paid-ads/paid-ads-optimize/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-optimize/SKILL.md`, not `<plugin-root>/skills/paid-ads-optimize/paid-ads-optimize/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-optimize/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../paid-ads/paid-ads-optimize/WORKFLOW.md`](../../paid-ads/paid-ads-optimize/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-optimize/WORKFLOW.md`, not `<plugin-root>/skills/paid-ads-optimize/paid-ads-optimize/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-optimize/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/paid-ads-reddit/SKILL.md b/skills/paid-ads-reddit/SKILL.mdindex a59696e2..c16fd95c 100644--- a/skills/paid-ads-reddit/SKILL.md+++ b/skills/paid-ads-reddit/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<account, campaign, date range, or Reddit Ads goal>"# Canonical NotFair workflow-Read [`../../paid-ads/paid-ads-reddit/SKILL.md`](../../paid-ads/paid-ads-reddit/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-reddit/SKILL.md`, not `<plugin-root>/skills/paid-ads-reddit/paid-ads-reddit/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-reddit/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../paid-ads/paid-ads-reddit/WORKFLOW.md`](../../paid-ads/paid-ads-reddit/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-reddit/WORKFLOW.md`, not `<plugin-root>/skills/paid-ads-reddit/paid-ads-reddit/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-reddit/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/paid-ads-review/SKILL.md b/skills/paid-ads-review/SKILL.mdindex ab7e7c8e..0da3213f 100644--- a/skills/paid-ads-review/SKILL.md+++ b/skills/paid-ads-review/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<date range, platform, or 'weekly review'>"# Canonical NotFair workflow-Read [`../../paid-ads/paid-ads-review/SKILL.md`](../../paid-ads/paid-ads-review/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-review/SKILL.md`, not `<plugin-root>/skills/paid-ads-review/paid-ads-review/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-review/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../paid-ads/paid-ads-review/WORKFLOW.md`](../../paid-ads/paid-ads-review/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-review/WORKFLOW.md`, not `<plugin-root>/skills/paid-ads-review/paid-ads-review/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-review/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/paid-ads-setup/SKILL.md b/skills/paid-ads-setup/SKILL.mdindex 6cd065a0..ac2f3c36 100644--- a/skills/paid-ads-setup/SKILL.md+++ b/skills/paid-ads-setup/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<connect accounts, workspace, or brand>"# Canonical NotFair workflow-Read [`../../paid-ads/paid-ads-setup/SKILL.md`](../../paid-ads/paid-ads-setup/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-setup/SKILL.md`, not `<plugin-root>/skills/paid-ads-setup/paid-ads-setup/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-setup/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../paid-ads/paid-ads-setup/WORKFLOW.md`](../../paid-ads/paid-ads-setup/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-setup/WORKFLOW.md`, not `<plugin-root>/skills/paid-ads-setup/paid-ads-setup/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-setup/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/paid-ads-tiktok/SKILL.md b/skills/paid-ads-tiktok/SKILL.mdindex d1b0ba63..6f9ca7a9 100644--- a/skills/paid-ads-tiktok/SKILL.md+++ b/skills/paid-ads-tiktok/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<account, campaign, date range, or TikTok Ads goal>"# Canonical NotFair workflow-Read [`../../paid-ads/paid-ads-tiktok/SKILL.md`](../../paid-ads/paid-ads-tiktok/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-tiktok/SKILL.md`, not `<plugin-root>/skills/paid-ads-tiktok/paid-ads-tiktok/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-tiktok/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../paid-ads/paid-ads-tiktok/WORKFLOW.md`](../../paid-ads/paid-ads-tiktok/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-tiktok/WORKFLOW.md`, not `<plugin-root>/skills/paid-ads-tiktok/paid-ads-tiktok/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-tiktok/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/paid-ads-x/SKILL.md b/skills/paid-ads-x/SKILL.mdindex 513cdd02..511969c9 100644--- a/skills/paid-ads-x/SKILL.md+++ b/skills/paid-ads-x/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<account, campaign, date range, or X Ads goal>"# Canonical NotFair workflow-Read [`../../paid-ads/paid-ads-x/SKILL.md`](../../paid-ads/paid-ads-x/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-x/SKILL.md`, not `<plugin-root>/skills/paid-ads-x/paid-ads-x/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-x/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../paid-ads/paid-ads-x/WORKFLOW.md`](../../paid-ads/paid-ads-x/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads-x/WORKFLOW.md`, not `<plugin-root>/skills/paid-ads-x/paid-ads-x/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads-x/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/paid-ads/SKILL.md b/skills/paid-ads/SKILL.mdindex 8186933a..1ef4ce9b 100644--- a/skills/paid-ads/SKILL.md+++ b/skills/paid-ads/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<goal, platform, or 'review my ads'>"# Canonical NotFair workflow-Read [`../../paid-ads/paid-ads/SKILL.md`](../../paid-ads/paid-ads/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads/SKILL.md`, not `<plugin-root>/skills/paid-ads/paid-ads/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../paid-ads/paid-ads/WORKFLOW.md`](../../paid-ads/paid-ads/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/paid-ads/paid-ads/WORKFLOW.md`, not `<plugin-root>/skills/paid-ads/paid-ads/WORKFLOW.md`. Resolve every relative reference from the canonical file against `<plugin-root>/paid-ads/paid-ads/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/skills/programmatic-seo/SKILL.md b/skills/programmatic-seo/SKILL.mdindex bb730199..9a3943e6 100644--- a/skills/programmatic-seo/SKILL.md+++ b/skills/programmatic-seo/SKILL.md@@ -18,4 +18,4 @@ description: ># Canonical NotFair workflow-Read [`../../seo/programmatic-seo/SKILL.md`](../../seo/programmatic-seo/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/programmatic-seo/`.+Read [`../../seo/programmatic-seo/WORKFLOW.md`](../../seo/programmatic-seo/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/programmatic-seo/`.diff --git a/skills/schema-markup-generator/SKILL.md b/skills/schema-markup-generator/SKILL.mdindex eba3cc5b..2796dc3c 100644--- a/skills/schema-markup-generator/SKILL.md+++ b/skills/schema-markup-generator/SKILL.md@@ -12,4 +12,4 @@ description: ># Canonical NotFair workflow-Read [`../../seo/schema-markup-generator/SKILL.md`](../../seo/schema-markup-generator/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/schema-markup-generator/`.+Read [`../../seo/schema-markup-generator/WORKFLOW.md`](../../seo/schema-markup-generator/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/schema-markup-generator/`.diff --git a/skills/search-console/SKILL.md b/skills/search-console/SKILL.mdindex 4daae909..2cf5e417 100644--- a/skills/search-console/SKILL.md+++ b/skills/search-console/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<property, URL, query, date range, or sitemap>"# Canonical NotFair workflow-Read [`../../analytics/search-console/SKILL.md`](../../analytics/search-console/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../analytics/search-console/`.+Read [`../../analytics/search-console/WORKFLOW.md`](../../analytics/search-console/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../analytics/search-console/`.diff --git a/skills/seo-analysis/SKILL.md b/skills/seo-analysis/SKILL.mdindex 3d73ccfc..f1274d73 100644--- a/skills/seo-analysis/SKILL.md+++ b/skills/seo-analysis/SKILL.md@@ -18,4 +18,4 @@ description: ># Canonical NotFair workflow-Read [`../../seo/seo-analysis/SKILL.md`](../../seo/seo-analysis/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/seo-analysis/`.+Read [`../../seo/seo-analysis/WORKFLOW.md`](../../seo/seo-analysis/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/seo-analysis/`.diff --git a/skills/seo-drift/SKILL.md b/skills/seo-drift/SKILL.mdindex 50b020a6..1a8ee09c 100644--- a/skills/seo-drift/SKILL.md+++ b/skills/seo-drift/SKILL.md@@ -19,4 +19,4 @@ description: ># Canonical NotFair workflow-Read [`../../seo/seo-drift/SKILL.md`](../../seo/seo-drift/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/seo-drift/`.+Read [`../../seo/seo-drift/WORKFLOW.md`](../../seo/seo-drift/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/seo-drift/`.diff --git a/skills/seo-page/SKILL.md b/skills/seo-page/SKILL.mdindex b4008495..fc2b13be 100644--- a/skills/seo-page/SKILL.md+++ b/skills/seo-page/SKILL.md@@ -18,4 +18,4 @@ description: ># Canonical NotFair workflow-Read [`../../seo/seo-page/SKILL.md`](../../seo/seo-page/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/seo-page/`.+Read [`../../seo/seo-page/WORKFLOW.md`](../../seo/seo-page/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/seo-page/`.diff --git a/skills/setup-cms/SKILL.md b/skills/setup-cms/SKILL.mdindex 20dee7e2..f2f0822f 100644--- a/skills/setup-cms/SKILL.md+++ b/skills/setup-cms/SKILL.md@@ -9,13 +9,8 @@ description: >user says "connect my CMS", "set up WordPress", "configure Strapi", "addContentful", "connect Ghost", or "CMS setup". Also trigger if the user askswhy no CMS data appears in a seo-analysis report.-allowed-tools:- - Bash- - Read- - Write- - AskUserQuestion---# Canonical NotFair workflow-Read [`../../seo/setup-cms/SKILL.md`](../../seo/setup-cms/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/setup-cms/`.+Read [`../../seo/setup-cms/WORKFLOW.md`](../../seo/setup-cms/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/setup-cms/`.diff --git a/skills/sitemap-audit/SKILL.md b/skills/sitemap-audit/SKILL.mdindex 637ecb3d..42103003 100644--- a/skills/sitemap-audit/SKILL.md+++ b/skills/sitemap-audit/SKILL.md@@ -19,4 +19,4 @@ description: ># Canonical NotFair workflow-Read [`../../seo/sitemap-audit/SKILL.md`](../../seo/sitemap-audit/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/sitemap-audit/`.+Read [`../../seo/sitemap-audit/WORKFLOW.md`](../../seo/sitemap-audit/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/sitemap-audit/`.diff --git a/skills/sxo/SKILL.md b/skills/sxo/SKILL.mdindex d3d08e9e..fbdf23de 100644--- a/skills/sxo/SKILL.md+++ b/skills/sxo/SKILL.md@@ -19,4 +19,4 @@ description: ># Canonical NotFair workflow-Read [`../../seo/sxo/SKILL.md`](../../seo/sxo/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/sxo/`.+Read [`../../seo/sxo/WORKFLOW.md`](../../seo/sxo/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../seo/sxo/`.diff --git a/skills/upgrade/SKILL.md b/skills/upgrade/SKILL.mdindex 1abd1ae6..8f8f0ef0 100644--- a/skills/upgrade/SKILL.md+++ b/skills/upgrade/SKILL.md@@ -6,12 +6,8 @@ description: >installs the new version to the plugin cache, and updates installed_plugins.json.Use when asked to "upgrade notfair", "update notfair", or "get latest version".Also handles inline upgrade prompts when a skill detects UPGRADE_AVAILABLE at startup.-allowed-tools:- - Bash- - Read- - AskUserQuestion---# Canonical NotFair workflow-Read [`../../notfair-upgrade-skill/SKILL.md`](../../notfair-upgrade-skill/SKILL.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../notfair-upgrade-skill/`.+Read [`../../notfair-upgrade-skill/WORKFLOW.md`](../../notfair-upgrade-skill/WORKFLOW.md) completely, then follow it as the active workflow. Resolve every relative reference from that file against `../../notfair-upgrade-skill/`.diff --git a/skills/wordpress/SKILL.md b/skills/wordpress/SKILL.mdindex d43dd669..bbc4f358 100644--- a/skills/wordpress/SKILL.md+++ b/skills/wordpress/SKILL.md@@ -6,4 +6,4 @@ argument-hint: "<site, content, plugin, or WordPress change>"# Canonical NotFair workflow-Read [`../../wordpress/SKILL.md`](../../wordpress/SKILL.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/wordpress/SKILL.md`, not `<plugin-root>/skills/wordpress/wordpress/SKILL.md`. Resolve every relative reference from the canonical file against `<plugin-root>/wordpress/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.+Read [`../../wordpress/WORKFLOW.md`](../../wordpress/WORKFLOW.md) completely, then follow it as the active workflow. Normalize that path from the directory containing this wrapper: the canonical file is `<plugin-root>/wordpress/WORKFLOW.md`, not `<plugin-root>/skills/wordpress/wordpress/WORKFLOW.md`. Resolve every relative reference from the canonical file against `<plugin-root>/wordpress/`. If the canonical file cannot be read, stop and report the packaging error; never substitute a similarly named skill from another plugin.diff --git a/test/helpers/session_runner.py b/test/helpers/session_runner.pyindex 00ccc708..0278bc03 100644--- a/test/helpers/session_runner.py+++ b/test/helpers/session_runner.py@@ -87,6 +87,9 @@ def create_skill_workdir(skill_path: str, skill_name: str) -> str:tmpdir = tempfile.mkdtemp(prefix=f'notfair-test-')dest = os.path.join(tmpdir, '.claude', 'skills', skill_name)shutil.copytree(skill_path, dest)+ workflow = os.path.join(dest, "WORKFLOW.md")+ if os.path.isfile(workflow):+ shutil.copyfile(workflow, os.path.join(dest, "SKILL.md"))return tmpdirdiff --git a/test/helpers/touchfiles.py b/test/helpers/touchfiles.pyindex 334de1d2..a4794a54 100644--- a/test/helpers/touchfiles.py+++ b/test/helpers/touchfiles.py@@ -24,11 +24,11 @@ LLM_JUDGE_TOUCHFILES: dict[str, list[str]] = {}ADS_LLM_JUDGE_TOUCHFILES: dict[str, list[str]] = {- 'ads-heuristics-clarity': ['google-ads/manage/SKILL.md', 'google-ads/manage/references/**'],- 'ads-workflows-clarity': ['google-ads/manage/SKILL.md'],- 'ads-audit-scoring-clarity': ['google-ads/audit/SKILL.md', 'google-ads/audit/references/**'],- 'ads-audit-report-clarity': ['google-ads/audit/SKILL.md'],- 'ads-copy-formulas-clarity': ['google-ads/copy/SKILL.md', 'google-ads/copy/references/**'],+ 'ads-heuristics-clarity': ['google-ads/manage/WORKFLOW.md', 'google-ads/manage/references/**'],+ 'ads-workflows-clarity': ['google-ads/manage/WORKFLOW.md'],+ 'ads-audit-scoring-clarity': ['google-ads/audit/WORKFLOW.md', 'google-ads/audit/references/**'],+ 'ads-audit-report-clarity': ['google-ads/audit/WORKFLOW.md'],+ 'ads-copy-formulas-clarity': ['google-ads/copy/WORKFLOW.md', 'google-ads/copy/references/**'],}ROUTING_TOUCHFILES: dict[str, list[str]] = {diff --git a/test/install.test.sh b/test/install.test.shindex ac8aa703..e7461856 100755--- a/test/install.test.sh+++ b/test/install.test.sh@@ -192,11 +192,11 @@ for entry in "${SKILL_ENTRIES[@]}"; doskill=$(skill_name "$entry")path=$(skill_path "$entry")assert_dir "$REPO_ROOT/$path" "skill directory: $skill ($path)"- assert_file "$REPO_ROOT/$path/SKILL.md" "SKILL.md exists: $skill"+ assert_file "$REPO_ROOT/$path/WORKFLOW.md" "SKILL.md exists: $skill"done# Guard: actual SKILL.md count must match-actual_skill_count=$(find "$REPO_ROOT/paid-ads" "$REPO_ROOT/google-ads" "$REPO_ROOT/seo" "$REPO_ROOT/meta-ads" "$REPO_ROOT/analytics" "$REPO_ROOT/wordpress" "$REPO_ROOT/gohighlevel" "$REPO_ROOT/notfair-upgrade-skill" "$REPO_ROOT/gemini" -name "SKILL.md" | wc -l | tr -d ' ')+actual_skill_count=$(find "$REPO_ROOT/paid-ads" "$REPO_ROOT/google-ads" "$REPO_ROOT/seo" "$REPO_ROOT/meta-ads" "$REPO_ROOT/analytics" "$REPO_ROOT/wordpress" "$REPO_ROOT/gohighlevel" "$REPO_ROOT/notfair-upgrade-skill" "$REPO_ROOT/gemini" -name "WORKFLOW.md" | wc -l | tr -d ' ')if [ "$actual_skill_count" -ne "${#SKILL_ENTRIES[@]}" ]; thenfail "Expected ${#SKILL_ENTRIES[@]} SKILL.md files but found $actual_skill_count"else@@ -212,10 +212,10 @@ echo "=== 3. Legacy structure + helpers ==="&& pass "setup script removed" \|| fail "setup script still exists (should be deleted)"-assert_dir "$REPO_ROOT/bin" "bin/ helper directory exists"-assert_file "$REPO_ROOT/bin/notfair-config" "bin/notfair-config exists"-assert_file "$REPO_ROOT/bin/notfair-update-check" "bin/notfair-update-check exists"-assert_file "$REPO_ROOT/bin/notfair-change-watch" "bin/notfair-change-watch exists"+assert_dir "$REPO_ROOT/scripts" "scripts/ readable helper directory exists"+assert_file "$REPO_ROOT/scripts/notfair-config.sh" "scripts/notfair-config.sh exists"+assert_file "$REPO_ROOT/scripts/notfair-update-check.sh" "scripts/notfair-update-check.sh exists"+assert_file "$REPO_ROOT/scripts/notfair-change-watch.sh" "scripts/notfair-change-watch.sh exists"# Old toprank-* bin names must not coexist (0.24.0 rename should be clean)[ ! -f "$REPO_ROOT/bin/toprank-config" ] \@@ -241,7 +241,7 @@ for entry in "${SKILL_ENTRIES[@]}"; dopath=$(skill_path "$entry")wrapper="$REPO_ROOT/skills/$skill/SKILL.md"assert_file "$wrapper" "Codex skill wrapper: $skill"- assert_contains "$wrapper" "../../$path/SKILL.md" "Codex skill wrapper forwards $skill to $path"+ assert_contains "$wrapper" "../../$path/WORKFLOW.md" "Codex skill wrapper forwards $skill to $path"done[ ! -d "$REPO_ROOT/.agents" ] \@@ -260,18 +260,18 @@ assert_file "$REPO_ROOT/analytics/shared/operating-contract.md" "Analytics share# Ads skills reference the shared preamble (not inline MCP detection)for skill in manage audit copy assets; do- assert_contains "$REPO_ROOT/google-ads/$skill/SKILL.md" "../shared/preamble.md" \+ assert_contains "$REPO_ROOT/google-ads/$skill/WORKFLOW.md" "../shared/preamble.md" \"google-ads/$skill references shared preamble"- assert_not_contains "$REPO_ROOT/google-ads/$skill/SKILL.md" "mcp__notfair__listConnectedAccounts" \+ assert_not_contains "$REPO_ROOT/google-ads/$skill/WORKFLOW.md" "mcp__notfair__listConnectedAccounts" \"google-ads/$skill does not inline MCP detection (notfair prefix)"done-assert_contains "$REPO_ROOT/meta-ads/creative/SKILL.md" "../shared/preamble.md" \+assert_contains "$REPO_ROOT/meta-ads/creative/WORKFLOW.md" "../shared/preamble.md" \"meta-ads/creative references shared preamble"# SEO skills that need GSC reference the shared preamblefor skill in seo-analysis setup-cms; do- assert_contains "$REPO_ROOT/seo/$skill/SKILL.md" "../shared/preamble.md" \+ assert_contains "$REPO_ROOT/seo/$skill/WORKFLOW.md" "../shared/preamble.md" \"$skill references shared preamble"done@@ -345,7 +345,7 @@ echo "=== 9. Argument hints ==="for entry in "${SKILL_ENTRIES[@]}"; doskill=$(skill_name "$entry")path=$(skill_path "$entry")- assert_contains "$REPO_ROOT/$path/SKILL.md" "argument-hint" \+ assert_contains "$REPO_ROOT/$path/WORKFLOW.md" "argument-hint" \"$skill has argument-hint in frontmatter"donediff --git a/test/test_mcp_skill_e2e.py b/test/test_mcp_skill_e2e.pyindex 07163446..394665a4 100644--- a/test/test_mcp_skill_e2e.py+++ b/test/test_mcp_skill_e2e.py@@ -47,49 +47,36 @@ def test_universal_mcp_is_the_only_registered_server_and_skills_are_portable():assert codex_plugin["mcpServers"] == "./.mcp.json"assert codex_plugin["version"] == plugin["version"]- codex_wrappers = {path.name: path for path in (ROOT / "skills").iterdir()}- assert len(codex_wrappers) == len(plugin["skills"])- for skill in plugin["skills"]:- canonical = (ROOT / skill).resolve()- canonical_text = (canonical / "SKILL.md").read_text()- skill_name = re.search(r"^name:\s*(.+)$", canonical_text, re.MULTILINE)- assert skill_name, skill- wrapper = codex_wrappers[skill_name.group(1).strip()]- assert wrapper.is_dir() and not wrapper.is_symlink()- wrapper_text = (wrapper / "SKILL.md").read_text()- assert wrapper_text.split("---\n", 2)[1] == canonical_text.split("---\n", 2)[1]- canonical_rel = canonical.relative_to(ROOT).as_posix()- assert f"../../{canonical_rel}/SKILL.md" in wrapper_text+ entries = sorted((ROOT / "skills").glob("*/SKILL.md"))+ assert len(entries) == len(plugin["skills"]) == 48+ assert {"./" + p.parent.relative_to(ROOT).as_posix() for p in entries} == set(plugin["skills"])+ names = []+ for entry in entries:+ entry_text = entry.read_text()+ name = re.search(r"^name:\s*(.+)$", entry_text, re.MULTILINE).group(1).strip()+ names.append(name.casefold())+ target = re.search(r"\]\((\.\./\.\./[^)]+/WORKFLOW\.md)\)", entry_text)+ assert target, entry+ workflow = (entry.parent / target.group(1)).resolve()+ assert workflow.is_relative_to(ROOT) and workflow.is_file()+ assert entry_text.split("---\n", 2)[1] == workflow.read_text().split("---\n", 2)[1]+ assert len(names) == len(set(names))for skill, placeholder in PLATFORM_SKILLS.items():- skill_path = ROOT / skill / "SKILL.md"- assert skill_path.is_file()- skill_text = skill_path.read_text()- assert placeholder in skill_text- assert f"./{skill}" in plugin["skills"]+ workflow = ROOT / skill / "WORKFLOW.md"+ assert placeholder in workflow.read_text()+ assert not (workflow.parent / "SKILL.md").exists()def test_ads_wrappers_resolve_from_the_plugin_root_without_fallback():- plugin = json.loads((ROOT / ".claude-plugin/plugin.json").read_text())- ads_skill_roots = ("./paid-ads/", "./google-ads/", "./meta-ads/")- canonical_paths = [- ROOT / skill.removeprefix("./") / "SKILL.md"- for skill in plugin["skills"]- if skill.startswith(ads_skill_roots)- ]-- for canonical in canonical_paths:- canonical_text = canonical.read_text()- skill_name = re.search(r"^name:\s*(.+)$", canonical_text, re.MULTILINE)- assert skill_name, canonical- wrapper = ROOT / "skills" / skill_name.group(1).strip() / "SKILL.md"- wrapper_text = wrapper.read_text()- relative_target = re.search(r"\]\((\.\./\.\./[^)]+/SKILL\.md)\)", wrapper_text)-- assert relative_target, skill_name- assert (wrapper.parent / relative_target.group(1)).resolve() == canonical.resolve()- assert "not `<plugin-root>/skills/" in wrapper_text- assert "never substitute a similarly named skill from another plugin" in wrapper_text+ for entry in (ROOT / "skills").glob("*/SKILL.md"):+ text = entry.read_text()+ if not any("../../" + prefix in text for prefix in ("paid-ads/", "google-ads/", "meta-ads/")):+ continue+ target = re.search(r"\]\((\.\./\.\./[^)]+/WORKFLOW\.md)\)", text)+ assert target and (entry.parent / target.group(1)).resolve().is_file()+ assert "not `<plugin-root>/skills/" in text+ assert "never substitute a similarly named skill from another plugin" in textdef test_all_host_configs_and_registry_use_one_versioned_connection():@@ -130,7 +117,7 @@ def test_active_plugin_files_do_not_advertise_legacy_endpoints():# Historical release notes and the separately shipped local app are not# plugin installation configuration. Inspect every active plugin surface.roots = [ROOT / name for name in (- "README.md", "AGENTS.md", "CLAUDE.md", "INSTALL_FOR_AGENTS.md",+ "README.md", "AGENTS.md", "INSTALL_FOR_AGENTS.md","docs", "install", "paid-ads", "google-ads", "meta-ads", "analytics", "seo","wordpress", "gohighlevel",".claude-plugin", ".codex-plugin", ".cursor-plugin", ".github",diff --git a/test/unit/test_content_calendar_auto_open.py b/test/unit/test_content_calendar_auto_open.pyindex 7240dd2c..4d8cc11b 100644--- a/test/unit/test_content_calendar_auto_open.py+++ b/test/unit/test_content_calendar_auto_open.py@@ -5,7 +5,7 @@ import sysfrom pathlib import Path# bin script has no .py extension, so give spec an explicit source loader.-script_path = Path(__file__).parent.parent.parent / 'bin' / 'notfair-content-calendar'+script_path = Path(__file__).parent.parent.parent / 'scripts' / 'notfair-content-calendar.py'loader = SourceFileLoader("notfair_content_calendar", str(script_path))spec = importlib.util.spec_from_file_location("notfair_content_calendar", str(script_path), loader=loader)mod = importlib.util.module_from_spec(spec)diff --git a/test/unit/test_plugin_submission.py b/test/unit/test_plugin_submission.pynew file mode 100644index 00000000..d466974c--- /dev/null+++ b/test/unit/test_plugin_submission.py@@ -0,0 +1,49 @@+"""Guard the Claude directory failures against the files actually shipped."""++import json+import re+import struct+import subprocess+from pathlib import Path+++ROOT = Path(__file__).resolve().parents[2]+++def test_one_registered_entry_per_skill_across_hosts():+ files = subprocess.check_output(["git", "ls-files"], cwd=ROOT, text=True).splitlines()+ skills = [ROOT / name for name in files if name.endswith("/SKILL.md")]+ names = [re.search(r"^name:\s*(.+)$", p.read_text(), re.M).group(1).strip().casefold() for p in skills]+ assert len(names) == len(set(names)) == 48+ assert all(p.parent.parent == ROOT / "skills" for p in skills)+ assert not (ROOT / "CLAUDE.md").exists()+++def test_package_stays_within_directory_inspection_limits():+ files = subprocess.check_output(["git", "ls-files"], cwd=ROOT, text=True).splitlines()+ assert len(files) <= 512+ for name in files:+ path = ROOT / name+ assert not path.is_symlink()+ assert not name.startswith(("notfair/", "notfair-nextjs-blog/", "bin/"))+ if path.suffix not in {".png", ".svg"}:+ assert path.stat().st_size < 256 * 1024, name+ assert b"\x00" not in path.read_bytes(), name+++def test_claude_listing_metadata_and_icon():+ manifest = json.loads((ROOT / ".claude-plugin/plugin.json").read_text())+ for key in ("documentationUrl", "supportUrl", "privacyPolicyUrl", "termsOfServiceUrl"):+ assert manifest[key].startswith("https://")+ icon = ROOT / manifest["icon"]+ data = icon.read_bytes()+ assert data[:8] == b"\x89PNG\r\n\x1a\n"+ width, height = struct.unpack(">II", data[16:24])+ assert width == height and 512 <= width <= 2048+ assert len(data) < 2 * 1024 * 1024+++def test_skills_do_not_preapprove_shell_or_file_writes():+ for path in (ROOT / "skills").glob("*/SKILL.md"):+ frontmatter = path.read_text().split("---", 2)[1]+ assert "allowed-tools:" not in frontmatter, pathdiff --git a/test/unit/test_shell_line_endings.py b/test/unit/test_shell_line_endings.pyindex 1e162c78..88cb9dfb 100644--- a/test/unit/test_shell_line_endings.py+++ b/test/unit/test_shell_line_endings.py@@ -7,9 +7,9 @@ import pytestROOT = Path(__file__).resolve().parents[2]HELPERS = [- "bin/notfair-change-watch",- "bin/notfair-config",- "bin/notfair-update-check",+ "scripts/notfair-change-watch.sh",+ "scripts/notfair-config.sh",+ "scripts/notfair-update-check.sh",]diff --git a/test/unit/test_skill_descriptions.py b/test/unit/test_skill_descriptions.pyindex 40eb6a5e..b117a619 100644--- a/test/unit/test_skill_descriptions.py+++ b/test/unit/test_skill_descriptions.py@@ -13,7 +13,7 @@ import pytestROOT = Path(__file__).resolve().parents[2]MAX_DESCRIPTION_CHARS = 1024-SKIP_DIRS = {".git", "node_modules"}+SKIP_DIRS = {".git", ".claude", "node_modules"}def _skill_files():@@ -66,9 +66,9 @@ def test_description_within_limit(path):WRAPPERS = []for wrapper in sorted((ROOT / "skills").glob("*/SKILL.md")):- target = re.search(r"\.\./\.\./(.+?)/SKILL\.md", wrapper.read_text(encoding="utf-8"))- if target and (ROOT / target.group(1) / "SKILL.md").exists():- WRAPPERS.append((wrapper, ROOT / target.group(1) / "SKILL.md"))+ target = re.search(r"\.\./\.\./(.+?)/WORKFLOW\.md", wrapper.read_text(encoding="utf-8"))+ if target and (ROOT / target.group(1) / "WORKFLOW.md").exists():+ WRAPPERS.append((wrapper, ROOT / target.group(1) / "WORKFLOW.md"))@pytest.mark.parametrize(diff --git a/wordpress/SKILL.md b/wordpress/WORKFLOW.mdsimilarity index 100%rename from wordpress/SKILL.mdrename to wordpress/WORKFLOW.md