Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
add pr-watcher task: run a configurable AI prompt on newly-opened PRs
[._.]/ Adam Eivy69673c0ab4f1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 97b8f438e8..6976445abf 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@## Added+- **PR Watcher task — run a custom AI prompt whenever a PR opens** — A new `pr-watcher` task type (Chief of Staff → Schedule, enable per app on the Automation tab) polls each managed app's GitHub repo and, whenever a pull request is opened against the default branch, dispatches an agent running a prompt you control. A "PR Author Filter" gates triggering on authorship — react to any PR, only your own (the gh-authenticated user / your automation), or only PRs opened by others — and the task prompt is fully editable, so you decide what the agent does for each opened PR (the shipped default reviews the diff and leaves a summary comment; you can rewrite it to label, triage, run checks, or make changes). Pick the provider/model like any other task. It tracks a per-app high-water mark so each PR fires once; the first run after you enable it baselines silently so it only reacts to PRs opened from then on, not your existing backlog.- **Search & browse more LoRAs per base model on /media/loras** — Each "Top for …" base-model section (Flux 1, Flux 2, Z-Image, ERNIE, HiDream, Qwen) gains a keyword search box and a "Load more" button. Type a term (e.g. a character or style name) to query Civitai live within that base model so you can find a specific LoRA that targets the model you're using, and click "Load more" to page past the top few into Civitai's deeper results (cursor-paginated). Clearing the search drops back to the cached top ranking. The curated picks section is unchanged.- **Custom scheduled tasks per app** — Each managed app's Automation tab gains a "Custom Tasks" section where you write your own prompt and pick a schedule (interval or cron), and a Chief-of-Staff agent runs it against that app's repo on cadence — just like the built-in task types, but fully your own. Per task you choose priority, autonomy level, and whether the agent works in an isolated worktree and opens a PR (or commits/auto-merges) in the target app. Run-now triggers an immediate pass. Custom tasks also appear (with an app badge) in the Chief of Staff → System Tasks list, where the create/edit form now has an optional app-scope picker so any agent job can be pointed at a specific app or left global.- **Password-protected federated peers** — If one of your PortOS instances sits behind an HTTP Basic auth proxy (Tailscale `serve`, Caddy, nginx), its peers can now reach it: probes were failing with `HTTP 401`. Each peer in the Instances page gains an optional credential — set a username (optional) and password when adding a peer, or click "set credential" on an existing peer. The credential is attached to every outbound hop to that peer (health probes, snapshot sync, per-record push/pull, asset pulls, and the live agent socket relay), so a reachable-but-401 peer now connects. A peer that returns 401/403 is flagged "auth required" in the UI instead of just reading as offline. Credentials are stored locally per peer and are never synced or announced to the peer itself.diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.jsindex cfa85d9a4b..6000470cb0 100644--- a/client/src/components/cos/constants.js+++ b/client/src/components/cos/constants.js@@ -75,6 +75,17 @@ export const REVIEWER_OPTIONS = [{ value: 'ollama', label: 'Ollama', description: 'Local Ollama model reviews the diff (set model on AI Providers)' }];export const LOCAL_LLM_REVIEWERS = ['lmstudio', 'ollama'];++// pr-watcher author gate (taskMetadata.prAuthorFilter). Mirrors+// PR_AUTHOR_FILTERS in server/lib/validation.js. 'self' = PRs opened by the+// gh-authenticated operator (or their automation); 'others' = external+// contributors; 'any' = react to every opened PR.+export const PR_AUTHOR_FILTER_OPTIONS = [+ { value: 'any', label: 'Any author', description: 'React to every PR opened on the default branch' },+ { value: 'self', label: 'Opened by me', description: 'Only PRs opened by the gh-authenticated user (or their automation)' },+ { value: 'others', label: 'Opened by others', description: 'Only PRs opened by someone other than the gh-authenticated user' }+];+export const DEFAULT_REVIEWER = 'copilot';export const DEFAULT_REVIEWERS = ['copilot'];diff --git a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsxindex 8aebc1d77a..026a727448 100644--- a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx+++ b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx@@ -1,7 +1,7 @@import { useState, useEffect, useRef } from 'react';import { Play, RotateCcw, ChevronDown, AlertCircle, Package, Info } from 'lucide-react';import CronInput from '../../../CronInput';-import { AGENT_OPTIONS, DEFAULT_REVIEW_STOP_MODE } from '../../constants';+import { AGENT_OPTIONS, DEFAULT_REVIEW_STOP_MODE, PR_AUTHOR_FILTER_OPTIONS } from '../../constants';import ReviewerPicker from '../../ReviewerPicker';import Banner from '../../../ui/Banner';import { useCodeReviewDefaults } from '../../../../hooks/useCodeReviewDefaults';@@ -104,6 +104,16 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTrisetUpdating(false);};+ const handlePrAuthorFilterChange = async (value) => {+ setUpdating(true);+ // Send the full merged taskMetadata — updateTaskInterval replaces the+ // object wholesale, and loadSchedule re-merges defaults on read.+ await onUpdate(taskType, {+ taskMetadata: { ...(config.taskMetadata || {}), prAuthorFilter: value }+ });+ setUpdating(false);+ };+const handleSavePrompt = async () => {setUpdating(true);const prompt = promptValue.trim() === '' ? null : promptValue;@@ -209,6 +219,27 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri</>)}+ {taskType === 'pr-watcher' && (+ <div>+ <label htmlFor={`pr-author-filter-${taskType}`} className="text-sm text-gray-400 block mb-2">PR Author Filter</label>+ <select+ id={`pr-author-filter-${taskType}`}+ value={config.taskMetadata?.prAuthorFilter || 'any'}+ onChange={(e) => handlePrAuthorFilterChange(e.target.value)}+ disabled={updating}+ className="w-full bg-port-card border border-port-border rounded px-3 py-2 text-white text-sm"+ >+ {PR_AUTHOR_FILTER_OPTIONS.map(opt => (+ <option key={opt.value} value={opt.value}>{opt.label}</option>+ ))}+ </select>+ <p className="text-xs text-gray-500 mt-1">+ {PR_AUTHOR_FILTER_OPTIONS.find(o => o.value === (config.taskMetadata?.prAuthorFilter || 'any'))?.description}+ {' '}Edit the prompt below to control what the agent does for each opened PR (it can use <code>{'{prData}'}</code>, <code>{'{repoFullName}'}</code>, <code>{'{defaultBranch}'}</code>).+ </p>+ </div>+ )}+<PromptEditorconfig={config}promptValue={promptValue}diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 96c05a1603..935e1fdc37 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1339,6 +1339,12 @@ export const MAX_TOTAL_SPAWNS = 5;const ALLOWED_TASK_METADATA_KEYS = [...PIPELINE_BEHAVIOR_FLAGS, 'readOnly'];+// pr-watcher author-gate values. 'self' = PRs opened by the gh-authenticated+// user (the PortOS operator / their automation); 'others' = everyone else;+// 'any' = no gate. Kept here so both the sanitizer and the prWatcher service+// agree on the vocabulary.+export const PR_AUTHOR_FILTERS = ['any', 'self', 'others'];+/*** Sanitize taskMetadata to an allow-list of agent-option keys. Boolean flags* (`useWorktree`/`openPR`/`simplify`/`reviewLoop`/`readOnly`/`reviewerApplies`)@@ -1382,6 +1388,13 @@ export function sanitizeTaskMetadata(raw) {clean.reviewerApplies = raw.reviewerApplies;hasKeys = true;}+ // `prAuthorFilter` gates pr-watcher dispatch on PR authorship — constrained+ // to a known value so a hand-edited config can't smuggle in an arbitrary+ // string the watcher would silently treat as "any".+ if (Object.prototype.hasOwnProperty.call(raw, 'prAuthorFilter') && PR_AUTHOR_FILTERS.includes(raw.prAuthorFilter)) {+ clean.prAuthorFilter = raw.prAuthorFilter;+ hasKeys = true;+ }// Pass through pipeline config (validated shape: object with stages array)if (raw.pipeline && typeof raw.pipeline === 'object' && Array.isArray(raw.pipeline.stages)) {clean.pipeline = raw.pipeline;diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 34b50acde5..6526d54265 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -1210,6 +1210,56 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, streferenceDataBlock = blocks.join('\n\n---\n\n');}+ // pr-watcher: poll the app's GitHub repo for PRs newly opened against the+ // default branch, gated on authorship (self / others / any). Dispatches one+ // agent run covering all new PRs; injects {prData}/{repoFullName}/+ // {defaultBranch}. State (the lastSeenPrNumber high-water mark) is persisted+ // inline on the app, mirroring reference-watch's lastReviewedSha.+ let prDataBlock = '';+ let prRepoFullName = '';+ let prDefaultBranch = '';+ if (taskType === 'pr-watcher') {+ const prWatcher = await import('./prWatcher.js');+ // prAuthorFilter was already merged (global → per-app override) and+ // value-constrained into `metadata` by sanitizeTaskMetadata above, so read+ // it from there rather than re-merging the raw configs.+ const authorFilter = metadata.prAuthorFilter || 'any';++ const check = await prWatcher.checkPullRequests(app, { authorFilter });+ const checkedAt = new Date().toISOString();++ if (!check.ok) {+ await prWatcher.persistPrWatcherState(app.id, { lastCheckedAt: checkedAt, lastError: check.reason });+ emitLog('info', `Skipping pr-watcher for ${app.name}: ${check.reason}`, { appId: app.id });+ return null;+ }++ // Always advance the high-water mark + clear any prior error. First run+ // baselines silently; later runs mark every evaluated PR (dispatched AND+ // gated-out) as seen so a fixed author filter doesn't re-fire them.+ await prWatcher.persistPrWatcherState(app.id, {+ lastSeenPrNumber: check.newLastSeen,+ lastCheckedAt: checkedAt,+ lastError: null+ });++ if (check.firstRun) {+ emitLog('info', `pr-watcher baselined ${app.name} at PR #${check.newLastSeen} — no dispatch on first run`, { appId: app.id });+ return null;+ }+ if (check.newPrs.length === 0) {+ emitLog('info', `Skipping pr-watcher for ${app.name}: no new PRs (author filter: ${authorFilter})`, { appId: app.id });+ return null;+ }++ prDataBlock = prWatcher.formatPullRequestsForPrompt(check.newPrs, {+ repoFullName: check.repoFullName, defaultBranch: check.defaultBranch+ });+ prRepoFullName = check.repoFullName;+ prDefaultBranch = check.defaultBranch;+ emitLog('info', `pr-watcher dispatching for ${app.name}: ${check.newPrs.length} new PR(s)`, { appId: app.id, analysisType: taskType });+ }+const planMeta = await applyPlanIdMetadata(taskType, app.repoPath, metadata);if (planMeta.skipReason) {emitLog('info', `Skipping ${taskType} for ${app.name}: ${planMeta.skipReason}`, { appId: app.id });@@ -1228,6 +1278,9 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st// legitimately contain `$` (env-var docs, prices, awk snippets) and// would get mangled. The function form passes the value verbatim..replace(/\{referenceData\}/g, () => referenceDataBlock)+ .replace(/\{prData\}/g, () => prDataBlock)+ .replace(/\{repoFullName\}/g, () => prRepoFullName)+ .replace(/\{defaultBranch\}/g, () => prDefaultBranch).replace(/\{planConstraint\}/g, () => planConstraintBlock);applyAppWorktreeDefault(metadata, app);diff --git a/server/services/prWatcher.js b/server/services/prWatcher.jsnew file mode 100644index 0000000000..69fe42970c--- /dev/null+++ b/server/services/prWatcher.js@@ -0,0 +1,218 @@+/**+ * PR Watcher service.+ *+ * Each PortOS-managed app can enable the `pr-watcher` scheduled task. On every+ * run the task polls the app's GitHub repo for pull requests newly opened+ * against the default branch and dispatches a CoS agent (running the+ * configurable `pr-watcher` prompt) for the new ones.+ *+ * "Newly opened" is tracked with a single high-water mark per app+ * (`prWatcherState.lastSeenPrNumber`) stored inline on the app record in+ * data/apps.json — GitHub PR numbers are monotonic and never reused, so any+ * PR with a number above the mark is one we haven't dispatched for yet. The+ * very first run baselines the mark to the current max open PR number WITHOUT+ * dispatching, so the watcher only fires for PRs opened after it was enabled+ * (matching "react whenever a PR is opened", not "re-process the backlog").+ *+ * Authorship gating (`taskMetadata.prAuthorFilter`): 'self' = PRs opened by the+ * gh-authenticated user (the operator / their automation), 'others' = everyone+ * else, 'any' = no gate.+ *+ * All gh access goes through the shared `execGh` wrapper. Functions here never+ * throw — they return structured `{ ok, reason, ... }` results — so the+ * scheduler tick that calls them (cosTaskGenerator) can't be crashed by a gh+ * failure on one app.+ */++import { execGh } from './github.js';+import { getAppById, updateApp } from './apps.js';+import { getOriginInfo } from '../lib/gitRemote.js';+import { PR_AUTHOR_FILTERS } from '../lib/validation.js';++// Bound the gh query + the per-run dispatch. An app left unwatched for a long+// time could otherwise surface a huge batch; 50 open PRs is already far beyond+// a single-user app's normal state.+const PR_LIST_LIMIT = 50;++// Cache the gh-authenticated login for the process lifetime. It's the PortOS+// operator's identity and effectively never changes within a run; re-resolving+// it on every scheduler tick would add a gh round-trip per watched app.+let _selfLoginCache;++/**+ * Resolve the gh-authenticated user's login (e.g. "atomantic"). Returns null+ * when gh isn't authenticated / installed — callers that need it for an+ * author gate must treat null as "can't gate, don't fire blindly".+ */+export async function getSelfLogin() {+ if (_selfLoginCache !== undefined) return _selfLoginCache;+ const login = await execGh(['api', 'user', '--jq', '.login']).catch(() => null);+ _selfLoginCache = login ? login.trim() : null;+ return _selfLoginCache;+}++// Test seam — reset the memoized login between cases.+export function __resetSelfLoginCache() {+ _selfLoginCache = undefined;+}++/**+ * Resolve a repo's default branch via gh. Returns null on failure.+ */+async function getDefaultBranch(repoFullName) {+ const name = await execGh(['repo', 'view', repoFullName, '--json', 'defaultBranchRef', '-q', '.defaultBranchRef.name'])+ .catch(() => null);+ return name ? name.trim() : null;+}++/**+ * List open PRs targeting `baseBranch` for `repoFullName`. Returns an array of+ * normalized PR objects, or null when the gh call fails.+ */+async function listOpenPullRequests(repoFullName, baseBranch) {+ const raw = await execGh([+ 'pr', 'list', '--repo', repoFullName,+ '--base', baseBranch, '--state', 'open',+ '--limit', String(PR_LIST_LIMIT),+ '--json', 'number,title,author,url,createdAt,isDraft,headRefName'+ ]).catch(() => null);+ if (raw === null) return null;+ const parsed = JSON.parse(raw);+ if (!Array.isArray(parsed)) return [];+ return parsed.map((pr) => ({+ number: pr.number,+ title: pr.title || '',+ authorLogin: pr.author?.login || null,+ authorIsBot: pr.author?.is_bot === true || pr.author?.type === 'Bot',+ url: pr.url || '',+ createdAt: pr.createdAt || null,+ isDraft: pr.isDraft === true,+ headRefName: pr.headRefName || ''+ }));+}++/**+ * Does this PR match the author gate? Pure — exported for tests.+ * 'any' → always+ * 'self' → PR author === selfLogin+ * 'others' → PR author !== selfLogin (and author is known)+ */+export function matchesAuthorFilter(pr, authorFilter, selfLogin) {+ if (authorFilter === 'any') return true;+ const author = pr.authorLogin;+ if (authorFilter === 'self') return Boolean(author) && author === selfLogin;+ if (authorFilter === 'others') return Boolean(author) && author !== selfLogin;+ return true;+}++/**+ * Compute the new-PR set and the next high-water mark from a list of open PRs.+ * Pure — no I/O — so the dispatch decision is unit-testable without gh.+ *+ * @returns {{ firstRun: boolean, newPrs: object[], newLastSeen: number, candidateCount: number }}+ * - firstRun: prevLastSeen was unset → baseline only, never dispatch.+ * - newPrs: PRs above the mark that also pass the author gate.+ * - newLastSeen: high-water mark to persist (max of prev mark and every open+ * PR number we evaluated, so gated-out PRs don't get re-evaluated forever).+ * - candidateCount: PRs above the mark before the author gate (for logging).+ */+export function computePrCheck({ prs, prevLastSeen, authorFilter, selfLogin }) {+ const maxOpen = prs.reduce((m, p) => Math.max(m, p.number), 0);++ if (prevLastSeen === null || prevLastSeen === undefined) {+ return { firstRun: true, newPrs: [], newLastSeen: maxOpen, candidateCount: 0 };+ }++ const candidates = prs.filter((p) => p.number > prevLastSeen);+ const newPrs = candidates.filter((p) => matchesAuthorFilter(p, authorFilter, selfLogin));+ // Advance past every open PR we've now evaluated — including gated-out ones —+ // so a fixed author gate doesn't re-surface the same PRs each tick.+ const newLastSeen = Math.max(prevLastSeen, maxOpen);+ return { firstRun: false, newPrs, newLastSeen, candidateCount: candidates.length };+}++/**+ * Read the persisted watcher state off an app record (tolerant of absence).+ */+export function readPrWatcherState(app) {+ const state = app?.prWatcherState;+ return state && typeof state === 'object' && !Array.isArray(state) ? state : {};+}++/**+ * Merge a patch into the app's persisted watcher state. Re-reads the app first+ * so the merge is against the freshest record.+ */+export async function persistPrWatcherState(appId, patch) {+ const app = await getAppById(appId);+ if (!app) return null;+ const next = { ...readPrWatcherState(app), ...patch };+ return updateApp(appId, { prWatcherState: next });+}++/**+ * Check an app's GitHub repo for newly-opened PRs against its default branch.+ *+ * Never throws. Returns:+ * { ok: false, reason } — nothing to do / config gap+ * { ok: true, firstRun: true, repoFullName, defaultBranch, newLastSeen }+ * { ok: true, newPrs, newLastSeen, repoFullName, defaultBranch, candidateCount }+ */+export async function checkPullRequests(app, { authorFilter = 'any' } = {}) {+ const filter = PR_AUTHOR_FILTERS.includes(authorFilter) ? authorFilter : 'any';++ const origin = await getOriginInfo(app.repoPath).catch(() => null);+ if (!origin?.hasOrigin || !origin.isGithub || !origin.fullName) {+ return { ok: false, reason: 'not-a-github-repo' };+ }+ const repoFullName = origin.fullName;++ const defaultBranch = await getDefaultBranch(repoFullName);+ if (!defaultBranch) {+ return { ok: false, reason: 'default-branch-unresolved', repoFullName };+ }++ // Resolve self up front when the gate needs it — bail rather than firing+ // blindly if gh can't tell us who "self" is.+ let selfLogin = null;+ if (filter !== 'any') {+ selfLogin = await getSelfLogin();+ if (!selfLogin) {+ return { ok: false, reason: 'self-login-unavailable', repoFullName, defaultBranch };+ }+ }++ const prs = await listOpenPullRequests(repoFullName, defaultBranch);+ if (prs === null) {+ return { ok: false, reason: 'pr-list-failed', repoFullName, defaultBranch };+ }++ const lastSeen = readPrWatcherState(app).lastSeenPrNumber;+ const prevLastSeen = Number.isInteger(lastSeen) ? lastSeen : null;++ const { firstRun, newPrs, newLastSeen, candidateCount } = computePrCheck({+ prs, prevLastSeen, authorFilter: filter, selfLogin+ });++ return { ok: true, firstRun, newPrs, newLastSeen, candidateCount, repoFullName, defaultBranch };+}++/**+ * Render the new-PR list into a Markdown block injected into the agent prompt+ * via the `{prData}` placeholder. Kept here (not in the template) so the format+ * can iterate without touching the prompt catalog.+ */+export function formatPullRequestsForPrompt(prs, { repoFullName, defaultBranch }) {+ const lines = [];+ lines.push(`Repo: ${repoFullName} — base branch: \`${defaultBranch}\``);+ lines.push('');+ for (const pr of prs) {+ const author = pr.authorLogin ? `by ${pr.authorLogin}` : 'by unknown author';+ const draft = pr.isDraft ? ' _(draft)_' : '';+ const when = pr.createdAt ? ` — opened ${pr.createdAt.slice(0, 10)}` : '';+ lines.push(`- **#${pr.number}** ${pr.title}${draft}`);+ lines.push(` - ${author}${when} · head: \`${pr.headRefName}\``);+ if (pr.url) lines.push(` - ${pr.url}`);+ }+ return lines.join('\n');+}diff --git a/server/services/prWatcher.test.js b/server/services/prWatcher.test.jsnew file mode 100644index 0000000000..ced567677f--- /dev/null+++ b/server/services/prWatcher.test.js@@ -0,0 +1,217 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// ─── mocks (must precede the import under test) ──────────────────────────────++const execGhMock = vi.fn();+vi.mock('./github.js', () => ({+ execGh: (...args) => execGhMock(...args),+}));++const mockApps = new Map();+vi.mock('./apps.js', () => ({+ getAppById: vi.fn(async (id) => mockApps.get(id) || null),+ updateApp: vi.fn(async (id, patch) => {+ const cur = mockApps.get(id) || { id };+ const next = { ...cur, ...patch };+ mockApps.set(id, next);+ return next;+ }),+}));++const getOriginInfoMock = vi.fn();+vi.mock('../lib/gitRemote.js', () => ({+ getOriginInfo: (...args) => getOriginInfoMock(...args),+}));++import {+ matchesAuthorFilter,+ computePrCheck,+ formatPullRequestsForPrompt,+ readPrWatcherState,+ checkPullRequests,+ getSelfLogin,+ __resetSelfLoginCache,+} from './prWatcher.js';++const pr = (number, login, extra = {}) => ({+ number,+ title: `PR ${number}`,+ authorLogin: login,+ url: `https://github.com/o/r/pull/${number}`,+ createdAt: '2026-06-05T00:00:00Z',+ isDraft: false,+ headRefName: `feat/${number}`,+ ...extra,+});++beforeEach(() => {+ execGhMock.mockReset();+ getOriginInfoMock.mockReset();+ mockApps.clear();+ __resetSelfLoginCache();+});++describe('matchesAuthorFilter', () => {+ it('any matches everything', () => {+ expect(matchesAuthorFilter(pr(1, 'alice'), 'any', 'bob')).toBe(true);+ expect(matchesAuthorFilter(pr(1, null), 'any', 'bob')).toBe(true);+ });+ it('self matches only the operator login', () => {+ expect(matchesAuthorFilter(pr(1, 'bob'), 'self', 'bob')).toBe(true);+ expect(matchesAuthorFilter(pr(1, 'alice'), 'self', 'bob')).toBe(false);+ expect(matchesAuthorFilter(pr(1, null), 'self', 'bob')).toBe(false);+ });+ it('others matches everyone but the operator', () => {+ expect(matchesAuthorFilter(pr(1, 'alice'), 'others', 'bob')).toBe(true);+ expect(matchesAuthorFilter(pr(1, 'bob'), 'others', 'bob')).toBe(false);+ expect(matchesAuthorFilter(pr(1, null), 'others', 'bob')).toBe(false);+ });+});++describe('computePrCheck', () => {+ it('first run baselines to max open PR and dispatches nothing', () => {+ const r = computePrCheck({ prs: [pr(5, 'a'), pr(8, 'b')], prevLastSeen: null, authorFilter: 'any', selfLogin: null });+ expect(r.firstRun).toBe(true);+ expect(r.newPrs).toEqual([]);+ expect(r.newLastSeen).toBe(8);+ });++ it('first run with no open PRs baselines to 0', () => {+ const r = computePrCheck({ prs: [], prevLastSeen: null, authorFilter: 'any', selfLogin: null });+ expect(r.firstRun).toBe(true);+ expect(r.newLastSeen).toBe(0);+ });++ it('detects only PRs above the high-water mark', () => {+ const r = computePrCheck({ prs: [pr(5, 'a'), pr(8, 'b'), pr(9, 'c')], prevLastSeen: 8, authorFilter: 'any', selfLogin: null });+ expect(r.newPrs.map(p => p.number)).toEqual([9]);+ expect(r.candidateCount).toBe(1);+ expect(r.newLastSeen).toBe(9);+ });++ it('applies the author gate but still advances the mark past gated-out PRs', () => {+ const r = computePrCheck({+ prs: [pr(10, 'bob'), pr(11, 'alice')],+ prevLastSeen: 9, authorFilter: 'others', selfLogin: 'bob'+ });+ // #10 (bob) gated out, #11 (alice) dispatched+ expect(r.newPrs.map(p => p.number)).toEqual([11]);+ expect(r.candidateCount).toBe(2);+ // mark advances past BOTH so the gated-out #10 never re-fires+ expect(r.newLastSeen).toBe(11);+ });++ it('never regresses the mark when open PRs are below it', () => {+ const r = computePrCheck({ prs: [pr(3, 'a')], prevLastSeen: 10, authorFilter: 'any', selfLogin: null });+ expect(r.newPrs).toEqual([]);+ expect(r.newLastSeen).toBe(10);+ });+});++describe('readPrWatcherState', () => {+ it('tolerates missing / malformed state', () => {+ expect(readPrWatcherState(undefined)).toEqual({});+ expect(readPrWatcherState({})).toEqual({});+ expect(readPrWatcherState({ prWatcherState: null })).toEqual({});+ expect(readPrWatcherState({ prWatcherState: [1, 2] })).toEqual({});+ expect(readPrWatcherState({ prWatcherState: { lastSeenPrNumber: 7 } })).toEqual({ lastSeenPrNumber: 7 });+ });+});++describe('formatPullRequestsForPrompt', () => {+ it('renders a markdown block with numbers, authors and urls', () => {+ const out = formatPullRequestsForPrompt(+ [pr(12, 'alice', { isDraft: true })],+ { repoFullName: 'o/r', defaultBranch: 'main' }+ );+ expect(out).toContain('o/r');+ expect(out).toContain('`main`');+ expect(out).toContain('#12');+ expect(out).toContain('by alice');+ expect(out).toContain('_(draft)_');+ expect(out).toContain('https://github.com/o/r/pull/12');+ });+});++describe('getSelfLogin', () => {+ it('caches the resolved login', async () => {+ execGhMock.mockResolvedValueOnce('bob\n');+ expect(await getSelfLogin()).toBe('bob');+ expect(await getSelfLogin()).toBe('bob');+ expect(execGhMock).toHaveBeenCalledTimes(1);+ });+ it('returns null when gh fails', async () => {+ execGhMock.mockRejectedValueOnce(new Error('not authed'));+ expect(await getSelfLogin()).toBe(null);+ });+});++describe('checkPullRequests', () => {+ const app = { id: 'app1', repoPath: '/repos/app1' };++ it('bails when the repo is not a github repo', async () => {+ getOriginInfoMock.mockResolvedValue({ hasOrigin: false, isGithub: false, fullName: null });+ const r = await checkPullRequests(app, { authorFilter: 'any' });+ expect(r).toEqual({ ok: false, reason: 'not-a-github-repo' });+ });++ it('bails when the default branch cannot be resolved', async () => {+ getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, fullName: 'o/r' });+ execGhMock.mockResolvedValueOnce(''); // repo view → empty+ const r = await checkPullRequests(app, { authorFilter: 'any' });+ expect(r.ok).toBe(false);+ expect(r.reason).toBe('default-branch-unresolved');+ });++ it('bails when an author gate is set but self login is unavailable', async () => {+ getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, fullName: 'o/r' });+ execGhMock+ .mockResolvedValueOnce('main') // repo view → default branch+ .mockRejectedValueOnce(new Error('no auth')); // api user → fails+ const r = await checkPullRequests(app, { authorFilter: 'self' });+ expect(r.ok).toBe(false);+ expect(r.reason).toBe('self-login-unavailable');+ });++ it('bails when the PR list call fails', async () => {+ getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, fullName: 'o/r' });+ execGhMock+ .mockResolvedValueOnce('main') // repo view+ .mockRejectedValueOnce(new Error('list failed')); // pr list+ const r = await checkPullRequests(app, { authorFilter: 'any' });+ expect(r.ok).toBe(false);+ expect(r.reason).toBe('pr-list-failed');+ });++ it('first run baselines without dispatching', async () => {+ getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, fullName: 'o/r' });+ execGhMock+ .mockResolvedValueOnce('main') // repo view+ .mockResolvedValueOnce(JSON.stringify([+ { number: 4, title: 'a', author: { login: 'x' }, url: 'u4', createdAt: '2026-06-01T00:00:00Z', isDraft: false, headRefName: 'h4' }+ ]));+ const r = await checkPullRequests({ ...app, prWatcherState: {} }, { authorFilter: 'any' });+ expect(r.ok).toBe(true);+ expect(r.firstRun).toBe(true);+ expect(r.newLastSeen).toBe(4);+ expect(r.newPrs).toEqual([]);+ });++ it('dispatches new PRs above the mark, honoring the author gate', async () => {+ getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, fullName: 'o/r' });+ execGhMock+ .mockResolvedValueOnce('main') // repo view+ .mockResolvedValueOnce('bob') // api user+ .mockResolvedValueOnce(JSON.stringify([+ { number: 7, title: 'mine', author: { login: 'bob' }, url: 'u7', createdAt: '2026-06-04T00:00:00Z', isDraft: false, headRefName: 'h7' },+ { number: 8, title: 'theirs', author: { login: 'alice' }, url: 'u8', createdAt: '2026-06-05T00:00:00Z', isDraft: false, headRefName: 'h8' }+ ]));+ const r = await checkPullRequests({ ...app, prWatcherState: { lastSeenPrNumber: 6 } }, { authorFilter: 'others' });+ expect(r.ok).toBe(true);+ expect(r.firstRun).toBe(false);+ expect(r.newPrs.map(p => p.number)).toEqual([8]);+ expect(r.newLastSeen).toBe(8);+ expect(r.repoFullName).toBe('o/r');+ expect(r.defaultBranch).toBe('main');+ });+});diff --git a/server/services/taskPromptService.js b/server/services/taskPromptService.jsindex 003d486ad1..5159c651d8 100644--- a/server/services/taskPromptService.js+++ b/server/services/taskPromptService.js@@ -1114,7 +1114,41 @@ Repository: {repoPath}- How many commits you reviewed (across all refs).- How many security flags you raised (with one-line reasons + SHAs).- How many slug-tagged PLAN.md items you appended (Adopt + Maybe) vs- how many commits you skipped as not-for-us.`+ how many commits you skipped as not-for-us.`,++ 'pr-watcher': `[Improvement: {appName}] Pull Request Watcher++One or more pull requests were just opened against {appName}'s default branch+(\`{defaultBranch}\`). React to each one according to the instructions below.++Repository: {repoPath}+GitHub repo: {repoFullName}++## Newly opened pull requests++{prData}++## What to do++For EACH pull request listed above:++1. Inspect it. Read the description and the diff:+ - \`gh pr view <number> --repo {repoFullName}\`+ - \`gh pr diff <number> --repo {repoFullName}\`++2. Review the change for correctness, obvious bugs, and security issues+ (injection, path traversal, leaked secrets, auth/permission regressions).+ Be specific — reference file paths and line numbers from the diff.++3. Leave a concise review summary as a PR comment:+ \`gh pr comment <number> --repo {repoFullName} --body "<your summary>"\`++Do NOT merge, close, approve, or push code to the PR unless the instructions in+this prompt explicitly say to. This default behavior is review-and-comment only;+the operator customizes this prompt to change what happens on each opened PR.++Finish with a 2–3 sentence assistant summary: how many PRs you handled and what+you did for each (one line per PR with its number).`};// Prompt versions — bump when a default prompt changes so existing instances auto-upgrade.@@ -1125,7 +1159,8 @@ export const PROMPT_VERSIONS = {'pr-reviewer': 3, // v3: multi-stage pipeline (security scan → code review + merge)'code-reviewer-a': 1, // v1: 2-stage pipeline (codebase review → triage & implement)'code-reviewer-b': 1, // v1: 2-stage pipeline (codebase review → triage & implement)- 'reference-watch': 2 // v2: append slug-tagged checklist items to PLAN.md (Adopt + Maybe) instead of writing REFERENCE_REVIEW.md; security-flagged commits get no PLAN entry (mentioned only in final summary)+ 'reference-watch': 2, // v2: append slug-tagged checklist items to PLAN.md (Adopt + Maybe) instead of writing REFERENCE_REVIEW.md; security-flagged commits get no PLAN entry (mentioned only in final summary)+ 'pr-watcher': 1 // v1: review-and-comment default for newly-opened PRs on the app's default branch};// Audit anchor for reference-watch's read/write coupling.@@ -2378,7 +2413,12 @@ For each reference above:6. Once REFERENCE_REVIEW.md is written, your final assistant message must be a2-3 sentence summary of how many commits you reviewed, how many securityflags you raised, and how many you marked Adopt vs. Maybe vs. Skip.`- ]+ ],++ // pr-watcher shipped at v1 — no prior defaults to recognize yet. Kept as an+ // empty list so the auto-upgrade machinery has an entry to consult and the+ // next prompt revision just appends the v1 body here.+ 'pr-watcher': []};// ============================================================diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex 0a56e77305..7dc43ee6b8 100644--- a/server/services/taskSchedule.js+++ b/server/services/taskSchedule.js@@ -139,6 +139,11 @@ export const SELF_IMPROVEMENT_TASK_TYPES = ['ui-bugs', 'mobile-responsive', 'feature-ideas', 'plan-task', 'error-handling','typing', 'release-check', 'pr-reviewer', 'code-reviewer-a', 'code-reviewer-b','jira-sprint-manager', 'jira-status-report', 'do-replan',+ // Polls the app's GitHub repo for pull requests newly opened against the+ // default branch and dispatches an agent (running the configurable+ // pr-watcher prompt) for each one. `taskMetadata.prAuthorFilter` gates on+ // PR authorship (self / others / any). See server/services/prWatcher.js.+ 'pr-watcher',// Watches `referenceRepos` configured on the app — fetches each upstream// repo, finds commits since lastReviewedSha, and appends slug-tagged// `[ref-watch-…]` checklist items to the app's PLAN.md for `/claim` /@@ -198,7 +203,15 @@ export const DEFAULT_TASK_INTERVALS = {// `readOnly` is coupled to PROMPT_VERSIONS['reference-watch'] — see// REFERENCE_WATCH_AUDITED_VERSION above; bumping the prompt version requires// re-auditing this default (a guard test in taskSchedule.test.js enforces it).- 'reference-watch': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { readOnly: false } }+ 'reference-watch': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { readOnly: false } },+ // pr-watcher polls for newly-opened PRs, so it runs on a short custom+ // interval rather than the loose rotation/daily cadence. 30 min keeps the+ // gh polling cheap while still reacting to a PR within one cycle. Default+ // gate is `prAuthorFilter: 'any'` (react to every PR); the operator narrows+ // it to 'self' or 'others' in the schedule UI. `readOnly: false` so a+ // customized prompt can make changes if the operator wants — the shipped+ // default prompt only reviews + comments.+ 'pr-watcher': { type: INTERVAL_TYPES.CUSTOM, intervalMs: 1800000, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { prAuthorFilter: 'any', readOnly: false } }};// Agent-options that a task manages internally — UI locks the toggle, and@@ -1160,6 +1173,7 @@ function getTaskTypeDescription(taskType) {'error-handling': 'Improve error handling','typing': 'Improve TypeScript types','pr-reviewer': 'Review open PRs from contributors',+ 'pr-watcher': 'Run a custom prompt on PRs newly opened against the default branch','jira-sprint-manager': 'Triage and implement JIRA sprint tickets','jira-status-report': 'Generate JIRA weekly status report'};