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
refactor: break the getConfig import cycle and dedupe agentPromptBuilder derivations
[._.]/ Adam Eivy6837e8c2dd40
diff --git a/server/services/agentCompletion.js b/server/services/agentCompletion.jsindex 1160acc1b0..4a24b4ab62 100644--- a/server/services/agentCompletion.js+++ b/server/services/agentCompletion.js@@ -6,7 +6,7 @@*/import { updateAgent } from './cosAgentLifecycle.js';-import { getConfig } from './cos.js';+import { getConfig } from './cosState.js';import { startAppCooldown, markAppReviewCompleted } from './appActivity.js';import { emitLog } from './cosEvents.js';import { extractAndStoreMemories } from './memoryExtractor.js';diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex a403f25d8b..29ff70e8cb 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -1954,6 +1954,49 @@ function buildPostPRMergeSteps(startStep, { prCompletion = PR_COMPLETIONS.REVIEW* return this IS a Claude session, so `/simplify` and `/do:pr` are both safe to* emit without a second provider check.*/+/**+ * Resolve the review-loop invocation shared by buildTuiCompletionSection and+ * buildCliCompletionSection: the normalized reviewer usernames, the+ * `--review-with ...` argument text, and the effort-pin note. Both callers+ * used to re-derive this identical trio from the same 8-field reviewer-config+ * bundle independently.+ */+function resolveReviewInvocation({ willOpenPR, runsReviewLoop, reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies }) {+ const reviewUsernames = normalizeReviewUsernames(usernames);+ const reviewArgs = willOpenPR+ ? (runsReviewLoop ? buildReviewWithArgs(reviewers, { stopMode: reviewStopMode, reviewerApplies, usernames: reviewUsernames, optionalReviewers, reviewerMaxRounds, reviewerModels }) : '--review-with none')+ : '';+ // Effort pins can't ride `--review-with` (no suffix for them in slashdo's+ // grammar), so they're stated as an instruction on the invocation instead.+ const effortNote = willOpenPR && runsReviewLoop ? buildReviewerEffortNote(reviewers, reviewerEfforts) : '';+ return { reviewUsernames, reviewArgs, effortNote };+}++/**+ * The `.agent-done` sentinel-write instruction block shared by+ * buildTuiCompletionSection and buildManualTuiCompletionSection: the "write a+ * short summary, then stop" instruction plus the fenced heredoc template.+ * Returns the lines to splice into the caller's own line array — output must+ * stay byte-identical since this is agent-facing prompt text.+ */+function buildSentinelWriteSteps(stepNumber, sentinelPath, sentinelTail) {+ return [+ `${stepNumber}. Write a short markdown summary (~5–15 lines) to the completion sentinel, then stop — this sentinel is the done signal. PortOS polls it every 2s, finalizes the run, and closes the session for you. Do NOT run \`/quit\` (it's a UI command, not something you can invoke) and do NOT wait for anything after writing the sentinel.`,+ '',+ ' ```bash',+ ` cat > "${sentinelPath}" <<'EOF'`,+ ' ## Summary',+ ' <one-sentence statement of what was accomplished>',+ '',+ ' ## Changes',+ ' - <key file or area>: <what changed and why>',+ '',+ sentinelTail,+ ' EOF',+ ' ```'+ ];+}+function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, simplifyEnabled, sentinelPath, slashdoFree = false, branchName = null, baseBranch = null, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewerModels = {}, reviewerEfforts = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;@@ -1964,13 +2007,10 @@ function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.Mreturn buildManualTuiCompletionSection({ willOpenPR, prCompletion, simplifyEnabled, sentinelPath, branchName, baseBranch, leavePrOpen });}const cmd = willOpenPR ? '/do:pr' : '/do:push';- const reviewUsernames = normalizeReviewUsernames(usernames);// `/do:pr` may inherit a saved `review-with` default. Explicitly opt out// when the task's Review Loop control is off so that default cannot start a// Copilot (or other external) review unexpectedly.- const reviewArgs = willOpenPR- ? (runsReviewLoop ? buildReviewWithArgs(reviewers, { stopMode: reviewStopMode, reviewerApplies, usernames: reviewUsernames, optionalReviewers, reviewerMaxRounds, reviewerModels }) : '--review-with none')- : '';+ const { reviewUsernames, reviewArgs, effortNote } = resolveReviewInvocation({ willOpenPR, runsReviewLoop, reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies });// A saved slashdo `merge: true` default would otherwise merge a PR that must// stay open — dropping our own merge steps isn't enough, `/do:pr` has to be// told not to merge (see lib/prDisposition.js).@@ -1983,9 +2023,6 @@ function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.M? ' — `/do:pr` runs the Copilot review loop after the PR opens.': ` — \`/do:pr\` runs the review loop for ${reviewerListLabel} in order after the PR opens.`): (willOpenPR ? ' — external review is disabled for this task.' : '');- // Effort pins can't ride `--review-with` (no suffix for them in slashdo's- // grammar), so they're stated as an instruction on the invocation instead.- const effortNote = willOpenPR && runsReviewLoop ? buildReviewerEffortNote(reviewers, reviewerEfforts) : '';// Reached only for a Claude TUI (a non-Claude one took the slashdoFree branch// above), so `/simplify` — a Claude Code built-in — is invokable here.const simplifyStep = simplifyEnabled ? '1. `/simplify`' : '1. (simplify disabled — skip)';@@ -2006,19 +2043,7 @@ function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.M`2. \`${cmd}${reviewerArg}\`${reviewSuffix}`,...(effortNote ? [` ${effortNote}`] : []),...merge.lines,- `${sentinelStep}. Write a short markdown summary (~5–15 lines) to the completion sentinel, then stop — this sentinel is the done signal. PortOS polls it every 2s, finalizes the run, and closes the session for you. Do NOT run \`/quit\` (it's a UI command, not something you can invoke) and do NOT wait for anything after writing the sentinel.`,- '',- ' ```bash',- ` cat > "${sentinelPath}" <<'EOF'`,- ' ## Summary',- ' <one-sentence statement of what was accomplished>',- '',- ' ## Changes',- ' - <key file or area>: <what changed and why>',- '',- sentinelTail,- ' EOF',- ' ```'+ ...buildSentinelWriteSteps(sentinelStep, sentinelPath, sentinelTail)].join('\n');}@@ -2068,21 +2093,7 @@ function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETlines.push(`${step++}. Do NOT push this worktree branch yourself. PortOS will merge it back after completion.`);}- lines.push(- `${step}. Write a short markdown summary (~5–15 lines) to the completion sentinel, then stop — this sentinel is the done signal. PortOS polls it every 2s, finalizes the run, and closes the session for you. Do NOT run \`/quit\` (it's a UI command, not something you can invoke) and do NOT wait for anything after writing the sentinel.`,- '',- ' ```bash',- ` cat > "${sentinelPath}" <<'EOF'`,- ' ## Summary',- ' <one-sentence statement of what was accomplished>',- '',- ' ## Changes',- ' - <key file or area>: <what changed and why>',- '',- sentinelTail,- ' EOF',- ' ```',- );+ lines.push(...buildSentinelWriteSteps(step, sentinelPath, sentinelTail));return lines.join('\n');}@@ -2100,16 +2111,13 @@ function buildManualTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETfunction buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, hasSlashdo = false, simplifyEnabled = false, leavePrOpen = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewerModels = {}, reviewerEfforts = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false }) {const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;- const reviewUsernames = normalizeReviewUsernames(usernames);if (hasSlashdo && worktreeInfo && willOpenPR) {const lines = ['## Completion', 'When finished, run these in order:'];let step = 1;if (simplifyEnabled) {lines.push(`${step++}. \`/simplify\` — review the changed code for reuse, quality, and efficiency, and fix any findings.`);}- const reviewArgs = runsReviewLoop- ? buildReviewWithArgs(reviewers, { stopMode: reviewStopMode, reviewerApplies, usernames: reviewUsernames, optionalReviewers, reviewerMaxRounds, reviewerModels })- : '--review-with none';+ const { reviewUsernames, reviewArgs, effortNote } = resolveReviewInvocation({ willOpenPR, runsReviewLoop, reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts, reviewStopMode, reviewerApplies });// `--no-merge` overrides a saved slashdo `merge: true` default, which would// otherwise merge a PR this task must leave open (see lib/prDisposition.js).const reviewerArg = (reviewArgs ? ` ${reviewArgs}` : '') + ((leavePrOpen || policyLeavesOpen) ? ' --no-merge' : '');@@ -2121,7 +2129,6 @@ function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion = PRlines.push(`${step++}. \`/do:pr${reviewerArg}\` — commits your changes, pushes the branch, and opens a pull request against the default branch ${completionNote}`);// Effort pins have no `--review-with` suffix to ride, so they're stated as an// instruction on the invocation instead (see buildReviewerEffortNote).- const effortNote = runsReviewLoop ? buildReviewerEffortNote(reviewers, reviewerEfforts) : '';if (effortNote) lines.push(` ${effortNote}`);// Merge steps follow — review-gated with a loop, CI-gated without one — unless// this PR is a human's to land (JIRA-tracked; see lib/prDisposition.js).diff --git a/server/services/cos.js b/server/services/cos.jsindex 72d79ebc09..eb60d560f1 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -15,17 +15,16 @@* - cosHealthMonitor.js — daemon health checks (PM2/memory, auto-restart)*/-import { readFile, writeFile, readdir, rm } from 'fs/promises';+import { readFile, writeFile, readdir } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';-import { v4 as uuidv4 } from '../lib/uuid.js';import { getActiveProvider } from './providers.js';import { isInternalTaskId } from '../lib/taskParser.js';import { isRetryHeld, isStaleRetryHold } from '../lib/taskRetryHold.js';import { isAppOnCooldown, markAppReviewCooldown, bindAppReviewAgent, clearStaleActiveAgents } from './appActivity.js';import { getActiveApps } from './apps.js';import { getPerformanceSummary, checkAndRehabilitateSkippedTasks, getLearningInsights } from './taskLearning.js';-import { schedule as scheduleEvent, cancel as cancelEvent, getStats as getSchedulerStats } from './eventScheduler.js';+import { schedule as scheduleEvent, cancel as cancelEvent } from './eventScheduler.js';import { generateProactiveTasks as generateMissionTasks } from './missions.js';import { recordJobExecution } from './autonomousJobs.js';import { atomicWrite, safeJSONParse, sleep } from '../lib/fileUtils.js';@@ -39,7 +38,7 @@ import { getDomainBudgetStatus } from './domainUsage.js';import { useRunner } from './agentState.js';// Shared state management (extracted to avoid circular deps)-import { loadState, saveState, withStateLock, ensureDirectories, isImprovementEnabled, canQueueImprovementTasks, AGENTS_DIR, REPORTS_DIR, SCRIPTS_DIR, ROOT_DIR, isDaemonRunning, setDaemonRunning } from './cosState.js';+import { loadState, saveState, withStateLock, ensureDirectories, isImprovementEnabled, canQueueImprovementTasks, SCRIPTS_DIR, isDaemonRunning, setDaemonRunning } from './cosState.js';// Events and logging (canonical source: cosEvents.js)import { cosEvents, emitLog } from './cosEvents.js';@@ -74,7 +73,7 @@ export { runHealthCheck, getHealthStatus };// backward compat with `import * as cos` and the cos route handlers. The store// emits `tasks:changed`; init() below turns that into tryImmediateSpawn /// dequeueNextTask so the spawn-side logic stays here, not in the store.-import { firstLine, PRIORITY_VALUES, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks } from './cosTaskStore.js';+import { firstLine, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks } from './cosTaskStore.js';export { firstLine, getUserTasks, getCosTasks, getAllTasks, getTasks, getTaskById, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks };import { ensureInstanceId } from './instances.js';import { isHeldByOther, buildRenewal, buildClaim, getClaimOwner } from './cosTaskClaim.js';@@ -172,13 +171,9 @@ export async function getStatus() {};}-/**- * Get current configuration- */-export async function getConfig() {- const state = await loadState();- return state.config;-}+// Get current configuration (moved to cosState.js to break an import cycle;+// re-exported here for backward compat with `import * as cos`).+export { getConfig } from './cosState.js';/*** Update configurationdiff --git a/server/services/cosState.js b/server/services/cosState.jsindex 7b8294a16f..12dc7e5a49 100644--- a/server/services/cosState.js+++ b/server/services/cosState.js@@ -146,6 +146,14 @@ export function canQueueImprovementTasks(state) {return Boolean(state.config.idleReviewEnabled) && getDomainMode(state.config, 'cos') === 'execute';}+/**+ * Get current configuration+ */+export async function getConfig() {+ const state = await loadState();+ return state.config;+}+export async function loadState() {if (stateCache) return stateCache;