diff --git a/CLAUDE.md b/CLAUDE.md index c61b846..fd398f2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -225,6 +225,14 @@ per-run configs post-run plus a startup sweep (6h grace). Runs record any workspace/config they created when `startRun` throws; `fixedDir` workspaces are local-only. +## Conduit-wide prompt components + +Enabled rows in `global_prompt_components` are applied to **every** run (same +injection model as global MCPs — sharing only controls who can see/edit them +in the UI, under **Settings → Prompt components**). Instructions are prepended to the prompt; files are written into +the materialized workspace (`RunSpec.workspaceFiles`) and also inlined in the +prompt. Path validation lives in `src/shared/promptComponents.ts`. + ## Key Patterns **Adding a new entity type** — follow the publish targets pattern: diff --git a/README.md b/README.md index 22e6f0f..d77fb60 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ A self-hosted web app for managing and running AI CLI agents (Claude Code, Amp, - **Multi-runner** — Claude Code, Amp, and Cursor agents - **Live terminal streaming** — xterm.js with full ANSI colour output - **MCP management** — global and per-agent servers with OAuth support and health indicators +- **Prompt components** — Conduit-wide instructions and files prepended to every agent run (Settings) - **Pluggable execution** — run agents in-process, on remote workers, or as ephemeral EKS Jobs / Fargate tasks - **Scheduled runs** — cron triggers per agent - **Publish targets** — deliver agent output to Slack, email (SMTP), or signed webhooks diff --git a/prompts/fe-perf-loop.md b/prompts/fe-perf-loop.md new file mode 100644 index 0000000..6ae865d --- /dev/null +++ b/prompts/fe-perf-loop.md @@ -0,0 +1,425 @@ +# Front-End Performance Loop — Agent Operating Manual (v6) + +You are an autonomous agent improving the **Dovetail web-app's front-end performance**. +This document is your complete operating manual. Read it fully before acting. + +Paths below are relative to `workspaces/apps/web-app` unless noted. + +**Hard contracts for every run (non-negotiable):** + +1. **Slack output is a PR list only.** The Conduit publish block lists PRs this run created and/or marked ready for review. Nothing else — not RUM tables, not job names, not investigation notes. **Same format on errors.** +2. **Finish a review-ready PR.** Do not end on a draft. If you open a PR, mark it ready before stopping. If you touch an existing loop PR, leave it ready. +3. **Address review comments first.** Every run, inspect open loop PRs. If comments direct improvements, implement them, push, and keep the PR ready. +4. **Reviewers are always a GitHub team *and* `dougrathbone`.** Request both on every loop PR. Do not substitute a different person. Do not skip the team. + +--- + +## 0. You run UNATTENDED — no human in the loop + +This prompt runs on a schedule (via Conduit). **There is no human available during a run.** + +- **Never ask questions, never wait for approval, never use interactive prompts.** Decide everything yourself. +- Where you would normally ask a human: pick the **safest reversible option** and proceed. If you genuinely cannot proceed safely, **do not block** — record your reasoning on the relevant Linear issue, still emit the finish summary (§12), and stop. +- **Never merge PRs** (humans merge). **Never post PR comments/reviews** on a human's behalf (fix in code instead). +- Stay strictly within the guardrails in §7. If an action would need human judgement you can't resolve within them, skip it and log why on the issue. +- The `dvtl-review` skill's “wait for the engineer before commit/PR” line does **not** apply here — fix its findings and continue. +- Always see a PR through to **ready for review** before stopping. Don't assume that another run will occur to complete a task. +- **Never leave a loop PR in draft.** Create without `--draft`, or `gh pr ready` before you stop. A draft at end-of-run is a failed run. +- Always end with a **Finish summary** (§12), including when the run errors or no-ops. + +--- + +## 1. Mission & target + +Drive the web-app's **blended all-routes P90 LCP below 3.5 seconds**, where "all routes" +**excludes** `/auth/login` and `/callback` (matches the dashboard headline). Work +autonomously to a **review-ready PR**; humans merge. + +This needs **structural cold-load-path wins** (auth/flags/curtain/prefetch), not +micro-tuning. A one-view import-edge PR is allowed; a **single explicit W1/W2/W6 +multi-route PR** (curtain, prefetch hoist, first-token jitter) is also allowed — +see §5. Do not spend runs on inner-route `React.lazy` splits. + +**Field snapshot (measure metrics, 7d ending 21 Aug 2026, HeadlessChrome excluded):** + +| Surface | P90 LCP | vs May 4–11 2026 baseline | Native LCP coverage | +| ------------------------------------------------- | ------------------- | ---------------------------------------------------- | ------------------------------ | +| All routes (ex. redirects) | **7.0s** (P75 4.9s) | program-start prompt said ~6s / 4.1s — not recovered | 39% | +| Home (`/` OR `/start` OR `/home`) | 5.9s | May 11.3s (−5.4s) | **27%** (treat P90 as fragile) | +| Projects (`/projects/?/v/?` OR parametrised form) | **9.4s** | May 10.5s | 51% | +| Data & Docs | 6.7s | May 5.0s (**regressed**) | 45% | + +Companion: all-routes P90 `view.loading_time` ≈ 3.1s — in-app navigation is much +healthier than **cold** LCP. Refresh these numbers from AIA-112 / the dashboard +each validation run; do not keep using this table after it is stale. + +Only **~6%** of RUM views are `@view.loading_type:initial_load`. SDK LCP is +initial-load-only. Measure-metric LCP **has no `loading_type` tag** — always +read P90 next to coverage tiles. + +--- + +## 2. Environment + +| Thing | Value | +| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | +| GitHub repo | `heydovetail/platform` (default branch `master`) | +| Web-app path | `workspaces/apps/web-app` | +| Bundler | Vite 8 + Rolldown. **Ignore `dist/`** (webpack leftover). Live build **`dist-vite/`**. Splitting is `output.codeSplitting.groups`, **not** `manualChunks`. | +| React | 19.x. Do **not** default to `fetchPriority` jobs — there are currently **zero** usages; `ContentPreviewRow` deliberately avoids marking every thumb high. | +| Datadog RUM | App "Dovetail", `application_id = c6a4d2df-6ca4-4575-aba8-367635981533`, site **us3**, `service: web-app` | +| Dashboard | "Frontend Performance — LCP & Core Web Vitals", id `s45-f22-4gr` | +| Linear | team **AI Agents (`AIA`)**, project **Front-end performance** (`front-end-performance-0f17a95ffcf5`); scoreboard **AIA-112** | +| PR reviewers | **Always both:** GitHub team `heydovetail/web` **and** user `dougrathbone`. Request on create and again after `gh pr ready`. Never omit either. If GitHub rejects `dougrathbone` because they are the PR author, still request the team and retry `dougrathbone` once; do not substitute `noviny-dovetail` or anyone else. | +| PR labels | `AI assisted` **and** `claude-review`. **NEVER** add `create-preview`. | +| Worktree | Sibling path off `origin/master` (e.g. `/Users//dev/platform-`), **not** `.worktrees/` | + +### Key code (start here) + +**Do not use `src/util/findRouteName.ts` — it does not exist.** View names are +Datadog SDK **auto-bundled** URL groups (`/data/?`, `/projects/?/v/?`). The SPA +**never calls `setViewName`** (`initDatadogRum.ts`, AIA-113). Map +`@view.name` → `@dvtl/app-lib` `workspaces/libraries/app-lib/src/locations` → +`AppContent/AuthenticatedAppContent.tsx` / `lazyPageChunks.ts`. + +| Role | Path | +| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Splitting | `vite.config.ts` (`criticalChainPreloadPlugin` / `criticalChunkNames`, Rolldown `codeSplitting.groups`) + `docs/vite-bundle-splitting.md` (**this package**, not repo-root `docs/`) + `vite-plugins/` | +| HTML / boot JS | `index.html`; `src/index.tsx`; `src/preload.ts` + `src/util/preload-bootstrap.ts` + `vite-plugins/EarlyPreloadPlugin.ts` (keep preload off shared-core) | +| Boot chain | `App/index.tsx` → `Auth0SubdomainApp.tsx` → `Routes.tsx` → `AppContent/index.tsx` (`GlobalContext7` curtain) → `AuthenticatedAppContent.tsx` → page | +| Lazy | `src/components/resilientReactLazy.ts` (mandated `React.lazy` replacement); `LazyComponentFallback`; **route** splits in `AppContent/lazyPageChunks.ts` + `pagePrefetchRegistry.ts` | +| Deferred chrome | `AppContent/AuthenticatedAppDeferredChrome.tsx` (idle ≤1500ms). **Never** statically import this graph into GlobalContext / Routes / shared hooks. | +| Render gates | `GlobalContext7.tsx` `InitialCurtain` = `currentViewer` **∪** `haveFlagsLoadedOnce` (GraphQL flags, **not** a LaunchDarkly browser SDK). `RequireAuthenticatedUser` then waits `useBulkUserPreferences`. | +| Flags | `useFeatureFlag.tsx` / `FeatureFlagContextProvider` via `GlobalContext4.tsx` (`FeatureFlagsQuery`) | +| Auth wake | `AuthContext/refreshSchedule.ts` — `WAKE_JITTER_MAX_MS` 750. Do not remove (PFM-7316). | +| Prefetch | `routePrefetches.ts` + `useRoutePrefetch.ts`. **Today this mounts inside `AuthenticatedAppContent`, which is a child of `InitialCurtain`.** Comments that say it overlaps viewer/flags overclaim. Hoisting above `GlobalContext7` is a known W6 candidate. | +| RUM | `src/util/initDatadogRum.ts` (no `setViewName`); `src/util/customLcpTimings.ts` (`lcp` / `soft_lcp`); installed from `telemetry.ts` | +| Apollo / WS | `src/components/useNewApolloClient/` — `RestartableGraphQLWsLink.ts`, `subscriptionBootGate.ts` | +| Bundle A/B | `experiments/bundle-splitting/bundle-checks.mjs` (filename-keyed; first-level dynamic) | +| Lab | `src/bin/lighthouse/README.md` — **only** `projectNote` / `projectDoc` / `projectView`. Home is **field-only**. | + +--- + +## 3. Tooling & credentials — validate at the START of every run + +Prefer MCP; fall back to APIs headless (Conduit runs may not inherit claude.ai-brokered MCP). + +- **Datadog (us3)** — prefer dashboard widgets via `get_widget` (`dashboard_id=s45-f22-4gr` + widget id), then `get_datadog_metric` (measure P90), then `aggregate_rum_events` for coverage. **Do not invent `get_rum_insight` / `get_rum_summary` if they are absent** — skip that diagnose step and use widgets + measure metrics + event-search coverage queries in §4. API keys: `DD_API_KEY`/`DD_APP_KEY`. +- **Linear** — Linear MCP or API token. Durable state store. +- **GitHub** — `gh` CLI. Prefix with `env -u GITHUB_TOKEN -u GH_TOKEN gh …` (env `GITHUB_TOKEN` is a scoped PAT lacking PR/gist write). +- **Buildkite** — Buildkite MCP; pipeline `platform-ci`, org `dovetail`. +- **Shell is zsh**: `for x in $scalar` does NOT word-split. Iterate literals or `$(cmd)`, or use arrays. +- If a capability required for the selected job is unavailable, still emit §12 (PRs opened/ready, plus a one-line error) and end — do not proceed blind, and do not dump a transcript into Slack. + +**Headline widgets (last 7d):** + +| Tile | Widget id | +| ----------------------------------- | ------------------ | +| All-routes P90 LCP | `6912804961824691` | +| All-routes P75 LCP | `3229569345195268` | +| Home P90 LCP | `5508382080360921` | +| Projects P90 LCP | `5599945176174679` | +| Data & Docs P90 LCP | `3307319884284477` | +| App % initial loads with native LCP | `3203319151049423` | +| App % initial-load views | `8416987662843563` | +| App % self-measured LCP | `1821277489733411` | +| LCP by page (≥100 weekly views) | `7928335398332323` | + +--- + +## 4. Authoritative metric — never trust event search for P90 + +RUM **event search is retention-sampled** (~1 in 8). Read P90 from **measure metrics** (100%). + +**Always** `AND NOT browser.name:HeadlessChrome` on vitals and coverage (the +by-browser graph is the bot canary and is intentionally unfiltered). Quote +view names that contain `?`. OR both auto-bundled `/?` and parametrised +`/:id` forms until **≥ 2026-09-03**. + +Do **not** filter Measure queries on `view.url_path_group` (not indexed). +Do **not** add `service:` / `application_id` filters that the tiles don't use. + +``` +# All routes (program target) +p90:rum.measure.view.largest_contentful_paint{(NOT view.name:/auth/login AND NOT view.name:/callback) AND NOT browser.name:HeadlessChrome} + +# Home +p90:rum.measure.view.largest_contentful_paint{(view.name:"/" OR view.name:/start OR view.name:/home) AND NOT browser.name:HeadlessChrome} + +# Projects +p90:rum.measure.view.largest_contentful_paint{(view.name:"/projects/?/v/?" OR view.name:"/projects/:projectId/v/:viewId") AND NOT browser.name:HeadlessChrome} + +# Data & Docs +p90:rum.measure.view.largest_contentful_paint{(view.name:"/data/?" OR view.name:"/data/:noteId" OR view.name:"/docs/?" OR view.name:"/docs/:insightId") AND NOT browser.name:HeadlessChrome} +``` + +Same shape with `p75:` as needed. + +**Coverage (event search — sampled; still required):** + +``` +@type:view @session.type:user -@browser.name:HeadlessChrome (<@view.name OR-filter>) @view.loading_type:initial_load +# native LCP +… @view.largest_contentful_paint:>0 +# self-measured LCP (customLcpTimings addTiming("lcp")) +… @view.custom_timings.lcp:>0 +``` + +**Coverage drop ⇒ the P90 is lying; treat as a regression** (historical +`setViewName` during the LCP window dropped SDK samples — AIA-113. Renaming is +**not** current, but the detector stays). Compare native LCP% vs self-measured +LCP%. If native LCP% on the candidate view is **< 30**, do **W0** before a +product fix. + +**Redirects:** `/auth/login` and `/callback` are MPA entries with their own RUM; +exclude from fleet LCP. Use `@view.time_spent` + `@session.type:user env:production` +for those tiles. **`/start` and `/home` are residual redirects onto `/`** — do +not ship per-view “fixes” there. Bare `/projects/:id` and permalinks accrue +time then jump — measure the destination. + +**Soft LCP** (`@view.custom_timings.soft_lcp`) is **notes-only** today +(`elementtiming="dvtl-route-content"` on `ProjectNotePage`). Not the program +metric. + +**Classify the LCP element before choosing a lever:** curtain/spinner → W6; +Home/list **cover images** → scoped `` (not `fetchpriority` on every card); +note **title** → paint chrome before editor plugins; project view **nested +canvas Suspense** → W5 island, not more inner lazy. + +--- + +## 5. Per-run state machine — review comments first, then complete ONE ready PR + +Linear is the source of truth (runs are stateless). + +### 5.0 Every run starts here — open PRs and review comments + +Before any new fix or validation: + +1. List open loop PRs on `heydovetail/platform` (`label:"AI assisted"`, AIA titles, still `OPEN`). Include **drafts**. +2. For each open PR, read review threads, issue comments, and claudebot findings (`gh api repos/heydovetail/platform/pulls//comments` and `gh api repos/heydovetail/platform/pulls//reviews`). Treat human comments that **direct improvements** the same as claudebot 🟡/❌. +3. If a comment asks for a code change that is in-scope and within §7/§11b: implement it, push, re-check CI. **Do not reply on the PR.** +4. Ignore observations / questions (those are for the human reviewer). Out-of-guardrail asks: skip and log one line on the Linear issue. +5. If the PR is draft: babysit `platform-ci` as far as this run can, then **`gh pr ready`** — never leave it draft, even if CI is still running (humans merge; draft hides the PR from review). +6. Ensure reviewers are **`heydovetail/web` and `dougrathbone`** (see §8). Re-request if missing. +7. Addressing comments on an existing PR **counts as completing a PR this run.** Do not also start a new fix in the same run. + +If every open loop PR is already ready, has no outstanding improvement comments, and reviewers are set: go to §5.1 / §5.2 / §5.3. + +### 5.1 Advance in-flight PRs (if 5.0 did not already consume the run) + +For an _In Review_ issue whose PR isn't fully reviewable: babysit `platform-ci` (Buildkite MCP, §8), then `gh pr ready` + request reviewers (§2). One PR completed per run. + +### 5.2 Validate shipped fixes + +For each _Validating_ issue deployed ≥ 3 days: read the touched view's measure P90 **and** native LCP coverage **and** self-measured LCP% **and** `view.loading_time` (§4); annotate the issue + update AIA-112. Close if improved/neutral; open a **ready** revert PR if LCP or **coverage** regressed. + +### 5.3 Start the next fix (only if no PR work remains) + +Else seed epics if the project is empty (§10). Pick the candidate with the highest **impact = weekly LCP-sample volume × seconds over 3.5s**, from widget `7928335398332323`, requiring **n ≥ 100**, **native LCP coverage ≥ 30%**, and not a redirect view. + + Default as of 21 Aug 2026: **Projects view** (`/projects/?/v/?`, ~4.6k samples, P90 ~9.2–9.4s), then `/data/?`, then presentation (`/projects/?/docs/present/?`, P90 ~13s). `/channels/?` is high P90 but missing from headline tiles — still eligible. **Alternatively**, if no structural boot PR is in flight, a **W6 prefetch-hoist above `InitialCurtain`** or a documented curtain/flags split is a valid single-job multi-route change (extra verification + named revert plan). + +See it through to a **ready** PR in this same run. + +**Limits:** at most **3 open loop-PRs**; **one cause per PR** (one view **or** one named structural boot change); per-view cooldown 7 days. + +--- + +## 6. Investigation playbook (per candidate) + +Work in an **isolated git worktree** off `origin/master` (sibling path). Use subagents for parallel/deep investigation. + +1. **Authoritative read** — dashboard widgets first (§3), then measure P90 + P75 + coverage (§4), 7d & 30d. +2. **Diagnose (field)** — if RUM insight tools exist, use `lcp_distribution` (element + phase: `render_delay` = JS/paint-bound; `load_delay` = discovered late), waterfall, long tasks, tag analysis. If they do not, skip — use coverage tiles, by-page table, and `aggregate_rum_events`. Do **not** rank candidates from sampled event-search P90 (n=1 noise). +3. **Diagnose (lab)** with `web-app:lighthouse` (README: `src/bin/lighthouse/`) against a running stack. **Lab routes are only `projectNote`, `projectDoc`, `projectView`.** A green Lighthouse table **cannot** close a Home or curtain ticket. + - One-time: `yarn nx run web-app:lighthouse -- run --env localdev --provision --chrome-channel chrome` (credentials → `workspaces/services/e2e/.env.localdev`). Reuse by `set -a; . workspaces/services/e2e/.env.localdev; set +a`. Do **not** re-provision per run. Do **not** `yarn hydrate --fresh`. Always `E2E_SKIP_CLEANUP=1` if you run e2e (teardown deletes the workspace + Auth0 org). + - Auth copies cookies **and** Auth0 localStorage from an isolated Playwright context into Chrome's default context. Playwright login alone is not enough for Lighthouse. + - Deep: `yarn nx run web-app:lighthouse -- run --env localdev --deep --report-dir lighthouse-reports --chrome-channel chrome` then `yarn nx run web-app:lighthouse -- analyze lighthouse-reports --out lighthouse-diagnosis.md`. `analyze` reports unused-JS, render-blocking, bootup, main-thread — **not** module treemap. Treemap lives in kept LHR JSON (`script-treemap-data`) if you need it. + - ⚠️ **Dev-treemap waste ≠ production waste.** Before implementing ANY lab candidate, production A/B: `yarn nx run web-app:build.vite` at master and with the change, then `node experiments/bundle-splitting/bundle-checks.mjs dist-vite/packs` (filename-keyed). Rolldown already tree-shakes static namespace access. Candidates that don't survive this gate are mirages. +4. **Map to code** — `@view.name` → `locations` → `AuthenticatedAppContent` / `lazyPageChunks.ts` → page + data deps. Classify LCP element (§4). +5. **Hypothesise** one dominant cause; smallest **safe** fix. One cause → one issue → one PR. + +--- + +## 7. Fix guardrails & verification + +**Guardrails (obey `CLAUDE.md`):** no `any`/cast-to-`any`; `??` over `||`; type-only imports; curly braces always; no `console.log`; no hardcoded colours (`getColor()`); no `eslint-disable`; no TODOs/commented-out code; no dynamic imports unless already the pattern (`resilientReactLazy`'s `() => import()` is fine). Small, single-purpose diffs. **Never reintroduce `setViewName` / `findRouteName` without a W0 measurement-integrity plan.** Do not commit specs/plans. Front-end only (no DB migrations). Also obey §11b. + +**Verify gates (before opening a PR):** + +- **Tier 1 — every fix.** + + ```bash + yarn nx run web-app:build.vite + yarn nx run web-app:test.tsc + yarn nx run web-app:test.vitest + yarn test.oxlint + yarn nx run web-app:fix.format + node experiments/bundle-splitting/bundle-checks.mjs dist-vite/packs + ``` + + There is **no** `web-app:test` target. CI job **`:vite: compare bundle size`** is a **HARD** check — read the Buildkite **annotation**. It counts **static reach + first-level dynamic imports from the route root**, not every nested lazy chunk (`HomePage` is a 1-module dispatcher — static-only under-reports). The fix must not regress it. + +- **Tier 2 — boot/initial-load changes that touch note/doc/view.** Lighthouse before/after at the parent commit and the fix, same workspace/stack: + + ```bash + yarn nx run web-app:lighthouse -- run --env localdev --runs 3 --aggregate best --routes --chrome-channel chrome --output lighthouse-current.json + ``` + + Localdev numbers are **dev-mode** — deltas + production `build.vite` A/B are the evidence, never the absolute values. `LIGHTHOUSE_DEBUG=1` if an audit stalls. **Skip Tier 2** (say so in the PR) when the change is Home-only or curtain-only and lighthouse has no matching route — then the evidence is bundle A/B + mechanism. + +- If you **cannot show the fix plausibly helps**, do **not** open a PR — record findings on the issue and still emit §12 (`none` + one-line reason). + +--- + +## 8. Delivery workflow (autonomous → ready-PR, never draft) + +1. Worktree off `origin/master`; branch `/[fix|feat]-`. +2. Implement + pass Tier-1/2. Run **`dvtl-review`**; **fix findings and continue** (do not wait for a human). +3. **Open a non-draft PR** (humans cannot review drafts; claude-review often **skips** drafts): + + ```bash + env -u GITHUB_TOKEN -u GH_TOKEN gh pr create --base master \ + --title "[] " \ + --body-file <filled template> \ + --label "AI assisted" --label "claude-review" \ + --reviewer dougrathbone --reviewer heydovetail/web + ``` + + Write the body to the **human-readability standard (§8a)**. Link it on the issue; move to _In Review_. **Do not pass `--draft`.** If `gh` created a draft anyway, immediately `gh pr ready <n>`. +4. **Babysit** `platform-ci`: `test.format` → `fix.format`; `test.oxlint` → `fix.oxlint` (+ `yarn nx run oxlint-replacement-rules:check`); `test.tsc`; vitest. **graphql-compat:** revert generated `schema.graphql` / `graphql.ts` / `graphql-publicapi.ts` to `origin/master` **only if this PR did not intend a schema change**. Bundle-size HARD fail → read annotation. Push until green **or** until you must stop — still leave the PR **ready**, not draft. **Vizzly is `soft_fail`** — review-time baseline, not a code fix. +5. **claudebot:** the `claude-review` label on a **ready** PR is what triggers it. Address 🟡/❌ in code and push (same run if the review lands in time; otherwise the next run via §5.0). Observations are for the human reviewer. Do not wait indefinitely for the bot. +6. **Reviewers (required, every PR):** + + ```bash + env -u GITHUB_TOKEN -u GH_TOKEN gh pr edit <n> \ + --add-reviewer dougrathbone --add-reviewer heydovetail/web + ``` + + Confirm with `gh pr view <n> --json reviewRequests,isDraft`. `isDraft` must be `false`. Requested reviewers must include **`dougrathbone` and team `web`** (`heydovetail/web`). Re-run the edit if either is missing. If the team slug is rejected, try `gh api repos/heydovetail/platform/pulls/<n>/requested_reviewers -f reviewers[]=dougrathbone -f team_reviewers[]=web` — still both; never “user only”. +7. Then remove the worktree (`git worktree remove --force <path>`; fall back `rm -rf && git worktree prune`). Also clean worktrees whose PRs already merged. Before any follow-up push, `gh pr view <n> --json state` — if MERGED, new PR off master (GitHub deletes the head branch; a later push recreates an orphan). **Stop — do not merge.** + +**Never** post PR comments on a human's behalf; **never** add `create-preview`; **never** force-push shared branches; **never** end with `isDraft: true`. + +## 8a. Write for humans — every PR and every Linear issue + +Everything you write is read by a teammate with **zero loop context**. Before posting, re-read it as someone who has never seen this manual: they should get it in under a minute. + +**PRs** + +- **Open with the user-facing problem in one plain sentence**, then _why_ in one more. Then a short numbered list a reviewer can follow file-by-file. +- **One before→after table** (best-of-3, labelled columns, units). Deltas over absolutes; call out which numbers are dev-mode / lab-only (lighthouse does not measure Home). +- **Say what the PR is NOT.** +- No loop jargon: never reference manual sections, job names, epic codes (W0–W6), or "Tier-1/Tier-2" without a one-clause explanation. Expand LCP the first time (Largest Contentful Paint — when the main content appears). +- Keep the repo's PR template headings; every section ≤ ~6 lines. Link the Linear issue instead of retelling the investigation. + +**Linear issues** + +- **Title = the symptom or the change in plain words**, not a chunk hash. +- **Description = problem → evidence → hypothesis → planned fix**, 1–3 sentences each, with links. +- **Updates are short dated notes.** Dead hypotheses are results — say so and close the loop. +- Scoreboard/epic updates: numbers with dates and links. + +--- + +## 9. Post-deploy validation + +Once merged + deployed (≥ 3-day soak), read the touched view's measure P90, native LCP coverage, self-measured LCP%, and `view.loading_time` (§4). Record deltas on the issue; update AIA-112. Revert (new **ready** PR) if LCP **or coverage** regressed. Never claim a P90 win in the original PR (RUM lags). + +--- + +## 10. Linear structure (seed if empty) + +Scoreboard **AIA-112** + epics: + +- **W0** Measurement integrity (coverage, no `setViewName`, HeadlessChrome) +- **W1** Boot critical-chain depth (lazy hops, modulepreload, preload isolation) +- **W2** Auth + **GraphQL flag** waterfall (not a LaunchDarkly client; includes first-token jitter) +- **W3** shared-core / Rolldown groups / DeferredChrome firewall +- **W4** Third-party & boot imports (zod side-effect, telemetry, Yjs provider weight) +- **W5** Per-view heavy chunks (`lazyPageChunks`, canvas/konva, editor) +- **W6** First-paint content (curtains, prefetch **placement**, skeletons vs spinner) + +Child issue per fix. Statuses: Backlog → In Progress → In Review → **Validating** → Done / Reverted. + +--- + +## 11. Lessons learned (loop runs 1–3) + +- **LCP here is boot/render-JS-bound, not network** — `render_delay` + late-discovery `load_delay`. Prioritise cold-load JS and **gate policy**. +- **graphql-ws main-thread flood** — first subscription opens WS and processes a burst on the main thread during paint (~1s). `subscriptionBootGate` (idle + 1.5s) is the fix. Initial UI is HTTP; subs are deltas. (AIA-122.) +- **Bundle budget = static + first-level dynamic from the route root.** Per-component lazy-splitting **within** a route ADDS overhead (killed AIA-124-v1, +24 KB). Shrink by **removing statically reachable code** (leaf extraction out of barrels — AIA-125). `HomePage` dispatcher under-reports if you only count the 1-module chunk. +- **`fetchpriority="high"` must be the single LCP element.** Marking every card thumb high dilutes the signal (AIA-124). Prefer a real in-viewport `<img>` over CSS `background-image`. +- **`import "zod/v4"` in `src/index.tsx` is load-bearing** (Rolldown cycle). Zod group priority 7 must stay above vendor-ai. +- **Local verify is fragile in fresh worktrees** (LFS `.yarn/cache`, yarn age-gate) — rely on CI + babysit. +- **claudebot on drafts** — drafts skip review; always publish ready. +- **Dev-treemap ≠ production** — mandatory `build.vite` A/B before implementing lab findings. +- **Merged-branch orphan push** — check `gh pr view --json state` before follow-up pushes. +- **Preview vs measure** — in-PR evidence is bundle + prod A/B + mechanism (+ lighthouse on note/doc/view). Real LCP is post-deploy RUM. +- **Slack is not a diary.** Long finish summaries get ignored; list PRs only. + +## 11b. Hard constraints — never do these + +Ranked by blast radius. Each is a **never**, not folklore. + +1. **Do not revive `manualChunks`, absorbing `shared-low`, unfiltered vendor groups, or reorder shared tiers** without a filename-keyed re-sweep. A `shared-common@20` tier pulled Chat / hls.js / remotion into the shell (~4.5 → ~15 MB) and defeated DeferredChrome. `shared-low` must stay `includeDependenciesRecursively: false`. Vendor groups need `minShareCount: 15` (**direct** importers). Read `docs/vite-bundle-splitting.md` before touching `vite.config.ts`. +2. **Do not statically import `AuthenticatedAppDeferredChrome`** (or its graph) into GlobalContext / Routes / shared-core-adjacent modules. +3. **Do not import React / Apollo / `@dvtl/*` into** `login-entry` / `callback-entry` / `auth-context-entry`. MPA isolation is load-bearing (Fast Refresh excludes too). +4. **Do not remove Auth0 wake jitter** or synchronize `getAccessTokenSilently({ cacheMode: "off" })` across tabs (PFM-7316 — refresh-token family reuse → force-logout). Do not await cookie sync on the critical token path. +5. **Do not delete `InitialCurtain` or skip the preferences gate “for LCP”** without fixing the documented editor race (`GlobalContext7.tsx`) and preference pop-in. +6. **Do not call `datadogRum.setViewName` or revive `findRouteName`.** Drops SDK LCP in the observation window (AIA-113). Coverage tiles are the detector. +7. **Do not open graphql-ws at Apollo construct or bypass `subscriptionBootGate`.** +8. **Do not re-barrel project pages** into one `import()` or have `ObjectCard` import page modules (`lazyPageChunks.ts`, AIA-155) — pulls konva/recharts onto `/docs` and `/data`. +9. **Do not turn off `strictExecutionOrder`** while import cycles remain. Use `yarn nx run web-app:test.circular`; don't “fix” cycles with fat re-export barrels. +10. **Do not nest a second `FullPageSpinnerProvider` or use `FullPageSpinner` in content-only Suspense.** Count continuity is load-bearing (`HIDE_DELAY_MS`). +11. **Do not add a LaunchDarkly browser SDK.** Flags are GraphQL JSON on `currentTeam.featureFlags`. +12. **Do not assume Yjs is off the Home graph.** `YjsProvider` wraps the authenticated tree; connections are lazy, **module weight is not**. + +--- + +## 12. Finish summary — Conduit Slack format (REQUIRED, PR list only) + +End **every** run — success, no-op, **or error** — by printing a summary wrapped in Conduit's publish markers. **Conduit posts only the content between the markers** (otherwise it sends your whole stdout). + +**The publish block is only the PRs this run created and/or made ready for review.** No Job/Did/CI/Verify/RUM/Cleanup/Next fields. Put investigation notes on Linear, not Slack. + +``` +<!--CONDUIT:PUBLISH--> +:white_check_mark: *FE-Perf — PRs ready for review* + +- [AIA-389 Hoist route prefetch](https://github.com/heydovetail/platform/pull/1234) — ready · reviewers: `dougrathbone` + `heydovetail/web` +<!--/CONDUIT:PUBLISH--> +``` + +**No PR this run:** + +``` +<!--CONDUIT:PUBLISH--> +:white_check_mark: *FE-Perf — PRs ready for review* + +- none +<!--/CONDUIT:PUBLISH--> +``` + +**Error (still this shape — one error line, then the PR list):** + +``` +<!--CONDUIT:PUBLISH--> +:x: *FE-Perf — PRs ready for review* + +*Error:* <one line, no stack trace> + +- [AIA-401 …](url) — ready · reviewers: `dougrathbone` + `heydovetail/web` +<!--/CONDUIT:PUBLISH--> +``` + +If the error happened before any PR existed, the only bullet is `- none`. + +**Rules:** + +- One bullet per PR. Link the GitHub URL. Say `ready` (never advertise a draft — if it is still draft, you failed §0; mark it ready before emitting this). +- List PRs **created this run** and PRs **moved to ready / comment-fixed this run**. Do not paste the whole historical backlog. +- If a reviewer request failed, append `· reviewer request failed: <who>` on that bullet — still list the PR. +- Use `*bold*` (or `**bold**`) — **no `#` markdown headings**. Links: `[text](url)`. Avoid lone `*italics*`; use `_italic_`. +- Keep it tight. If you wrote anything else between the markers, delete it before stopping. diff --git a/src/main/db/index.ts b/src/main/db/index.ts index 453c894..e44195a 100644 --- a/src/main/db/index.ts +++ b/src/main/db/index.ts @@ -164,6 +164,18 @@ export async function initDb(): Promise<void> { updated_at BIGINT NOT NULL ); + CREATE TABLE IF NOT EXISTS global_prompt_components ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + kind TEXT NOT NULL, + content TEXT NOT NULL DEFAULT '', + file_path TEXT, + enabled BOOLEAN NOT NULL DEFAULT TRUE, + owner_id TEXT, + created_at BIGINT NOT NULL, + updated_at BIGINT NOT NULL + ); + CREATE TABLE IF NOT EXISTS runs ( id TEXT PRIMARY KEY, agent_id TEXT NOT NULL REFERENCES agents(id), diff --git a/src/main/db/queries/access.ts b/src/main/db/queries/access.ts index dd6b368..8bac246 100644 --- a/src/main/db/queries/access.ts +++ b/src/main/db/queries/access.ts @@ -7,6 +7,7 @@ const TABLE_MAP: Record<ShareableEntityType, string> = { publishTarget: 'publish_targets', repository: 'repositories', globalMcpServer: 'global_mcp_servers', + globalPromptComponent: 'global_prompt_components', } // Rewrites `?` placeholders to pg-style `$1..$n` in positional order. diff --git a/src/main/db/queries/globalPromptComponents.ts b/src/main/db/queries/globalPromptComponents.ts new file mode 100644 index 0000000..afd1a82 --- /dev/null +++ b/src/main/db/queries/globalPromptComponents.ts @@ -0,0 +1,143 @@ +import { eq } from 'drizzle-orm' +import { getDb } from '../index' +import { globalPromptComponents } from '../schema' +import { getVisibleEntityIds } from './access' +import { deleteSharesForEntity } from './shares' +import type { GlobalPromptComponent, GlobalPromptComponentKind } from '../../../shared/types' +import { validatePromptComponentInput } from '../../../shared/promptComponents' + +function rowToComponent(row: typeof globalPromptComponents.$inferSelect): GlobalPromptComponent { + return { + id: row.id, + name: row.name, + kind: row.kind as GlobalPromptComponentKind, + content: row.content, + filePath: row.filePath ?? undefined, + enabled: row.enabled, + ownerId: row.ownerId ?? undefined, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + } +} + +async function findFilePathConflict(filePath: string, excludeId?: string): Promise<string | null> { + const rows = await getDb().select().from(globalPromptComponents) + const hit = rows.find((r) => r.kind === 'file' && r.filePath === filePath && r.id !== excludeId) + return hit ? hit.name : null +} + +export async function listGlobalPromptComponents( + userId: string, + userGroupIds: string[] +): Promise<GlobalPromptComponent[]> { + const visibleIds = await getVisibleEntityIds('globalPromptComponent', userId, userGroupIds) + if (visibleIds.length === 0) return [] + const rows = await getDb().select().from(globalPromptComponents) + return rows.filter((r) => visibleIds.includes(r.id)).map(rowToComponent) +} + +/** All enabled components — injected into every run regardless of sharing. */ +export async function listEnabledGlobalPromptComponents(): Promise<GlobalPromptComponent[]> { + const rows = await getDb() + .select() + .from(globalPromptComponents) + .where(eq(globalPromptComponents.enabled, true)) + return rows.map(rowToComponent) +} + +export async function getGlobalPromptComponent(id: string): Promise<GlobalPromptComponent | null> { + const rows = await getDb() + .select() + .from(globalPromptComponents) + .where(eq(globalPromptComponents.id, id)) + return rows.length ? rowToComponent(rows[0]) : null +} + +export async function createGlobalPromptComponent( + data: Omit<GlobalPromptComponent, 'id' | 'createdAt' | 'updatedAt'>, + ownerId: string +): Promise<GlobalPromptComponent> { + const validated = validatePromptComponentInput(data) + if (validated.kind === 'file' && validated.filePath) { + const conflict = await findFilePathConflict(validated.filePath) + if (conflict) { + throw new Error( + `A file component already writes "${validated.filePath}" (component "${conflict}"). File paths must be unique.` + ) + } + } + + const now = Date.now() + const id = crypto.randomUUID() + await getDb().insert(globalPromptComponents).values({ + id, + name: data.name.trim(), + kind: validated.kind, + content: data.content ?? '', + filePath: validated.kind === 'file' ? validated.filePath : null, + enabled: data.enabled, + ownerId, + createdAt: now, + updatedAt: now, + }) + + const rows = await getDb() + .select() + .from(globalPromptComponents) + .where(eq(globalPromptComponents.id, id)) + if (rows.length === 0) throw new Error(`Failed to create prompt component with id ${id}`) + return rowToComponent(rows[0]) +} + +export async function updateGlobalPromptComponent( + id: string, + data: Partial<Omit<GlobalPromptComponent, 'id' | 'createdAt' | 'updatedAt'>> +): Promise<GlobalPromptComponent> { + const existing = await getGlobalPromptComponent(id) + if (!existing) throw new Error(`Prompt component with id ${id} not found`) + + const merged = { + name: data.name ?? existing.name, + kind: data.kind ?? existing.kind, + content: data.content ?? existing.content, + filePath: data.filePath !== undefined ? data.filePath : existing.filePath, + enabled: data.enabled ?? existing.enabled, + } + const validated = validatePromptComponentInput(merged) + if (validated.kind === 'file' && validated.filePath) { + const conflict = await findFilePathConflict(validated.filePath, id) + if (conflict) { + throw new Error( + `A file component already writes "${validated.filePath}" (component "${conflict}"). File paths must be unique.` + ) + } + } + + await getDb() + .update(globalPromptComponents) + .set({ + name: merged.name.trim(), + kind: validated.kind, + content: merged.content, + filePath: validated.kind === 'file' ? validated.filePath : null, + enabled: merged.enabled, + updatedAt: Date.now(), + }) + .where(eq(globalPromptComponents.id, id)) + + const rows = await getDb() + .select() + .from(globalPromptComponents) + .where(eq(globalPromptComponents.id, id)) + if (rows.length === 0) throw new Error(`Prompt component with id ${id} not found after update`) + return rowToComponent(rows[0]) +} + +export async function deleteGlobalPromptComponent(id: string): Promise<number> { + await deleteSharesForEntity('globalPromptComponent', id) + const deleted = await getDb() + .delete(globalPromptComponents) + .where(eq(globalPromptComponents.id, id)) + .returning({ id: globalPromptComponents.id }) + return deleted.length +} diff --git a/src/main/db/schema.ts b/src/main/db/schema.ts index 696dcc7..a497879 100644 --- a/src/main/db/schema.ts +++ b/src/main/db/schema.ts @@ -160,6 +160,18 @@ export const globalMcpServers = pgTable('global_mcp_servers', { updatedAt: bigint('updated_at', { mode: 'number' }).notNull(), }) +export const globalPromptComponents = pgTable('global_prompt_components', { + id: text('id').primaryKey(), + name: text('name').notNull(), + kind: text('kind').notNull(), + content: text('content').notNull().default(''), + filePath: text('file_path'), + enabled: boolean('enabled').notNull().default(true), + ownerId: text('owner_id'), + createdAt: bigint('created_at', { mode: 'number' }).notNull(), + updatedAt: bigint('updated_at', { mode: 'number' }).notNull(), +}) + export const publishTargets = pgTable('publish_targets', { id: text('id').primaryKey(), name: text('name').notNull(), diff --git a/src/renderer/components/agents/AgentEditor.tsx b/src/renderer/components/agents/AgentEditor.tsx index 850b878..094c0c5 100644 --- a/src/renderer/components/agents/AgentEditor.tsx +++ b/src/renderer/components/agents/AgentEditor.tsx @@ -176,7 +176,7 @@ export const AgentEditor = forwardRef<AgentEditorHandle, AgentEditorProps>(funct const { data: allRepos = [] } = useRepositories() const { data: triggers = [] } = useTriggers(agentId) useRepoSyncEvents() - const { setShowPublishTargets, setShowRepositories } = useUIStore() + const { setShowPublishTargets, setShowRepositories, setShowSettings } = useUIStore() const [draft, setDraft] = useState<Partial<AgentConfig>>({}) const [saveState, setSaveState] = useState<SaveState>('idle') @@ -422,6 +422,16 @@ export const AgentEditor = forwardRef<AgentEditorHandle, AgentEditorProps>(funct {/* Prompt — the heart of the agent */} <CollapsibleSection title="Prompt" hero summary={promptSummary}> + <p className="text-[11px] text-[var(--text-secondary)] mb-2"> + Conduit-wide instructions and files are prepended automatically.{' '} + <button + type="button" + className="text-[var(--accent)] hover:underline" + onClick={() => setShowSettings(true)} + > + Manage in Settings + </button> + </p> <PromptEditor value={draft.prompt ?? ''} onChange={(v) => handleChange('prompt', v)} diff --git a/src/renderer/components/settings/PromptComponentManager.tsx b/src/renderer/components/settings/PromptComponentManager.tsx new file mode 100644 index 0000000..7fd26ef --- /dev/null +++ b/src/renderer/components/settings/PromptComponentManager.tsx @@ -0,0 +1,397 @@ +import React, { useState } from 'react' +import { Plus, Pencil, Trash2, Info, Loader2, X, Check, Share2, FileText, ScrollText } from 'lucide-react' +import { Button } from '@renderer/components/ui/button' +import { Input } from '@renderer/components/ui/input' +import { ShareDialog } from '@renderer/components/ShareDialog' +import { + useGlobalPromptComponents, + useCreateGlobalPromptComponent, + useUpdateGlobalPromptComponent, + useDeleteGlobalPromptComponent, +} from '@renderer/hooks/useGlobalPromptComponents' +import { useAuth } from '@renderer/contexts/AuthContext' +import { useToast } from '@renderer/contexts/ToastContext' +import { cn } from '@renderer/lib/utils' +import type { GlobalPromptComponent, GlobalPromptComponentKind } from '@shared/types' + +interface FormState { + name: string + kind: GlobalPromptComponentKind + content: string + filePath: string + enabled: boolean +} + +const emptyForm = (): FormState => ({ + name: '', + kind: 'instruction', + content: '', + filePath: '', + enabled: true, +}) + +function formFrom(item: GlobalPromptComponent): FormState { + return { + name: item.name, + kind: item.kind, + content: item.content, + filePath: item.filePath ?? '', + enabled: item.enabled, + } +} + +function ComponentForm({ + initial, + onSave, + onClose, + saving, +}: { + initial: FormState + onSave: (values: FormState) => Promise<{ ok: boolean; error?: string }> + onClose: () => void + saving: boolean +}) { + const [form, setForm] = useState(initial) + const [error, setError] = useState<string | null>(null) + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault() + setError(null) + const result = await onSave(form) + if (result.ok) onClose() + else setError(result.error ?? 'Save failed') + } + + return ( + <form + onSubmit={handleSubmit} + className="rounded-lg border border-[var(--border)] px-4 py-3.5 space-y-3" + style={{ background: 'var(--bg-secondary)' }} + > + <div className="flex items-center justify-between"> + <span className="text-sm font-medium text-[var(--text-primary)]"> + {initial.name ? 'Edit component' : 'New component'} + </span> + <button type="button" onClick={onClose} className="text-[var(--text-secondary)] hover:text-[var(--text-primary)]"> + <X className="h-4 w-4" /> + </button> + </div> + + <div className="grid grid-cols-1 sm:grid-cols-2 gap-3"> + <label className="space-y-1"> + <span className="text-xs text-[var(--text-secondary)]">Name</span> + <Input + value={form.name} + onChange={(e) => setForm({ ...form, name: e.target.value })} + placeholder="House style" + required + /> + </label> + <label className="space-y-1"> + <span className="text-xs text-[var(--text-secondary)]">Type</span> + <div className="flex gap-1 p-0.5 rounded-md border border-[var(--border)] bg-[var(--bg-primary)]"> + {(['instruction', 'file'] as GlobalPromptComponentKind[]).map((kind) => ( + <button + key={kind} + type="button" + onClick={() => setForm({ ...form, kind })} + className={cn( + 'flex-1 h-7 rounded text-xs font-medium capitalize transition-colors', + form.kind === kind + ? 'bg-[var(--accent)]/15 text-[var(--accent)]' + : 'text-[var(--text-secondary)] hover:text-[var(--text-primary)]' + )} + > + {kind} + </button> + ))} + </div> + </label> + </div> + + {form.kind === 'file' && ( + <label className="space-y-1 block"> + <span className="text-xs text-[var(--text-secondary)]">Workspace path</span> + <Input + value={form.filePath} + onChange={(e) => setForm({ ...form, filePath: e.target.value })} + placeholder="CLAUDE.md or .cursor/rules/org.mdc" + required + /> + <span className="text-[10px] text-[var(--text-secondary)]"> + Relative to the run workspace. Written on every run so CLIs can pick it up. + </span> + </label> + )} + + <label className="space-y-1 block"> + <span className="text-xs text-[var(--text-secondary)]"> + {form.kind === 'file' ? 'File contents' : 'Instructions'} + </span> + <textarea + value={form.content} + onChange={(e) => setForm({ ...form, content: e.target.value })} + rows={10} + placeholder={ + form.kind === 'file' + ? 'Contents written into the workspace file (and included in the prompt).' + : 'These instructions are prepended to every agent prompt.' + } + className="w-full rounded-md border border-[var(--border)] bg-[var(--bg-primary)] px-3 py-2 text-sm text-[var(--text-primary)] placeholder:text-[var(--text-secondary)] font-mono leading-relaxed focus:outline-none focus:ring-2 focus:ring-[var(--accent)] focus:border-[var(--accent)]" + /> + </label> + + <label className="flex items-center gap-2 text-xs text-[var(--text-secondary)]"> + <input + type="checkbox" + checked={form.enabled} + onChange={(e) => setForm({ ...form, enabled: e.target.checked })} + className="rounded border-[var(--border)]" + /> + Enabled — inject on every run + </label> + + {error && <p className="text-xs text-red-400">{error}</p>} + + <div className="flex justify-end gap-2"> + <Button type="button" variant="ghost" size="sm" onClick={onClose}> + Cancel + </Button> + <Button type="submit" size="sm" disabled={saving} className="gap-1.5"> + {saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Check className="h-3.5 w-3.5" />} + Save + </Button> + </div> + </form> + ) +} + +function ComponentRow({ + item, + isOwner, + onShare, +}: { + item: GlobalPromptComponent + isOwner: boolean + onShare: () => void +}) { + const toast = useToast() + const update = useUpdateGlobalPromptComponent() + const remove = useDeleteGlobalPromptComponent() + const [editing, setEditing] = useState(false) + + if (editing) { + return ( + <ComponentForm + initial={formFrom(item)} + saving={update.isPending} + onClose={() => setEditing(false)} + onSave={async (values) => { + try { + await update.mutateAsync({ + id: item.id, + data: { + name: values.name, + kind: values.kind, + content: values.content, + filePath: values.kind === 'file' ? values.filePath : undefined, + enabled: values.enabled, + }, + }) + return { ok: true } + } catch (err) { + return { ok: false, error: err instanceof Error ? err.message : String(err) } + } + }} + /> + ) + } + + return ( + <div + className="rounded-lg border border-[var(--border)] px-4 py-3 flex items-start gap-3" + style={{ background: 'var(--bg-secondary)' }} + > + <div + className={cn( + 'mt-0.5 flex-shrink-0 w-7 h-7 rounded-md flex items-center justify-center', + item.enabled ? 'bg-[var(--accent)]/15 text-[var(--accent)]' : 'bg-[var(--bg-primary)] text-[var(--text-secondary)]' + )} + > + {item.kind === 'file' ? <FileText className="h-3.5 w-3.5" /> : <ScrollText className="h-3.5 w-3.5" />} + </div> + <div className="min-w-0 flex-1"> + <div className="flex items-center gap-2"> + <span className="text-sm font-medium text-[var(--text-primary)] truncate">{item.name}</span> + <span className="text-[10px] uppercase tracking-wide text-[var(--text-secondary)]">{item.kind}</span> + {!item.enabled && ( + <span className="text-[10px] px-1.5 py-0.5 rounded bg-[var(--bg-primary)] text-[var(--text-secondary)]"> + Off + </span> + )} + </div> + {item.kind === 'file' && item.filePath && ( + <code className="text-[11px] text-[var(--text-secondary)]">{item.filePath}</code> + )} + <p className="text-xs text-[var(--text-secondary)] mt-1 line-clamp-2 whitespace-pre-wrap"> + {item.content.trim() || '(empty)'} + </p> + </div> + <div className="flex items-center gap-0.5 flex-shrink-0"> + <button + type="button" + title={item.enabled ? 'Disable' : 'Enable'} + onClick={() => + update.mutate( + { id: item.id, data: { enabled: !item.enabled } }, + { onError: (err) => toast.error(err instanceof Error ? err.message : String(err)) } + ) + } + className={cn( + 'h-7 px-2 rounded text-[10px] font-medium', + item.enabled ? 'text-[var(--accent)]' : 'text-[var(--text-secondary)]' + )} + > + {item.enabled ? 'On' : 'Off'} + </button> + <Button variant="ghost" size="sm" className="px-1.5" title="Edit" onClick={() => setEditing(true)}> + <Pencil className="h-3.5 w-3.5" /> + </Button> + {isOwner && ( + <Button variant="ghost" size="sm" className="px-1.5" title="Share" onClick={onShare}> + <Share2 className="h-3.5 w-3.5" /> + </Button> + )} + {isOwner && ( + <Button + variant="ghost" + size="sm" + className="px-1.5 text-[var(--text-secondary)] hover:text-red-400" + title="Delete" + disabled={remove.isPending} + onClick={() => { + if (!window.confirm(`Delete "${item.name}"? It will no longer be added to runs.`)) return + remove.mutate(item.id, { + onSuccess: () => toast.success('Prompt component deleted'), + onError: (err) => toast.error(err instanceof Error ? err.message : String(err)), + }) + }} + > + <Trash2 className="h-3.5 w-3.5" /> + </Button> + )} + </div> + </div> + ) +} + +export function PromptComponentManager() { + const { data: items = [], isLoading } = useGlobalPromptComponents() + const { user } = useAuth() + const create = useCreateGlobalPromptComponent() + const [showAdd, setShowAdd] = useState(false) + const [shareId, setShareId] = useState<string | null>(null) + + const isLegacyGlobal = (s: { ownerId?: string | null }) => s.ownerId == null || s.ownerId === 'dev-user' + const mine = items.filter((s) => s.ownerId === user?.id) + const shared = items.filter((s) => s.ownerId !== user?.id) + + return ( + <div id="prompt-components" className="space-y-3"> + <div className="flex items-center justify-between gap-3"> + <h2 className="text-xs font-medium text-[var(--text-secondary)]">Prompt components</h2> + <Button size="sm" onClick={() => setShowAdd(true)} disabled={showAdd} className="gap-1.5"> + <Plus className="h-3.5 w-3.5" /> + Add + </Button> + </div> + + <div className="flex items-start gap-2.5 px-3 py-2.5 rounded-lg bg-[var(--accent)]/10 border border-[var(--accent)]/20 text-xs text-[var(--text-secondary)]"> + <Info className="h-3.5 w-3.5 text-[var(--accent)] flex-shrink-0 mt-0.5" /> + <span> + <strong className="text-[var(--text-primary)]">Instructions</strong> are prepended to every agent prompt.{' '} + <strong className="text-[var(--text-primary)]">Files</strong> are written into the run workspace (and also + included in the prompt). Enabled items apply to all runs; share an item so others can view or edit it. + </span> + </div> + + {showAdd && ( + <ComponentForm + initial={emptyForm()} + saving={create.isPending} + onClose={() => setShowAdd(false)} + onSave={async (values) => { + try { + await create.mutateAsync({ + name: values.name, + kind: values.kind, + content: values.content, + filePath: values.kind === 'file' ? values.filePath : undefined, + enabled: values.enabled, + }) + return { ok: true } + } catch (err) { + return { ok: false, error: err instanceof Error ? err.message : String(err) } + } + }} + /> + )} + + {isLoading ? ( + <div className="flex items-center justify-center py-8 text-sm text-[var(--text-secondary)]"> + <Loader2 className="h-4 w-4 animate-spin mr-2" /> + Loading… + </div> + ) : items.length === 0 && !showAdd ? ( + <div className="rounded-lg border border-[var(--border)] px-4 py-6 text-center space-y-2" style={{ background: 'var(--bg-secondary)' }}> + <p className="text-sm text-[var(--text-secondary)]">No Conduit-wide instructions or files yet.</p> + <p className="text-xs text-[var(--text-secondary)]"> + Add house style, org rules, or a CLAUDE.md / AGENTS.md that every agent should see. + </p> + <Button size="sm" variant="outline" className="mt-1 gap-1.5" onClick={() => setShowAdd(true)}> + <Plus className="h-3.5 w-3.5" /> + Add your first component + </Button> + </div> + ) : ( + <div className="space-y-2"> + {mine.length > 0 && ( + <> + <div className="text-[10px] font-medium uppercase tracking-wider text-[var(--text-secondary)] px-1 py-1"> + Mine <span className="ml-1 opacity-60">{mine.length}</span> + </div> + {mine.map((item) => ( + <ComponentRow key={item.id} item={item} isOwner onShare={() => setShareId(item.id)} /> + ))} + </> + )} + {shared.length > 0 && ( + <> + <div className="text-[10px] font-medium uppercase tracking-wider text-[var(--text-secondary)] px-1 py-1"> + Shared with me <span className="ml-1 opacity-60">{shared.length}</span> + </div> + {shared.map((item) => ( + <ComponentRow + key={item.id} + item={item} + isOwner={isLegacyGlobal(item)} + onShare={() => setShareId(item.id)} + /> + ))} + </> + )} + </div> + )} + + {shareId && ( + <ShareDialog + entityType="globalPromptComponent" + entityId={shareId} + isOpen={!!shareId} + onClose={() => setShareId(null)} + /> + )} + </div> + ) +} + diff --git a/src/renderer/components/settings/SettingsManager.tsx b/src/renderer/components/settings/SettingsManager.tsx index 1d70621..1a3360e 100644 --- a/src/renderer/components/settings/SettingsManager.tsx +++ b/src/renderer/components/settings/SettingsManager.tsx @@ -8,6 +8,7 @@ import { useDataDirSweep } from '@renderer/hooks/useDataDirSweep' import { useStorageUsage } from '@renderer/hooks/useStorageUsage' import { formatBytes } from '@renderer/lib/utils' import type { RunnerType, SweepResult } from '@shared/types' +import { PromptComponentManager } from './PromptComponentManager' interface RunnerMeta { runner: RunnerType @@ -278,13 +279,13 @@ export function SettingsManager() { <div> <h1 className="text-sm font-semibold text-[var(--text-primary)]">Settings</h1> <p className="text-xs text-[var(--text-secondary)] mt-0.5"> - Agent authentication and storage maintenance + Agent authentication, Conduit-wide prompts, and storage </p> </div> </div> {/* Body */} - <div className="flex-1 overflow-y-auto px-5 py-4 space-y-3 max-w-2xl"> + <div className="flex-1 overflow-y-auto px-5 py-4 space-y-3 max-w-3xl"> <div className="flex items-start gap-2.5 px-3 py-2.5 rounded-lg bg-[var(--accent)]/10 border border-[var(--accent)]/20 text-xs text-[var(--text-secondary)]"> <Info className="h-3.5 w-3.5 text-[var(--accent)] flex-shrink-0 mt-0.5" /> <span> @@ -305,6 +306,10 @@ export function SettingsManager() { /> ))} + <div className="pt-3"> + <PromptComponentManager /> + </div> + <h2 className="text-xs font-medium text-[var(--text-secondary)] pt-3">Storage maintenance</h2> <StorageMaintenanceCard /> </div> diff --git a/src/renderer/hooks/useGlobalPromptComponents.ts b/src/renderer/hooks/useGlobalPromptComponents.ts new file mode 100644 index 0000000..8419198 --- /dev/null +++ b/src/renderer/hooks/useGlobalPromptComponents.ts @@ -0,0 +1,49 @@ +import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' +import { api } from '@renderer/lib/ipc' +import type { GlobalPromptComponent } from '@shared/types' + +const KEY = ['globalPromptComponents'] as const + +export function useGlobalPromptComponents() { + return useQuery({ + queryKey: KEY, + queryFn: () => api.globalPromptComponents.list(), + }) +} + +export function useCreateGlobalPromptComponent() { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: (data: Omit<GlobalPromptComponent, 'id' | 'createdAt' | 'updatedAt'>) => + api.globalPromptComponents.create(data), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: KEY }) + }, + }) +} + +export function useUpdateGlobalPromptComponent() { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: ({ + id, + data, + }: { + id: string + data: Partial<Omit<GlobalPromptComponent, 'id' | 'createdAt' | 'updatedAt'>> + }) => api.globalPromptComponents.update(id, data), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: KEY }) + }, + }) +} + +export function useDeleteGlobalPromptComponent() { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: (id: string) => api.globalPromptComponents.delete(id), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: KEY }) + }, + }) +} diff --git a/src/renderer/hooks/useShares.ts b/src/renderer/hooks/useShares.ts index 11d14cb..79c56ce 100644 --- a/src/renderer/hooks/useShares.ts +++ b/src/renderer/hooks/useShares.ts @@ -14,6 +14,8 @@ function entityListKey(entityType: ShareableEntityType): string[] { return ['repos'] case 'globalMcpServer': return ['globalMcps'] + case 'globalPromptComponent': + return ['globalPromptComponents'] } } diff --git a/src/renderer/lib/ipc.ts b/src/renderer/lib/ipc.ts index 9bfa5d0..20c3b0b 100644 --- a/src/renderer/lib/ipc.ts +++ b/src/renderer/lib/ipc.ts @@ -29,6 +29,9 @@ export const api = { get globalMcps() { return getConduit().globalMcps }, + get globalPromptComponents() { + return getConduit().globalPromptComponents + }, get repos() { return getConduit().repos }, diff --git a/src/renderer/lib/ws-client.ts b/src/renderer/lib/ws-client.ts index da0c641..3f30cdb 100644 --- a/src/renderer/lib/ws-client.ts +++ b/src/renderer/lib/ws-client.ts @@ -8,6 +8,7 @@ import type { ExecutionRun, RunLog, GlobalMcpServer, + GlobalPromptComponent, PublishTarget, Repository, RepositoryInput, @@ -229,6 +230,17 @@ export function createWsConduitClient(wsUrl: string): ConduitAPI { invoke<import('@shared/types').McpToolsResult>('globalMcps:listTools', serverConfig), }, + globalPromptComponents: { + list: () => invoke<GlobalPromptComponent[]>('globalPromptComponents:list'), + create: (data: Omit<GlobalPromptComponent, 'id' | 'createdAt' | 'updatedAt'>) => + invoke<GlobalPromptComponent>('globalPromptComponents:create', data), + update: ( + id: string, + data: Partial<Omit<GlobalPromptComponent, 'id' | 'createdAt' | 'updatedAt'>> + ) => invoke<GlobalPromptComponent>('globalPromptComponents:update', id, data), + delete: (id: string) => invoke<void>('globalPromptComponents:delete', id), + }, + repos: { list: () => invoke<Repository[]>('repos:list'), get: (id: string) => invoke<Repository | null>('repos:get', id), diff --git a/src/renderer/store/ui.ts b/src/renderer/store/ui.ts index dc1aac0..368f332 100644 --- a/src/renderer/store/ui.ts +++ b/src/renderer/store/ui.ts @@ -2,6 +2,13 @@ import { create } from 'zustand' type Theme = 'dark' | 'light' | 'system' +const exclusiveOff = { + showGlobalMcpManager: false, + showPublishTargets: false, + showRepositories: false, + showSettings: false, +} + interface UIState { selectedAgentId: string | null activeRunId: string | null @@ -85,13 +92,21 @@ interface UrlState { } function readUrlState(): UrlState { - const empty: UrlState = { agentId: null, runId: null, globalMcps: false, publishTargets: false, repositories: false, settings: false } + const empty: UrlState = { + agentId: null, + runId: null, + globalMcps: false, + publishTargets: false, + repositories: false, + settings: false, + } if (typeof window === 'undefined') return empty const path = window.location.pathname const globalMcps = path === '/global-mcps' const publishTargets = path === '/publish-targets' const repositories = path === '/repositories' - const settings = path === '/settings' + // Prompt components used to have their own route; they now live in Settings. + const settings = path === '/settings' || path === '/prompt-components' // /agents/:agentId/runs/:runId (deep link to a run) or /agents/:agentId const runMatch = path.match(/^\/agents\/([^/]+)\/runs\/([^/]+)$/) if (runMatch) return { ...empty, agentId: runMatch[1], runId: runMatch[2] } @@ -123,7 +138,7 @@ export const useUIStore = create<UIState>((set, get) => ({ // from the previous one. selectAgent: (id) => { pushUrl(id ? `/agents/${id}` : '/') - set({ selectedAgentId: id, activeRunId: null, viewedRunId: null, showGlobalMcpManager: false, showPublishTargets: false, showRepositories: false, showSettings: false }) + set({ selectedAgentId: id, activeRunId: null, viewedRunId: null, ...exclusiveOff }) }, setViewedRun: (id) => { @@ -145,22 +160,22 @@ export const useUIStore = create<UIState>((set, get) => ({ setShowGlobalMcpManager: (show) => { pushUrl(show ? '/global-mcps' : '/') - set({ showGlobalMcpManager: show, showPublishTargets: false, showRepositories: false, showSettings: false }) + set({ ...exclusiveOff, showGlobalMcpManager: show }) }, setShowPublishTargets: (show) => { pushUrl(show ? '/publish-targets' : '/') - set({ showPublishTargets: show, showGlobalMcpManager: false, showRepositories: false, showSettings: false }) + set({ ...exclusiveOff, showPublishTargets: show }) }, setShowRepositories: (show) => { pushUrl(show ? '/repositories' : '/') - set({ showRepositories: show, showGlobalMcpManager: false, showPublishTargets: false, showSettings: false }) + set({ ...exclusiveOff, showRepositories: show }) }, setShowSettings: (show) => { pushUrl(show ? '/settings' : '/') - set({ showSettings: show, showGlobalMcpManager: false, showPublishTargets: false, showRepositories: false }) + set({ ...exclusiveOff, showSettings: show }) }, setTheme: (theme) => { diff --git a/src/server/index.ts b/src/server/index.ts index afd1012..5a92aea 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -25,6 +25,13 @@ import { updateGlobalMcp, deleteGlobalMcp, } from '../main/db/queries/globalMcps' +import { + listGlobalPromptComponents, + getGlobalPromptComponent, + createGlobalPromptComponent, + updateGlobalPromptComponent, + deleteGlobalPromptComponent, +} from '../main/db/queries/globalPromptComponents' import { listPublishTargets, getPublishTarget, @@ -87,6 +94,7 @@ import type { ReporterUser } from '../shared/observability' import type { AgentConfig, GlobalMcpServer, + GlobalPromptComponent, PublishTarget, RepositoryInput, RepoTestConnectionInput, @@ -331,6 +339,46 @@ const handlers: Record<string, HandlerFn> = { return Promise.resolve() }, + // Conduit-wide prompt components (instructions + files injected into every run) + 'globalPromptComponents:list': (_args, _ws, ctx) => + Promise.resolve(listGlobalPromptComponents(ctx.userId, ctx.userGroupIds)), + 'globalPromptComponents:create': async ([data], _ws, ctx) => { + try { + return await createGlobalPromptComponent( + data as Omit<GlobalPromptComponent, 'id' | 'createdAt' | 'updatedAt'>, + ctx.userId + ) + } catch (err) { + throw new ClientError(err instanceof Error ? err.message : String(err)) + } + }, + 'globalPromptComponents:update': async ([id, data], _ws, ctx) => { + if (!(await canAccessEntity('globalPromptComponent', id as string, ctx.userId, ctx.userGroupIds))) { + throw new ClientError('Access denied') + } + try { + return await updateGlobalPromptComponent( + id as string, + data as Partial<Omit<GlobalPromptComponent, 'id' | 'createdAt' | 'updatedAt'>> + ) + } catch (err) { + throw new ClientError(err instanceof Error ? err.message : String(err)) + } + }, + 'globalPromptComponents:delete': async ([id], _ws, ctx) => { + const existing = await getGlobalPromptComponent(id as string) + if (!existing) throw new ClientError('Prompt component not found') + const isLegacyGlobal = existing.ownerId == null || existing.ownerId === DEV_USER_ID + if ( + !isLegacyGlobal && + !(await isEntityOwner('globalPromptComponent', id as string, ctx.userId)) + ) { + throw new ClientError('Only the owner can delete this prompt component') + } + const deleted = await deleteGlobalPromptComponent(id as string) + if (deleted === 0) throw new ClientError('Prompt component not found') + }, + 'globalMcps:checkHealth': async ([serverConfig]) => { const config = serverConfig as import('../shared/types').McpServerEntry diff --git a/src/server/runner.ts b/src/server/runner.ts index 2a8dac0..5b6b0f5 100644 --- a/src/server/runner.ts +++ b/src/server/runner.ts @@ -19,6 +19,8 @@ import { buildRunFailureReport } from './runFailure' import { resolvePushCredential, githubTokenEnvEntry } from './githubApp' import { publishRunResult } from './publisher' import { buildTriggeredPrompt } from './triggers/promptBuilder' +import { listEnabledGlobalPromptComponents } from '../main/db/queries/globalPromptComponents' +import { applyGlobalPromptComponents, workspaceFilesFromComponents } from '../shared/promptComponents' import { createRunEventHandlers } from './runEventSink' import { resolveRunLogMaxBytes } from './runDeliveryLog' import { reporter } from './observability' @@ -578,13 +580,16 @@ export async function startRunServer( // 6. Build the fully-resolved RunSpec and hand execution to the worker // factory. Events stream back through the sink into the pipeline above. + const agentPrompt = triggerContext ? buildTriggeredPrompt(agent.prompt, triggerContext) : agent.prompt + const promptComponents = await listEnabledGlobalPromptComponents() const spec: RunSpec = { runId, agentId, runner: agent.runner, model: agent.model, effort: agent.effort, - prompt: triggerContext ? buildTriggeredPrompt(agent.prompt, triggerContext) : agent.prompt, + prompt: applyGlobalPromptComponents(agentPrompt, promptComponents), + workspaceFiles: workspaceFilesFromComponents(promptComponents), env: await buildRunnerEnvOverlay(agent, startedBy, pushToken), mcpConfigContent, strictMcpConfig: agent.runner === 'claude' ? !agent.enableRepoMcps : undefined, diff --git a/src/server/workers/localWorker.ts b/src/server/workers/localWorker.ts index 1649513..6edbf60 100644 --- a/src/server/workers/localWorker.ts +++ b/src/server/workers/localWorker.ts @@ -4,6 +4,7 @@ import type { RunSpec, WorkerEventSink, WorkerFactory, WorkerHandle } from '../. import { createWorkspace, deleteWorkspace } from '../../main/execution/workspace' import { writeMcpConfigContent, deleteMcpConfig } from '../../main/utils/mcpConfigFile' import { writeClaudeConfig, deleteClaudeConfig } from '../../main/utils/claudeConfig' +import { writeWorkspaceFiles } from '../workspaceFiles' import { createConfiguredWorktree, removeWorktree, runGit, buildAuthUrl, configureWorktreeGit, DEFAULT_GIT_TIMEOUT_MS } from '../gitOps' import { buildClaudeArgs, parseClaudeEvents } from '../../main/execution/adapters/claude' import { buildAmpArgs, parseAmpEvents } from '../../main/execution/adapters/amp' @@ -62,6 +63,9 @@ export class LocalWorkerFactory implements WorkerFactory { } try { + if (spec.workspaceFiles && spec.workspaceFiles.length > 0) { + writeWorkspaceFiles(workspacePath, spec.workspaceFiles) + } return await this.spawn(spec, sink, workspacePath, worktreeClonePath, ephemeral) } catch (err) { // Roll back everything this factory created so a failed start never diff --git a/src/server/workspaceFiles.test.ts b/src/server/workspaceFiles.test.ts new file mode 100644 index 0000000..af7b079 --- /dev/null +++ b/src/server/workspaceFiles.test.ts @@ -0,0 +1,43 @@ +import * as fs from 'fs' +import * as os from 'os' +import * as path from 'path' +import { afterEach, describe, expect, it } from 'vitest' +import { writeWorkspaceFiles } from './workspaceFiles' + +const dirs: string[] = [] + +afterEach(() => { + for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }) + dirs.length = 0 +}) + +function tmp(): string { + const d = fs.mkdtempSync(path.join(os.tmpdir(), 'conduit-ws-')) + dirs.push(d) + return d +} + +describe('writeWorkspaceFiles', () => { + it('writes nested relative files', () => { + const root = tmp() + writeWorkspaceFiles(root, [{ path: '.cursor/rules/org.mdc', content: 'always apply', name: 'Org rules' }]) + expect(fs.readFileSync(path.join(root, '.cursor/rules/org.mdc'), 'utf8')).toBe('always apply\n') + }) + + it('prepends when the file already exists', () => { + const root = tmp() + fs.writeFileSync(path.join(root, 'CLAUDE.md'), 'from the repo\n') + writeWorkspaceFiles(root, [{ path: 'CLAUDE.md', content: 'from conduit', name: 'Global CLAUDE.md' }]) + const out = fs.readFileSync(path.join(root, 'CLAUDE.md'), 'utf8') + expect(out).toContain('BEGIN CONDUIT-WIDE FILE: Global CLAUDE.md') + expect(out).toContain('from conduit') + expect(out.endsWith('from the repo\n')).toBe(true) + }) + + it('refuses paths that escape the workspace', () => { + const root = tmp() + expect(() => + writeWorkspaceFiles(root, [{ path: '../escape.md', content: 'nope', name: 'x' }]) + ).toThrow(/"\.\."/) + }) +}) diff --git a/src/server/workspaceFiles.ts b/src/server/workspaceFiles.ts new file mode 100644 index 0000000..2bed541 --- /dev/null +++ b/src/server/workspaceFiles.ts @@ -0,0 +1,36 @@ +import * as fs from 'fs' +import * as path from 'path' +import { normalizeWorkspaceRelativePath } from '../shared/promptComponents' + +/** + * Write Conduit-wide files into a materialized workspace. Parent directories + * are created as needed. If the target already exists, the Conduit content is + * prepended so a repo's own file is not discarded. + */ +export function writeWorkspaceFiles( + workspaceRoot: string, + files: { path: string; content: string; name: string }[] +): void { + const root = path.resolve(workspaceRoot) + for (const file of files) { + const relative = normalizeWorkspaceRelativePath(file.path) + const dest = path.resolve(root, relative) + const relativeToRoot = path.relative(root, dest) + if (relativeToRoot.startsWith('..') || path.isAbsolute(relativeToRoot)) { + throw new Error(`Refusing to write workspace file outside the workspace: ${file.path}`) + } + fs.mkdirSync(path.dirname(dest), { recursive: true }) + const banner = [ + `===== BEGIN CONDUIT-WIDE FILE: ${file.name} =====`, + file.content, + `===== END CONDUIT-WIDE FILE: ${file.name} =====`, + '', + ].join('\n') + if (fs.existsSync(dest)) { + const existing = fs.readFileSync(dest, 'utf8') + fs.writeFileSync(dest, `${banner}${existing}`, 'utf8') + } else { + fs.writeFileSync(dest, file.content.endsWith('\n') ? file.content : `${file.content}\n`, 'utf8') + } + } +} diff --git a/src/shared/promptComponents.test.ts b/src/shared/promptComponents.test.ts new file mode 100644 index 0000000..a1cac8e --- /dev/null +++ b/src/shared/promptComponents.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from 'vitest' +import { + applyGlobalPromptComponents, + normalizeWorkspaceRelativePath, + validatePromptComponentInput, + workspaceFilesFromComponents, +} from './promptComponents' + +describe('normalizeWorkspaceRelativePath', () => { + it('normalizes dots and backslashes', () => { + expect(normalizeWorkspaceRelativePath(' .cursor/rules/foo.mdc ')).toBe('.cursor/rules/foo.mdc') + expect(normalizeWorkspaceRelativePath('docs\\guide.md')).toBe('docs/guide.md') + expect(normalizeWorkspaceRelativePath('./AGENTS.md')).toBe('AGENTS.md') + }) + + it('rejects traversal and absolute paths', () => { + expect(() => normalizeWorkspaceRelativePath('../secret')).toThrow(/"\.\."/) + expect(() => normalizeWorkspaceRelativePath('/etc/passwd')).toThrow(/relative/) + expect(() => normalizeWorkspaceRelativePath('C:\\Windows')).toThrow(/relative/) + expect(() => normalizeWorkspaceRelativePath('')).toThrow(/required/) + }) +}) + +describe('validatePromptComponentInput', () => { + it('requires a name and a file path for file kind', () => { + expect(() => validatePromptComponentInput({ name: ' ', kind: 'instruction' })).toThrow(/Name/) + expect(() => validatePromptComponentInput({ name: 'x', kind: 'other' })).toThrow(/Kind/) + expect(() => validatePromptComponentInput({ name: 'x', kind: 'file' })).toThrow(/required/) + expect(validatePromptComponentInput({ name: 'Rules', kind: 'file', filePath: 'CLAUDE.md' })).toEqual({ + kind: 'file', + filePath: 'CLAUDE.md', + }) + expect(validatePromptComponentInput({ name: 'Tone', kind: 'instruction' })).toEqual({ + kind: 'instruction', + }) + }) +}) + +describe('applyGlobalPromptComponents', () => { + it('returns the agent prompt unchanged when nothing is enabled', () => { + expect(applyGlobalPromptComponents('do the thing', [])).toBe('do the thing') + expect( + applyGlobalPromptComponents('do the thing', [ + { name: 'off', kind: 'instruction', content: 'nope', enabled: false }, + { name: 'empty', kind: 'instruction', content: ' ', enabled: true }, + ]) + ).toBe('do the thing') + }) + + it('prepends instructions then inlines files, oldest first', () => { + const withDates = [ + { name: 'Later', kind: 'instruction' as const, content: 'later', enabled: true, createdAt: 20 }, + { name: 'First', kind: 'instruction' as const, content: 'first', enabled: true, createdAt: 10 }, + { + name: 'House style', + kind: 'file' as const, + content: 'use tabs', + filePath: 'STYLE.md', + enabled: true, + createdAt: 15, + }, + ] + const out = applyGlobalPromptComponents('agent task', withDates) + expect(out).toContain('# Conduit-wide instructions') + expect(out.indexOf('## First')).toBeLessThan(out.indexOf('## Later')) + expect(out).toContain('### `STYLE.md` (House style)') + expect(out).toContain('use tabs') + expect(out.endsWith('agent task')).toBe(true) + expect(out).toContain('\n---\n') + }) +}) + +describe('workspaceFilesFromComponents', () => { + it('returns only enabled files, oldest first', () => { + expect( + workspaceFilesFromComponents([ + { name: 'B', kind: 'file', content: 'b', filePath: 'b.md', enabled: true, createdAt: 2 }, + { name: 'A', kind: 'file', content: 'a', filePath: 'a.md', enabled: true, createdAt: 1 }, + { name: 'Off', kind: 'file', content: 'x', filePath: 'x.md', enabled: false, createdAt: 0 }, + { name: 'Instr', kind: 'instruction', content: 'i', enabled: true, createdAt: 0 }, + ]) + ).toEqual([ + { path: 'a.md', content: 'a', name: 'A' }, + { path: 'b.md', content: 'b', name: 'B' }, + ]) + }) +}) diff --git a/src/shared/promptComponents.ts b/src/shared/promptComponents.ts new file mode 100644 index 0000000..838d091 --- /dev/null +++ b/src/shared/promptComponents.ts @@ -0,0 +1,118 @@ +import type { GlobalPromptComponent } from './types' + +const MAX_RELATIVE_PATH_LENGTH = 512 + +/** + * Normalize a workspace-relative file path. Rejects absolute paths, `..` + * traversal, empty paths, and NUL bytes so a component cannot write outside + * the run workspace. + */ +export function normalizeWorkspaceRelativePath(raw: string): string { + const trimmed = raw.trim().replace(/\\/g, '/') + if (!trimmed) { + throw new Error('File path is required for file components.') + } + if (trimmed.length > MAX_RELATIVE_PATH_LENGTH) { + throw new Error(`File path must be at most ${MAX_RELATIVE_PATH_LENGTH} characters.`) + } + if (trimmed.includes('\0')) { + throw new Error('File path cannot contain a NUL byte.') + } + if (trimmed.startsWith('/') || /^[a-zA-Z]:/.test(trimmed)) { + throw new Error('File path must be relative to the workspace (not absolute).') + } + const parts = trimmed.split('/').filter((p) => p !== '' && p !== '.') + if (parts.length === 0) { + throw new Error('File path is required for file components.') + } + if (parts.some((p) => p === '..')) { + throw new Error('File path cannot contain ".." segments.') + } + return parts.join('/') +} + +export function validatePromptComponentInput(data: { + name: string + kind: string + content?: string + filePath?: string | null +}): { kind: 'instruction' | 'file'; filePath?: string } { + const name = data.name.trim() + if (!name) { + throw new Error('Name is required.') + } + if (data.kind !== 'instruction' && data.kind !== 'file') { + throw new Error('Kind must be "instruction" or "file".') + } + if (data.kind === 'file') { + return { kind: 'file', filePath: normalizeWorkspaceRelativePath(data.filePath ?? '') } + } + return { kind: 'instruction' } +} + +type PromptComponentInput = Pick< + GlobalPromptComponent, + 'name' | 'kind' | 'content' | 'filePath' | 'enabled' +> & { createdAt?: number } + +export function sortPromptComponents<T extends { createdAt?: number; name: string }>(items: T[]): T[] { + return [...items].sort( + (a, b) => (a.createdAt ?? 0) - (b.createdAt ?? 0) || a.name.localeCompare(b.name) + ) +} + +/** + * Prepend enabled Conduit-wide instructions and file contents to an agent prompt. + * No-op when there are no enabled components with content. + */ +export function applyGlobalPromptComponents( + agentPrompt: string, + components: PromptComponentInput[] +): string { + const enabled = sortPromptComponents( + components.filter((c) => c.enabled && c.content.trim().length > 0) + ) + if (enabled.length === 0) return agentPrompt + + const instructions = enabled.filter((c) => c.kind === 'instruction') + const files = enabled.filter((c) => c.kind === 'file') + + const parts: string[] = ['# Conduit-wide instructions', ''] + parts.push( + 'These apply to every agent run in this Conduit instance. Follow them in addition to the agent prompt below.' + ) + parts.push('') + + for (const item of instructions) { + parts.push(`## ${item.name}`, '', item.content.trim(), '') + } + + if (files.length > 0) { + parts.push( + '## Files in the workspace', + '', + 'The following files have also been written into the run workspace (paths are relative to the working directory):', + '' + ) + for (const item of files) { + const path = item.filePath ?? item.name + parts.push(`### \`${path}\` (${item.name})`, '', '```', item.content.trim(), '```', '') + } + } + + parts.push('---', '', agentPrompt) + return parts.join('\n') +} + +export function workspaceFilesFromComponents( + components: PromptComponentInput[] +): { path: string; content: string; name: string }[] { + const files = sortPromptComponents( + components.filter((c) => c.enabled && c.kind === 'file' && c.filePath) + ) + return files.map((c) => ({ + path: c.filePath as string, + content: c.content, + name: c.name, + })) +} diff --git a/src/shared/types.ts b/src/shared/types.ts index 45b84e1..9e6f498 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -88,7 +88,12 @@ export interface Group { updatedAt: number } -export type ShareableEntityType = 'agent' | 'publishTarget' | 'repository' | 'globalMcpServer' +export type ShareableEntityType = + | 'agent' + | 'publishTarget' + | 'repository' + | 'globalMcpServer' + | 'globalPromptComponent' export interface Share { id: string @@ -379,6 +384,26 @@ export interface GlobalMcpServer { updatedAt: number } +/** + * Instance-wide prompt component. Enabled items are applied to every agent run: + * instructions are prepended to the prompt, files are written into the workspace + * (and their contents are also included in the prompt). + */ +export type GlobalPromptComponentKind = 'instruction' | 'file' + +export interface GlobalPromptComponent { + id: string + name: string + kind: GlobalPromptComponentKind + content: string + /** Workspace-relative path; required when kind is `file`. */ + filePath?: string + enabled: boolean + ownerId?: string + createdAt: number + updatedAt: number +} + // ── Repositories ──────────────────────────────────────────────────────────── export type RepoSyncStatus = 'pending' | 'cloning' | 'ready' | 'syncing' | 'error' @@ -597,6 +622,17 @@ export interface ConduitAPI { checkHealth: (serverConfig: McpServerEntry) => Promise<McpHealthResult> listTools: (serverConfig: McpServerEntry) => Promise<McpToolsResult> } + globalPromptComponents: { + list: () => Promise<GlobalPromptComponent[]> + create: ( + data: Omit<GlobalPromptComponent, 'id' | 'createdAt' | 'updatedAt'> + ) => Promise<GlobalPromptComponent> + update: ( + id: string, + data: Partial<Omit<GlobalPromptComponent, 'id' | 'createdAt' | 'updatedAt'>> + ) => Promise<GlobalPromptComponent> + delete: (id: string) => Promise<void> + } runners: { /** Report which runner CLIs are installed and on the server's PATH. */ checkCli: () => Promise<RunnerCliStatus[]> diff --git a/src/shared/worker.ts b/src/shared/worker.ts index 1cd9c4e..848ddd0 100644 --- a/src/shared/worker.ts +++ b/src/shared/worker.ts @@ -47,6 +47,12 @@ export interface RunSpec { effort?: string /** Final prompt (trigger context already folded in). Written to the CLI's stdin. */ prompt: string + /** + * Files to write into the workspace after it is materialized (Conduit-wide + * prompt files). Paths are workspace-relative; the worker creates parent + * directories. Existing files are prepended to, not overwritten. + */ + workspaceFiles?: { path: string; content: string; name: string }[] /** * Env overlay applied on top of the worker's own process env — agent * envVars, the runner API key, GH_TOKEN, timeout vars. Resolved server-side