Skip to content

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

feat(cos): orchestrate development with an agent-free maintainer watchdog (#7825)

[._.]/354df7973a8e
diff --git a/docs/features/development-watchdog.md b/docs/features/development-watchdog.md
new file mode 100644
index 0000000000..9b1d8e1038
--- /dev/null
+++ b/docs/features/development-watchdog.md
@@ -0,0 +1,51 @@
+# Development watchdog
+
+The instance-local Persistent Mind maintainer role selects managed repositories.
+The watchdog intersects that scope with the live `readPortos`, `createTasks`, and
+managed-app grants. Enabling a role does not enable inference or widen grants.
+GitHub repositories are supported; other forges report an explicit blocker.
+
+The existing CoS health scheduler checks the configurable interval (hourly by
+default), and evaluation and configuration changes reconcile the same service.
+A cadence may fire late by one health-check interval. There is no additional
+polling timer. Paused CoS, revoked grants, full capacity, unknown ownership and
+exhausted autonomy budgets defer writes. The generic Improve switch does not
+control this separately opted-in role. Agent execution retains normal provider
+budget and capacity gates.
+
+The Schedule page's **Development Watchdog** Run Now invokes the programmatic
+handler. `POST /api/cos/mind/maintainer/watchdog` with `{ "dryRun": true }` performs
+a fresh nonmutating scan; omit `dryRun` for Run Now. The GET endpoint returns the
+latest persisted receipt. Both route bodies and task handlers enter the same
+serialized service. Maintenance cannot be used as a quota-spending job.
+
+`runDevelopmentWatchdog({ dryRun, force, source })` returns a receipt.
+`readDevelopmentWatchdogSnapshot()` only reads the last persisted receipt;
+callers requiring fresh read-only context should use a forced dry run. Automatic
+runs respect the interval and invalidate cached decisions when role/grants,
+CoS pause or autonomy changes. Disabled roles create no runtime state.
+
+Receipts contain `schemaVersion`, `checkedAt`, `complete`, `source`, `dryRun`,
+`availableSlots`, `blockers`, scoped `apps`, `decisions`, `counts`, and bounded
+`recovery` provenance. Each app includes issues and all open PR dispositions.
+PR rows carry current head SHA, first observed time and an evidence fingerprint.
+Counts distinguish queued work, owned skips and duplicate admissions prevented;
+none claims to measure an agent that was actually duplicated. The service makes
+zero model calls and performs no autonomous merge itself: eligible PRs queue the
+existing review-then-merge workflow. Pending CI, drafts, ownership and unchanged
+failed evidence need no resolution agent.
+
+The latest receipt and 24 historical receipts use the existing machine-local
+CoS runtime state, not a new record store. A bounded current-PR dispatch ledger
+survives restarts and prevents repeated resolution of unchanged evidence. Queue
+admission shares structured work identity across user/internal task files and
+existing scheduler/manual follow-up producers. Untargeted claims reserve their
+app's issue lane. Full-sync peers participate in ownership reads; unrelated
+peers do not block the scan. Failed or capped participating-peer and forge reads
+remain unknown. A claim branch alone is not an active agent: an open in-progress
+claim without local task evidence remains an explicit unresolved owner.
+
+Recovery metadata identifies source tasks/agents and blocked categories without
+copying private transcripts. This watchdog neither spawns cleanup agents nor
+runs destructive git cleanup. Existing deterministic completion cleanup retains
+ownership of that work.
diff --git a/server/lib/README.md b/server/lib/README.md
index f60f1678b6..cbc6212a97 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -720,3 +720,5 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `layaMlx.js` | Pinned Laya-MLX experiment model, request validation and probability normalization; entropy confidence stays distinct from entailment. |
| `persistentMindMaintainer.js` | Machine-local maintainer intent, inference allowance schema, normalization and additive wake charter; never grants authority. |
+
+| `developmentWorkIdentity.js` | Canonical development task identity and cross-producer ownership matching. |
diff --git a/server/lib/developmentWorkIdentity.js b/server/lib/developmentWorkIdentity.js
new file mode 100644
index 0000000000..afedb38c56
--- /dev/null
+++ b/server/lib/developmentWorkIdentity.js
@@ -0,0 +1,25 @@
+/** Structured work ownership shared by scheduler, manual actions and watchdog. */
+export const DEVELOPMENT_ACTIVE_STATUSES = new Set(['pending', 'queued', 'running', 'in_progress', 'finalizing', 'blocked', 'paused']);
+
+export function developmentWorkIdentity(task) {
+ const m = { ...task, ...task?.metadata };
+ const app = m.app || m.appId || m.taskApp;
+ const url = m.reviewLoopPRUrl || m.prUrl;
+ if (typeof url === 'string') {
+ const match = url.match(/^https?:\/\/([^/]+)\/(.+?)\/(?:pull|merge_requests|\-\/merge_requests)\/(\d+)(?:[/?#]|$)/);
+ if (match) return { app, key: `${match[1]}/${match[2]}/pr/${match[3]}`.toLowerCase(), kind: 'pr' };
+ }
+ if (m.claimFlow === true || m.claimFlow === 'true' || ['claim-work', 'claim-issue', 'claim-issue-gitlab'].includes(m.taskAnalysisType)) {
+ return { app, kind: 'issue', key: m.claimTarget ? `issue/${m.claimTarget}` : '*' };
+ }
+ if ((m.analysisType || m.taskAnalysisType) === 'pr-watcher') return { app, kind: 'pr', key: '*' };
+ return null;
+}
+
+export function sameDevelopmentWork(left, right) {
+ const a = developmentWorkIdentity(left);
+ const b = developmentWorkIdentity(right);
+ if (!a || !b || a.kind !== b.kind) return false;
+ if (a.kind === 'pr' && a.key !== '*' && b.key !== '*') return a.key === b.key;
+ return !!a.app && a.app === b.app && (a.key === '*' || b.key === '*' || a.key === b.key);
+}
diff --git a/server/lib/index.js b/server/lib/index.js
index 177f14cec5..f729da423a 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -703,3 +703,5 @@ export * from './openchamber.js';
export * from './layaMlx.js';
export * from './persistentMindMaintainer.js';
+
+export * from './developmentWorkIdentity.js';
diff --git a/server/lib/quotaBurnTaskRef.js b/server/lib/quotaBurnTaskRef.js
index 3177926bff..306fbe9010 100644
--- a/server/lib/quotaBurnTaskRef.js
+++ b/server/lib/quotaBurnTaskRef.js
@@ -218,7 +218,8 @@ export function evaluateOnDemandEligibility({ taskType, appId = null, entry, imp
return unavailable(QUOTA_BURN_UNAVAILABLE.WRONG_SCOPE, `Task type '${taskType}' is not enabled for app '${appId}'`);
}
- return improvementVerdict(improvementEnabled);
+ // The local maintainer role supplies its own standing grant and cadence.
+ return taskType === 'development-watchdog' ? null : improvementVerdict(improvementEnabled);
}
/**
diff --git a/server/lib/taskTargetScope.js b/server/lib/taskTargetScope.js
index 6602cf1c09..6867055371 100644
--- a/server/lib/taskTargetScope.js
+++ b/server/lib/taskTargetScope.js
@@ -47,6 +47,7 @@ export function requiresManagedAppTarget(taskType) {
* needs it, and `lib` may not import upward into `services`.
*/
export const PROGRAMMATIC_SCHEDULED_TASK_TYPES = Object.freeze([
+ 'development-watchdog',
'universe-bible-describe',
'universe-bible-images',
]);
diff --git a/server/routes/cosMindRoutes.js b/server/routes/cosMindRoutes.js
index 9ab450514a..a6328a237a 100644
--- a/server/routes/cosMindRoutes.js
+++ b/server/routes/cosMindRoutes.js
@@ -260,6 +260,16 @@ router.delete('/mind/thinking-request', asyncHandler(async (_req, res) => {
res.json(await cancelPersistentMindThinkingRequest());
}));
+router.get('/mind/maintainer/watchdog', asyncHandler(async (_req, res) => {
+ const { readDevelopmentWatchdogSnapshot } = await import('../services/developmentWatchdog.js');
+ res.json(await readDevelopmentWatchdogSnapshot());
+}));
+router.post('/mind/maintainer/watchdog', asyncHandler(async (req, res) => {
+ const request = validateRequest(z.object({ dryRun: z.boolean().optional() }).strict(), req.body || {});
+ const { runDevelopmentWatchdog } = await import('../services/developmentWatchdog.js');
+ res.json(await runDevelopmentWatchdog({ dryRun: request.dryRun === true, force: true, source: 'manual' }));
+}));
+
router.get('/mind/maintainer', asyncHandler(async (_req, res) => {
const { describePersistentMindMaintainerSetup } = await import('../services/persistentMindMaintainer.js');
res.json(await describePersistentMindMaintainerSetup());
diff --git a/server/services/appPullRequests.js b/server/services/appPullRequests.js
index 4060047c27..4c7899163f 100644
--- a/server/services/appPullRequests.js
+++ b/server/services/appPullRequests.js
@@ -26,7 +26,7 @@ const GL_PER_PAGE = 100;
// fork's own address (#6064). They are free on this same call.
const GH_PR_FIELDS = [
'number', 'title', 'author', 'url', 'createdAt', 'updatedAt', 'isDraft',
- 'headRefName', 'baseRefName', 'reviewDecision', 'mergeStateStatus',
+ 'headRefName', 'headRefOid', 'baseRefName', 'reviewDecision', 'mergeStateStatus',
'mergeable', 'statusCheckRollup', 'labels',
'isCrossRepository', 'maintainerCanModify', 'headRepository', 'headRepositoryOwner'
].join(',');
@@ -66,6 +66,7 @@ function normalizeGithubPullRequest(pr) {
createdAt: typeof pr?.createdAt === 'string' ? pr.createdAt : null,
updatedAt: typeof pr?.updatedAt === 'string' ? pr.updatedAt : null,
isDraft: pr?.isDraft === true,
+ headSha: typeof pr?.headRefOid === 'string' ? pr.headRefOid : null,
headBranch: typeof pr?.headRefName === 'string' ? pr.headRefName : '',
baseBranch: typeof pr?.baseRefName === 'string' ? pr.baseRefName : '',
reviewDecision: typeof pr?.reviewDecision === 'string' ? pr.reviewDecision : null,
@@ -134,9 +135,10 @@ function normalizeGitlabPullRequest(mr) {
};
}
-function answeredResult(rows, normalize) {
+function answeredResult(rows, normalize, limit) {
+ if (rows.length >= limit) return { pullRequests: [], reason: 'incomplete-page', transient: true };
const pullRequests = rows.map(normalize).filter(pr => Number.isInteger(pr.number) && pr.number > 0);
- if (rows.length > 0 && pullRequests.length === 0) {
+ if (pullRequests.length !== rows.length) {
return {
pullRequests: [],
reason: 'unreadable-response',
@@ -185,12 +187,12 @@ async function fetchGithubPullRequests(repoSpec, apiHost, { repoPath = null, for
remedy: 'run `gh pr list` in the repo to see what gh reports',
};
}
- return answeredResult(rows, normalizeGithubPullRequest);
+ return answeredResult(rows, normalizeGithubPullRequest, GH_LIST_LIMIT);
}
async function fetchGitlabPullRequests(repoPath) {
const { rows, reason } = await execGlabJson(['mr', 'list', '--per-page', String(GL_PER_PAGE)], repoPath);
- if (rows) return answeredResult(rows, normalizeGitlabPullRequest);
+ if (rows) return answeredResult(rows, normalizeGitlabPullRequest, GL_PER_PAGE);
if (reason === 'not-json') {
return {
pullRequests: [],
diff --git a/server/services/appPullRequests.test.js b/server/services/appPullRequests.test.js
index d39879cbfe..225001f2fa 100644
--- a/server/services/appPullRequests.test.js
+++ b/server/services/appPullRequests.test.js
@@ -266,3 +266,10 @@ describe('listAppPullRequests', () => {
expect(result).toMatchObject({ tracker: 'plan', pullRequests: [], reason: 'unsupported-forge', transient: false });
});
});
+
+it('defers at the pagination boundary and rejects mixed malformed ownership rows', async () => {
+ execGh.mockResolvedValue(JSON.stringify(Array.from({ length: 200 }, (_, i) => ({ number: i + 1 }))));
+ expect(await listAppPullRequests(APP)).toMatchObject({ transient: true, reason: 'incomplete-page', pullRequests: [] });
+ execGh.mockResolvedValue(JSON.stringify([{ number: 1 }, { broken: true }]));
+ expect(await listAppPullRequests(APP)).toMatchObject({ transient: true, reason: 'unreadable-response' });
+});
diff --git a/server/services/cos.js b/server/services/cos.js
index e28841654d..4c80c4c6ea 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -425,6 +425,8 @@ async function runStart() {
intervalMs: state.config.healthCheckIntervalMs,
handler: async () => {
await runHealthCheck();
+ const { runDevelopmentWatchdog } = await import('./developmentWatchdog.js');
+ await runDevelopmentWatchdog().catch(err => console.error(`❌ Development watchdog failed: ${err.message}`));
const cleaned = await cleanupOrphanedAgents();
if (cleaned > 0) {
emitLog('info', `🧹 Periodic cleanup: ${cleaned} orphaned agent(s)`);
@@ -1586,7 +1588,13 @@ export async function init() {
// eligible. Re-run the normal dequeue so autonomy, budgets, leases, and
// capacity remain the same as for every other system task.
cosEvents.on('config:changed', () => {
- if (isDaemonRunning()) scheduleDequeue();
+ if (isDaemonRunning()) {
+ scheduleDequeue();
+ // Standing role/grant changes reconcile immediately; the watchdog's
+ // persisted policy fingerprint coalesces unrelated config updates.
+ import('./developmentWatchdog.js').then(({ runDevelopmentWatchdog }) => runDevelopmentWatchdog({ source: 'configuration' }))
+ .catch(err => console.error(`❌ Development watchdog configuration reconciliation failed: ${err.message}`));
+ }
});
cosEvents.on('tasks:cos:added', () => {
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index c87a4e2980..04adc1bb77 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -1149,6 +1149,11 @@ export async function evaluateTasks(options) {
}
}
+ if (state.config.persistentMindMaintainer?.enabled) {
+ const { runDevelopmentWatchdog } = await import('./developmentWatchdog.js');
+ await runDevelopmentWatchdog().catch(err => console.error(`❌ Development watchdog failed: ${err.message}`));
+ }
+
// Resolve this instance's federation id once per cycle so the priority tiers
// can skip tasks a peer holds a live lease on (#1650). Warm path is the cheap
// cached read; only the cold boot creates the identity.
@@ -1728,6 +1733,7 @@ function stampApprovalReason(metadata, approval) {
* Used by both normal rotation and on-demand task requests
*/
export async function generateSelfImprovementTaskForType(taskType, state) {
+ if (taskType === 'development-watchdog') return null;
const taskSchedule = await import('./taskSchedule.js');
const { getTaskPrompt } = await import('./taskPromptService.js');
const interval = await taskSchedule.getTaskInterval(taskType);
@@ -2177,7 +2183,7 @@ export async function drainProgrammaticOnDemandRequests({ taskScheduleMod, reque
for (const request of pending) {
const taskConfig = schedule?.tasks?.[request.taskType];
handled.add(request.id);
- if (!isImprovementEnabled(state)) {
+ if (request.taskType !== 'development-watchdog' && !isImprovementEnabled(state)) {
emitLog('warn', `On-demand request dropped — improvement is disabled (Config → Improve)`, { requestId: request.id, taskType: request.taskType });
await taskScheduleMod.clearOnDemandRequest(request.id);
continue;
diff --git a/server/services/cosTaskGenerator.programmaticOnDemand.test.js b/server/services/cosTaskGenerator.programmaticOnDemand.test.js
index 0235f5c7d7..37cc47d330 100644
--- a/server/services/cosTaskGenerator.programmaticOnDemand.test.js
+++ b/server/services/cosTaskGenerator.programmaticOnDemand.test.js
@@ -154,3 +154,11 @@ describe('drainProgrammaticOnDemandRequests — cross-engine claim', () => {
expect(cosEvents.emit).not.toHaveBeenCalled();
});
});
+
+
+it('runs the opted-in maintenance handler independently of the Improve toggle', async () => {
+ isImprovementEnabled.mockReturnValue(false);
+ await drainProgrammaticOnDemandRequests({ taskScheduleMod, requests: [request('development-watchdog')],
+ schedule: { tasks: { 'development-watchdog': { enabled: true } } }, state: {} });
+ expect(runScheduledHandler).toHaveBeenCalledWith(expect.objectContaining({ taskType: 'development-watchdog' }));
+});
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 08b28f96b7..37ef3b794d 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -13,6 +13,7 @@
* logic stays in cos.js while persistence lives here.
*/
+import { DEVELOPMENT_ACTIVE_STATUSES, developmentWorkIdentity, sameDevelopmentWork } from '../lib/developmentWorkIdentity.js';
import { reviewerModelsFromDefaults } from '../lib/reviewerConfig.js';
import { readFile, writeFile, stat } from 'fs/promises';
import { existsSync } from 'fs';
@@ -353,6 +354,16 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore
tasks = await readTaskFile(filePath);
}
+ // One state lock covers BOTH task files: manual and autonomous producers
+ // must acquire the same durable work identity even with different titles.
+ if (developmentWorkIdentity(taskData)) {
+ const otherPath = join(ROOT_DIR, taskType === 'user' ? state.config.cosTasksFile : state.config.userTasksFile);
+ const other = existsSync(otherPath) ? await readTaskFile(otherPath) : [];
+ const owner = [...tasks, ...other].find(task => task.id !== ignoreTaskId
+ && DEVELOPMENT_ACTIVE_STATUSES.has(task.status) && sameDevelopmentWork(task, taskData));
+ if (owner) return { ...owner, duplicate: true };
+ }
+
// Reject duplicate: same first-line description AND same target app already
// pending, in_progress, or blocked. The `metadata.app` scope matters — the same
// description against two different apps is two different pieces of work
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index 400b2ce2c2..3a27e8b383 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -2334,3 +2334,21 @@ describe('cosTaskStore — a repaired task is returned exactly as it is persiste
expect((await getTaskById(created.id)).priority).toBe('MEDIUM');
});
});
+
+describe('shared development work admission', () => {
+ it('matches a manual PR resolution and autonomous follow-up across task files and titles', async () => {
+ const metadata = { app: 'example', reviewLoopPRUrl: 'https://github.com/acme/example/pull/42' };
+ const manual = await addTask({ description: 'Manual resolve', metadata }, 'user');
+ const scheduled = await addTask({ description: 'Scheduled follow-up', metadata }, 'internal');
+ expect(scheduled).toMatchObject({ id: manual.id, duplicate: true });
+ expect((await getCosTasks()).tasks).toHaveLength(0);
+ await updateTask(manual.id, { status: 'completed' }, 'user');
+ expect((await addTask({ description: 'New evidence', metadata }, 'internal')).duplicate).not.toBe(true);
+ });
+ it('reserves untargeted claims against targeted work while preserving independent apps', async () => {
+ const claim = await addTask({ description: 'Claim next', app: 'example', claimFlow: true }, 'internal');
+ expect(await addTask({ description: 'Claim 42', app: 'example', claimFlow: true, claimTarget: '42' }, 'user'))
+ .toMatchObject({ id: claim.id, duplicate: true });
+ expect((await addTask({ description: 'Claim 42', app: 'different', claimFlow: true, claimTarget: '42' }, 'user')).duplicate).not.toBe(true);
+ });
+});
diff --git a/server/services/developmentWatchdog.js b/server/services/developmentWatchdog.js
new file mode 100644
index 0000000000..b541da1b5c
--- /dev/null
+++ b/server/services/developmentWatchdog.js
@@ -0,0 +1,281 @@
+/** Agent-free maintenance scans. Receipts live with the existing CoS runtime state. */
+import { randomUUID } from 'node:crypto';
+import { loadState, saveState, withStateLock } from './cosState.js';
+import { normalizePersistentMindMaintainer } from '../lib/persistentMindMaintainer.js';
+import { normalizePersistentMindCapabilities } from '../lib/persistentMindCapabilities.js';
+import { getDomainMode } from '../lib/domainAutonomy.js';
+import { DEVELOPMENT_ACTIVE_STATUSES, sameDevelopmentWork } from '../lib/developmentWorkIdentity.js';
+
+let scanTail = Promise.resolve();
+const tasksFrom = data => [...data.user.tasks, ...data.cos.tasks];
+const ownershipTask = (app, pr) => ({ metadata: { app: app.id, reviewLoopPRUrl: pr.url } });
+
+function authorized(state, appId, write = false) {
+ const role = normalizePersistentMindMaintainer(state.config?.persistentMindMaintainer);
+ const caps = normalizePersistentMindCapabilities(state.config?.persistentMindCapabilities);
+ return role.enabled && caps.readPortos && (!write || caps.createTasks)
+ && role.appIds.includes(appId) && (!caps.allowedAppIds || caps.allowedAppIds.includes(appId));
+}
+
+/** Latest bounded receipt; this read never refreshes, queues or invokes a model. */
+export async function readDevelopmentWatchdogSnapshot() {
+ return (await loadState()).developmentWatchdog?.latest || null;
+}
+
+async function participatingPeerTasks() {
+ const { getPeers } = await import('./instances.js');
+ const { peerFetch } = await import('../lib/peerHttpClient.js');
+ const { peerBaseUrl } = await import('../lib/peerUrl.js');
+ const { peerCosTasksSchema } = await import('../lib/peerSyncValidation.js');
+ const { PORTOS_SCHEMA_VERSIONS } = await import('../lib/schemaVersions.js');
+ let peers;
+ try { peers = (await getPeers()).filter(p => p.enabled !== false && p.fullSync === true); }
+ catch { return { tasks: [], blockers: [{ source: 'peer-ownership', reason: 'peer-registry-unavailable' }] }; }
+ const tasks = [];
+ const blockers = [];
+ for (const peer of peers) {
+ try {
+ const response = await peerFetch(`${peerBaseUrl(peer)}/api/peer-sync/cos-tasks`, {
+ signal: AbortSignal.timeout(10000), maxBytes: 8 * 1024 * 1024,
+ }, peer);
+ if (!response.ok) throw new Error('unavailable');
+ const parsed = peerCosTasksSchema.safeParse(await response.json());
+ if (!parsed.success || parsed.data.schemaVersion > PORTOS_SCHEMA_VERSIONS.cosTasks
+ || parsed.data.tasks.length >= 50000) throw new Error('incomplete');
+ tasks.push(...parsed.data.tasks);
+ } catch {
+ blockers.push({ source: 'peer-ownership', reason: 'participating-peer-unavailable-or-incomplete', peerId: peer.id });
+ }
+ }
+ return { tasks, blockers };
+}
+
+async function inspectApp(app, tasks) {
+ const { resolveAppForgeTarget } = await import('../lib/workTracker.js');
+ const { listAppPullRequests } = await import('./appPullRequests.js');
+ const { detectActionableWork, listConfiguredForgeIssues, issueNumberFromRef } = await import('./perpetualWork.js');
+ const { resolveClaimWorkMetadata } = await import('./cosTaskGenerator.js');
+ const { execGh } = await import('./github.js');
+ const { resolveForgeExecOptions } = await import('./forgeExecOptions.js');
+ const { createGithubActorTrust } = await import('./forgeActorTrust.js');
+ const { execGit } = await import('../lib/execGit.js');
+ const { tracker, target } = await resolveAppForgeTarget(app);
+ const row = { appId: app.id, repository: target?.fullName || null, complete: false, blockers: [], pullRequests: [], issues: [], eligibleCount: 0 };
+ // Other forge support remains explicit rather than silently using GitHub semantics.
+ if (tracker !== 'github' || !target?.repoSpec) { row.blockers.push('unsupported-forge'); return row; }
+ const account = target.fullName?.split('/')[0]?.toLowerCase() === 'atomantic' ? 'atomantic' : app.forgeAccount;
+ if (account === 'atomantic' && app.forgeAccount && app.forgeAccount !== 'atomantic') { row.blockers.push('conflicting-forge-account-pin'); return row; }
+ const exec = await resolveForgeExecOptions(app.repoPath, { forgeAccount: account });
+ const login = (await execGh(['api', 'user', '--hostname', target.apiHost, '--jq', '.login'], undefined, exec)).trim();
+ if (account === 'atomantic' && login !== 'atomantic') { row.blockers.push('required-forge-account-unavailable'); return row; }
+ // Every downstream resolver receives the same explicit account pin.
+ const pinned = { ...app, forgeAccount: account };
+ const { metadata: preview } = await resolveClaimWorkMetadata(pinned);
+ const [prs, backlog, branches, issues] = await Promise.all([
+ listAppPullRequests(pinned),
+ detectActionableWork('claim-issue', pinned, { issueAuthorFilter: preview.issueAuthorFilter, issueExcludeLabels: preview.issueExcludeLabels, requireComplete: true }),
+ execGit(['ls-remote', '--heads', 'origin'], app.repoPath),
+ listConfiguredForgeIssues('gh', pinned, { issueAuthorFilter: preview.issueAuthorFilter, issueExcludeLabels: preview.issueExcludeLabels }, exec.env),
+ ]);
+ if (!issues.ok || issues.truncated || issues.issues.some(issue => !Number.isInteger(issue.number) || !Array.isArray(issue.labels) || !Array.isArray(issue.assignees))) { row.blockers.push('issue-source-incomplete'); return row; }
+ if (prs.transient || backlog.transient) { row.blockers.push(prs.transient ? prs.reason : backlog.reason); return row; }
+ const trust = await createGithubActorTrust({ runGh: (args, timeout) => execGh(args, timeout, exec), host: target.apiHost, repoFullName: target.fullName });
+ const active = tasks.filter(task => DEVELOPMENT_ACTIVE_STATUSES.has(task.status));
+ for (const pr of prs.pullRequests) {
+ const owner = active.find(task => sameDevelopmentWork(task, ownershipTask(app, pr)));
+ let disposition = 'eligible';
+ if (owner) disposition = owner.status === 'blocked' ? 'blocked' : 'actively-owned';
+ else if (!pr.headSha) disposition = 'unknown';
+ else if (pr.isDraft) disposition = 'draft';
+ else if (!await trust.isTrusted(pr.author)) disposition = 'untrusted-excluded';
+ else if (pr.labels.some(label => ['blocked', 'do-not-merge', 'hold'].includes(label.toLowerCase()))) disposition = 'blocked';
+ else if (pr.checks.some(check => ['PENDING', 'QUEUED', 'IN_PROGRESS', 'EXPECTED', 'WAITING'].includes(check.status))) disposition = 'waiting-for-ci-review';
+ // A live external claim branch is not proof of an orphan. Leave its owner
+ // accountable until the existing claim/reconcile flow establishes otherwise.
+ else if (issueNumberFromRef(pr.headBranch) || /^claim\//.test(pr.headBranch)) {
+ const number = issueNumberFromRef(pr.headBranch);
+ if (!number) disposition = 'unknown';
+ else {
+ const claim = JSON.parse(await execGh(['issue', 'view', String(number), '--repo', target.repoSpec, '--json', 'state,labels'], undefined, exec));
+ if (claim.state === 'OPEN' && claim.labels?.some(label => label.name === 'in-progress')) disposition = 'unknown';
+ }
+ }
+ row.pullRequests.push({ number: pr.number, headSha: pr.headSha, fingerprint: JSON.stringify([pr.headSha, pr.reviewDecision, pr.mergeStateStatus, pr.checks, pr.labels]), disposition, taskId: owner?.id || null,
+ reason: owner?.metadata?.blockedCategory || (disposition === 'unknown' ? 'external-claim-owner-unverified' : null), url: pr.url, headBranch: pr.headBranch, forkHead: pr.forkHead });
+ }
+ row.eligibleCount = backlog.count || 0;
+ const externalClaims = new Set([
+ ...branches.stdout.split('\n').map(line => line.trim().split(/\s+/).at(-1)?.replace(/^refs\/heads\//, '')),
+ ...prs.pullRequests.map(pr => pr.headBranch),
+ ].map(issueNumberFromRef).filter(Number.isInteger));
+ const candidates = new Set((backlog.items || []).map(item => item.ref));
+ row.candidateSelectionLimited = (backlog.count || 0) > candidates.size;
+ for (const issue of issues.issues) {
+ const item = { ref: String(issue.number) };
+ const labels = issue.labels.map(label => typeof label === 'string' ? label : label.name);
+ const candidate = { metadata: { app: app.id, claimFlow: true, claimTarget: item.ref } };
+ const owner = active.find(task => sameDevelopmentWork(task, candidate));
+ const hasBranch = externalClaims.has(issue.number);
+ row.issues.push({ number: Number(item.ref), disposition: owner ? 'actively-owned' : hasBranch || labels.includes('in-progress') ? 'external-claim' : labels.includes('blocked') ? 'blocked' : candidates.has(item.ref) ? 'eligible' : 'excluded-or-unselected', taskId: owner?.id || null });
+ }
+ row.complete = true;
+ return row;
+}
+
+async function dispatch(app, decision) {
+ // Refresh grant, pause and ownership through the durable queue immediately
+ // before a write. The queue's shared work-key admission is authoritative.
+ const current = await loadState();
+ if (!authorized(current, app.id, true) || current.paused || getDomainMode(current.config, 'cos') !== 'execute') return { reason: 'authority-changed' };
+ const { resolveAutonomyBudget, buildClaimWorkTask } = await import('./cosTaskGenerator.js');
+ const budget = await resolveAutonomyBudget(current, Object.values(current.agents || {}).filter(a => a.status === 'running'));
+ if (budget.cosAutonomyMode !== 'execute' || budget.autonomousActionsRemaining <= 0) return { reason: 'autonomy-budget' };
+ const { getAllTasks, addTask } = await import('./cosTaskStore.js');
+ const peers = await participatingPeerTasks();
+ if (peers.blockers.length) return { reason: 'peer-ownership-unknown' };
+ const liveTasks = [...tasksFrom(await getAllTasks()), ...peers.tasks];
+ const agents = Object.values(current.agents || {}).filter(a => ['running', 'queued', 'finalizing', 'paused'].includes(a.status));
+ const queued = liveTasks.filter(t => t.status === 'pending');
+ const project = a => (a.metadata?.app || a.metadata?.taskApp) === app.id;
+ if (agents.length + queued.length >= (current.config.maxConcurrentAgents || 1)
+ || agents.filter(project).length + queued.filter(project).length >= (current.config.maxConcurrentAgentsPerProject || current.config.maxConcurrentAgents || 1)) return { reason: 'capacity-changed' };
+ const fresh = await inspectApp(app, liveTasks);
+ const item = (decision.kind === 'pr' ? fresh.pullRequests : fresh.issues).find(row => row.number === decision.number);
+ if (!fresh.complete || item?.disposition !== 'eligible' || (decision.kind === 'pr' && item.headSha !== decision.headSha)) return { reason: 'evidence-changed' };
+ const { resolveAppForgeTarget } = await import('../lib/workTracker.js');
+ const { target } = await resolveAppForgeTarget(app);
+ const { resolveForgeExecOptions } = await import('./forgeExecOptions.js');
+ const exec = await resolveForgeExecOptions(app.repoPath, { forgeAccount: target.fullName.startsWith('atomantic/') ? 'atomantic' : app.forgeAccount });
+ const { execGh } = await import('./github.js');
+ const { parseBlockingIssueNumbers } = await import('./blockedIssueReconcile.js');
+ const body = JSON.parse(await execGh([decision.kind === 'pr' ? 'pr' : 'issue', 'view', String(item.number), '--repo', target.repoSpec, '--json', 'body'], undefined, exec));
+ for (const number of parseBlockingIssueNumbers(body.body)) {
+ const dependency = JSON.parse(await execGh(['issue', 'view', String(number), '--repo', target.repoSpec, '--json', 'state'], undefined, exec));
+ if (dependency.state !== 'CLOSED') return { reason: 'open-dependency' };
+ }
+ const finalState = await loadState();
+ if (!authorized(finalState, app.id, true) || finalState.paused || getDomainMode(finalState.config, 'cos') !== 'execute') return { reason: 'authority-changed' };
+ if (decision.kind === 'issue') {
+ const claim = await buildClaimWorkTask(app, { target: String(item.number) });
+ const task = await addTask({ description: `Claim issue #${item.number} for ${app.name}`, app: app.id,
+ prompt: claim.prompt, metadata: { ...claim.taskMetadata, app: app.id, claimTarget: String(item.number),
+ claimFlow: true, developmentWatchdog: true, dispatchProvenance: 'development-watchdog' } }, 'internal');
+ return { taskId: task.id, duplicate: !!task.duplicate };
+ }
+ const { resolveReviewLoopOptions } = await import('./codeReview.js');
+ const { normalizeReviewers, claimSafeReviewers } = await import('../lib/reviewerConfig.js');
+ const { isTruthyMeta } = await import('./agentState.js');
+ const options = await resolveReviewLoopOptions({}, { normalize: normalizeReviewers, isTruthyMeta });
+ const reviewers = claimSafeReviewers(options.reviewers);
+ const { spawnReviewLoopFollowUp } = await import('./agentWorktreeCleanup.js');
+ const task = await spawnReviewLoopFollowUp({ originalAgentId: null,
+ originalTask: { id: `watchdog-${randomUUID()}`, description: `Resolve PR #${item.number}`, metadata: { app: app.id } },
+ prUrl: item.url, prBranch: item.headBranch, forkHead: item.forkHead, sourceWorkspace: app.repoPath,
+ prCompletion: 'review-then-merge', ...options, reviewers, optionalReviewers: (options.optionalReviewers || []).filter(r => r !== 'copilot'), dispatch: 'queue' });
+ return task ? { taskId: task.id, duplicate: !!task.duplicate } : { reason: 'queue-unavailable' };
+}
+
+async function scan({ dryRun = false, force = false, source = 'scheduled' } = {}) {
+ const state = await loadState();
+ const role = normalizePersistentMindMaintainer(state.config?.persistentMindMaintainer);
+ const prior = state.developmentWatchdog?.latest;
+ const policyKey = JSON.stringify([role, normalizePersistentMindCapabilities(state.config?.persistentMindCapabilities), state.paused, getDomainMode(state.config, 'cos')]);
+ if (!dryRun && !force && state.developmentWatchdog?.policyKey === policyKey && prior && Date.now() - Date.parse(prior.checkedAt) < role.intervalMinutes * 60000) return prior;
+ const receipt = { schemaVersion: 1, id: randomUUID(), checkedAt: new Date().toISOString(), source, dryRun,
+ complete: true, availableSlots: 0, blockers: [], apps: [], decisions: [], recovery: [] };
+ if (!role.enabled) receipt.blockers.push('maintainer-disabled');
+ else if (!role.appIds.some(id => authorized(state, id))) {
+ receipt.complete = false;
+ receipt.blockers.push('no-readable-maintainer-scope');
+ receipt.apps = role.appIds.map(appId => ({ appId, complete: false, blockers: ['app-unavailable-or-not-granted'], pullRequests: [], issues: [] }));
+ } else {
+ const { getActiveApps } = await import('./apps.js');
+ const { getAllTasks } = await import('./cosTaskStore.js');
+ const tasks = tasksFrom(await getAllTasks());
+ const peers = await participatingPeerTasks();
+ const allTasks = [...tasks, ...peers.tasks];
+ const agents = Object.values(state.agents || {});
+ // Include finalization and queued ownership, not only live subprocesses.
+ const activeAgents = agents.filter(agent => ['running', 'queued', 'finalizing', 'paused'].includes(agent.status));
+ for (const agent of activeAgents) {
+ const task = tasks.find(t => t.id === agent.taskId);
+ if (task) allTasks.push({ ...task, status: 'running' });
+ else if (agent.metadata) allTasks.push({ ...agent, status: 'running' });
+ }
+ const queued = tasks.filter(task => ['pending', 'in_progress'].includes(task.status));
+ receipt.availableSlots = Math.max(0, (state.config.maxConcurrentAgents || 1) - activeAgents.length - queued.filter(t => t.status === 'pending').length);
+ receipt.recovery = tasks.filter(task => authorized(state, task.metadata?.app || task.metadata?.taskApp) && (task.metadata?.sourceAgentId || task.metadata?.isInvestigation || task.metadata?.diagnostics))
+ .slice(-30).map(task => ({ taskId: task.id, status: task.status, sourceAgentId: task.metadata.sourceAgentId || null,
+ sourceTaskId: task.metadata.sourceTaskId || null, kind: task.metadata.reviewLoopFollowUp ? 'review-follow-up' : task.metadata.isInvestigation ? 'investigation' : 'recovery',
+ blockedReason: task.metadata.blockedCategory || null }));
+ receipt.blockers.push(...peers.blockers);
+ const apps = await getActiveApps();
+ for (const id of role.appIds) {
+ const app = apps.find(item => item.id === id);
+ if (!app || !authorized(state, id)) { receipt.apps.push({ appId: id, complete: false, blockers: ['app-unavailable-or-not-granted'], pullRequests: [], issues: [] }); continue; }
+ let row;
+ try { row = await inspectApp(app, allTasks); }
+ catch { row = { appId: id, complete: false, blockers: ['source-unavailable'], pullRequests: [], issues: [] }; }
+ for (const pr of row.pullRequests) {
+ const previous = state.developmentWatchdog?.dispatches?.[`${id}:pr:${pr.number}`];
+ if (pr.disposition === 'eligible' && previous?.fingerprint === pr.fingerprint) {
+ pr.disposition = 'blocked'; pr.reason = 'unchanged-after-dispatch'; pr.taskId = previous.taskId;
+ }
+ }
+ receipt.apps.push(row);
+ if (!row.complete || peers.blockers.length) continue;
+ const projectCount = activeAgents.filter(a => (a.metadata?.app || a.metadata?.taskApp) === id).length + queued.filter(t => t.metadata?.app === id && t.status === 'pending').length;
+ let capacity = Math.min(receipt.availableSlots, Math.max(0, (state.config.maxConcurrentAgentsPerProject || state.config.maxConcurrentAgents || 1) - projectCount));
+ for (const item of [...row.pullRequests.map(p => ({ ...p, kind: 'pr' })), ...row.issues.map(i => ({ ...i, kind: 'issue' }))]) {
+ if (item.disposition !== 'eligible') continue;
+ const decision = { appId: id, kind: item.kind, number: item.number, headSha: item.headSha || null, fingerprint: item.fingerprint || null,
+ outcome: capacity <= 0 ? 'capacity-full' : dryRun ? 'would-queue' : 'pending' };
+ if (capacity > 0 && !dryRun) {
+ let outcome;
+ try { outcome = await dispatch(app, item); } catch (err) { console.error(`❌ Development watchdog dispatch failed: ${err.message}`); outcome = { reason: 'dispatch-source-unavailable' }; }
+ Object.assign(decision, outcome, { outcome: outcome.taskId ? outcome.duplicate ? 'already-owned' : 'queued' : 'deferred' });
+ }
+ receipt.decisions.push(decision);
+ if (decision.taskId) {
+ const record = (item.kind === 'pr' ? row.pullRequests : row.issues).find(record => record.number === item.number);
+ record.disposition = 'queued-for-resolution'; record.taskId = decision.taskId;
+ }
+ if (capacity > 0 && (dryRun || decision.outcome === 'queued')) { capacity--; receipt.availableSlots--; }
+ }
+ }
+ receipt.complete = !peers.blockers.length && receipt.apps.every(app => app.complete);
+ }
+ const firstSeen = new Map((prior?.apps || []).flatMap(app => (app.pullRequests || []).map(pr => [`${app.appId}:${pr.number}`, pr.firstObservedAt || prior.checkedAt])));
+ for (const app of receipt.apps) for (const pr of app.pullRequests) pr.firstObservedAt = firstSeen.get(`${app.appId}:${pr.number}`) || receipt.checkedAt;
+ receipt.counts = {
+ dispatched: receipt.decisions.filter(d => d.outcome === 'queued').length,
+ ownedSkips: receipt.apps.reduce((n, app) => n + [...app.pullRequests, ...app.issues].filter(item => ['actively-owned', 'external-claim'].includes(item.disposition)).length, 0),
+ duplicateAdmissionsPrevented: receipt.decisions.filter(d => d.duplicate).length,
+ deferred: receipt.decisions.filter(d => ['deferred', 'capacity-full'].includes(d.outcome)).length,
+ deterministicActions: 0,
+ modelCalls: 0,
+ };
+ if (!dryRun && (role.enabled || prior)) await withStateLock(async () => {
+ const current = await loadState();
+ const dispatches = { ...current.developmentWatchdog?.dispatches };
+ for (const decision of receipt.decisions) if (decision.kind === 'pr' && decision.outcome === 'queued') {
+ dispatches[`${decision.appId}:pr:${decision.number}`] = { fingerprint: decision.fingerprint, taskId: decision.taskId };
+ }
+ // Retain only still-open scoped work; an incomplete scan cannot erase the
+ // previous hold. Bound the ledger independently from the receipt history.
+ for (const app of receipt.apps) if (app.complete) {
+ for (const key of Object.keys(dispatches)) if (key.startsWith(`${app.appId}:pr:`)
+ && !app.pullRequests.some(pr => key === `${app.appId}:pr:${pr.number}`)) delete dispatches[key];
+ }
+ current.developmentWatchdog = { policyKey, dispatches: Object.fromEntries(Object.entries(dispatches).slice(-1000)), latest: receipt, history: [...(current.developmentWatchdog?.history || []), receipt].slice(-24) };
+ await saveState(current);
+ });
+ return receipt;
+}
+
+/** All invocation paths share one scan; queue admission survives restart. Dry runs never persist. */
+export function runDevelopmentWatchdog(options = {}) {
+ const next = scanTail.catch(() => undefined).then(() => scan(options));
+ scanTail = next;
+ return next;
+}
diff --git a/server/services/developmentWatchdog.test.js b/server/services/developmentWatchdog.test.js
new file mode 100644
index 0000000000..d4672e77bd
--- /dev/null
+++ b/server/services/developmentWatchdog.test.js
@@ -0,0 +1,117 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+const m = vi.hoisted(() => ({ state: null, tasks: [], prs: [], backlog: [], peers: [], adds: [], save: vi.fn(), branch: '', account: 'atomantic', nextPrs: null, prReads: 0, dependencies: [], dependencyOpen: false, issueTruncated: false }));
+vi.mock('./cosState.js', () => ({ loadState: async () => m.state, saveState: m.save, withStateLock: async fn => fn() }));
+vi.mock('./apps.js', () => ({ getActiveApps: async () => [{ id: 'app', name: 'Example', repoPath: '/example' }] }));
+vi.mock('./cosTaskStore.js', () => ({ getAllTasks: async () => ({ user: { tasks: [] }, cos: { tasks: m.tasks } }), addTask: async task => { const result = { ...task, id: 'queued', status: 'pending' }; m.tasks.push(result); m.adds.push(result); return result; } }));
+vi.mock('./instances.js', () => ({ getPeers: async () => m.peers }));
+vi.mock('../lib/workTracker.js', () => ({ resolveAppForgeTarget: async () => ({ tracker: 'github', target: { fullName: 'atomantic/example', repoSpec: 'github.com/atomantic/example', apiHost: 'github.com' } }) }));
+vi.mock('./appPullRequests.js', () => ({ listAppPullRequests: async () => ({ pullRequests: ++m.prReads > 1 && m.nextPrs ? m.nextPrs : m.prs, transient: false }) }));
+vi.mock('./perpetualWork.js', async importOriginal => ({ ...(await importOriginal()), detectActionableWork: async () => ({ count: m.backlog.length, items: m.backlog }), listConfiguredForgeIssues: async () => ({ ok: true, truncated: m.issueTruncated, issues: m.backlog.map(i => ({ number: Number(i.ref), labels: [], assignees: [] })) }) }));
+vi.mock('./cosTaskGenerator.js', () => ({ resolveClaimWorkMetadata: async () => ({ metadata: {} }), resolveAutonomyBudget: async () => ({ cosAutonomyMode: 'execute', autonomousActionsRemaining: 10 }), buildClaimWorkTask: async () => ({ prompt: 'Claim', taskMetadata: { claimFlow: true } }) }));
+vi.mock('./github.js', () => ({ execGh: async args => args[0] === 'api' ? m.account : JSON.stringify({ body: '', state: m.dependencyOpen ? 'OPEN' : 'CLOSED', labels: m.dependencyOpen ? [{ name: 'in-progress' }] : [] }) }));
+vi.mock('./forgeExecOptions.js', () => ({ resolveForgeExecOptions: async () => ({}) }));
+vi.mock('./forgeActorTrust.js', () => ({ createGithubActorTrust: async () => ({ isTrusted: async () => true }) }));
+vi.mock('../lib/execGit.js', () => ({ execGit: async () => ({ stdout: m.branch }) }));
+vi.mock('../lib/peerHttpClient.js', () => ({ peerFetch: async () => { throw new Error('offline'); } }));
+vi.mock('./blockedIssueReconcile.js', () => ({ parseBlockingIssueNumbers: () => m.dependencies }));
+vi.mock('./codeReview.js', () => ({ resolveReviewLoopOptions: async () => ({ reviewers: ['codex'] }) }));
+vi.mock('./agentState.js', () => ({ isTruthyMeta: value => value === true }));
+vi.mock('./agentWorktreeCleanup.js', () => ({ spawnReviewLoopFollowUp: async options => { m.adds.push(options); return { id: 'resolution' }; } }));
+import { runDevelopmentWatchdog, readDevelopmentWatchdogSnapshot } from './developmentWatchdog.js';
+
+beforeEach(() => {
+ m.state = { config: { persistentMindMaintainer: { enabled: true, appIds: ['app'] }, persistentMindCapabilities: { readPortos: true, createTasks: true }, maxConcurrentAgents: 3 }, agents: {} };
+ m.tasks = []; m.prs = []; m.backlog = []; m.peers = []; m.adds = []; m.branch = ''; m.account = 'atomantic'; m.save.mockClear(); m.nextPrs = null; m.prReads = 0; m.dependencies = []; m.dependencyOpen = false; m.issueTruncated = false;
+});
+describe('development watchdog scan to dispatch', () => {
+ it('records empty scans without an agent or inference', async () => {
+ const receipt = await runDevelopmentWatchdog({ force: true });
+ expect(receipt.complete).toBe(true); expect(receipt.counts).toMatchObject({ dispatched: 0, modelCalls: 0 });
+ expect(m.adds).toEqual([]); expect(await readDevelopmentWatchdogSnapshot()).toEqual(receipt);
+ });
+ it('serializes competing scans and resumes from persisted task ownership', async () => {
+ m.backlog = [{ ref: '42' }];
+ const results = await Promise.all([runDevelopmentWatchdog({ force: true }), runDevelopmentWatchdog({ force: true })]);
+ expect(m.adds).toHaveLength(1); expect(results[1].apps[0].issues[0].disposition).toBe('actively-owned');
+ m.state.developmentWatchdog = null;
+ await runDevelopmentWatchdog({ force: true }); expect(m.adds).toHaveLength(1);
+ });
+ it('dry-run is nonmutating even after real scan and external claims do not become agents', async () => {
+ await runDevelopmentWatchdog({ force: true }); m.save.mockClear();
+ m.backlog = [{ ref: '42' }];
+ const preview = await runDevelopmentWatchdog({ dryRun: true });
+ expect(preview.decisions[0].outcome).toBe('would-queue'); expect(m.save).not.toHaveBeenCalled();
+ m.branch = 'abcdef\trefs/heads/claim/issue-42';
+ const receipt = await runDevelopmentWatchdog({ force: true });
+ expect(receipt.apps[0].issues[0].disposition).toBe('external-claim'); expect(m.adds).toEqual([]);
+ });
+ it('pending CI and blocked owners need no resolution agent', async () => {
+ m.prs = [{ number: 5, url: 'https://github.com/atomantic/example/pull/5', headSha: 'abc', labels: [], checks: [{ status: 'PENDING' }], author: 'atomantic', headBranch: 'fix' }];
+ let receipt = await runDevelopmentWatchdog({ force: true }); expect(receipt.apps[0].pullRequests[0].disposition).toBe('waiting-for-ci-review');
+ m.tasks = [{ id: 'held', status: 'blocked', metadata: { app: 'app', reviewLoopPRUrl: m.prs[0].url, blockedCategory: 'max-spawns' } }];
+ receipt = await runDevelopmentWatchdog({ force: true }); expect(receipt.apps[0].pullRequests[0].disposition).toBe('blocked'); expect(m.adds).toEqual([]);
+ });
+ it('unknown participating peer and wrong account defer work', async () => {
+ m.backlog = [{ ref: '42' }]; m.peers = [{ id: 'peer', fullSync: true }];
+ let receipt = await runDevelopmentWatchdog({ force: true }); expect(receipt.complete).toBe(false); expect(m.adds).toEqual([]);
+ m.peers = []; m.account = 'other'; receipt = await runDevelopmentWatchdog({ force: true });
+ expect(receipt.apps[0].blockers).toContain('required-forge-account-unavailable'); expect(m.adds).toEqual([]);
+ });
+ it('invalidates cadence after revoked scope and disable; pause defers writes', async () => {
+ m.backlog = [{ ref: '42' }]; m.state.paused = true;
+ expect((await runDevelopmentWatchdog({ force: true })).decisions[0].reason).toBe('authority-changed');
+ m.state.config.persistentMindCapabilities.allowedAppIds = [];
+ expect((await runDevelopmentWatchdog()).apps[0].complete).toBe(false);
+ m.state.config.persistentMindMaintainer.enabled = false;
+ expect((await runDevelopmentWatchdog()).blockers).toContain('maintainer-disabled'); expect(m.adds).toEqual([]);
+ });
+});
+
+const orphan = { number: 5, url: 'https://github.com/atomantic/example/pull/5', headSha: 'abc', labels: [], checks: [], author: 'atomantic', headBranch: 'claim/issue-5' };
+it('queues abandoned claim PRs through review-then-merge and withholds changed heads', async () => {
+ m.prs = [orphan];
+ expect((await runDevelopmentWatchdog({ force: true })).counts.dispatched).toBe(1);
+ expect(m.adds[0]).toMatchObject({ prCompletion: 'review-then-merge', dispatch: 'queue', reviewers: ['codex'] });
+ m.adds = []; m.state.developmentWatchdog = null; m.prReads = 0; m.nextPrs = [{ ...orphan, headSha: 'changed' }];
+ expect((await runDevelopmentWatchdog({ force: true })).decisions[0].reason).toBe('evidence-changed'); expect(m.adds).toEqual([]);
+});
+it('keeps explicit live claim and open dependency evidence out of dispatch', async () => {
+ m.prs = [orphan]; m.dependencyOpen = true;
+ let receipt = await runDevelopmentWatchdog({ force: true });
+ expect(receipt.apps[0].pullRequests[0]).toMatchObject({ disposition: 'unknown', reason: 'external-claim-owner-unverified' });
+ expect(receipt.counts.ownedSkips).toBe(0);
+ m.prs = [{ ...orphan, headBranch: 'fix' }]; m.dependencies = [10];
+ receipt = await runDevelopmentWatchdog({ force: true });
+ expect(receipt.decisions[0].reason).toBe('open-dependency'); expect(m.adds).toEqual([]);
+});
+
+it('does not repeatedly resolve unchanged PR evidence after its task completes', async () => {
+ m.prs = [orphan];
+ await runDevelopmentWatchdog({ force: true });
+ const again = await runDevelopmentWatchdog({ force: true });
+ expect(m.adds).toHaveLength(1);
+ expect(again.apps[0].pullRequests[0]).toMatchObject({ disposition: 'blocked', reason: 'unchanged-after-dispatch' });
+});
+
+it('reconsiders completed resolution only when review evidence changes', async () => {
+ m.prs = [{ ...orphan, reviewDecision: 'REVIEW_REQUIRED' }];
+ await runDevelopmentWatchdog({ force: true });
+ m.prs = [{ ...orphan, reviewDecision: 'APPROVED' }];
+ expect((await runDevelopmentWatchdog({ force: true })).counts.dispatched).toBe(1);
+ expect(m.adds).toHaveLength(2);
+});
+
+it('uses complete PR and remote branch ownership rather than the legacy first page', async () => {
+ m.backlog = [{ ref: '42' }];
+ m.prs = [{ ...orphan, number: 99, headBranch: 'cos/work/issue-42/agent', isDraft: true }];
+ expect((await runDevelopmentWatchdog({ force: true })).apps[0].issues[0].disposition).toBe('external-claim');
+ m.prs = []; m.branch = 'abcdef\trefs/heads/cos/work/issue-42/agent';
+ expect((await runDevelopmentWatchdog({ force: true })).apps[0].issues[0].disposition).toBe('external-claim');
+ expect(m.adds).toEqual([]);
+});
+it('partial issue pagination remains unknown and cannot dispatch', async () => {
+ m.backlog = [{ ref: '42' }]; m.issueTruncated = true;
+ const receipt = await runDevelopmentWatchdog({ force: true });
+ expect(receipt.complete).toBe(false); expect(receipt.apps[0].blockers).toContain('issue-source-incomplete');
+ expect(m.adds).toEqual([]);
+});
diff --git a/server/services/perpetualWork.js b/server/services/perpetualWork.js
index 80c5dd5981..6b45616358 100644
--- a/server/services/perpetualWork.js
+++ b/server/services/perpetualWork.js
@@ -558,7 +558,7 @@ async function countOpenIssuesUnfiltered(cfg, repoPath, env) {
* issues; 'any' = every author). The in-flight scan runs only when the list is
* non-empty, so an empty queue parks without a wasted branch/PR scan.
*/
-async function detectForgeIssues(forgeKey, app, { issueAuthorFilter = 'self', issueExcludeLabels = [] } = {}, contextOnly = false, env) {
+async function detectForgeIssues(forgeKey, app, { issueAuthorFilter = 'self', issueExcludeLabels = [], requireComplete = false } = {}, contextOnly = false, env) {
const cfg = FORGE_ISSUE_CONFIG[forgeKey];
const repoPath = app?.repoPath;
if (!repoPath) return { actionable: false, count: 0, reason: 'no-repo-path' };
@@ -692,6 +692,8 @@ async function detectForgeIssues(forgeKey, app, { issueAuthorFilter = 'self', is
};
}
+ if (requireComplete && (listingTruncated || (trustedLogins?.size || 0) > MAX_COLLABORATOR_AUTHOR_QUERIES)) return transient('incomplete-issue-page');
+
if (issues.length === 0) {
// An empty *filtered* list is ambiguous: the repo may truly have no open
// issues, OR it has open issues that just don't match the author filter —
diff --git a/server/services/scheduledHandlers/developmentWatchdog.js b/server/services/scheduledHandlers/developmentWatchdog.js
new file mode 100644
index 0000000000..00001d5c9c
--- /dev/null
+++ b/server/services/scheduledHandlers/developmentWatchdog.js
@@ -0,0 +1,12 @@
+import { runDevelopmentWatchdog } from '../developmentWatchdog.js';
+
+export async function countPending() {
+ const receipt = await runDevelopmentWatchdog({ dryRun: true, force: true, source: 'probe' });
+ return { count: receipt.decisions.filter(d => d.outcome === 'would-queue').length, detail: receipt.complete ? 'Maintenance snapshot complete' : 'Maintenance sources incomplete' };
+}
+
+export async function run({ params, family } = {}) {
+ if (family) return { dispatched: false, reason: 'maintenance-is-not-quota-spending' };
+ const receipt = await runDevelopmentWatchdog({ force: true, dryRun: params?.dryRun === true, source: 'manual' });
+ return { dispatched: receipt.counts.dispatched > 0, summary: `Maintenance scan: ${receipt.counts.dispatched} queued`, detail: receipt };
+}
diff --git a/server/services/scheduledHandlers/index.js b/server/services/scheduledHandlers/index.js
index 39dc32c2c2..5ef530da83 100644
--- a/server/services/scheduledHandlers/index.js
+++ b/server/services/scheduledHandlers/index.js
@@ -51,6 +51,7 @@
* agree, so the split cannot drift.
*/
export const SCHEDULED_HANDLER_MODULES = {
+ 'development-watchdog': () => import('./developmentWatchdog.js'),
'universe-bible-describe': () => import('./universeBibleDescribe.js'),
'universe-bible-images': () => import('./universeBibleImages.js'),
};
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 1a5626f8b4..b91af5b65d 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -854,6 +854,9 @@ async function evaluateTaskReadiness(taskType, appId, { featureEnabled, continui
return { shouldRun: false, reason: 'feature-disabled', feature: interval.feature };
}
+ // The maintainer role owns recurring cadence; this card is its manual door.
+ if (taskType === 'development-watchdog') return { shouldRun: false, reason: 'on-demand-only' };
+
// Fetch timezone once for reuse across weekday and cron checks
const timezone = await getUserTimezone();
diff --git a/server/services/taskScheduleRegistry.js b/server/services/taskScheduleRegistry.js
index 5433cd17b6..19c930ca12 100644
--- a/server/services/taskScheduleRegistry.js
+++ b/server/services/taskScheduleRegistry.js
@@ -400,6 +400,7 @@ export const DEFAULT_TASK_INTERVALS = {
//
// ON_DEMAND with NO interval and NO cron: enabled so the user can press Run
// Now, never clock-due, so a fresh install spends nothing until they do.
+ 'development-watchdog': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, taskMetadata: null },
'universe-bible-describe': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, taskMetadata: { universeId: 'all', scope: 'all', depth: 'full', maxEntries: 10 } },
'universe-bible-images': { type: INTERVAL_TYPES.ON_DEMAND, enabled: true, providerId: null, model: null, prompt: null, taskMetadata: { universeId: 'all', scope: 'all', maxEntries: 10, requireDescribed: false } }
};
@@ -558,6 +559,7 @@ export const TASK_TYPE_DESCRIPTIONS = {
'plan-feature': "Brainstorm one feature and file its decision-complete plan to the app's work tracker (no code)",
'user-action-review': 'Review the operator-action log for repeated manual work and propose automations — file issues (default) or queue CoS tasks',
'layered-intelligence': "Use app goals + performance metrics to file at most one deduplicated improvement issue; inspect read-only context and file a visibility gap when evidence is insufficient — no code",
+ 'development-watchdog': 'Inspect maintainer repository ownership and queue eligible work without an inference call',
'universe-bible-describe': 'Fill in blank universe bible sheets — one expand prompt per entry, emptiest first. No agent',
'universe-bible-images': 'Render images for universe bible entries that have none yet. No agent — PortOS enqueues the renders itself'
};
@@ -576,6 +578,7 @@ export function getTaskTypeDescription(taskType) {
* real execution shape without changing prompt-version migration state.
*/
export const TASK_TYPE_PROMPT_INFO = Object.freeze({
+ 'development-watchdog': Object.freeze({ mode: 'programmatic', description: 'Agent-free maintenance. Configure recurring cadence and repository scope in the Persistent Mind maintainer role; Run Now scans immediately.' }),
[PRIVATE_SECURITY_TASK_TYPE]: Object.freeze({ mode: 'runtime-generated', description: 'Private assessment of committed source and remediation guidance. Requires a pinned local Ollama or LM Studio CLI provider/model and macOS Seatbelt; tools, remote networking and publishing are disabled. Reports appear in the local Review Hub. No issues or PRs.' }),
'pr-reviewer': Object.freeze({
mode: 'runtime-generated',
diff --git a/server/services/taskScheduleRegistry.programmatic.test.js b/server/services/taskScheduleRegistry.programmatic.test.js
index a10d592a2c..403d62cd29 100644
--- a/server/services/taskScheduleRegistry.programmatic.test.js
+++ b/server/services/taskScheduleRegistry.programmatic.test.js
@@ -69,6 +69,13 @@ describe('programmatic scheduled handlers — shipped params', () => {
// it was started from.
for (const taskType of PROGRAMMATIC_SCHEDULED_TASK_TYPES) {
const params = catalogParams(taskType);
+ // Maintenance is configured by its standing instance role, never a quota
+ // spending form. It has no handler params or legacy quota catalog entry.
+ if (taskType === 'development-watchdog') {
+ expect(params).toEqual({});
+ expect(DEFAULT_TASK_INTERVALS[taskType].taskMetadata).toBeNull();
+ continue;
+ }
expect(Object.keys(params).length, taskType).toBeGreaterThan(0);
const expected = Object.fromEntries(
Object.entries(params)