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([issue-5596]): grow the operator-action allowlist and detect leftover idle branches (#5930)

atomanticagenta17c303b9089
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 524b6312ab..2db36def8f 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -32,7 +32,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- `catalog_ingredient_relations` — directed ingredient→ingredient graph edges (the strongest argument for Postgres as the catalog graph store).
- `memories` / `memory_links` — long-term memory + pgvector similarity.
- `post_runs` / `post_attempts` — normalized MeatSpace POST test, benchmark, and training history. A run owns its planned composition and lifecycle timestamps; attempts carry queryable module/drill, difficulty/config version, correctness/score, latency/completion, hint/confidence, input mode, and scorer provenance, with the compatibility payload retained in JSONB. The complete attempt set is replaced in one transaction and stable client ids make retries idempotent. Migrated from `data/meatspace/post-sessions.json` and `post-training-log.json` by `server/scripts/migratePostRunsToDB.js`; the sources are parked as `.imported` recovery copies. **Intentionally machine-local — never federated** because cognitive-performance history is personal activity data. Adapter: `server/services/postRunStore.js` (legacy JSON only under the dev/test file escape hatch).
-- `user_action_events` — the operator-action ledger (#5594): one row per action the HUMAN took in PortOS (queued a CoS task, edited/deleted/approved/force-spawned one, rated an agent run, hit Run Now on a scheduled task, saved settings). `db-primary` because the value is in querying it — by type, actor, target, and time window — which is exactly what a JSONL append log cannot do. Columns carry the queryable axes (`type`/`actor`/`happened_at`/`target`/`success`) with structured detail in `payload` JSONB and the hook site in `source` JSONB; a unique `(type, dedupe_key)` index plus `ON CONFLICT DO NOTHING` makes a retried request idempotent. Bounded inline after each insert by BOTH a 20,000-row cap and a 90-day age cap — no cron. Credential-shaped payload keys are dropped at write time and their paths listed under `payload.redactedKeys`. **Intentionally machine-local — never federated**: it records what one operator did on one machine, and PII must not ride the federation layer (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md)); guarded in `server/services/sharing/peerSync.test.js`. Deliberately NOT in `auditedTables` — auditing an audit log doubles every row, same rationale as `post_runs`. Adapter: `server/services/userActions.js` (file backend only under the dev/test escape hatch).
+- `user_action_events` — the operator-action ledger (#5594, epic #5593): one row per action the HUMAN took in PortOS (queued a CoS task, edited/deleted/approved/force-spawned one, rated an agent run, hit Run Now on a scheduled task, saved settings; phase 3 / #5596 also records event-only creative/Brain pointers, instance-feature toggles, and CoS schedule updates that skip `PUT /api/settings`). The leftover-branch idle detector is a **consumer** of this ledger (plus live git state), not a store of its own. `db-primary` because the value is in querying it — by type, actor, target, and time window — which is exactly what a JSONL append log cannot do. Columns carry the queryable axes (`type`/`actor`/`happened_at`/`target`/`success`) with structured detail in `payload` JSONB and the hook site in `source` JSONB; a unique `(type, dedupe_key)` index plus `ON CONFLICT DO NOTHING` makes a retried request idempotent. Bounded inline after each insert by BOTH a 20,000-row cap and a 90-day age cap — no cron. Credential-shaped payload keys are dropped at write time and their paths listed under `payload.redactedKeys`. **Intentionally machine-local — never federated**: it records what one operator did on one machine, and PII must not ride the federation layer (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md)); guarded in `server/services/sharing/peerSync.test.js`. Deliberately NOT in `auditedTables` — auditing an audit log doubles every row, same rationale as `post_runs`. Adapter: `server/services/userActions.js` (file backend only under the dev/test escape hatch).
- `creative_director_projects` — Creative Director project/treatment/scene/run state, one row per project (`id`/`status`/timestamps as columns, the full record in `data` JSONB). Migrated from the monolithic `data/creative-director-projects.json` in Phase 3 (#997); CD is local-only, so the row carries no sync cursor/tombstone. Adapter: `server/services/creativeDirector/projectsDB.js`.
- `catalog_user_types` — user-defined ingredient types (the registry that defines catalog row semantics), one row per type (`id` PK, the definition in `data` JSONB, `updated_at`/`deleted_at` mirroring the federation LWW clock + tombstone). Migrated from the `data/settings.json` `catalogUserTypes` slice in Phase 4 lead-in (#1001) so type evolution versions/syncs alongside the catalog data it governs. Federates via the catalog sync `catalogTypes` envelope block (wire shape unchanged by the move). Adapter: `server/services/catalogUserTypes/db.js`, dispatched via `store.js`.
- `universes` / `universe_runs` — Universe Builder records (canon bibles, categories, composite sheets, locks, influences, and portable character production packages) one row per universe with the full sanitized record in `data` JSONB and `name`/`schema_version`/`ephemeral`/`updated_at`/`deleted`/`deleted_at` mirrored into columns; render-run history one row per run (local-only, capped 200, never federated). Character production packages carry only versioned voice direction and approved managed-image roles; local profiles, recordings, provider ids, and training artifacts are excluded from the federated wire. Migrated from `data/universes/{id}/index.json` (collectionStore) in Phase 3 Create slice 1 (#1014). **NO `sync_sequence`** — universes federate via the EXISTING `dataSync` snapshot/push model (LWW on the body's `updatedAt`), so the storage swap is invisible to peers (no schema-version bump). The store bumps an in-process mutation epoch on every write that `dataSync` folds into its checksum fingerprint, since a DB edit no longer changes the `data/universes/` directory the fingerprint used to watch. **`universe_runs` is intentionally never federated** — a regenerable render cache under a 200-row *global* cap that two producers would mutually evict, while the durable universe record already syncs (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724). Adapter: `server/services/universeBuilder/db.js`, dispatched via `store.js`.
diff --git a/server/lib/README.md b/server/lib/README.md
index 4318169e7a..23ecfd27a1 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -493,7 +493,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `repoIntakeActions.js` | `REPO_INTAKE_KEYS` + `normalizeRepoIntake(input)` — the opt-in post-clone agent actions a Brain capture can request for a GitHub repo URL (`malwareScan` → `/do:scan`, `learn` → a `repo-study` review). Pure half of `services/repoIntake.js` (which pulls the CoS task graph), so the link write path and the Zod schemas can import it freely. Normalizes to null when nothing was ticked, so "no intake" is never persisted onto a link. |
| `tombstones.js` | Generic timestamped tombstones (`{ <keyField>, deletedAt }`) that let an otherwise add-only peer merge represent a DELETE, so a record removed on one machine is not resurrected by a peer that still has it (#3530). `normalizeTombstones` / `recordTombstone` / `clearTombstone` / `tombstoneTimestamp` maintain the list; `mergeTombstones` unions it in both directions (newest deletion per key wins) so a delete propagates rather than only defending locally; `isTombstoned(list, key, createdAt)` suppresses a record unless its own creation stamp is strictly NEWER than the deletion; `pruneTombstones(list, records)` drops tombstones a re-created record has superseded (otherwise a stale peer copy keeps reaping it); `supersedingTimestamp(deletedAt)` stamps a re-create that lands in the same millisecond (or behind a skewed peer clock). Comparison goes through `lwwTimestamp.js`, so polarity matches every other sync merge. Key on a field that means the same thing on every machine — locally-minted ids usually do not. `DEFAULT_TOMBSTONE_LIMIT` (200) caps growth. |
| `uploadLimits.js` | Single source of truth for upload size caps — `JSON_BODY_LIMIT`/`JSON_BODY_LIMIT_BYTES` (the express.json limit applied in `index.js`), `MAX_BASE64_UPLOAD_BYTES` derived from it (base64 ×4/3, so a bigger per-route cap is unreachable), `MAX_SCREENSHOT_BYTES`. Mirrored client-side as `JSON_UPLOAD_MAX_FILE_SIZE`. |
-| `userActionTypes.js` | Closed vocabulary for the operator-action ledger (`user_action_events`, #5594): `USER_ACTION_TYPES` (the phase-1 action list), `USER_ACTION_ACTORS` (`user` / `mind` / `schedule` / `system`), and the `isUserActionType` / `isUserActionActor` predicates. `recordUserAction` (`services/userActions.js`) throws on a type absent from the list, so a typo fails a test instead of writing a row nothing can filter on. |
+| `userActionTypes.js` | Closed vocabulary for the operator-action ledger (`user_action_events`, #5594 / #5596): `USER_ACTION_TYPES` (CoS task/feedback/schedule + settings + instance-feature toggles + event-only creative/Brain pointers), `USER_ACTION_ACTORS` (`user` / `mind` / `schedule` / `system`), and the `isUserActionType` / `isUserActionActor` predicates. `recordUserAction` (`services/userActions.js`) throws on a type absent from the list, so a typo fails a test instead of writing a row nothing can filter on. |
| `uuid.js` | `v4()` thin wrapper over `crypto.randomUUID()`. |
| `versionUtils.js` | `compareSemver(a, b)` — semver ordering (-1/0/1) with pre-release precedence and build-metadata stripping. Shared by the self-update checker (`updateChecker.js`) and the local-LLM Ollama update detector (`localLlm.js`). Inputs must be `v`-stripped. |
| `workTracker.js` | `WORK_TRACKERS`/`CONCRETE_WORK_TRACKERS`/`DEFAULT_WORK_TRACKER`, `workTrackerLabel`, `hostToWorkTracker`, `isGithubHost` (GitHub-family host test — github.com + enterprise github.*; enterprise-aware replacement for the github.com-only `isGithub` gate), `githubRepoSpec(origin)` (host-qualified `HOST/OWNER/REPO` selector for `gh --repo`, or null for a non-GitHub origin — pairs the isGithubHost gate with the selector so prWatcher/branchReconcile/issueReconcile share one "resolvable GitHub repo" definition), `forgeCliForTracker`, `isFileTracker` (true when the tracker records work as repo files — PLAN.md — so an agent's proposal necessarily dirties the worktree; false for github/gitlab/jira), `trackerToClaimTaskType`, `hostFromOriginUrl` (subgroup-tolerant host parse), pure `resolveWorkTracker({configured,host})`, async `resolveAppWorkTracker(app)` — resolves a managed app's autonomous work source (PLAN.md / GitHub / GitLab / JIRA), defaulting `'auto'` to the git origin host. Async `resolveRepoForgeTarget(repoPath)` — the ONE definition of "which forge can we query for this checkout", returning `{ forge, fullName, repoSpec, apiHost }` (enterprise-aware `gh --repo` selector for GitHub; `repoSpec: null` for GitLab, which `glab` resolves from its cwd) or null for a non-forge origin; shared by `issueReconcile.js` and `appIssues.js`. Async `resolveAppForgeTarget(app, {repoPath})` — the composed `resolveAppWorkTracker` + `resolveRepoForgeTarget` for callers holding the managed-app record, returning `{ tracker, target }` with the app's github/gitlab pin threaded in as `preferredForge` (so a self-hosted forge on a hostname matching neither pattern still resolves); use this instead of re-threading the pin by hand. Also owns the `{trackerInstructions}` prompt block shared by the TRACKER-FILING task types (types that read the app read-only and deliver findings as tracker items, not a commit): `TRACKER_FILING_PRESETS` (per-task-type slug prefix / label / body requirements — `reference-watch`, `ux`, `repo-study`), `TRACKER_FILING_TASK_TYPES` (derived from the presets, so a gated type always has wording), and `formatTrackerInstructions(tracker, options)` which renders the plan/github/gitlab/jira block (reference-watch is the default option set, so a bare call stays byte-identical for it). Consumed by the `claim-work` router in `cosTaskGenerator.js`, `referenceRepos.js`, and `routes/apps.js`. |
diff --git a/server/lib/userActionTypes.js b/server/lib/userActionTypes.js
index 83da3f0c8a..0352eea32c 100644
--- a/server/lib/userActionTypes.js
+++ b/server/lib/userActionTypes.js
@@ -26,7 +26,7 @@
*/
export const USER_ACTION_ACTORS = Object.freeze(['user', 'mind', 'schedule', 'system']);
-/** Phase-1 operator actions (issue #5594). */
+/** Phase-1 operator actions (issue #5594) plus phase-3 growth (#5596). */
export const USER_ACTION_TYPES = Object.freeze([
'cos.task.create',
'cos.task.update',
@@ -35,7 +35,12 @@ export const USER_ACTION_TYPES = Object.freeze([
'cos.task.spawn',
'cos.agent.feedback',
'cos.schedule.trigger',
+ 'cos.schedule.update',
'settings.update',
+ 'instance-feature.toggle',
+ 'media.image.enqueue',
+ 'media.video.enqueue',
+ 'brain.capture',
]);
const TYPES = new Set(USER_ACTION_TYPES);
diff --git a/server/routes/apps/taskTypes.js b/server/routes/apps/taskTypes.js
index 6f6ee619ea..e3604189f1 100644
--- a/server/routes/apps/taskTypes.js
+++ b/server/routes/apps/taskTypes.js
@@ -16,6 +16,7 @@
*/
import { Router } from 'express';
+import { logCosScheduleUpdate } from '../../services/userActionScheduleLog.js';
import * as appsService from '../../services/apps.js';
import { PORTOS_APP_ID } from '../../services/apps.js';
import { sanitizeTaskMetadata, ISSUE_AUTHOR_FILTERS } from '../../lib/validation.js';
@@ -47,6 +48,12 @@ router.put('/bulk-task-type/:taskType', asyncHandler(async (req, res) => {
}
const result = await appsService.bulkUpdateAppTaskTypeOverride(req.params.taskType, { enabled });
+ await logCosScheduleUpdate({
+ target: req.params.taskType,
+ patch: { enabled },
+ source: { route: `${req.baseUrl}${req.route?.path ?? ''}`, method: req.method },
+ extra: { bulk: true, appsUpdated: result.count },
+ });
console.log(`📋 Bulk ${enabled ? 'enabled' : 'disabled'} task type ${req.params.taskType} for ${result.count} apps`);
res.json({ success: true, taskType: req.params.taskType, enabled, appsUpdated: result.count });
}));
@@ -189,6 +196,12 @@ router.put('/:id/task-types/all', loadApp, asyncHandler(async (req, res) => {
if (!result) {
throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });
}
+ await logCosScheduleUpdate({
+ target: req.params.id,
+ patch: { enabled },
+ source: { route: `${req.baseUrl}${req.route?.path ?? ''}`, method: req.method },
+ extra: { all: true },
+ });
console.log(`📋 ${enabled ? 'Enabled' : 'Disabled'} all task types for ${result.name}`);
res.json({ success: true, appId: result.id, taskTypeOverrides: result.taskTypeOverrides || {} });
}));
@@ -258,10 +271,17 @@ router.put('/:id/task-types/:taskType', asyncHandler(async (req, res) => {
}
}
- const result = await appsService.updateAppTaskTypeOverride(req.params.id, req.params.taskType, { enabled, interval, intervalMs, providerId, model, taskMetadata: sanitizedTaskMetadata });
+ const override = { enabled, interval, intervalMs, providerId, model, taskMetadata: sanitizedTaskMetadata };
+ const result = await appsService.updateAppTaskTypeOverride(req.params.id, req.params.taskType, override);
if (!result) {
throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });
}
+ await logCosScheduleUpdate({
+ target: req.params.taskType,
+ patch: override,
+ source: { route: `${req.baseUrl}${req.route?.path ?? ''}`, method: req.method },
+ extra: { appId: result.id },
+ });
const action = typeof enabled === 'boolean' ? (enabled ? 'Enabled' : 'Disabled') : 'Updated interval for';
console.log(`📋 ${action} task type ${req.params.taskType} for ${result.name}`);
diff --git a/server/routes/apps/taskTypes.test.js b/server/routes/apps/taskTypes.test.js
index 01e68af17c..9900a276be 100644
--- a/server/routes/apps/taskTypes.test.js
+++ b/server/routes/apps/taskTypes.test.js
@@ -6,6 +6,9 @@ import taskTypeRoutes from './taskTypes.js';
// Only the apps service is mocked; SELF_IMPROVEMENT_TASK_TYPES (taskScheduleRegistry) and
// parseCronToNextRun (eventScheduler) run for real, as do the sanitizeTaskMetadata
// validators.
+const recordUserAction = vi.hoisted(() => vi.fn(async () => ({ id: 'evt' })));
+vi.mock('../../services/userActions.js', () => ({ recordUserAction }));
+
vi.mock('../../services/apps.js', () => ({
getAppById: vi.fn(),
updateAppTaskTypeOverride: vi.fn(),
@@ -265,6 +268,15 @@ describe('Apps Task-Type Routes', () => {
expect(response.status).toBe(200);
expect(response.body.success).toBe(true);
+ expect(recordUserAction).toHaveBeenCalledWith(expect.objectContaining({
+ type: 'cos.schedule.update',
+ target: 'feature-ideas',
+ payload: expect.objectContaining({
+ keysChanged: ['taskMetadata'],
+ changes: { taskMetadata: { changed: true } },
+ appId: 'app-001',
+ }),
+ }));
});
it('should accept taskMetadata: null to clear metadata', async () => {
diff --git a/server/routes/brain.test.js b/server/routes/brain.test.js
index abc92d799a..27fbb5d89e 100644
--- a/server/routes/brain.test.js
+++ b/server/routes/brain.test.js
@@ -5,6 +5,9 @@ import { ServerError } from '../lib/errorHandler.js';
import brainRoutes from './brain.js';
// Mock the brain service
+const recordUserAction = vi.hoisted(() => vi.fn(async () => ({ id: 'evt' })));
+vi.mock('../services/userActions.js', () => ({ recordUserAction }));
+
vi.mock('../services/brain.js', () => ({
// Capture & Inbox
captureThought: vi.fn(),
@@ -331,6 +334,13 @@ describe('Brain Routes', () => {
expect(response.status).toBe(200);
expect(response.body.inboxLog.id).toBe('inbox-001');
expect(brainService.captureThought).toHaveBeenCalledWith('Test thought', undefined, undefined, { creative: undefined });
+ expect(recordUserAction).toHaveBeenCalledWith(expect.objectContaining({
+ type: 'brain.capture',
+ target: 'inbox-001',
+ summary: 'captured thought',
+ payload: { id: 'inbox-001' },
+ }));
+ expect(JSON.stringify(recordUserAction.mock.calls[0][0])).not.toContain('Test thought');
});
it('should return 400 if text is missing', async () => {
diff --git a/server/routes/brainCapture.js b/server/routes/brainCapture.js
index e9c6a33ff4..80fddbd110 100644
--- a/server/routes/brainCapture.js
+++ b/server/routes/brainCapture.js
@@ -6,6 +6,7 @@
import { Router } from 'express';
import * as brainService from '../services/brain.js';
+import { recordUserAction } from '../services/userActions.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import {
@@ -28,6 +29,24 @@ router.post('/capture', asyncHandler(async (req, res) => {
const captureOptions = { creative, repoIntake };
if (note !== undefined) captureOptions.note = note;
const result = await brainService.captureThought(text, providerOverride, modelOverride, captureOptions);
+ const inboxId = result?.inboxLog?.id;
+ if (inboxId) {
+ try {
+ const happenedAt = new Date().toISOString();
+ await recordUserAction({
+ type: 'brain.capture',
+ actor: 'user',
+ target: inboxId,
+ summary: 'captured thought',
+ payload: { id: inboxId },
+ source: { route: `${req.baseUrl}${req.route?.path ?? ''}`, method: req.method },
+ happenedAt,
+ dedupeKey: `brain.capture:${inboxId}`,
+ });
+ } catch (error) {
+ console.error(`❌ Failed to record brain.capture: ${error.message}`);
+ }
+ }
res.json(result);
}));
diff --git a/server/routes/cosInsightRoutes.js b/server/routes/cosInsightRoutes.js
index 8b3df7ca53..297905bbd1 100644
--- a/server/routes/cosInsightRoutes.js
+++ b/server/routes/cosInsightRoutes.js
@@ -10,6 +10,7 @@ import * as goalProgress from '../services/goalProgress.js';
import * as decisionLog from '../services/decisionLog.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { parsePagination } from '../lib/validation.js';
+import { detectIdleLeftoverBranches } from '../services/userActionDetectors.js';
const router = Router();
@@ -48,13 +49,14 @@ router.get('/productivity/calendar', asyncHandler(async (req, res) => {
// GET /api/cos/actionable-insights - Get prioritized action items requiring user attention
// Surfaces the most important things to address right now across all CoS subsystems
router.get('/actionable-insights', asyncHandler(async (req, res) => {
- const [tasksData, learningSummary, healthCheck, notificationsModule, optimalTimeInfo, pendingFeedbackCount] = await Promise.all([
+ const [tasksData, learningSummary, healthCheck, notificationsModule, optimalTimeInfo, pendingFeedbackCount, leftoverFindings] = await Promise.all([
cos.getAllTasks().catch(err => { console.error(`❌ Failed to load tasks: ${err.message}`); return { user: null, cos: null }; }),
taskLearning.getLearningInsights().catch(err => { console.error(`❌ Failed to load learning insights: ${err.message}`); return null; }),
cos.runHealthCheck().catch(err => { console.error(`❌ Failed to run health check: ${err.message}`); return { issues: [] }; }),
import('../services/notifications.js').catch(err => { console.error(`❌ Failed to load notifications: ${err.message}`); return null; }),
productivity.getOptimalTimeInfo().catch(() => ({ hasData: false })),
- cos.getPendingAgentFeedbackCount().catch(err => { console.error(`❌ Failed to load pending agent feedback: ${err.message}`); return 0; })
+ cos.getPendingAgentFeedbackCount().catch(err => { console.error(`❌ Failed to load pending agent feedback: ${err.message}`); return 0; }),
+ detectIdleLeftoverBranches().catch(err => { console.error(`❌ Failed to detect leftover branches: ${err.message}`); return []; })
]);
const notificationsData = notificationsModule ? await notificationsModule.getNotifications({ unreadOnly: true, limit: 10 }).catch(() => []) : [];
@@ -132,6 +134,26 @@ router.get('/actionable-insights', asyncHandler(async (req, res) => {
});
}
+ // 4b. Leftover idle branches (#5596) — propose-only; Run Now deep-links to the schedule.
+ if (Array.isArray(leftoverFindings) && leftoverFindings.length > 0) {
+ const leftoverCount = leftoverFindings.reduce((sum, finding) => sum + finding.leftoverCount, 0);
+ const first = leftoverFindings[0];
+ const single = leftoverFindings.length === 1;
+ insights.push({
+ type: 'leftover-branches',
+ priority: 'medium',
+ icon: 'AlertTriangle',
+ title: single
+ ? `${first.leftoverCount} leftover branches on ${first.appId}, agents idle. Run branch-reconcile?`
+ : `${leftoverCount} leftover branches across ${leftoverFindings.length} apps, agents idle. Run branch-reconcile?`,
+ description: first.lastUserReconcileAt
+ ? `Last manual reconcile ${first.lastUserReconcileAt}. Propose a Run Now — never enact.`
+ : 'No manual reconcile in the last 14 days. Propose a Run Now — never enact.',
+ action: { label: 'Run Now', route: '/cos/schedule' },
+ count: leftoverCount
+ });
+ }
+
// 5. Learning failures (skipped task types)
const skippedTypes = learningSummary?.skippedTypes || [];
if (skippedTypes.length > 0) {
diff --git a/server/routes/cosInsightRoutes.test.js b/server/routes/cosInsightRoutes.test.js
index e39230ccaf..5441e7232d 100644
--- a/server/routes/cosInsightRoutes.test.js
+++ b/server/routes/cosInsightRoutes.test.js
@@ -36,6 +36,9 @@ vi.mock('../services/decisionLog.js', () => ({
getDecisionPatterns: vi.fn()
}));
+const detectIdleLeftoverBranches = vi.hoisted(() => vi.fn(async () => []));
+vi.mock('../services/userActionDetectors.js', () => ({ detectIdleLeftoverBranches }));
+
vi.mock('../services/notifications.js', () => ({
getNotifications: vi.fn().mockResolvedValue([])
}));
@@ -153,6 +156,32 @@ describe('CoS Insight Routes', () => {
}));
});
+ it('surfaces leftover idle branches as a Run Now insight card', async () => {
+ cos.getAllTasks.mockResolvedValue({
+ user: { grouped: { pending: [], blocked: [] } },
+ cos: { awaitingApproval: [], grouped: { pending: [], blocked: [] } }
+ });
+ taskLearning.getLearningInsights.mockResolvedValue({ skippedTypes: [] });
+ cos.runHealthCheck.mockResolvedValue({ issues: [] });
+ cos.getPendingAgentFeedbackCount.mockResolvedValue(0);
+ productivity.getOptimalTimeInfo.mockResolvedValue({ hasData: false });
+ detectIdleLeftoverBranches.mockResolvedValueOnce([{
+ appId: 'app-acme', leftoverCount: 3, lastUserReconcileAt: null, agentsIdle: true,
+ }]);
+
+ const response = await request(app).get('/api/cos/actionable-insights');
+
+ expect(response.status).toBe(200);
+ expect(response.body.insights).toContainEqual(expect.objectContaining({
+ type: 'leftover-branches',
+ priority: 'medium',
+ icon: 'AlertTriangle',
+ title: '3 leftover branches on app-acme, agents idle. Run branch-reconcile?',
+ action: { label: 'Run Now', route: '/cos/schedule' },
+ count: 3,
+ }));
+ });
+
// The health insight filtered on a `severity` field runHealthCheck never
// writes, so a PM2 process that failed to auto-restart banner'd at the same
// muted `medium` priority as a memory warning.
diff --git a/server/routes/cosScheduleRoutes.js b/server/routes/cosScheduleRoutes.js
index 9920927119..7018064aea 100644
--- a/server/routes/cosScheduleRoutes.js
+++ b/server/routes/cosScheduleRoutes.js
@@ -5,6 +5,7 @@
import { Router } from 'express';
import { z } from 'zod';
import * as taskSchedule from '../services/taskSchedule.js';
+import { logCosScheduleUpdate } from '../services/userActionScheduleLog.js';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { sanitizeTaskMetadata, taskDataInputsSchema, validateRequest, parsePagination } from '../lib/validation.js';
import { promptSourceSchema, PROMPT_SOURCES } from '../lib/cosValidation.js';
@@ -144,6 +145,11 @@ router.put('/schedule/task/:taskType', asyncHandler(async (req, res) => {
if (settings.runAfter.length === 0) settings.runAfter = null;
}
const result = await taskSchedule.updateTaskInterval(taskType, settings);
+ await logCosScheduleUpdate({
+ target: taskType,
+ patch: settings,
+ source: { route: `${req.baseUrl}${req.route?.path ?? ''}`, method: req.method },
+ });
res.json({ success: true, taskType, interval: result });
}));
diff --git a/server/routes/cosScheduleRoutes.test.js b/server/routes/cosScheduleRoutes.test.js
index b55d5f380a..34ad5c6df6 100644
--- a/server/routes/cosScheduleRoutes.test.js
+++ b/server/routes/cosScheduleRoutes.test.js
@@ -3,6 +3,9 @@ import express from 'express';
import { request } from '../lib/testHelper.js';
import scheduleRoutes from './cosScheduleRoutes.js';
+const recordUserAction = vi.hoisted(() => vi.fn(async () => ({ id: 'evt' })));
+vi.mock('../services/userActions.js', () => ({ recordUserAction }));
+
vi.mock('../services/taskSchedule.js', () => ({
getScheduleStatus: vi.fn(),
getUpcomingTasks: vi.fn(),
@@ -141,6 +144,31 @@ describe('CoS Schedule Routes', () => {
expect(taskSchedule.updateTaskInterval).toHaveBeenCalledWith('review', expect.objectContaining({
runAfter: ['deploy']
}));
+ expect(recordUserAction).toHaveBeenCalledWith(expect.objectContaining({
+ type: 'cos.schedule.update',
+ target: 'review',
+ payload: expect.objectContaining({
+ keysChanged: ['runAfter'],
+ changes: { runAfter: { changed: true } },
+ }),
+ }));
+ });
+
+ it('records a long prompt as { changed: true }, never the body', async () => {
+ taskSchedule.updateTaskInterval.mockResolvedValue({ type: 'daily' });
+ const prompt = 'x'.repeat(200);
+ const response = await request(app)
+ .put('/api/cos/schedule/task/review')
+ .send({ prompt });
+ expect(response.status).toBe(200);
+ expect(recordUserAction).toHaveBeenCalledWith(expect.objectContaining({
+ type: 'cos.schedule.update',
+ payload: expect.objectContaining({
+ keysChanged: ['prompt'],
+ changes: { prompt: { changed: true } },
+ }),
+ }));
+ expect(JSON.stringify(recordUserAction.mock.calls.at(-1)[0])).not.toContain(prompt);
});
it('should set runAfter to null when only self-reference remains', async () => {
diff --git a/server/routes/imageGen.js b/server/routes/imageGen.js
index b841aa6e76..eaffd75e8b 100644
--- a/server/routes/imageGen.js
+++ b/server/routes/imageGen.js
@@ -22,6 +22,7 @@ import { local, IMAGE_GEN_MODE, IMAGE_GEN_MODES } from '../services/imageGen/ind
import { resolveCloudProviderConfig } from '../services/imageGen/cloudProviderConfig.js';
import setupRouter from './imageGenSetup.js';
import { enqueueJob, attachSseClient as attachQueueSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';
+import { recordUserAction } from '../services/userActions.js';
import { getImageModels, requiredReposForModel } from '../lib/mediaModels.js';
import { inspectModelCache, verifyModelCache, repairModelCache, aggregateVerifies } from '../lib/hfCache.js';
import { startHfDownloadStream } from '../services/hfDownloadStream.js';
@@ -55,6 +56,31 @@ import { EFFORT_LEVELS } from '../lib/providerModels.js';
const router = Router();
+const routeSource = (req) => ({ route: `${req.baseUrl}${req.route?.path ?? ''}`, method: req.method });
+
+// Event-only pointer: job id in `target`, never the generation prompt (#5596).
+async function enqueueLoggedImage(req, job) {
+ const queued = enqueueJob(job);
+ try {
+ const happenedAt = new Date().toISOString();
+ await recordUserAction({
+ type: 'media.image.enqueue',
+ actor: 'user',
+ target: queued.jobId,
+ summary: 'enqueued image job',
+ payload: { jobId: queued.jobId },
+ source: routeSource(req),
+ happenedAt,
+ dedupeKey: `media.image.enqueue:${queued.jobId}`,
+ });
+ } catch (error) {
+ // Ledger is a side effect — the job is already queued.
+ console.error(`❌ Failed to record media.image.enqueue: ${error.message}`);
+ }
+ return queued;
+}
+
+
// Shared validation limits. MAX_REFERENCE_IMAGES must stay in sync with the
// number of `referenceImageN` upload field names below.
const MAX_PROMPT_LENGTH = 8000;
@@ -573,7 +599,7 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
// normalizes any job carrying one into the downgrade-safe shape, so this
// render cannot be re-run for real by a build rolled back past
// `remoteMedia`. Contract: services/federatedMedia/routedJobParams.js.
- const queued = enqueueJob({
+ const queued = await enqueueLoggedImage(req, {
kind: 'image',
params: { ...jobParams, remoteMedia },
});
@@ -601,12 +627,12 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {
// dispatches to the matching imageGen provider module when it sees it.
// `cloud.modelId` is the *effective* model so the response metadata reports
// what actually renders (gpt-5.6-luna by default) instead of "codex"/null.
- const queued = enqueueJob({ kind: 'image', params: { ...cloud.jobParams, ...params } });
+ const queued = await enqueueLoggedImage(req, { kind: 'image', params: { ...cloud.jobParams, ...params } });
return res.json(queuedImageResponse({ ...queued, mode, model: cloud.modelId }));
}
if (mode === IMAGE_GEN_MODE.LOCAL) {
const { pythonPath: py, selectedModel } = resolveLocalImageModel(settings, params);
- const queued = enqueueJob({
+ const queued = await enqueueLoggedImage(req, {
kind: 'image',
params: {
...params,
@@ -966,7 +992,7 @@ router.post('/:filename/regenerate', asyncHandler(async (req, res) => {
initImageAbsPath,
annotated: !!body.annotated,
});
- const queued = enqueueJob({ kind: 'image', params });
+ const queued = await enqueueLoggedImage(req, { kind: 'image', params });
const via = body.annotated ? 'annotation re-render' : 'Regenerating';
console.log(`♻️ ${via} ${filename} via ${backend.model.id} (strength=${strength}) → job ${queued.jobId.slice(0, 8)}`);
return res.json(queuedImageResponse({ ...queued, mode: IMAGE_GEN_MODE.LOCAL, model: backend.model.id }));
diff --git a/server/routes/imageGen.multipart.test.js b/server/routes/imageGen.multipart.test.js
index b59b116515..3c7cbc5c23 100644
--- a/server/routes/imageGen.multipart.test.js
+++ b/server/routes/imageGen.multipart.test.js
@@ -78,6 +78,11 @@ vi.mock('../services/mediaJobQueue/index.js', () => ({
listJobs: vi.fn(() => []),
}));
+// /generate now records media.image.enqueue after enqueueJob (#5596). Mock the
+// ledger so this packing suite does not trip the test data-root guard (500).
+const recordUserAction = vi.hoisted(() => vi.fn(async () => ({ id: 'evt' })));
+vi.mock('../services/userActions.js', () => ({ recordUserAction }));
+
let imageGenRoutes;
let enqueueJob;
diff --git a/server/routes/imageGen.test.js b/server/routes/imageGen.test.js
index 6e4bbeee4c..3fc185420c 100644
--- a/server/routes/imageGen.test.js
+++ b/server/routes/imageGen.test.js
@@ -103,6 +103,9 @@ vi.mock('../services/mediaJobQueue/index.js', () => ({
listJobs: vi.fn(() => []),
}));
+const recordUserAction = vi.hoisted(() => vi.fn(async () => ({ id: 'evt' })));
+vi.mock('../services/userActions.js', () => ({ recordUserAction }));
+
// The /generate route resolves an optional universeRun collection target via
// findOrCreateUniverseCollection. Mock it so the universeRun test asserts the
// tag-resolution wiring without touching real collection storage.
@@ -419,6 +422,13 @@ describe('Image Gen Routes', () => {
// Synchronous generateImage MUST NOT be called in local mode — the
// queue takes ownership of the job lifecycle.
expect(imageGen.generateImage).not.toHaveBeenCalled();
+ expect(recordUserAction).toHaveBeenCalledWith(expect.objectContaining({
+ type: 'media.image.enqueue',
+ target: 'queued-job-001',
+ summary: 'enqueued image job',
+ payload: { jobId: 'queued-job-001' },
+ }));
+ expect(JSON.stringify(recordUserAction.mock.calls[0][0])).not.toContain('a fox in a forest');
});
it('local mode maps cfgScale to guidance before enqueueing', async () => {
diff --git a/server/routes/settings.test.js b/server/routes/settings.test.js
index ec2b093328..c34786287c 100644
--- a/server/routes/settings.test.js
+++ b/server/routes/settings.test.js
@@ -5,6 +5,8 @@ import { request } from '../lib/testHelper.js';
// In-memory settings store backing the mocked service.
let store = {};
+vi.mock('../services/userActions.js', () => ({ recordUserAction: vi.fn(async () => ({ id: 'evt' })) }));
+
vi.mock('../services/settings.js', () => ({
getSettings: vi.fn(async () => ({ ...store })),
getSettingsWithStatus: vi.fn(async () => ({ corrupt: false, settings: { ...store } })),
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index eea7898f0c..e56be52b1c 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -23,6 +23,7 @@ import {
videoModelTermsGateId,
} from '../lib/videoDisclosure.js';
import { getSettings, updateSettingsWith } from '../services/settings.js';
+import { recordUserAction } from '../services/userActions.js';
import { checkPackages, isAllowedPython } from '../lib/pythonSetup.js';
import {
listVideoModels,
@@ -945,7 +946,23 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
await cleanupMultipartTemp(uploads);
failValidation(parsed);
}
- res.json(await submitVideoGenJob(parsed.data, uploads));
+ const queued = await submitVideoGenJob(parsed.data, uploads);
+ try {
+ const happenedAt = new Date().toISOString();
+ await recordUserAction({
+ type: 'media.video.enqueue',
+ actor: 'user',
+ target: queued.jobId,
+ summary: 'enqueued video job',
+ payload: { jobId: queued.jobId },
+ source: { route: `${req.baseUrl}${req.route?.path ?? ''}`, method: req.method },
+ happenedAt,
+ dedupeKey: `media.video.enqueue:${queued.jobId}`,
+ });
+ } catch (error) {
+ console.error(`❌ Failed to record media.video.enqueue: ${error.message}`);
+ }
+ res.json(queued);
}));
// Currently-running video job (if any) so the page can re-attach after a
diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.js
index 1d4fc8120b..bf0c8c279f 100644
--- a/server/routes/videoGen.test.js
+++ b/server/routes/videoGen.test.js
@@ -212,6 +212,9 @@ vi.mock('../services/mediaJobQueue/index.js', () => ({
listJobs: vi.fn(() => []),
}));
+const recordUserAction = vi.hoisted(() => vi.fn(async () => ({ id: 'evt' })));
+vi.mock('../services/userActions.js', () => ({ recordUserAction }));
+
// Pending file metadata for tests that need to simulate an upload. Tests set
// this via `setPendingUpload({ fieldname, ... })` before issuing the request;
// the mocked uploadFields middleware reads it off the holder, attaches it as
@@ -993,6 +996,13 @@ describe('videoGen routes', () => {
seed: undefined,
}),
}));
+ expect(recordUserAction).toHaveBeenCalledWith(expect.objectContaining({
+ type: 'media.video.enqueue',
+ target: 'mock-video-job',
+ summary: 'enqueued video job',
+ payload: { jobId: 'mock-video-job' },
+ }));
+ expect(JSON.stringify(recordUserAction.mock.calls[0][0])).not.toContain('a cat');
});
it('translates the universal loraFilenames/loraScales contract into internal { filename, scale } params', async () => {
diff --git a/server/services/cos.js b/server/services/cos.js
index 84dae7829d..243cd9ad3b 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -25,6 +25,7 @@ import { INTERVAL_TYPES, isReconcileDrainTaskType } from './taskScheduleConstant
import { isRetryHeld, isStaleRetryHold } from '../lib/taskRetryHold.js';
import { isAppOnCooldown, markAppReviewCooldown, bindAppReviewAgent, clearStaleActiveAgents } from './appActivity.js';
import { getActiveApps } from './apps.js';
+import { logCosScheduleUpdate } from './userActionScheduleLog.js';
import { getPerformanceSummary, checkAndRehabilitateSkippedTasks, getLearningInsights } from './taskLearning.js';
import { schedule as scheduleEvent, cancel as cancelEvent } from './eventScheduler.js';
import { generateProactiveTasks as generateMissionTasks } from './missions.js';
@@ -278,6 +279,15 @@ export async function updateConfig(updates) {
await saveState(state);
return state.config;
});
+ const improveKeys = ['improvementEnabled', 'selfImprovementEnabled', 'appImprovementEnabled'];
+ const improvePatch = Object.fromEntries(
+ improveKeys.filter((key) => Object.prototype.hasOwnProperty.call(updates, key)).map((key) => [key, updates[key]]),
+ );
+ await logCosScheduleUpdate({
+ target: 'cos-config',
+ patch: improvePatch,
+ source: { service: 'cos', fn: 'updateConfig' },
+ });
cosEvents.emit('config:changed', config);
if (persistentMindWakeCadenceChanged) {
await refreshPersistentMindWakeCadence();
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 58f9a1493a..bc27179ba2 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -87,6 +87,7 @@ import {
resolveRepoSyncBlock,
resolveSwarmBlock,
} from './cosTaskPreStepBlocks.js';
+import { detectIdleLeftoverBranches, formatUserActionDetectorBlock } from './userActionDetectors.js';
// Back-compat shim — these five were public here before the pre-step layer moved
// to its own module, so a deep import of this file keeps resolving them.
@@ -1828,6 +1829,7 @@ export async function generateSelfImprovementTaskForType(taskType, state) {
// user-action-review: render the delivery posture the operator chose
// (fileIssues on = tracker issues, off = queued CoS tasks).
description = applyUserActionDeliveryMode(description, taskType, metadata);
+ description = await applyUserActionDetectorSection(description, taskType);
const repoSync = await resolveRepoSyncBlock(null, taskType, metadata);
if (repoSync.skip) return null;
@@ -2698,6 +2700,24 @@ export function applyUserActionDeliveryMode(promptTemplate, taskType, metadata)
return `## Delivery mode\n\n${block}\n\n---\n\n${prompt}`;
}
+/**
+ * Render leftover-branch detector findings into a user-action-review prompt.
+ * A customized stored prompt that dropped `{userActionDetectors}` still gets
+ * the section PREPENDED — otherwise the detector would be a silent no-op.
+ */
+export async function applyUserActionDetectorSection(promptTemplate, taskType) {
+ if (taskType !== 'user-action-review') return typeof promptTemplate === 'string' ? promptTemplate : '';
+ const prompt = typeof promptTemplate === 'string' ? promptTemplate : '';
+ const findings = await detectIdleLeftoverBranches().catch((error) => {
+ console.error(`❌ user-action-review detector interpolation failed: ${error.message}`);
+ return [];
+ });
+ const block = formatUserActionDetectorBlock(findings) || 'No leftover-branch findings.';
+ if (prompt.includes('{userActionDetectors}')) return prompt.replace(/\{userActionDetectors\}/g, () => block);
+ return `## Detectors\n\n${block}\n\n---\n\n${prompt}`;
+}
+
+
const EMPTY_PROVIDER_PIN = Object.freeze({ providerId: null, model: null });
/**
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index 697720f940..cef391ac16 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -51,6 +51,15 @@ vi.mock('./taskSchedule.js', async (importActual) => {
// emitOnDemandEmpty's gh-health read spawns `gh api rate_limit` for real. Stub it
// so the transient-verdict tests assert OUR branching, not the machine's gh.
const ghHealth = vi.fn(async () => ({ status: 'ok', ok: true, detail: null, remedy: null }));
+const detectorMocks = vi.hoisted(() => ({
+ detectIdleLeftoverBranches: vi.fn(async () => []),
+ formatUserActionDetectorBlock: vi.fn(() => ''),
+}));
+vi.mock('./userActionDetectors.js', () => ({
+ detectIdleLeftoverBranches: (...args) => detectorMocks.detectIdleLeftoverBranches(...args),
+ formatUserActionDetectorBlock: (...args) => detectorMocks.formatUserActionDetectorBlock(...args),
+}));
+
vi.mock('./github.js', async (importActual) => ({
...(await importActual()),
checkGhHealth: (...a) => ghHealth(...a),
@@ -78,6 +87,7 @@ import {
resolveTaskInputHook,
resolveUserActionDeliveryBlock,
applyUserActionDeliveryMode,
+ applyUserActionDetectorSection,
buildSecurityScanPipelineOutput
} from './cosTaskGenerator.js';
import * as cosTaskGenerator from './cosTaskGenerator.js';
@@ -1309,6 +1319,17 @@ describe('resolveUserActionDeliveryBlock (#5595)', () => {
expect(applyUserActionDeliveryMode('Prompt', 'security', {})).toBe('Prompt');
});
+ it('applyUserActionDetectorSection substitutes the token, or PREPENDS on a customized prompt that dropped it', async () => {
+ detectorMocks.formatUserActionDetectorBlock.mockReturnValue('LEFTOVER-FINDING');
+ const withToken = await applyUserActionDetectorSection('Intro\n\n{userActionDetectors}\n\nOutro', 'user-action-review');
+ expect(withToken).toContain('LEFTOVER-FINDING');
+ expect(withToken).not.toContain('{userActionDetectors}');
+ const custom = await applyUserActionDetectorSection('My custom review prompt', 'user-action-review');
+ expect(custom).toMatch(/^## Detectors\n\nLEFTOVER-FINDING/s);
+ expect(custom).toContain('My custom review prompt');
+ expect(await applyUserActionDetectorSection('Prompt', 'security')).toBe('Prompt');
+ });
+
it('the install-wide lane consumes the input hook and renders the delivery block', () => {
// Source-pinned like the approval-stamp guard above: the empty-ledger skip
// and the delivery posture must reach the "Run Now with no app" lane, which
@@ -1321,6 +1342,7 @@ describe('resolveUserActionDeliveryBlock (#5595)', () => {
expect(selfBody).toContain('if (taskSchedule.INSTALL_WIDE_TASK_TYPES.has(taskType)) {');
expect(selfBody).toContain("resolveTaskInputHook({ id: null, name: 'PortOS' }, taskType, taskSchedule)");
expect(selfBody).toContain('applyUserActionDeliveryMode(description, taskType, metadata)');
+ expect(selfBody).toContain('applyUserActionDetectorSection(description, taskType)');
// The action-output posture must be dispatch-stamped: noCodeOutput is not a
// sanitizer-allowed key, so it cannot ride in from DEFAULT_TASK_INTERVALS —
// without the stamp the completion contract tells a live-checkout agent to
diff --git a/server/services/cosToolRegistry.test.js b/server/services/cosToolRegistry.test.js
index 5e315e2a99..ffe2f6b7c5 100644
--- a/server/services/cosToolRegistry.test.js
+++ b/server/services/cosToolRegistry.test.js
@@ -108,8 +108,12 @@ describe('cosToolRegistry', () => {
it('includes only granted tools in the Persistent Mind prompt', () => {
const prompt = buildPersistentMindToolPrompt({ readPortos: true });
- expect(prompt).toContain('brain.search');
- expect(prompt).not.toContain('brain.capture');
+ // Catalog entries are JSON.stringified as `"name":"<tool>"`. A granted
+ // tool's input schema may list the same token as an enum (user-actions.query
+ // type `brain.capture`, #5596) — that must not be mistaken for advertising
+ // the ungranted write tool.
+ expect(prompt).toContain('"name":"brain.search"');
+ expect(prompt).not.toContain('"name":"brain.capture"');
});
it('exposes the operator-action ledger to mind and agent scopes only behind readPortos', async () => {
diff --git a/server/services/instanceFeatures.js b/server/services/instanceFeatures.js
index 44b5e36a1f..5bf297eb9e 100644
--- a/server/services/instanceFeatures.js
+++ b/server/services/instanceFeatures.js
@@ -11,6 +11,7 @@ import {
setEidoverseWorldsOrigin,
} from './eidoverse.js';
import { getSettingsWithStatus, updateSettingsWith } from './settings.js';
+import { recordUserAction } from './userActions.js';
// Runtime resolution for the feature registry in
// server/lib/instanceFeatureRegistry.js. Instance features are local to one
@@ -213,7 +214,23 @@ export async function updateInstanceFeature(featureId, enabled) {
[featureId]: { ...currentFeature, enabled },
},
};
- });
+ }, { actor: 'user', skipUserAction: true });
+
+ try {
+ const happenedAt = new Date().toISOString();
+ await recordUserAction({
+ type: 'instance-feature.toggle',
+ actor: 'user',
+ target: featureId,
+ summary: `Toggled instance feature ${featureId} ${enabled ? 'on' : 'off'}`,
+ payload: { id: featureId, enabled },
+ source: { service: 'instanceFeatures', fn: 'updateInstanceFeature' },
+ happenedAt,
+ dedupeKey: `instance-feature.toggle:${featureId}:${enabled}:${happenedAt}`,
+ });
+ } catch (error) {
+ console.error(`❌ Failed to record instance-feature.toggle: ${error.message}`);
+ }
const detected = await detectFeatureConfiguration();
return { features: await attachSetupStatus(resolveInstanceFeatures(settings, { detected }), settings) };
diff --git a/server/services/instanceFeatures.test.js b/server/services/instanceFeatures.test.js
index b39c4c4470..fccd5a89d8 100644
--- a/server/services/instanceFeatures.test.js
+++ b/server/services/instanceFeatures.test.js
@@ -13,6 +13,9 @@ const mock = vi.hoisted(() => ({
setEidoverseWorldsOrigin: vi.fn(),
}));
+const recordUserAction = vi.hoisted(() => vi.fn(async () => ({ id: 'evt' })));
+vi.mock('./userActions.js', () => ({ recordUserAction }));
+
vi.mock('./settings.js', () => ({
getSettings: vi.fn(async () => structuredClone(mock.settings)),
getSettingsWithStatus: vi.fn(async () => ({ corrupt: mock.corrupt, settings: structuredClone(mock.settings) })),
@@ -263,4 +266,15 @@ describe('instance features', () => {
await expect(updateInstanceFeature('nope', true)).rejects.toMatchObject({ status: 404 });
expect(await isInstanceFeatureEnabled('nope')).toBe(false);
});
+
+ it('records instance-feature.toggle with { id, enabled } and skips settings.update', async () => {
+ await updateInstanceFeature('post', false);
+ expect(mock.updateSettingsWith).toHaveBeenCalledWith(expect.any(Function), { actor: 'user', skipUserAction: true });
+ expect(recordUserAction).toHaveBeenCalledWith(expect.objectContaining({
+ type: 'instance-feature.toggle',
+ actor: 'user',
+ target: 'post',
+ payload: { id: 'post', enabled: false },
+ }));
+ });
});
diff --git a/server/services/persistentMindUserActions.js b/server/services/persistentMindUserActions.js
index f551fa9a72..402875b440 100644
--- a/server/services/persistentMindUserActions.js
+++ b/server/services/persistentMindUserActions.js
@@ -18,6 +18,7 @@
import { scrubSecretTokens } from '../lib/secretText.js';
import { listUserActions } from './userActions.js';
+import { detectIdleLeftoverBranches, formatLeftoverBranchSnippet } from './userActionDetectors.js';
export const USER_ACTIONS_SNIPPET_WINDOW_MS = 24 * 60 * 60 * 1000;
export const USER_ACTIONS_SNIPPET_MAX_CHARS = 1500;
@@ -92,12 +93,22 @@ export function buildPersistentMindUserActionsPrompt(events) {
* lifecycle), so a failure logs once and renders as "no section".
*/
export async function readPersistentMindUserActionsPrompt({ now = Date.now() } = {}) {
- const events = await listUserActions({
- from: new Date(now - USER_ACTIONS_SNIPPET_WINDOW_MS).toISOString(),
- limit: SNIPPET_FETCH_LIMIT,
- }).catch((error) => {
- console.error(`❌ Persistent mind user-action snippet read failed: ${error.message}`);
- return [];
- });
- return buildPersistentMindUserActionsPrompt(events);
+ const [events, findings] = await Promise.all([
+ listUserActions({
+ from: new Date(now - USER_ACTIONS_SNIPPET_WINDOW_MS).toISOString(),
+ limit: SNIPPET_FETCH_LIMIT,
+ }).catch((error) => {
+ console.error(`❌ Persistent mind user-action snippet read failed: ${error.message}`);
+ return [];
+ }),
+ detectIdleLeftoverBranches().catch((error) => {
+ console.error(`❌ Persistent mind leftover-branch detector failed: ${error.message}`);
+ return [];
+ }),
+ ]);
+ const eventsSection = buildPersistentMindUserActionsPrompt(events);
+ const detectorLines = formatLeftoverBranchSnippet(findings);
+ if (!eventsSection && !detectorLines) return '';
+ if (!eventsSection) return `# Recent user actions (last 24h)\n${detectorLines}`;
+ return detectorLines ? `${eventsSection}\n${detectorLines}` : eventsSection;
}
diff --git a/server/services/persistentMindUserActions.test.js b/server/services/persistentMindUserActions.test.js
index 368359f464..fcdc668400 100644
--- a/server/services/persistentMindUserActions.test.js
+++ b/server/services/persistentMindUserActions.test.js
@@ -1,9 +1,19 @@
import { describe, expect, it, vi } from 'vitest';
-const mocks = vi.hoisted(() => ({ listUserActions: vi.fn() }));
+const mocks = vi.hoisted(() => ({
+ listUserActions: vi.fn(),
+ detectIdleLeftoverBranches: vi.fn(async () => []),
+}));
vi.mock('./userActions.js', () => ({
listUserActions: (...args) => mocks.listUserActions(...args),
}));
+vi.mock('./userActionDetectors.js', async (importActual) => {
+ const actual = await importActual();
+ return {
+ ...actual,
+ detectIdleLeftoverBranches: (...args) => mocks.detectIdleLeftoverBranches(...args),
+ };
+});
import {
USER_ACTIONS_SNIPPET_MAX_CHARS,
@@ -102,4 +112,14 @@ describe('readPersistentMindUserActionsPrompt', () => {
mocks.listUserActions.mockRejectedValueOnce(new Error('database offline'));
await expect(readPersistentMindUserActionsPrompt()).resolves.toBe('');
});
+
+ it('appends leftover-branch detector lines even when the 24h ledger is empty', async () => {
+ mocks.listUserActions.mockResolvedValueOnce([]);
+ mocks.detectIdleLeftoverBranches.mockResolvedValueOnce([{
+ appId: 'app-acme', leftoverCount: 2, lastUserReconcileAt: null, agentsIdle: true,
+ }]);
+ const prompt = await readPersistentMindUserActionsPrompt();
+ expect(prompt).toContain('# Recent user actions (last 24h)');
+ expect(prompt).toContain('leftover-branches: app app-acme has 2 local branches, agents idle, last manual reconcile never');
+ });
});
diff --git a/server/services/settings.js b/server/services/settings.js
index 6e66f883ac..c50851ca35 100644
--- a/server/services/settings.js
+++ b/server/services/settings.js
@@ -232,7 +232,7 @@ const diffSettings = (prev, next) => {
* feature writes. Only `PUT /api/settings` passes `'user'`. `reloadSettings` does
* not call this at all, so a backup restore is excluded by construction.
*/
-const save = async (settings, { actor = 'system' } = {}) => {
+const save = async (settings, { actor = 'system', skipUserAction = false } = {}) => {
const cleaned = stripStoreKeys(settings);
// Stamp `timezoneUpdatedAt` whenever the effective `timezone` actually
// changes, so timezone-dependent schedulers can gate catch-up/re-evaluation
@@ -266,7 +266,7 @@ const save = async (settings, { actor = 'system' } = {}) => {
// A no-op save writes no ledger row: the settings page PUTs the whole object
// on every visit, and a log full of "changed nothing" rows would bury the
// changes that matter.
- if (change && change.keysChanged.length > 0) {
+ if (!skipUserAction && change && change.keysChanged.length > 0) {
const happenedAt = new Date().toISOString();
const changedKeys = change.keysChanged.join(',');
await recordUserAction({
diff --git a/server/services/settings.userActions.test.js b/server/services/settings.userActions.test.js
index 030b65ac25..a430f274da 100644
--- a/server/services/settings.userActions.test.js
+++ b/server/services/settings.userActions.test.js
@@ -114,6 +114,11 @@ describe('settings save → user_action_events (#5594)', () => {
expect(events.every((e) => e.dedupeKey.startsWith('settings.update:'))).toBe(true);
});
+ it('skipUserAction suppresses the generic settings.update row', async () => {
+ await updateSettings({ timezone: 'Europe/Berlin' }, { actor: 'user', skipUserAction: true });
+ expect(await listUserActions({ type: 'settings.update' })).toEqual([]);
+ });
+
it('records nothing for reloadSettings — a restore is not an operator edit', async () => {
seed({ timezone: 'Asia/Tokyo', theme: 'dark' });
await reloadSettings();
diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.json
index a962698051..b7de8d06cf 100644
--- a/server/services/taskPromptDefaults/integrity.snapshot.json
+++ b/server/services/taskPromptDefaults/integrity.snapshot.json
@@ -43,7 +43,7 @@
"test-coverage": "0d8359170529da12cd63356610b2e220",
"typing": "1f2758ce0bb62d789a21aec241549531",
"ui-bugs": "def9ad96bd74ab397233f234d79a1974",
- "user-action-review": "945a716d446d26a03e2805d28bd1ae16",
+ "user-action-review": "1a083430e43f60cdd586cfffbdebc583",
"ux": "e03d03fc7c16faa5b5db93be2896b9ad"
},
"PROMPT_VERSIONS": {
@@ -86,7 +86,7 @@
"test-coverage": 2,
"typing": 2,
"ui-bugs": 2,
- "user-action-review": 1,
+ "user-action-review": 2,
"ux": 1
},
"REFERENCE_WATCH_AUDITED_VERSION": 3,
@@ -284,6 +284,9 @@
],
"ui-bugs": [
"01d2a7e034713195f33071f2c71a3c99"
+ ],
+ "user-action-review": [
+ "945a716d446d26a03e2805d28bd1ae16"
]
}
}
diff --git a/server/services/taskPromptDefaults/previousDefaults.js b/server/services/taskPromptDefaults/previousDefaults.js
index 919560763c..5cf0ef0fd7 100644
--- a/server/services/taskPromptDefaults/previousDefaults.js
+++ b/server/services/taskPromptDefaults/previousDefaults.js
@@ -12309,3 +12309,5 @@ PREVIOUS_DEFAULT_PROMPTS['claim-issue-gitlab'].push("[Claim Issue: {appName}] Cl
// v23 default — before claimant-comment handoff and the untrusted-forge boundary.
PREVIOUS_DEFAULT_PROMPTS['claim-issue'].push("[Claim Issue: {appName}] Claim and ship the next open GitHub issue\n\nPick the next available unclaimed open GitHub issue, **create your own worktree at `claim/issue-<num>`**, implement the fix, ship a PR that closes the issue, and clean up. This is the `/claim --issues` flow — same in-flight scan, same branch naming, same no-local-merge cleanup, but the work source is the repo's GitHub issue tracker instead of PLAN.md. **YOU pick the issue in Phase 1 — the scheduler does not reserve one for you.** Picking at execution time and immediately claiming (worktree + assignee + label) **narrows** the window for two concurrent runs to collide on the same issue — it does NOT eliminate it. Do NOT modify files in the source repo directly; ALL editing happens inside the worktree you create.\n\n{issueAuthorFilter}\n\n**How claiming works.** An issue is \"in flight\" when its number appears as the issue-position segment in either a `claim/issue-<num>` ref (the human/TUI pattern) or a `cos/<task>/issue-<num>/<agent>` ref (the CoS sub-agent pattern) across local branches, remote branches, or open PR head refs — OR the issue is assigned to another account OR carries an `in-progress` label. An issue already assigned to the authenticated account remains eligible for a retry. The `claim/issue-<num>` branch + the assignee/`in-progress` markers you set ARE the claim, visible to every other agent (including parallel machines) and to the human running `/claim --issues` in a TUI.\n\n## Phase 1 — Pick the target issue\n\nRun steps 1–5 in order.\n\n1. cd into the repo root ({repoPath}) and confirm GitHub is the forge: `gh repo view --json nameWithOwner -q .nameWithOwner`. If `gh` is not authenticated or the remote is not GitHub, exit cleanly — this task only works against GitHub issue trackers.\n2. List candidate open issues **oldest-first**, honoring the author filter described above. `gh issue list` defaults to newest-first, so order on the SERVER with `--search \"sort:created-asc\"` — a client-side `jq` sort would only reorder the already-truncated newest page, dropping the true oldest issues on repos with more than `--limit` open issues:\n ```bash\n git fetch --prune 2>/dev/null\n # Author filter (see the block above). Pass --author as a QUOTED single token —\n # do NOT pack flag+value into one variable: a bare `$VAR` holding \"--author x\"\n # is a single argv token in zsh (no word-splitting) and gh rejects it.\n # Owner-only mode (default): resolve the owner, then add --author \"$OWNER\"\n # --limit 500 (not 100): the blocking-label filter below runs on this\n # fetched page, so a small cap risks missing eligible work further down\n # a busy queue when the first page is full of excluded/in-flight issues.\n # Keep an issue assigned to this authenticated account eligible for retry;\n # if this lookup fails, leave ME empty and skip all assigned issues.\n GH_HOST=\"$(git remote get-url origin 2>/dev/null | sed -E -e 's#^[^:]+://([^@/]+@)?([^/:]+)(:[0-9]+)?/.*#\\2#' -e 's#^([^@]+@)?([^:]+):.*#\\2#')\"\nif [ \"$GH_HOST\" = \"ssh.github.com\" ]; then GH_HOST=\"github.com\"; fi\n ME=\"$(gh api --hostname \"$GH_HOST\" user -q .login 2>/dev/null || true)\"\n OWNER=\"$(gh repo view --json owner -q .owner.login)\"\n gh issue list --state open --author \"$OWNER\" --search \"sort:created-asc\" --json number,title,author,assignees,labels,createdAt --limit 500\n # Any-author mode: run the SAME command WITHOUT the --author \"$OWNER\" flag.\n ```\n3. Build the in-flight set. Collect every branch/PR ref:\n ```bash\n git branch -a --no-color --format='%(refname:short)'\n gh pr list --state open --json headRefName -q '.[].headRefName' 2>/dev/null\n ```\n For each ref (after stripping any leading `origin/` / `upstream/` prefix), extract the issue number **only when the ref matches** `claim/issue-<num>` (number after `claim/issue-`) or `cos/<task>/issue-<num>/<agent>` (the `issue-<num>` third segment). Do NOT flag an issue just because its bare number appears elsewhere in a ref.\n4. **Pick the target issue:** walk the candidate list oldest-first in TWO passes. First pass, consider only NON-epic issues and take the first that satisfies every rule below — atomic work always outranks an epic, whatever their relative age. Only if that pass finds nothing do you make a second pass for an undecomposed epic (same rules), and an epic you pick goes to **Phase 1b**, not Phase 2. A single oldest-first pass would enter a decomposition the moment an epic happened to be older than claimable work, which is exactly backwards. The rules:\n - Its number is NOT in the in-flight set.\n - It has no assignees, or at least one assignee's login matches `$ME` (an issue assigned only to another account is already claimed). If `$ME` is empty, skip every assigned issue.\n - It does NOT carry any of these blocking labels: {issueExcludeLabels}.\n - It is NOT an ALREADY-DECOMPOSED tracking/umbrella **epic**. An epic is recognized by an `epic` label, a title ending in \"(epic)\", OR a title beginning with an `[epic]` bracket or `Epic:` tag (e.g. \"[Epic] …\" / \"Epic: …\", case-insensitive); it counts as decomposed once it ALSO carries the `decomposed` label. Skip a decomposed epic — its child slices are ordinary claimable issues in this very list, so claiming the parent would duplicate them. An undecomposed epic is eligible only in the second pass above. **The bare `plan` label is NOT a skip signal.** `do-replan --issues` (and `/do:replan --issues`) labels EVERY migrated backlog item `plan` — atomic bug-fixes included — so `plan` marks the *claimable* queue exactly as `/do:next --issues` treats it (it is that flow's required candidate label). Skipping all `plan` issues would discard the entire actionable backlog and falsely report an empty queue.\n5. **If no eligible issue exists**, exit cleanly — an empty actionable queue is a healthy state, not a failure. **But an open, undecomposed epic is NOT an empty queue**: never report \"no work available\" while one is unclaimed. Splitting it is the work — go to Phase 1b.\n\nCapture the issue number as `NUM`, its title, and its full body — you'll reuse them in the PR and the `Closes #<num>` trailer.\n\n## Phase 1b — Decompose an epic (only when Phase 1 landed on one)\n\nYou reach this phase two ways: Phase 1 found no eligible atomic issue and fell through to an undecomposed epic, or the user pinned this run to an epic. **Never end a run reporting \"nothing to do\" while an undecomposed epic is open** — turning it into shippable slices IS this round's work, and it is what refills the queue for every later run.\n\nCapture the epic's number as `EPIC`. This phase writes ONLY to the issue tracker: no worktree, no branch, no PR, no edits in the source repo.\n\n1. Read it in full, comments included: `gh issue view \"${EPIC}\" --comments`.\n2. **Find the children it already has** — an epic a human (or an earlier run) already split must never be re-split:\n ```bash\n gh issue view \"${EPIC}\" --json body -q .body\n gh issue list --state all --search \"in:body \\\"Part of #${EPIC}\\\"\" --json number,title,state,labels,assignees --limit 200\n ```\n Union that with every `#<num>` the epic's own body checklist references.\n3. **If children already exist, do NOT file more.**\n - **Some child still OPEN** → the epic is already decomposed. Make sure it carries the `decomposed` label and that its body checklist lists every child (step 6), then set `NUM` to the FIRST open child that passes Phase 1 step 4's eligibility rules (oldest-first) and continue at **Phase 2** with that child. If every open child is in flight, assigned elsewhere, or blocked, exit cleanly — that queue is busy, not empty.\n - **Every child CLOSED** → the epic's work is done. Post a comment naming the children that delivered it, close it (`gh issue close \"${EPIC}\" --reason completed`), and return to Phase 1 to look for other work.\n - **Labeled `decomposed` but NO children exist** → an earlier split claimed the epic and died before filing anything. Treat it as undecomposed and continue at step 4; the marker is already in place, so nothing needs re-claiming. (Auto-pick can't reach this state — the marker is exactly what makes Phase 1 skip the epic — so it is recovered only when a human or the work-item picker aims a claim straight at that epic. That is the deliberate trade: a stalled split waits for a human, rather than every marker-write failure re-splitting the same epic on every drain tick.)\n4. **Otherwise, plan the split.** Read the code the epic actually names before slicing — a split that never met the repo is worthless. Produce 2–8 slices, each of them independently shippable in ONE PR, valuable on its own, and written with concrete scope + acceptance criteria + the files/areas involved. Slice by user-visible behavior or subsystem; never one-issue-per-file, and never invent scope the epic doesn't ask for. Decide the boundaries yourself — an ambiguous epic is decided, not deferred (same rule as Phase 3). Only an epic so vague that no split survives contact with the code is a `needs-input` case: comment what is missing, `gh issue edit \"${EPIC}\" --add-label needs-input`, and exit.\n5. **Claim the epic, THEN file the slices.** Stamp the marker before the first `gh issue create` — the label IS this phase's claim (Phase 1 skips a `decomposed` epic). Like every other marker in this flow it **narrows** the window for two concurrent runs to collide — it does NOT eliminate it, since a label edit is an idempotent write, not a compare-and-set — so re-run step 2's child query immediately before the first create and abandon the split if children now exist. Marking last instead of first would leave the epic actionable forever whenever that final edit failed, and let a crashed run be re-split from scratch on the next tick:\n ```bash\n gh label create decomposed --color BFD4F2 --description 'Epic already split into per-slice child issues' 2>/dev/null || true\n gh issue edit \"${EPIC}\" --add-label decomposed\n gh issue comment \"${EPIC}\" --body \"Decomposing into per-slice issues — <one line on how you sliced it>\"\n # The queue label the slices carry must exist before the first create, or every\n # `gh issue create` below fails on a repo that has never used it.\n gh label create plan --color 0E8A16 --description \"Claimable backlog item\" 2>/dev/null || true\n ```\n Then file each slice, in the order you want them worked:\n ```bash\n gh issue create --title \"<specific, human-readable>\" --label plan \\\n --body \"<what + why + acceptance criteria + files/areas>\n\nPart of #${EPIC}\"\n ```\n Use `Part of #${EPIC}` — NEVER `Closes #${EPIC}`, which would close the whole epic on the first slice that merges. **Give every slice body the epic-closure instruction too** — a line telling the agent that ships it to check its box in #${EPIC} and, when it was the LAST open child, close #${EPIC} with a summarizing comment. That is what closes the epic: once it carries the marker, Phase 1 and the work detector both skip it, so no later claim run will revisit the parent on its own. Carry over the epic's `area:*` labels, and add dispatch hints (`model:light|medium|heavy`, `effort:low|medium|high|xhigh|max`) or contributor labels (`good first issue`, `help wanted`) only where that slice genuinely justifies them; create a missing label immediately before applying it.\n6. **Write the checklist back to the epic** so the next run can follow it — keep the original body and append a `## Decomposed into` list naming every child:\n ```bash\n EPIC_BODY=$(mktemp)\n gh issue view \"${EPIC}\" --json body -q .body > \"${EPIC_BODY}\"\n printf '\\n\\n## Decomposed into\\n\\n- [ ] #<a> — <title>\\n- [ ] #<b> — <title>\\n' >> \"${EPIC_BODY}\"\n gh issue edit \"${EPIC}\" --body-file \"${EPIC_BODY}\"\n rm -f \"${EPIC_BODY}\"\n ```\n The marker from step 5 is what stops the next run from splitting the same epic again; this checklist is what lets a claim aimed at the epic resolve the next available child. Leave the epic OPEN, unassigned, and WITHOUT `in-progress` — it closes when its last child closes.\n7. **Then claim the first slice you filed** — set `NUM` to it and continue at **Phase 2**, shipping that ONE slice normally (its PR closes the slice, never the epic). If claiming it fails because another run won the race, exit cleanly: the decomposition alone is a successful round, and the next claim run picks up the next linked child.\n\n## Phase 2 — Claim (worktree + markers)\n\nCreate the worktree on a branch named `claim/issue-<num>`, then set the cross-machine claim markers. Do all editing inside the worktree, NEVER in the source repo's working tree.\n\n```bash\nNUM=<picked-number>\nWORKTREE=\"{worktreesRoot}/claim-issue-${NUM}\"\nmkdir -p {worktreesRoot}\ngit fetch origin main\ngit worktree add --no-track -b \"claim/issue-${NUM}\" \"${WORKTREE}\" origin/main\n# Cross-machine claim markers (best-effort — do not abort the run if these fail):\ngh issue edit \"${NUM}\" --add-assignee @me 2>/dev/null\ngh issue edit \"${NUM}\" --add-label in-progress 2>/dev/null\n# Retire the contributor invitations — this issue is taken now, so it must stop\n# advertising itself to a human looking for something to pick up. One edit per\n# label: `--remove-label` fails the WHOLE call when a named label is absent, so\n# a combined call on an issue carrying only one of them would remove neither.\ngh issue edit \"${NUM}\" --remove-label 'good first issue' 2>/dev/null\ngh issue edit \"${NUM}\" --remove-label 'help wanted' 2>/dev/null\ncd \"${WORKTREE}\"\n```\n\n(If the repo's default branch is not `main`, detect it with `gh repo view --json defaultBranchRef -q .defaultBranchRef.name` and substitute it for `main` above.)\n\nReleasing `good first issue` / `help wanted` is deliberate and one-way: they invite a human contributor, and every path out of this flow either closes the issue or returns it to the AUTONOMOUS queue, where those labels mean nothing. Do NOT restore them when Phase 3 or Phase 7 releases the claim — re-advertising the issue to humans is a call for the human who wants it re-advertised.\n\n**If `git worktree add` fails because the `claim/issue-<num>` branch already exists** (a concurrent run won the race, or a remote claim branch is now visible), do NOT force or reuse it — that branch IS another run's claim. Treat the issue as in-flight, return to Phase 1, and pick the next eligible issue; if nothing else is eligible, exit cleanly. Stash `WORKTREE` — you'll need it for Phase 7 cleanup.\n\n## Phase 3 — Verify still valid\n\nRead the full issue (`gh issue view \"${NUM}\" --comments`) before writing any code. **Every exit from this phase must leave a CONVERGING outcome on the issue — closed, or labeled `needs-input`.** Phase 1 step 4 skips both, so an autonomous drain stops re-picking the item. Releasing an issue OPEN and unlabeled is NOT an exit: the work detector still reports it actionable, so the next pass re-picks it and burns another no-op agent — every pass, forever.\n\n- **Already fixed, superseded, or closed-then-reopened-for-tracking** — a comment says so, or the change it asks for is already on the default branch. **Close it:** post a comment naming the PR/commit (or issue) that already delivered it (`gh issue comment \"${NUM}\" --body \"...\"`), then `gh issue close \"${NUM}\" --reason completed` (use `--reason \"not planned\"` when it was superseded rather than delivered) and clear the markers (`gh issue edit \"${NUM}\" --remove-assignee @me --remove-label in-progress`). Remove the worktree and return to Phase 1. **Evidence gate: if you cannot name the PR, commit, or issue that delivered it, this branch does NOT apply** — closing on a hunch destroys live work, which is far worse than one wasted pass. Treat the issue as real work and continue to Phase 4.\n- **Stale reference** — the request names a function, file, or component that no longer exists (`grep -rn` the named identifiers; if they're gone, the issue is stale). Post a comment naming what you searched for and what you found instead, **tag it `needs-input`** (`gh issue edit \"${NUM}\" --add-label needs-input`), release the claim markers (`gh issue edit \"${NUM}\" --remove-assignee @me --remove-label in-progress`), remove the worktree, and return to Phase 1. Re-scoping a stale issue against today's code is a human call — and the label is what keeps the drain off it in the meantime.\n\n(A too-large scope is NOT in this list — it has its own park path below.)\n\n**A genuinely too-large issue gets SPLIT, not parked.** If the work is bigger than one coherent claim — it would touch files far outside the issue's scope (>5 unrelated files) — and you can't carve a valuable standalone slice to partial-ship via Phase 6's `Refs` path, promote it to an epic and decompose it: file the slices and rewrite the parent exactly as **Phase 1b** steps 4–6 describe (each slice carrying `Part of #${NUM}`). **Promote it on BOTH axes, creating the umbrella label first** — the queue skips a parent only when it is epic-shaped AND marked, so an issue left carrying only `decomposed` stays claimable and gets re-split every pass:\n```bash\ngh label create epic --color B60205 --description 'Umbrella/tracking issue — shipped as per-slice children, never as one PR' 2>/dev/null || true\ngh issue edit \"${NUM}\" --add-label epic --add-label decomposed\n```\nVerify BOTH labels are actually on the issue afterwards (`gh issue view \"${NUM}\" --json labels`); if the `epic` label still won't stick, append \" (epic)\" to the title instead (`gh issue edit \"${NUM}\" --title \"… (epic)\"`) — the title convention marks an epic with no label at all. Then release its claim markers (`gh issue edit \"${NUM}\" --remove-assignee @me --remove-label in-progress`), remove the worktree, and continue at Phase 2 with the first slice you filed. Splitting an omnibus issue is work you do, not a hand-off. Park to `needs-input` (`gh issue edit \"${NUM}\" --add-label needs-input`, release the markers, remove the worktree, exit) ONLY when the issue is too vague to slice against the code at all — that park is what stops a perpetual drain from re-picking an un-shippable issue every pass (Phase 1 step 4 skips `needs-input`).\n\n**Ambiguity is NOT a release trigger — decide, don't defer.** If the issue is merely open to more than one reasonable reading, or leaves a design choice unstated, do NOT bail to `needs-input`. Pick the most reasonable interpretation, record the approach you chose in a brief issue comment (`gh issue comment \"${NUM}\" --body \"...\"`) so the decision is on the record, and implement it. The user would rather iterate on top of a shipped best-guess than have the issue parked waiting on a decision they didn't ask to make. Reserve `needs-input` — which pulls the issue out of the autonomous queue — for the narrow cases where proceeding would be **destructive or irreversible**, or genuinely requires the human: specific hardware/credentials you don't have, or a judgment only they can make. In those cases only, post the explaining comment, **tag it `needs-input`** (`gh issue edit \"${NUM}\" --add-label needs-input`), release the claim markers (`gh issue edit \"${NUM}\" --remove-assignee @me --remove-label in-progress`), remove the worktree, and exit cleanly. **That label is what lets an autonomous drain converge** — Phase 1 step 4 skips `needs-input` issues. Never leave a half-claimed issue.\n\n## Phase 4 — Implement\n\nWrite the code, tests, and any docs the issue requires. Follow the repo conventions in AGENTS.md / CLAUDE.md (no try/catch in route handlers, functional programming, Zod validation, Tailwind tokens, reactive UI updates). Run the relevant test suite as you go.\n\n**Roll discovered backbone work INTO this PR** — small supporting helpers, refactors, and tests that the fix depends on belong here, not a follow-up. Only defer genuinely-large adjacent work; when you do, file a NEW issue (`gh issue create`) tagged `plan` that references this one (`Related to #<num>`) rather than appending to PLAN.md. Choose independent dispatch hints (`model:light|medium|heavy`, `effort:low|medium|high|xhigh|max`) and contributor labels (`good first issue`, `help wanted`) only when justified; omit an axis rather than guessing; create each missing label immediately before applying it; use repeated `--label` flags; do not prefix the title with `[category]` / `[model:…]`.\n\nCommit with a conventional message referencing the issue so the trail is grep-able:\n\n```\n<type>: <one-line description> (#<num>)\n```\n\n## Phase 5 — Review locally (BEFORE any PR exists)\n\n**Required-review publication rule:** Before running local reviewers, initialize the worktree-private status file with `REVIEW_STATUS_FILE=\"$(git rev-parse --git-path portos-review-status)\"; printf 'REVIEW_STATUS=clean\\n' > \"$REVIEW_STATUS_FILE\"`; if that write fails, stop before publication. A required local reviewer that cannot produce a verdict because its CLI/provider is unavailable, a quota or spend limit is exhausted, or the invocation has a timeout, transport failure, malformed/empty output, or no verdict is `review-blocked`, not a publication failure. Do NOT substitute a self-review. Record that state, continue to push and open the PR/MR, then post a comment saying it is intentionally left open and will not be merged until the required review completes. Preserve the claim markers and branch, and stop before merge. A substantive rejection or unresolved finding, failed build/test, unpushed fix, or state/publication failure still blocks publication.\n\n**Every reviewer that can read the working tree runs HERE, while there is still no PR.** Open the PR once the branch is review-clean or a required reviewer is recorded as review-blocked: the PR then carries the finished diff, and the only things left to satisfy are CI and the reviewers that genuinely cannot start until a PR is open.\n\nThe configured reviewers for this task, in order, are `{reviewers}`. Split that list in two, preserving its order:\n\n- **LOCAL reviewers — every token that is NOT an `@<login>`.** `claude` / `codex` / `antigravity` (CLI binary: `agy`) / `grok` / `cursor` invoke a local-CLI critique; `lmstudio` / `ollama` use the appended Local Reviewer Procedure. They read this branch's own diff and need no PR — run them in THIS phase.\n- **PR-SIDE reviewers — every `@<login>` token**, plus any review bot the repo requests automatically when a PR opens. They review cloud-side and cannot start before the PR exists — they run in Phase 6.\n\n1. **Write the changelog entry now, not after the reviewers run** — every commit the reviewers are about to read must already be on the branch, or the PR carries work nobody reviewed. If the repo maintains a changelog, record a one-line entry **following the convention that repo documents** — read its `AGENTS.md` (or `CLAUDE.md`) and changelog README (e.g. `.changelog/README.md`) first. Some repos collect per-branch fragments in a directory (e.g. `.changelog/next/`) via a helper script rather than appending to one shared file, precisely so parallel agents don't conflict on every merge; use that flow when it's documented. Fall back to appending to the unreleased section (`.changelog/NEXT.md`, or `## Unreleased` in `CHANGELOG.md`) in the repo's existing prose style only when no convention is documented. If the repo has no changelog, skip this — the PR + commit history is the record.\n2. **Self-review your diff for reuse, quality, and efficiency** (DRY, dead code, naming, simpler equivalents, missed edge cases) and fix the findings in the same diff, before any reviewer runs. Claude Code runs this as the three-agent `/simplify` pass; on other CLIs, do the equivalent review by hand.\n3. **Run each LOCAL reviewer in the listed order against the BRANCH diff, not a PR diff.** No PR exists yet, so `gh pr diff` has nothing to read — use the CLI's own base-diff mode or `git diff origin/main...HEAD` (substitute the repo's default branch when it isn't `main`). Apply the findings, run the tests, and commit the fixes — capped at 3 rounds per reviewer — then advance to the next reviewer. A missing CLI, quota/provider or transport failure, timeout, malformed response, empty response, or no-verdict result from a REQUIRED reviewer is unavailable, not clean: do NOT substitute your own self-review; record `REVIEW_STATUS=review-blocked` in the worktree-private status file and continue to Phase 6 when the code and tests are otherwise shippable. An optional inconclusive result remains non-blocking.\n4. **If the branch cannot be brought to a shippable state here, do NOT open a PR** — that means substantive reviewer findings remain after 3 rounds, fixes leave the build/tests red, a review fix is unpushed, or the review/status state cannot be persisted. Comment on the ISSUE naming the failure (`gh issue comment \"${NUM}\" --body \"...\"`), leave the assignee and the `in-progress` label in place, remove ONLY the worktree (`cd {repoPath} && git worktree remove \"${WORKTREE}\"`), and stop. Reviewer unavailability alone is `review-blocked`, so it does not take this stop path. Do NOT run Phase 7.\n\n## Phase 6 — Open the PR, satisfy PR-side review + CI, and merge\n\nEvery local reviewer's fixes are already committed, so the PR opens against finished work. This flow ships GitHub issues — it does NOT touch PLAN.md. The audit trail is the merged PR + `git log`.\n\n1. Push the branch: `git push -u origin \"claim/issue-${NUM}\"`. Then confirm `git log --oneline @{u}..HEAD` is empty — if it isn't, a Phase 5 review fix never left the machine and the PR would be opened against a stale diff; push again before continuing.\n2. Open the PR with `gh pr create`. Summarize what shipped + a short test plan. **Choose the issue trailer deliberately:** if this PR FULLY satisfies the issue's scope, the body MUST contain `Closes #${NUM}` so the merge auto-closes it. If you deliberately shipped only PART of the issue (a valuable slice, with real scope still remaining), use `Refs #${NUM}` instead (NOT `Closes`) and add a `## Remaining` section listing what's left — Phase 7 reconciles the issue so it is never stranded.\n2a. If Phase 5 recorded REVIEW_STATUS=review-blocked, source REVIEW_STATUS_FILE=\"$(git rev-parse --git-path portos-review-status)\" and post exactly this comment before doing anything else: gh pr comment \"$PR_URL\" --body \"Required code review was not completed before publication. This PR is intentionally left open and will not be merged until the required review completes.\" Verify the comment succeeds, preserve the claim markers and branch, leave the PR open, and stop before the PR-side review, CI, or merge steps.\n3. **Satisfy the PR-SIDE reviewers.** For each `@<login>` from the Phase 5 split, request the review now (`gh pr edit <pr-number> --add-reviewer <login>`, drop the `@`), poll every 5–15s for it, and address the findings — push fixes, capped at 3 rounds per reviewer. Their approval gates the merge. If the repo auto-requests a review bot when the PR opens, wait that round out and address it the same way. With no `@<login>` configured and no bot review appearing, this step is a no-op.\n\n **Review-stuck cleanup** (a PR-side reviewer still unsatisfied after 3 rounds): post one summarizing PR comment (`gh pr comment`), then run the worktree-only cleanup (`cd {repoPath} && git worktree remove \"${WORKTREE}\"`). Leave the local branch, the open PR, the assignee, and the `in-progress` label in place so the human picks up cold. Do NOT run Phase 7.\n4. **Let required CI finish and go green** — `gh pr checks <pr-number> --required --watch --fail-fast` (scope the wait to REQUIRED checks so an optional job can't stall a merge branch protection would allow). A red required check is not merge-eligible: fix it and re-push (same 3-round cap), or, if it stays red, stop exactly as the review-stuck cleanup above does.\n5. **Merge immediately via `gh pr merge`** — NEVER a local `git merge` and NEVER `--auto`, which can return successfully while leaving the PR queued and OPEN. Prefer a true merge commit, with squash/rebase fallbacks for repositories that disallow it:\n ```bash\n PR_URL=$(gh pr view --json url -q .url) # no number: resolves the PR from the checked-out branch\n gh pr merge \"$PR_URL\" --merge --delete-branch || {\n [ \"$(gh pr view \"$PR_URL\" --json state -q .state)\" = \"MERGED\" ] || gh pr merge \"$PR_URL\" --squash --delete-branch || gh pr merge \"$PR_URL\" --rebase --delete-branch\n }\n STATE=$(gh pr view \"$PR_URL\" --json state -q .state)\n [ \"$STATE\" = \"MERGED\" ] || { echo \"Expected MERGED, got $STATE\" >&2; exit 1; }\n ```\n The exact comparison MUST succeed. `OPEN` means CI, review, or branch protection still blocks the merge; investigate, fix, and retry. `CLOSED` is also not success. Do not enter Phase 7 until remote GitHub state is exactly `MERGED`.\n\n## Phase 7 — Clean up (post-merge ONLY)\n\nThis phase runs only after the PR merged via Phase 6. From the **source repo** (cd back to {repoPath} first):\n\n```bash\ncd {repoPath}\ngit worktree remove \"${WORKTREE}\"\ngit branch -d \"claim/issue-${NUM}\"\n```\n\nIf `git branch -d` refuses, fetch the default branch and re-check the PR's remote `MERGED` state. Retry `-d` only when Git can prove the branch is integrated; otherwise leave the local branch for the reconciliation task. Never force-delete with `-D`.\n\n**Reconcile the issue — did this PR FULLY satisfy its scope?**\n- **Yes (full)** — the `Closes #${NUM}` trailer already auto-closed it; if it's somehow still open, close it (`gh issue close \"${NUM}\"`) and remove the label (`gh issue edit \"${NUM}\" --remove-label in-progress`).\n- **No — the remainder is a clean, separable chunk** — close THIS issue with a summarizing comment (shipped ✓ / moved to #NEW), remove `in-progress`, and file ONE tightly-scoped follow-up for the remainder: `gh issue create --title \"…\" --label plan [--label model:<tier>] [--label effort:<level>] [--label \"good first issue\"] [--label \"help wanted\"] --body \"…\\n\\nRefs #${NUM}\"` (carry over any `area:*` labels the issue had; choose the optional labels independently and only when justified — a leftover mechanical sweep is not a good first issue).\n- **No — the remainder is a continuation of the same scope** — keep the issue OPEN, post a `Done ✓ / Remaining ▢` comment, and release the claim so the queue re-picks it. Remove the label and every current assignee, not only the authenticated account:\n `ASSIGNEES=\"$(gh issue view \"${NUM}\" --json assignees -q '[.assignees[].login] | join(\",\")')\"`\n `gh issue edit \"${NUM}\" --remove-label in-progress --remove-assignee \"${ASSIGNEES:-@me}\"`.\n\nNEVER leave the issue OPEN with `in-progress` still on it — that strands it as a zombie (the claim queue skips `in-progress`, so the remaining scope is never re-picked). **Do NOT `git pull`** from inside this phase — the work is already integrated on GitHub via `gh pr merge`; leave the user's working tree alone.");
+
+PREVIOUS_DEFAULT_PROMPTS['user-action-review'] = ["[Improvement] User Action Review — propose automations from the operator-action ledger\n\nPortOS keeps a machine-local ledger of what the operator actually did in the app (created CoS tasks, rated agent runs, pressed Run Now on scheduled tasks, changed settings). Your job is to read the last 7 days of that ledger, find the repetition a mind or a schedule should have handled, and PROPOSE concrete automations. You propose — you never enact.\n\n## Delivery mode\n\n{userActionDelivery}\n\n## Read the ledger\n\nQuery the last 7 days of events, then group them by `type` + `target` (for schedule triggers the target is the task type; for tasks/agents it is the record id):\n\n- If you can call PortOS semantic tools, use `user_actions_query` (readPortos grant) with a `from` timestamp 7 days back. Results are capped at 100 events per call and carry no event ids; when a result says `truncated: true`, narrow the window (set `to` just BELOW the oldest `happenedAt` you already have — the bound is inclusive, so reusing it verbatim repeats that event — or filter by `type`) and query again.\n- Otherwise call the local PortOS HTTP API from this machine: `GET http://localhost:5555/api/user-actions?from=<ISO-7-days-ago>&limit=100`. Filters: `type`/`types`, `actor`, `from`/`to`, `limit`, `offset`.\n\n**If the query returns no events, stop immediately**: report \"nothing to review\" in one line and make no further LLM tool calls, no proposals, and no filed items.\n\n## What counts as automatable tedium\n\nLook specifically for, in priority order:\n\n1. **Repeated manual schedule triggers** — multiple `cos.schedule.trigger` events with `actor=user` for the same task type (especially `branch-reconcile` / `issue-reconcile`) while that schedule presumably remains on-demand. The proposal is to enable a cadence (say which) or queue a reconcile run — proposed, never enacted.\n2. **Repeated similar CoS tasks** — several `cos.task.create` events whose prompts/settings look alike. Propose a scheduled task, a saved automation, or one recurring CoS task that replaces the hand-queued ones.\n3. **Negative feedback clusters** — `cos.agent.feedback` events with low ratings concentrated on one task type, provider, or model. Propose the configuration change worth trying (different model/effort, a prompt fix), as a proposal the operator applies.\n4. **Settings churn** — repeated `settings.update` events touching the same key paths. Propose whatever would remove the need to keep flipping them.\n\n## Propose (1–5 proposals, evidence-grounded)\n\nDeliver each surviving proposal through the delivery mode above. Every proposal must:\n\n- **Name its evidence**: event counts, types, date ranges, and — where the target is a task TYPE (schedule triggers) — the target itself (e.g. \"5× cos.schedule.trigger branch-reconcile between <date> and <date>\"). No evidence, no proposal.\n- **Describe the automation concretely**: which schedule/cadence/task/setting, and what the operator gains.\n- **Summarize, never paste**: a filed item is world-readable the moment it exists. CoS task prompts, target NAMES (task descriptions), and settings values in the ledger may contain private project names or personal context — describe them (\"three near-identical tasks asking for dependency updates on the same app\") and never quote prompt bodies, targetName values, or payload values. When a proposal must point at specific ledger rows, cite counts, event types, and time ranges — plus the opaque event `id`s when you read the ledger over the HTTP API (the semantic tool's projection carries no ids), nothing more.\n\n## Hard limits\n\n- NEVER change settings (`PUT /api/settings`), schedule types, cadences, or task metadata yourself — not even the automation you are proposing. The proposal IS the deliverable; enacting it is the operator's call.\n- Do not edit source, commit, open a PR, or create branches. The run must end with a clean `git status`.\n- Cap yourself at 5 proposals per run; fold duplicates of an already-filed proposal into a comment on the existing item instead of filing again.\n\n## Report\n\nEnd with a short summary: the event window you reviewed, total events by type, each proposal you delivered (with its issue/task reference), and anything you deliberately did not propose and why."];
diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.js
index 2623d5b368..a2b433b588 100644
--- a/server/services/taskPromptDefaults/prompts.js
+++ b/server/services/taskPromptDefaults/prompts.js
@@ -2041,6 +2041,12 @@ PortOS keeps a machine-local ledger of what the operator actually did in the app
{userActionDelivery}
+## Detectors
+
+{userActionDetectors}
+
+Leftover-branch findings (if any) are READ-ONLY. They never run reconcile and never trigger a scheduled task. If leftover local branches are reported while agents are idle, propose enabling a cadence or queuing a branch-reconcile run — proposed, never enacted.
+
## Read the ledger
Query the last 7 days of events, then group them by \`type\` + \`target\` (for schedule triggers the target is the task type; for tasks/agents it is the record id):
@@ -2048,7 +2054,7 @@ Query the last 7 days of events, then group them by \`type\` + \`target\` (for s
- If you can call PortOS semantic tools, use \`user_actions_query\` (readPortos grant) with a \`from\` timestamp 7 days back. Results are capped at 100 events per call and carry no event ids; when a result says \`truncated: true\`, narrow the window (set \`to\` just BELOW the oldest \`happenedAt\` you already have — the bound is inclusive, so reusing it verbatim repeats that event — or filter by \`type\`) and query again.
- Otherwise call the local PortOS HTTP API from this machine: \`GET ${PORTOS_API_URL}/api/user-actions?from=<ISO-7-days-ago>&limit=100\`. Filters: \`type\`/\`types\`, \`actor\`, \`from\`/\`to\`, \`limit\`, \`offset\`.
-**If the query returns no events, stop immediately**: report "nothing to review" in one line and make no further LLM tool calls, no proposals, and no filed items.
+**If the query returns no events AND the detectors section is empty, stop immediately**: report "nothing to review" in one line and make no further LLM tool calls, no proposals, and no filed items. If detectors reported leftover idle branches, continue and propose from that evidence even when the ledger is empty.
## What counts as automatable tedium
@@ -2058,6 +2064,7 @@ Look specifically for, in priority order:
2. **Repeated similar CoS tasks** — several \`cos.task.create\` events whose prompts/settings look alike. Propose a scheduled task, a saved automation, or one recurring CoS task that replaces the hand-queued ones.
3. **Negative feedback clusters** — \`cos.agent.feedback\` events with low ratings concentrated on one task type, provider, or model. Propose the configuration change worth trying (different model/effort, a prompt fix), as a proposal the operator applies.
4. **Settings churn** — repeated \`settings.update\` events touching the same key paths. Propose whatever would remove the need to keep flipping them.
+5. **Leftover idle branches** — the leftover-branch detector reports local branches with no live owner while agents are idle. Propose a \`branch-reconcile\` run or enabling its cadence. Do not run it yourself.
## Propose (1–5 proposals, evidence-grounded)
diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.js
index e929173cb8..ab496f4ebf 100644
--- a/server/services/taskPromptDefaults/versions.js
+++ b/server/services/taskPromptDefaults/versions.js
@@ -23,7 +23,7 @@ export const PROMPT_VERSIONS = {
'branch-reconcile': 3, // v3: SUPERSEDED is a first-class outcome — a branch whose problem the default branch already solved a different way is reported and left untouched, never merged (merging it undoes shipped work). A resolvable conflict is explicitly NOT evidence the work is still wanted, and every branch is rebased + test-verified before it reaches a PR. v2: a branch whose "Do:" line ends in a merge isn't finished until it IS merged — the sub-agent waits CI out in-session instead of handing back a green-but-open PR, and the old blanket "never merge unreviewed work" rule (which vetoed the per-branch merge instruction) is replaced by the explicit CI-green + MERGEABLE + review gate. v1: per-app coordinator that finishes in-flight LOCAL branches (open PR / resolve conflicts / drive review / auto-merge) after the deterministic merged-branch cleanup pass. Peer-safe (local refs only). Replaced the PortOS-only branchReconcileScheduler.
'issue-reconcile': 4, // v4: follow-up recipes apply independent slashdo dispatch hints and contributor labels (`good first issue`/`help wanted`, Jira hyphenated equivalents) instead of only `plan`. v3: adds a JIRA arm — status-based zombies (a ticket left In Review with remaining scope + no live claim; JIRA has no `in-progress` label) detected via the PortOS JIRA API and healed through ticket transitions + `POST tickets`, routed in via the app's resolved workTracker ('jira') rather than the git host. v2: forge-aware — the scan + coordinator now cover GitLab (`glab` issues + MRs) as well as GitHub, resolved from the app's origin host; every heal command is shown as gh/glab and the injected header names the forge. v1: per-app coordinator that heals ZOMBIE issues (open + in-progress but their PR merged with no live claim) after the deterministic gh/git scan. Applies the partial-ship hybrid — close + file a scoped follow-up when the remainder is separable, else comment "done/remaining" + release the claim so the queue re-picks it.
'refresh-local-llm-catalog': 4, // v4: follows the current no-per-branch-changelog contract and relies on a release-note-quality commit subject. v3: catalog maintenance now preserves the primary-lane + cross-lane recommendation taxonomy and reserves featured treatment for a deliberate first choice. v2: PortOS-only task, so it names the retired fragment command directly. v1: research current local models, refresh LOCAL_LLM_CATALOG + EDITORIAL_FAMILY_RANK, PR (PortOS repo only)
- 'user-action-review': 1, // v1: install-wide review of the operator-action ledger (#5595) — query the last 7 days, group repetition by type + target, propose 1–5 automations delivered per {userActionDelivery} (tracker issues by default, queued CoS tasks when the operator flips fileIssues off); never mutates settings or schedule types, summarizes CoS prompts instead of pasting them, exits immediately on an empty log.
+ 'user-action-review': 2, // v2: leftover-branch idle detector interpolates via {userActionDetectors}; empty-ledger skip is waived when detector findings exist; leftover findings are propose-only (never reconcile / Run Now). v1: install-wide review of the operator-action ledger (#5595) — query the last 7 days, group repetition by type + target, propose 1–5 automations delivered per {userActionDelivery} (tracker issues by default, queued CoS tasks when the operator flips fileIssues off); never mutates settings or schedule types, summarizes CoS prompts instead of pasting them, exits immediately on an empty log.
'plan-feature': 5, // v5: absent optional preload sections explicitly fall back to normal inventory/source reads. v4: truncated/unreadable preloads explicitly allow a direct source read. v3: consumes programmatically preloaded PRD/GOALS/open-issue/open-PR/closed-unmerged-PR snapshots and explicitly avoids re-fetching them. v2: PRD.md is the primary product/evaluation source, GOALS.md supplements or falls back, and repository documentation is the best-effort fallback when neither exists. v1: net-new planning-only sibling of feature-ideas.
// Basic self-improvement tasks — versioned so installs created before the
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index 883725257a..a7a435e18a 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -329,13 +329,14 @@ describe('taskSchedule', () => {
})
describe('user-action-review (operator-ledger automation proposals)', () => {
- it('is registered install-wide with an on-demand + enabled default and a v1 prompt', () => {
+ it('is registered install-wide with an on-demand + enabled default and a v2 prompt', () => {
expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('user-action-review');
expect(INSTALL_WIDE_TASK_TYPES.has('user-action-review')).toBe(true);
expect(TASK_TYPE_DESCRIPTIONS['user-action-review']).toContain('propose automations');
expect(DEFAULT_TASK_INTERVALS['user-action-review']).toMatchObject({ type: INTERVAL_TYPES.ON_DEMAND, enabled: true });
- expect(PROMPT_VERSIONS['user-action-review']).toBe(1);
+ expect(PROMPT_VERSIONS['user-action-review']).toBe(2);
expect(DEFAULT_TASK_PROMPTS['user-action-review']).toContain('{userActionDelivery}');
+ expect(DEFAULT_TASK_PROMPTS['user-action-review']).toContain('{userActionDetectors}');
// The prompt proposes; it must never instruct the agent to enact.
expect(DEFAULT_TASK_PROMPTS['user-action-review']).toContain('NEVER change settings');
});
diff --git a/server/services/userActionDetectors.js b/server/services/userActionDetectors.js
new file mode 100644
index 0000000000..b4fe158268
--- /dev/null
+++ b/server/services/userActionDetectors.js
@@ -0,0 +1,133 @@
+/**
+ * Read-only leftover-branch idle detector for the operator-action ledger
+ * (#5596, epic #5593).
+ *
+ * Surfaces local branches with no live owner while no CoS agents are running,
+ * plus the last time the operator pressed Run Now on `branch-reconcile`.
+ * NEVER invokes the branch reconciler or an on-demand schedule trigger — a finding is an insight,
+ * not an automatic Run Now.
+ *
+ * `gatherBranchState` already talks to git; this module does not scrape git
+ * itself and is not on the recorder hot path.
+ */
+
+import { PATHS } from '../lib/fileUtils.js';
+import { PORTOS_APP_ID } from '../lib/appIdentity.js';
+import { getActiveApps } from './apps.js';
+import { getActiveAgentIds } from './agentState.js';
+import { gatherBranchState, classifyBranches } from './branchReconcile.js';
+import { getDefaultBranch } from './git.js';
+import { listUserActions } from './userActions.js';
+
+export const LEFTOVER_BRANCH_LOOKBACK_DAYS = 14;
+export const LEFTOVER_BRANCH_CACHE_TTL_MS = 60_000;
+
+let leftoverCache = { at: 0, findings: null };
+
+export function __resetLeftoverBranchCache() {
+ leftoverCache = { at: 0, findings: null };
+}
+
+const lastManualReconcile = (events, appId) => {
+ const match = (events || []).find((event) => (
+ event?.type === 'cos.schedule.trigger'
+ && event.actor === 'user'
+ && event.target === 'branch-reconcile'
+ && (event.payload?.appId ?? event.targetName ?? null) === appId
+ ));
+ return match?.happenedAt ?? null;
+};
+
+async function computeIdleLeftoverBranches({
+ now,
+ getIds,
+ getApps,
+ gather,
+ classify,
+ getDefault,
+ listActions,
+ portosRoot,
+}) {
+ const activeAgentIds = getIds();
+ if ((activeAgentIds || []).length > 0) return [];
+
+ const apps = [...(await getApps())];
+ if (!apps.some((app) => app.id === PORTOS_APP_ID)) {
+ apps.unshift({ id: PORTOS_APP_ID, repoPath: portosRoot });
+ }
+
+ const from = new Date(now - LEFTOVER_BRANCH_LOOKBACK_DAYS * 24 * 60 * 60 * 1000).toISOString();
+ const triggers = await listActions({
+ type: 'cos.schedule.trigger',
+ actor: 'user',
+ from,
+ limit: 100,
+ }).catch((error) => {
+ console.error(`❌ leftover-branch detector: ledger read failed: ${error.message}`);
+ return [];
+ });
+
+ const findings = [];
+ for (const app of apps) {
+ const repoPath = app.repoPath;
+ if (!repoPath) continue;
+ try {
+ const defaultBranch = await getDefault(repoPath);
+ const inputs = await gather(repoPath, { defaultBranch, activeAgentIds: [] });
+ const leftoverCount = classify(inputs)
+ .filter((row) => !row.liveOwnerReason)
+ .length;
+ if (leftoverCount === 0) continue;
+ findings.push({
+ appId: app.id,
+ leftoverCount,
+ lastUserReconcileAt: lastManualReconcile(triggers, app.id),
+ agentsIdle: true,
+ });
+ } catch (error) {
+ console.error(`❌ leftover-branch detector: skipped ${app.id}: ${error.message}`);
+ }
+ }
+ return findings;
+}
+
+/**
+ * @param {object} [deps] injectable for tests. Passing deps bypasses the TTL cache.
+ * @returns {Promise<Array<{appId: string, leftoverCount: number, lastUserReconcileAt: string|null, agentsIdle: true}>>}
+ */
+export async function detectIdleLeftoverBranches(deps = null) {
+ const useCache = deps == null;
+ if (useCache && leftoverCache.findings && (Date.now() - leftoverCache.at) < LEFTOVER_BRANCH_CACHE_TTL_MS) {
+ return leftoverCache.findings;
+ }
+ const now = deps?.now ?? Date.now();
+ const findings = await computeIdleLeftoverBranches({
+ now,
+ getIds: deps?.getActiveAgentIds ?? getActiveAgentIds,
+ getApps: deps?.getActiveApps ?? getActiveApps,
+ gather: deps?.gatherBranchState ?? gatherBranchState,
+ classify: deps?.classifyBranches ?? classifyBranches,
+ getDefault: deps?.getDefaultBranch ?? getDefaultBranch,
+ listActions: deps?.listUserActions ?? listUserActions,
+ portosRoot: deps?.portosRoot ?? PATHS.root,
+ });
+ if (useCache) leftoverCache = { at: Date.now(), findings };
+ return findings;
+}
+
+export function formatLeftoverBranchSnippet(findings) {
+ if (!Array.isArray(findings) || findings.length === 0) return '';
+ return findings.map((finding) => (
+ `leftover-branches: app ${finding.appId} has ${finding.leftoverCount} local branches, agents idle, last manual reconcile ${finding.lastUserReconcileAt || 'never'}`
+ )).join('\n');
+}
+
+export function formatUserActionDetectorBlock(findings) {
+ const snippet = formatLeftoverBranchSnippet(findings);
+ if (!snippet) return '';
+ return [
+ 'Leftover-branch findings are READ-ONLY. They never run reconcile and never trigger a scheduled task. Propose a cadence or a Run Now — never enact.',
+ '',
+ snippet,
+ ].join('\n');
+}
diff --git a/server/services/userActionDetectors.test.js b/server/services/userActionDetectors.test.js
new file mode 100644
index 0000000000..f05d604ca7
--- /dev/null
+++ b/server/services/userActionDetectors.test.js
@@ -0,0 +1,87 @@
+import { readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ detectIdleLeftoverBranches,
+ formatLeftoverBranchSnippet,
+ __resetLeftoverBranchCache,
+} from './userActionDetectors.js';
+
+const SRC = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'userActionDetectors.js'), 'utf-8');
+
+const leftoverInput = (overrides = {}) => ({
+ branch: 'claim/issue-1',
+ liveOwnerReason: null,
+ ...overrides,
+});
+
+const deps = (overrides = {}) => ({
+ now: Date.parse('2026-09-02T12:00:00.000Z'),
+ getActiveAgentIds: () => [],
+ getActiveApps: async () => [
+ { id: 'portos-default', repoPath: '/tmp/portos' },
+ { id: 'app-acme', repoPath: '/tmp/acme' },
+ ],
+ getDefaultBranch: async () => 'main',
+ gatherBranchState: async (repoPath) => (repoPath === '/tmp/acme' ? [leftoverInput()] : []),
+ classifyBranches: (inputs) => inputs.map((input) => ({ ...input, state: 'NEEDS_PR' })),
+ listUserActions: async () => [{
+ type: 'cos.schedule.trigger',
+ actor: 'user',
+ target: 'branch-reconcile',
+ payload: { appId: 'app-acme' },
+ happenedAt: '2026-08-28T10:00:00.000Z',
+ }],
+ portosRoot: '/tmp/portos',
+ ...overrides,
+});
+
+describe('detectIdleLeftoverBranches', () => {
+ beforeEach(() => __resetLeftoverBranchCache());
+
+ it('never imports or calls reconcile / triggerOnDemandTask', () => {
+ expect(SRC).not.toMatch(/\btriggerOnDemandTask\b/);
+ expect(SRC).not.toMatch(/\breconcile\s*\(/);
+ expect(SRC).not.toMatch(/import\s*\{[^}]*\breconcile\b/);
+ });
+
+ it('returns a finding when agents are idle and leftover branches exist', async () => {
+ const findings = await detectIdleLeftoverBranches(deps());
+ expect(findings).toEqual([{
+ appId: 'app-acme',
+ leftoverCount: 1,
+ lastUserReconcileAt: '2026-08-28T10:00:00.000Z',
+ agentsIdle: true,
+ }]);
+ });
+
+ it('returns nothing while any agent is still running', async () => {
+ const gatherBranchState = async () => { throw new Error('must not gather while agents run'); };
+ await expect(detectIdleLeftoverBranches(deps({
+ getActiveAgentIds: () => ['agent-1'],
+ gatherBranchState,
+ }))).resolves.toEqual([]);
+ });
+
+ it('returns nothing when every leftover branch has a live owner', async () => {
+ await expect(detectIdleLeftoverBranches(deps({
+ gatherBranchState: async () => [leftoverInput({ liveOwnerReason: 'active-agent' })],
+ }))).resolves.toEqual([]);
+ });
+
+ it('skips an app whose gather fails rather than throwing', async () => {
+ const findings = await detectIdleLeftoverBranches(deps({
+ gatherBranchState: async () => { throw new Error('git lock'); },
+ }));
+ expect(findings).toEqual([]);
+ });
+});
+
+describe('formatLeftoverBranchSnippet', () => {
+ it('renders a compact per-app line, using never when there is no prior reconcile', () => {
+ expect(formatLeftoverBranchSnippet([{
+ appId: 'app-acme', leftoverCount: 3, lastUserReconcileAt: null, agentsIdle: true,
+ }])).toBe('leftover-branches: app app-acme has 3 local branches, agents idle, last manual reconcile never');
+ });
+});
diff --git a/server/services/userActionReviewHooks.js b/server/services/userActionReviewHooks.js
index 36f6712e57..f38b03ce90 100644
--- a/server/services/userActionReviewHooks.js
+++ b/server/services/userActionReviewHooks.js
@@ -10,6 +10,7 @@
*/
import { listUserActions } from './userActions.js';
+import { detectIdleLeftoverBranches } from './userActionDetectors.js';
export const USER_ACTION_REVIEW_LOOKBACK_DAYS = 7;
@@ -21,6 +22,12 @@ export async function buildTaskInput({ app } = {}) {
const from = new Date(Date.now() - USER_ACTION_REVIEW_LOOKBACK_DAYS * 24 * 60 * 60 * 1000).toISOString();
// One row is enough to answer "is there anything to review?".
const events = await listUserActions({ from, limit: 1 });
- if (events.length === 0) return { skip: { reason: 'no-user-actions' } };
+ if (events.length === 0) {
+ const findings = await detectIdleLeftoverBranches().catch((error) => {
+ console.error(`❌ user-action-review leftover-branch detector failed: ${error.message}`);
+ return [];
+ });
+ if (findings.length === 0) return { skip: { reason: 'no-user-actions' } };
+ }
return {};
}
diff --git a/server/services/userActionReviewHooks.test.js b/server/services/userActionReviewHooks.test.js
index 80201bf637..0c8b5eb599 100644
--- a/server/services/userActionReviewHooks.test.js
+++ b/server/services/userActionReviewHooks.test.js
@@ -1,9 +1,15 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-const mocks = vi.hoisted(() => ({ listUserActions: vi.fn() }));
+const mocks = vi.hoisted(() => ({
+ listUserActions: vi.fn(),
+ detectIdleLeftoverBranches: vi.fn(async () => []),
+}));
vi.mock('./userActions.js', () => ({
listUserActions: (...args) => mocks.listUserActions(...args),
}));
+vi.mock('./userActionDetectors.js', () => ({
+ detectIdleLeftoverBranches: (...args) => mocks.detectIdleLeftoverBranches(...args),
+}));
import { USER_ACTION_REVIEW_LOOKBACK_DAYS, buildTaskInput } from './userActionReviewHooks.js';
@@ -25,6 +31,14 @@ describe('user-action-review buildTaskInput hook', () => {
await expect(buildTaskInput({ app: { id: null, name: 'PortOS' } })).resolves.toEqual({});
});
+ it('dispatches when the ledger is empty but leftover-branch findings exist', async () => {
+ mocks.listUserActions.mockResolvedValueOnce([]);
+ mocks.detectIdleLeftoverBranches.mockResolvedValueOnce([{
+ appId: 'app-acme', leftoverCount: 1, lastUserReconcileAt: null, agentsIdle: true,
+ }]);
+ await expect(buildTaskInput()).resolves.toEqual({});
+ });
+
it('skips any per-app dispatch — the review is install-wide only', async () => {
// A per-app cadence override would otherwise queue one identical
// global-ledger review PER managed app.
diff --git a/server/services/userActionScheduleLog.js b/server/services/userActionScheduleLog.js
new file mode 100644
index 0000000000..e9b8dac20a
--- /dev/null
+++ b/server/services/userActionScheduleLog.js
@@ -0,0 +1,49 @@
+/**
+ * Operator-action rows for CoS schedule writes that do not go through
+ * PUT /api/settings (#5596). Changed keys only; long prompt/description
+ * bodies are recorded as `{ changed: true }`, never copied in.
+ */
+
+import { recordUserAction } from './userActions.js';
+
+const SHORT_SCALAR_MAX = 120;
+
+const isShortScalar = (value) => (
+ value === null
+ || typeof value === 'boolean'
+ || typeof value === 'number'
+ || (typeof value === 'string' && value.length <= SHORT_SCALAR_MAX)
+);
+
+export function scheduleChangePayload(patch) {
+ const keysChanged = Object.keys(patch || {})
+ .filter((key) => patch[key] !== undefined)
+ .sort();
+ const changes = {};
+ for (const key of keysChanged) {
+ const value = patch[key];
+ changes[key] = isShortScalar(value) ? { to: value } : { changed: true };
+ }
+ return { keysChanged, changes };
+}
+
+export async function logCosScheduleUpdate({ target, patch, source, extra = {} } = {}) {
+ const { keysChanged, changes } = scheduleChangePayload(patch);
+ if (keysChanged.length === 0) return null;
+ try {
+ const happenedAt = new Date().toISOString();
+ return await recordUserAction({
+ type: 'cos.schedule.update',
+ actor: 'user',
+ target,
+ summary: `Updated CoS schedule: ${keysChanged.join(', ')}`,
+ payload: { keysChanged, changes, ...extra },
+ source,
+ happenedAt,
+ dedupeKey: `cos.schedule.update:${target}:${happenedAt}:${keysChanged.join(',').slice(0, 200)}`,
+ });
+ } catch (error) {
+ console.error(`❌ Failed to record cos.schedule.update: ${error.message}`);
+ return null;
+ }
+}
diff --git a/server/services/userActions.test.js b/server/services/userActions.test.js
index dfea66bf63..900e8a0238 100644
--- a/server/services/userActions.test.js
+++ b/server/services/userActions.test.js
@@ -85,6 +85,15 @@ describe('recordUserAction', () => {
await expect(recordUserAction(action({ actor: 'schedule' }))).resolves.not.toBeNull();
});
+ it('accepts the phase-3 types (#5596)', async () => {
+ for (const type of [
+ 'media.image.enqueue', 'media.video.enqueue', 'brain.capture',
+ 'instance-feature.toggle', 'cos.schedule.update',
+ ]) {
+ await expect(recordUserAction(action({ type, dedupeKey: type }))).resolves.not.toBeNull();
+ }
+ });
+
it('refuses an action with no dedupe key', async () => {
await expect(recordUserAction(action({ dedupeKey: ' ' }))).rejects.toThrow(/missing a dedupeKey/);
});