Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add safety-kind override to CoS confidence auto-approval (#2440)
Adam Eivyc072b7c40b4a
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 85fadf1c79..7f290baade 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -24,6 +24,8 @@## Features+- **CoS confidence auto-approval now has a safety-kind override, so outward-facing / irreversible work always needs human sign-off (#2440).** Confidence auto-approval used to gate on ONE axis — a task type's historical success rate — so once a type crossed the threshold, *any* task of that type could auto-run, including inherently outward-facing work: publishing content that goes live, federating records to sync peers, opening external/upstream PRs, or releasing/deploying. A new **safety-kind** axis, orthogonal to confidence, classifies each generated task (`server/services/taskLearning/safetyKind.js`): outward-facing/irreversible kinds (`content`, `publish`, `federation`, `external-pr`) always require the user's approval regardless of how high the success rate is — a 100% score can't undo work that has already left the install — while reversible internal work (analysis, refactor, code-review, same-repo improvement PRs) keeps today's success-rate gate unchanged. Classification is driven by explicit task metadata (`safetyKind` / `outwardFacing` / capability flags) then conservative keyword signatures, defaulting to *reversible* so existing behavior is preserved unless a task carries an outward signal. The reason is surfaced on the task record (`safetyKind` + `approvalReason`) and in the approval log line, so the UI can show why a high-confidence task still needs review. Tunable via the new `safetyKindApproval` CoS config (`{ enabled, alwaysApproveKinds }`, default on) — additive optional key merged on read, no migration needed.+- **Layered Intelligence now evaluates a managed app against its OWN goals and performance — not PortOS's agent telemetry.** Running the loop on a managed app previously fed it the PortOS install's global autonomous-agent run stats (`data/cos/learning.json`) as the "CoS metrics" source — which is on by default for every app — so a managed-app run reasoned over PortOS's tooling performance instead of the app's own product performance. Two changes fix this: (1) a new **App metrics (METRICS.md)** telemetry source, on by default for every app, reads a repo-root `METRICS.md` from the app (same as `GOALS.md`/`PLAN.md`) — the place an app documents how it measures success (user-success KPIs, production telemetry, where its data lives, and read-only queries an agent can run); and (2) the **CoS metrics** source now defaults **on only for the PortOS install** (where the agent stats genuinely are its own-performance metric) and **off for managed apps** (where they're a tooling/interaction signal, still opt-in). The reasoning prompt is reframed around "how is THIS app performing against its own goals and purpose," and when a managed app exposes no own-performance metrics the loop is nudged to propose adding a `METRICS.md` as an `app-data-gap`. New standard documented in [`docs/METRICS.md`](../docs/METRICS.md); apps can also wire a custom `cmd`/`http` source to feed live numbers into each run. Back-compat: these are default changes only — any explicitly-stored source toggle is preserved, so no migration is needed.- **Grok is now selectable as a Review Loop code reviewer.** The reviewer picker (AI Providers → Code Review Defaults, plus the per-task task form and the per-task-type Schedule config) gains a **Grok** option alongside Claude, Codex, and Antigravity. Selecting it adds `grok` to slashdo's `--review-with` list, and the review-loop follow-up agent invokes the Grok Build CLI (`grok`) headless against the PR diff — the same CLI-reviewer path the other coding-agent reviewers use (it already routed any non-Copilot/non-local-LLM reviewer generically). New enum value `grok` in `REVIEWER_VALUES` (mirrored in the client `REVIEWER_OPTIONS`); no migration needed (absent from a stored list = not selected, and the default reviewer stays `copilot`).diff --git a/server/routes/cosStatusRoutes.js b/server/routes/cosStatusRoutes.jsindex e499f2a4eb..a8c670c1e7 100644--- a/server/routes/cosStatusRoutes.js+++ b/server/routes/cosStatusRoutes.js@@ -71,7 +71,14 @@ export const cosConfigSchema = z.object({autoFixThresholds: z.object({maxLinesChanged: z.number().int().min(1).optional(),allowedCategories: z.array(z.string()).optional()- }).optional()+ }).optional(),+ // Safety-kind override (#2440): which outward-facing/irreversible kinds always+ // require human approval, orthogonal to confidence. updateConfig() replaces the+ // whole object, so the client sends the full slice.+ safetyKindApproval: z.object({+ enabled: z.boolean().optional(),+ alwaysApproveKinds: z.array(z.string()).optional()+ }).strict().optional()}).strict();// GET /api/cos - Get CoS statusdiff --git a/server/services/cosState.js b/server/services/cosState.jsindex e064f1785f..7b8294a16f 100644--- a/server/services/cosState.js+++ b/server/services/cosState.js@@ -11,6 +11,7 @@ import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { ensureDirs, safeJSONParse, PATHS, atomicWrite } from '../lib/fileUtils.js';import { normalizeDomainAutonomy, getDomainMode } from '../lib/domainAutonomy.js';import { normalizeDomainBudgets } from '../lib/domainBudgets.js';+import { DEFAULT_ALWAYS_APPROVE_KINDS } from './taskLearning/safetyKind.js';export const STATE_FILE = join(PATHS.cos, 'state.json');export const AGENTS_DIR = join(PATHS.cos, 'agents');@@ -84,6 +85,14 @@ export const DEFAULT_CONFIG = {highThreshold: 80,lowThreshold: 50,minSamples: 5+ },+ // Safety axis orthogonal to confidence (#2440): outward-facing / irreversible+ // work always needs human sign-off regardless of success rate. Reversible+ // internal work keeps the confidence success-rate gate. Tune which kinds are+ // forced to approval via `alwaysApproveKinds`.+ safetyKindApproval: {+ enabled: true,+ alwaysApproveKinds: [...DEFAULT_ALWAYS_APPROVE_KINDS]}};diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex dcfc1b4fbb..e6357b206f 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -34,6 +34,7 @@ import { recordDecision, DECISION_TYPES } from './decisionLog.js';import { isAppOnCooldown, markAppReviewCooldown, bindAppReviewAgent, markIdleReviewStarted, getNextAppForReview, loadAppActivity, isAppActivityOnCooldown } from './appActivity.js';import { getActiveApps, getAppTaskTypeOverrides } from './apps.js';import { getTaskTypeConfidence } from './taskLearning.js';+import { classifySafetyKind, requiresSafetyApproval } from './taskLearning/safetyKind.js';import { generateProactiveTasks as generateMissionTasks } from './missions.js';import { isRecoveryTask } from './recoveryTasks.js';import { getCodeReviewDefaults } from './codeReview.js';@@ -1260,18 +1261,51 @@ export async function queueEligibleImprovementTasks(state, cosTaskData, { ignore}/**- * Resolve auto-approval for a task based on confidence scoring.- * Returns { autoApproved, approvalRequired } ready to spread into task objects.+ * Resolve auto-approval for a task based on confidence scoring, with a+ * safety-kind override (#2440) that is orthogonal to confidence.+ *+ * Outward-facing / irreversible work (publishing content, federating records to+ * sync peers, external/upstream PRs, releases) always requires the user's+ * sign-off no matter how high the task type's success rate is — a high score+ * can't undo work that has already left the install. Reversible internal work+ * (analysis, refactor, same-repo improvement PRs) keeps the pure success-rate+ * gate, so existing behavior is unchanged unless the task carries an outward+ * signal.+ *+ * Returns { autoApproved, approvalRequired, safetyKind, approvalReason? } ready+ * to spread into task objects — `safetyKind` + `approvalReason` surface WHY a+ * high-confidence task still needs approval on the task record and in the UI.*/-async function resolveConfidenceApproval(state, taskTypeKey, logLabel) {+async function resolveConfidenceApproval(state, taskTypeKey, logLabel, metadata = {}) {+ const safety = classifySafetyKind({ taskTypeKey, metadata });+ const safetyConfig = state?.config?.safetyKindApproval ?? {};++ // Safety-kind override runs BEFORE (and independent of) the confidence gate.+ if (safety.outwardFacing && requiresSafetyApproval(safety.kind, safetyConfig)) {+ emitLog('info', `🔒 ${logLabel} requires approval (safety-kind: ${safety.kind} — ${safety.reason})`, {}, '[Safety]');+ return {+ autoApproved: false,+ approvalRequired: true,+ safetyKind: safety.kind,+ approvalReason: `safety-kind:${safety.kind}`+ };+ }+const config = state?.config?.confidenceAutoApproval ?? {};- if (config.enabled === false) return { autoApproved: true, approvalRequired: false };+ if (config.enabled === false) {+ return { autoApproved: true, approvalRequired: false, safetyKind: safety.kind };+ }const confidence = await getTaskTypeConfidence(taskTypeKey, config);if (!confidence.autoApprove) {emitLog('info', `🔒 ${logLabel} requires approval (${confidence.reason})`, {}, '[Confidence]');}- return { autoApproved: confidence.autoApprove, approvalRequired: !confidence.autoApprove };+ return {+ autoApproved: confidence.autoApprove,+ approvalRequired: !confidence.autoApprove,+ safetyKind: safety.kind,+ ...(confidence.autoApprove ? {} : { approvalReason: `confidence:${confidence.tier}` })+ };}/**@@ -1313,7 +1347,7 @@ export async function generateSelfImprovementTaskForType(taskType, state) {metadata.model = interval.model;}- const approval = await resolveConfidenceApproval(state, `self-improve:${taskType}`, `Task self-improve:${taskType}`);+ const approval = await resolveConfidenceApproval(state, `self-improve:${taskType}`, `Task self-improve:${taskType}`, metadata);const task = {id: `self-improve-${taskType}-${Date.now().toString(36)}`,@@ -2063,7 +2097,7 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, stif (hookOverride.providerId) { metadata.provider = hookOverride.providerId; metadata.providerId = hookOverride.providerId; }if (hookOverride.model) { metadata.model = hookOverride.model; }- const approval = await resolveConfidenceApproval(state, `app-improve:${taskType}`, `Task app-improve:${taskType} for ${app.name}`);+ const approval = await resolveConfidenceApproval(state, `app-improve:${taskType}`, `Task app-improve:${taskType} for ${app.name}`, metadata);// All gates passed — record the rotation-pointer advance + emit the// generation log. Deferred from the top of the function (see note there);diff --git a/server/services/taskLearning/index.js b/server/services/taskLearning/index.jsindex f5ad37ca72..756b590e22 100644--- a/server/services/taskLearning/index.js+++ b/server/services/taskLearning/index.js@@ -9,6 +9,7 @@* - store.js — shared persistence, cache, mutex, pure helpers* - metrics.js — recording completions + rebuilding aggregates* - routing.js — heuristic routing, cooldown, skip, confidence+ * - safetyKind.js — outward-facing/irreversible safety-kind classifier* - correlationQuality.js — enriched-signal ↔ outcome correlation window* - durations.js — duration estimates + queue completion* - insights.js — insights view, recommendations, dismissals@@ -84,6 +85,14 @@ export {getAllPromptRecommendations} from './promptRecommendations.js';+export {+ classifySafetyKind,+ requiresSafetyApproval,+ REVERSIBLE_SAFETY_KIND,+ OUTWARD_SAFETY_KINDS,+ DEFAULT_ALWAYS_APPROVE_KINDS+} from './safetyKind.js';+export {initTaskLearning,backfillFromHistorydiff --git a/server/services/taskLearning/safetyKind.js b/server/services/taskLearning/safetyKind.jsnew file mode 100644index 0000000000..c8d680cd2a--- /dev/null+++ b/server/services/taskLearning/safetyKind.js@@ -0,0 +1,124 @@+/**+ * Safety-kind classifier (#2440)+ *+ * A safety axis ORTHOGONAL to confidence scoring. Confidence gates purely on a+ * task type's historical success rate; safety-kind gates on whether the work is+ * outward-facing / irreversible — publishing content that goes live, federating+ * records to sync peers, pushing PRs to an external/upstream repo, or+ * releasing/deploying. Outward-facing work always needs the single PortOS user's+ * sign-off regardless of how high the success rate is: a 100% score can't undo a+ * published post or a record already fanned out to peers. ("Escalate to human"+ * here means surface to the one PortOS user — the single-user trust model still+ * applies.)+ *+ * Internal, reversible work (analysis, refactor, code-review, dependency audits,+ * same-repo improvement PRs the user can just close) keeps the pure success-rate+ * gate. Reversible is the DEFAULT, so existing CoS auto-approval behavior is+ * unchanged unless a task carries an explicit outward-facing signal.+ *+ * Pure, deterministic (same input → same output), and side-effect free.+ */++/** Reversible internal work — retains today's confidence success-rate gate. */+export const REVERSIBLE_SAFETY_KIND = 'reversible';++/**+ * Outward-facing / irreversible kinds. This is the default set that always+ * requires human approval (issue #2440 acceptance #4). Tunable per install via+ * `config.safetyKindApproval.alwaysApproveKinds`.+ */+export const OUTWARD_SAFETY_KINDS = Object.freeze(['content', 'publish', 'federation', 'external-pr']);+export const DEFAULT_ALWAYS_APPROVE_KINDS = Object.freeze([...OUTWARD_SAFETY_KINDS]);++const OUTWARD_KIND_SET = new Set(OUTWARD_SAFETY_KINDS);++/**+ * Ordered keyword signatures — first match wins. Matched against a lowercased+ * haystack of the task-type key plus description/analysis hints. Kept+ * conservative and biased toward requiring approval: a false positive merely+ * asks the user to review a task that may not have needed it (safe direction);+ * a false negative would auto-approve genuinely outward work (the dangerous one+ * this feature exists to prevent).+ */+const KIND_SIGNATURES = [+ { kind: 'federation', re: /federat|peer[-\s]?sync|sync[-\s]?peer|fan[-\s]?out[-\s]?record/ },+ { kind: 'external-pr', re: /external[-\s]?pr|upstream[-\s]?pr|fork[-\s]?pr/ },+ { kind: 'publish', re: /\bpublish\b|\bdeploy\b|\brelease\b|go[-\s]?live|auto[-\s]?send|outbound[-\s]?message/ },+ { kind: 'content', re: /social[-\s]?media|newsletter|\bblog\b|generate[-\s]?content|publish[-\s]?content/ }+];++const normalizeKind = (k) => (typeof k === 'string' ? k.trim().toLowerCase() : '');++/**+ * Classify a task's safety kind from its task-type key and metadata.+ *+ * Priority order: explicit `metadata.safetyKind` / `metadata.outwardFacing`+ * override → boolean capability hints → keyword signatures → reversible default.+ *+ * @param {{ taskTypeKey?: string, metadata?: object }} [input]+ * @returns {{ kind: string, outwardFacing: boolean, reason: string }}+ */+export function classifySafetyKind({ taskTypeKey = '', metadata = {} } = {}) {+ const meta = metadata && typeof metadata === 'object' ? metadata : {};++ // 1) Explicit override wins — a producer that knows the work's kind says so.+ const explicit = normalizeKind(meta.safetyKind);+ if (explicit) {+ return {+ kind: explicit,+ outwardFacing: OUTWARD_KIND_SET.has(explicit),+ reason: `explicit metadata.safetyKind=${explicit}`+ };+ }+ if (meta.outwardFacing === true) {+ return { kind: 'publish', outwardFacing: true, reason: 'explicit metadata.outwardFacing flag' };+ }+ if (meta.outwardFacing === false) {+ return { kind: REVERSIBLE_SAFETY_KIND, outwardFacing: false, reason: 'explicit metadata.outwardFacing=false' };+ }++ // 2) Boolean capability hints a task builder can set when it knows the shape.+ if (meta.federatesRecords === true || meta.publishesToPeers === true) {+ return { kind: 'federation', outwardFacing: true, reason: 'metadata capability: federation' };+ }+ if (meta.publishesContent === true) {+ return { kind: 'content', outwardFacing: true, reason: 'metadata capability: content publish' };+ }+ if (meta.opensExternalPr === true) {+ return { kind: 'external-pr', outwardFacing: true, reason: 'metadata capability: external PR' };+ }++ // 3) Keyword signatures over the task-type key + free-form description hints.+ const haystack = [taskTypeKey, meta.analysisType, meta.selfImprovementType, meta.taskDescription]+ .filter((s) => typeof s === 'string' && s)+ .join(' ')+ .toLowerCase();+ if (haystack) {+ for (const { kind, re } of KIND_SIGNATURES) {+ if (re.test(haystack)) {+ return { kind, outwardFacing: true, reason: `signature match: ${kind}` };+ }+ }+ }++ // 4) Default — reversible internal work; keeps the success-rate gate.+ return { kind: REVERSIBLE_SAFETY_KIND, outwardFacing: false, reason: 'no outward signal — reversible internal work' };+}++/**+ * Should a task of this safety kind be forced to human approval, regardless of+ * confidence tier? Reads the `config.safetyKindApproval` slice.+ *+ * @param {string} kind - a safety kind from classifySafetyKind()+ * @param {{ enabled?: boolean, alwaysApproveKinds?: string[] }} [config]+ * @returns {boolean}+ */+export function requiresSafetyApproval(kind, config = {}) {+ if (config?.enabled === false) return false;+ const list = Array.isArray(config?.alwaysApproveKinds)+ ? config.alwaysApproveKinds+ : DEFAULT_ALWAYS_APPROVE_KINDS;+ const target = normalizeKind(kind);+ if (!target) return false;+ return list.map(normalizeKind).includes(target);+}diff --git a/server/services/taskLearning/safetyKind.test.js b/server/services/taskLearning/safetyKind.test.jsnew file mode 100644index 0000000000..77e17ed160--- /dev/null+++ b/server/services/taskLearning/safetyKind.test.js@@ -0,0 +1,131 @@+import { describe, it, expect } from 'vitest';+import {+ classifySafetyKind,+ requiresSafetyApproval,+ REVERSIBLE_SAFETY_KIND,+ OUTWARD_SAFETY_KINDS,+ DEFAULT_ALWAYS_APPROVE_KINDS+} from './safetyKind.js';++// Pure classifier for the safety-kind override (#2440). Confidence gates on+// success rate; safety-kind gates on whether the work is outward-facing /+// irreversible. Every branch is exercised directly — no I/O.++describe('classifySafetyKind (#2440)', () => {+ it('defaults internal improvement work to reversible', () => {+ for (const key of ['self-improve:code-review', 'app-improve:dependency-audit', 'self-improve:refactor', 'internal']) {+ const out = classifySafetyKind({ taskTypeKey: key, metadata: { analysisType: 'refactor' } });+ expect(out.kind).toBe(REVERSIBLE_SAFETY_KIND);+ expect(out.outwardFacing).toBe(false);+ }+ });++ it('returns reversible for empty/no input', () => {+ expect(classifySafetyKind().kind).toBe(REVERSIBLE_SAFETY_KIND);+ expect(classifySafetyKind({}).outwardFacing).toBe(false);+ expect(classifySafetyKind({ metadata: null }).kind).toBe(REVERSIBLE_SAFETY_KIND);+ });++ it('honors an explicit metadata.safetyKind override (outward)', () => {+ const out = classifySafetyKind({ taskTypeKey: 'self-improve:refactor', metadata: { safetyKind: 'Content' } });+ expect(out.kind).toBe('content'); // normalized lowercase+ expect(out.outwardFacing).toBe(true);+ expect(out.reason).toContain('explicit');+ });++ it('treats an explicit but unknown safetyKind as reversible (not in outward set)', () => {+ const out = classifySafetyKind({ metadata: { safetyKind: 'proposal-draft' } });+ expect(out.kind).toBe('proposal-draft');+ expect(out.outwardFacing).toBe(false);+ });++ it('honors metadata.outwardFacing boolean flags in both directions', () => {+ expect(classifySafetyKind({ metadata: { outwardFacing: true } }).outwardFacing).toBe(true);+ // outwardFacing:false wins even when a keyword signature would otherwise fire+ const forced = classifySafetyKind({ taskTypeKey: 'publish:blog', metadata: { outwardFacing: false } });+ expect(forced.kind).toBe(REVERSIBLE_SAFETY_KIND);+ expect(forced.outwardFacing).toBe(false);+ });++ it('classifies boolean capability hints', () => {+ expect(classifySafetyKind({ metadata: { federatesRecords: true } }).kind).toBe('federation');+ expect(classifySafetyKind({ metadata: { publishesToPeers: true } }).kind).toBe('federation');+ expect(classifySafetyKind({ metadata: { publishesContent: true } }).kind).toBe('content');+ expect(classifySafetyKind({ metadata: { opensExternalPr: true } }).kind).toBe('external-pr');+ });++ it('classifies via keyword signatures on the task-type key / description', () => {+ expect(classifySafetyKind({ taskTypeKey: 'app-improve:federate-records' }).kind).toBe('federation');+ expect(classifySafetyKind({ taskTypeKey: 'open-upstream-pr' }).kind).toBe('external-pr');+ expect(classifySafetyKind({ taskTypeKey: 'publish-release' }).kind).toBe('publish');+ expect(classifySafetyKind({ metadata: { taskDescription: 'Deploy the site to production' } }).kind).toBe('publish');+ expect(classifySafetyKind({ metadata: { taskDescription: 'Draft a social-media post' } }).kind).toBe('content');+ });++ it('all outward classifications set outwardFacing true; reversible sets false', () => {+ const outward = classifySafetyKind({ taskTypeKey: 'auto-send-outbound-message' });+ expect(outward.outwardFacing).toBe(true);+ expect(OUTWARD_SAFETY_KINDS).toContain(outward.kind);+ });+});++describe('requiresSafetyApproval (#2440)', () => {+ it('forces approval for every default outward kind', () => {+ for (const kind of DEFAULT_ALWAYS_APPROVE_KINDS) {+ expect(requiresSafetyApproval(kind)).toBe(true);+ }+ });++ it('does not force approval for reversible internal work', () => {+ expect(requiresSafetyApproval(REVERSIBLE_SAFETY_KIND)).toBe(false);+ });++ it('is case-insensitive on both the kind and the config list', () => {+ expect(requiresSafetyApproval('CONTENT')).toBe(true);+ expect(requiresSafetyApproval('content', { alwaysApproveKinds: ['CONTENT'] })).toBe(true);+ });++ it('respects a custom alwaysApproveKinds list', () => {+ const config = { alwaysApproveKinds: ['content'] };+ expect(requiresSafetyApproval('content', config)).toBe(true);+ expect(requiresSafetyApproval('federation', config)).toBe(false); // removed from list+ });++ it('returns false when the safety gate is disabled', () => {+ expect(requiresSafetyApproval('content', { enabled: false })).toBe(false);+ });++ it('falls back to defaults for a non-array / missing list', () => {+ expect(requiresSafetyApproval('federation', { alwaysApproveKinds: 'not-an-array' })).toBe(true);+ expect(requiresSafetyApproval('federation', {})).toBe(true);+ });++ it('returns false for an empty/blank kind', () => {+ expect(requiresSafetyApproval('')).toBe(false);+ expect(requiresSafetyApproval(null)).toBe(false);+ });+});++describe('safety-kind override branch (#2440) — composed decision', () => {+ // Mirrors resolveConfidenceApproval()'s override branch: an outward-facing+ // task is force-approved BEFORE (and regardless of) the confidence tier — even+ // a 100%-success task type. Reversible work falls through to the confidence gate.+ const wouldForceApproval = ({ taskTypeKey, metadata }, safetyConfig) => {+ const safety = classifySafetyKind({ taskTypeKey, metadata });+ return safety.outwardFacing && requiresSafetyApproval(safety.kind, safetyConfig);+ };++ it('overrides a would-be auto-approval for outward work regardless of confidence', () => {+ // Even if confidence tier is "high" (100% success), the safety override wins.+ expect(wouldForceApproval({ taskTypeKey: 'publish-release' }, {})).toBe(true);+ expect(wouldForceApproval({ metadata: { federatesRecords: true } }, {})).toBe(true);+ });++ it('leaves reversible internal tasks to the confidence gate (no override)', () => {+ expect(wouldForceApproval({ taskTypeKey: 'self-improve:code-review' }, {})).toBe(false);+ });++ it('lets the user disable the safety override entirely', () => {+ expect(wouldForceApproval({ taskTypeKey: 'publish-release' }, { enabled: false })).toBe(false);+ });+});