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: add persistent mind workspace preflight (#5156)

Adam Eivyfac2d4185e47
diff --git a/client/src/components/cos/PersistentMindVisibilityPanel.jsx b/client/src/components/cos/PersistentMindVisibilityPanel.jsx
new file mode 100644
index 0000000000..60cf090218
--- /dev/null
+++ b/client/src/components/cos/PersistentMindVisibilityPanel.jsx
@@ -0,0 +1,106 @@
+import { CheckCircle2, CircleAlert, CircleHelp, RefreshCw } from 'lucide-react';
+import { formatDateTime } from '../../utils/formatters.js';
+
+const readinessLabel = (readiness) => {
+ if (readiness === 'ready') return 'Ready';
+ if (readiness === 'degraded') return 'Degraded';
+ if (readiness === 'blocked') return 'Blocked';
+ return 'Unknown';
+};
+
+const readinessClass = (readiness) => {
+ if (readiness === 'ready') return 'text-port-success';
+ if (readiness === 'degraded') return 'text-port-warning';
+ if (readiness === 'blocked') return 'text-port-error';
+ return 'text-port-text-muted';
+};
+
+const ReadinessIcon = ({ readiness }) => {
+ if (readiness === 'ready') return <CheckCircle2 size={15} aria-hidden="true" />;
+ if (readiness === 'unknown') return <CircleHelp size={15} aria-hidden="true" />;
+ return <CircleAlert size={15} aria-hidden="true" />;
+};
+
+const checkLabel = (preflight, check) => {
+ const hasWorkspace = Array.isArray(preflight.workspaces) && preflight.workspaces.length > 0;
+ if (check === 'dependencies') return hasWorkspace && !preflight.workspaces.some((workspace) => workspace.dependencies?.status !== 'installed') ? 'Dependencies available' : 'Dependencies need attention';
+ if (check === 'engines') return hasWorkspace && !preflight.workspaces.some((workspace) => ['incompatible', 'unknown'].includes(workspace.engines?.node?.status) || ['incompatible', 'unknown'].includes(workspace.engines?.packageManager?.status)) ? 'Engines compatible' : 'Engine compatibility needs attention';
+ if (check === 'submodules') return preflight.submodules?.status === 'initialized' || preflight.submodules?.status === 'not-configured' ? 'Submodules ready' : 'Submodules need attention';
+ if (check === 'forge') return preflight.forge?.status === 'ready' ? 'Forge access available' : 'Forge access needs attention';
+ if (check === 'reviewers') return preflight.reviewers?.required?.status === 'ready' ? 'Required reviewers available' : 'Reviewer availability needs attention';
+ return null;
+};
+
+export default function PersistentMindVisibilityPanel({ visibility, error, loading, onRefresh }) {
+ const workspaces = Array.isArray(visibility?.workspaces) ? visibility.workspaces : [];
+ const readiness = visibility?.readiness || 'unknown';
+ const warnings = workspaces.flatMap((workspace) => workspace.preflight?.warnings || []);
+ const uniqueWarnings = warnings.filter((warning, index, values) => values.findIndex((candidate) => candidate.code === warning.code) === index);
+
+ return (
+ <section aria-label="Persistent mind environment visibility" className="rounded border border-port-border bg-port-card p-3 sm:p-4">
+ <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
+ <div>
+ <h3 className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-port-accent">Environment visibility</h3>
+ <p className="mt-1 text-xs text-port-text-muted">Read-only workspace facts used before the mind queues delegated work.</p>
+ </div>
+ <button type="button" onClick={onRefresh} disabled={loading} className="inline-flex items-center justify-center gap-1.5 rounded border border-port-border px-2.5 py-1.5 text-xs font-medium text-port-text hover:bg-port-border/20 disabled:cursor-not-allowed disabled:opacity-60">
+ <RefreshCw size={13} className={loading ? 'animate-spin motion-reduce:animate-none' : ''} aria-hidden="true" />
+ {loading ? 'Refreshing…' : 'Refresh'}
+ </button>
+ </div>
+
+ <div className="mt-3 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs">
+ <span className={`inline-flex items-center gap-1.5 font-semibold ${readinessClass(readiness)}`}>
+ <ReadinessIcon readiness={readiness} />
+ {readinessLabel(readiness)}
+ </span>
+ <span className="text-port-text-muted">
+ Captured {visibility?.capturedAt ? formatDateTime(visibility.capturedAt) : '—'} · {visibility?.freshness?.state || 'unknown'} snapshot
+ </span>
+ {visibility?.truncated && <span className="text-port-warning">Some checks were bounded before completion.</span>}
+ </div>
+
+ {workspaces.length > 0 ? (
+ <div className="mt-3 grid gap-2 md:grid-cols-2">
+ {workspaces.map((workspace) => {
+ const workspaceReadiness = workspace.readiness || 'unknown';
+ const preflight = workspace.preflight || {};
+ return (
+ <article key={workspace.appId || workspace.appName} className="rounded border border-port-border/80 p-3" aria-label={`${workspace.appName || 'Workspace'} preflight`}>
+ <div className="flex items-center justify-between gap-2">
+ <h4 className="min-w-0 truncate text-sm font-medium text-port-text">{workspace.appName || 'Workspace'}</h4>
+ <span className={`inline-flex shrink-0 items-center gap-1 text-xs font-semibold ${readinessClass(workspaceReadiness)}`}>
+ <ReadinessIcon readiness={workspaceReadiness} />
+ {readinessLabel(workspaceReadiness)}
+ </span>
+ </div>
+ <div className="mt-2 grid gap-1 text-xs text-port-text-muted sm:grid-cols-2">
+ {['dependencies', 'engines', 'submodules', 'forge', 'reviewers'].map((check) => (
+ <span key={check}>{checkLabel(preflight, check)}</span>
+ ))}
+ </div>
+ {(workspaceReadiness === 'blocked' || workspaceReadiness === 'unknown') && (
+ <p className="mt-2 text-xs text-port-warning">{workspaceReadiness === 'blocked' ? 'A required workspace check must be repaired before this task can run.' : 'A workspace probe could not complete. Refresh or repair the unavailable check before requiring it.'}</p>
+ )}
+ </article>
+ );
+ })}
+ </div>
+ ) : (
+ <p className="mt-3 text-xs text-port-text-muted">No configured workspaces were available to inspect.</p>
+ )}
+
+ {(uniqueWarnings.length > 0 || error) && (
+ <div className="mt-3 border-t border-port-border pt-3 text-xs text-port-warning">
+ {error && <p>Visibility refresh delayed: {error}. The last successful snapshot remains in use.</p>}
+ {uniqueWarnings.length > 0 && (
+ <ul className="mt-1 list-disc space-y-1 pl-4">
+ {uniqueWarnings.map((warning) => <li key={warning.code}>{warning.message}</li>)}
+ </ul>
+ )}
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/client/src/components/cos/tabs/MindTab.jsx b/client/src/components/cos/tabs/MindTab.jsx
index 8e2d2fe81e..0ddd47f656 100644
--- a/client/src/components/cos/tabs/MindTab.jsx
+++ b/client/src/components/cos/tabs/MindTab.jsx
@@ -15,6 +15,7 @@ import PersistentMindContextPanel from '../PersistentMindContextPanel';
import PersistentMindProfileControls from '../PersistentMindProfileControls';
import PersistentMindRuntimePanel, { PersistentMindThoughtStatus } from '../PersistentMindRuntimePanel';
import PersistentMindTaskAccessControls from '../PersistentMindTaskAccessControls';
+import PersistentMindVisibilityPanel from '../PersistentMindVisibilityPanel';
const PAGE_LIMIT = 200;
const MAX_BACKFILL_PAGES = 5;
@@ -124,12 +125,18 @@ export default function MindTab() {
const [runtime, setRuntime] = useState(null);
const [runtimeError, setRuntimeError] = useState(null);
const [runtimeLoading, setRuntimeLoading] = useState(true);
+ const [visibility, setVisibility] = useState(null);
+ const [visibilityError, setVisibilityError] = useState(null);
+ const [visibilityLoading, setVisibilityLoading] = useState(true);
const cursorRef = useRef(null);
const loadPendingRef = useRef(false);
const deferredLoadRef = useRef(false);
const runtimePendingRef = useRef(false);
const deferredRuntimeRef = useRef(false);
const runtimeLoadedRef = useRef(false);
+ const visibilityPendingRef = useRef(false);
+ const deferredVisibilityRefreshRef = useRef(false);
+ const visibilityLoadedRef = useRef(false);
const runtimeMountedRef = useMounted();
const messageDraftIdRef = useRef(null);
const annotationDraftIdRef = useRef(null);
@@ -214,17 +221,51 @@ export default function MindTab() {
}
}, []);
+ const loadVisibility = useCallback(async ({ refresh = false } = {}) => {
+ if (visibilityPendingRef.current) {
+ deferredVisibilityRefreshRef.current ||= refresh;
+ return;
+ }
+ visibilityPendingRef.current = true;
+ if (!visibilityLoadedRef.current) setVisibilityLoading(true);
+ try {
+ const response = await api.getPersistentMindVisibility({ refresh, silent: true });
+ if (!runtimeMountedRef.current) return;
+ setVisibility(response);
+ visibilityLoadedRef.current = true;
+ setVisibilityError(null);
+ } catch (error) {
+ if (runtimeMountedRef.current) {
+ setVisibilityError(error?.message || 'Could not refresh environment visibility');
+ }
+ } finally {
+ if (runtimeMountedRef.current) setVisibilityLoading(false);
+ visibilityPendingRef.current = false;
+ if (runtimeMountedRef.current && deferredVisibilityRefreshRef.current) {
+ const deferredRefresh = deferredVisibilityRefreshRef.current;
+ deferredVisibilityRefreshRef.current = false;
+ void loadVisibility({ refresh: deferredRefresh });
+ }
+ }
+ }, [runtimeMountedRef]);
+
useEffect(() => { void loadHistory({ reset: true }); }, [loadHistory]);
useEffect(() => {
void loadRuntime();
const interval = setInterval(() => { void loadRuntime(); }, 10_000);
return () => clearInterval(interval);
}, [loadRuntime]);
+ useEffect(() => {
+ void loadVisibility();
+ const interval = setInterval(() => { void loadVisibility(); }, 30_000);
+ return () => clearInterval(interval);
+ }, [loadVisibility]);
useEffect(() => {
const refresh = () => {
void loadHistory();
void loadRuntime();
+ void loadVisibility();
};
socket.on('connect', refresh);
socket.on('cos:mind:event', refresh);
@@ -234,7 +275,7 @@ export default function MindTab() {
socket.off('cos:mind:event', refresh);
socket.off('cos:mind:status', refresh);
};
- }, [loadHistory, loadRuntime, socket]);
+ }, [loadHistory, loadRuntime, loadVisibility, socket]);
useEffect(() => {
if (!stickToBottomRef.current || !messageListRef.current) return;
@@ -435,6 +476,7 @@ export default function MindTab() {
<ActionButton label="Reload" icon={RefreshCw} pending={loading || runtimeLoading} onClick={() => {
void loadHistory({ reset: true });
void loadRuntime();
+ void loadVisibility({ refresh: true });
}} />
</div>
</header>
@@ -448,7 +490,15 @@ export default function MindTab() {
{lifecycleError && <Banner tone="error" title="Action failed">{lifecycleError}</Banner>}
{activeView !== 'conversation' && (
- <PersistentMindRuntimePanel runtime={runtime} error={runtimeError} loading={runtimeLoading} onOpenContext={() => changeView('context')} />
+ <>
+ <PersistentMindVisibilityPanel
+ visibility={visibility}
+ error={visibilityError}
+ loading={visibilityLoading}
+ onRefresh={() => loadVisibility({ refresh: true })}
+ />
+ <PersistentMindRuntimePanel runtime={runtime} error={runtimeError} loading={runtimeLoading} onOpenContext={() => changeView('context')} />
+ </>
)}
{activeView === 'setup' && (
diff --git a/client/src/components/cos/tabs/MindTab.test.jsx b/client/src/components/cos/tabs/MindTab.test.jsx
index a5fef84d9f..3f3be4236f 100644
--- a/client/src/components/cos/tabs/MindTab.test.jsx
+++ b/client/src/components/cos/tabs/MindTab.test.jsx
@@ -18,6 +18,7 @@ const api = vi.hoisted(() => ({
updateCosConfig: vi.fn(),
getPersistentMindContext: vi.fn(),
getPersistentMindRuntime: vi.fn(),
+ getPersistentMindVisibility: vi.fn(),
createPersistentMindMemory: vi.fn(),
updatePersistentMindMemory: vi.fn(),
}));
@@ -123,6 +124,20 @@ describe('MindTab', () => {
cpu: { cores: 8, loadAvg1m: 1.25 },
},
});
+ api.getPersistentMindVisibility.mockResolvedValue({
+ schemaVersion: 1,
+ capturedAt: '2026-08-27T12:00:00.000Z',
+ freshness: { state: 'fresh', ageMs: 0, ttlMs: 30_000 },
+ readiness: 'ready',
+ truncated: false,
+ workspaces: [{ appId: 'demo-app', appName: 'Demo App', readiness: 'ready', preflight: {
+ workspaces: [{ dependencies: { status: 'installed' }, engines: { node: { status: 'compatible' }, packageManager: null } }],
+ submodules: { status: 'not-configured' },
+ forge: { status: 'ready' },
+ reviewers: { required: { status: 'ready' } },
+ warnings: [],
+ } }],
+ });
api.createPersistentMindMemory.mockResolvedValue({ success: true });
api.updatePersistentMindMemory.mockResolvedValue({ success: true });
});
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index c4fb93f1d8..d517978b8e 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -68,6 +68,10 @@ export const getPersistentMind = (filters = {}, options = {}) =>
export const getPersistentMindContext = (options = {}) => request('/cos/mind/context', options);
export const getPersistentMindTools = (options = {}) => request('/cos/mind/tools', options);
export const getPersistentMindRuntime = (options = {}) => request('/cos/mind/runtime', options);
+export const getPersistentMindVisibility = (options = {}) => {
+ const { refresh, ...requestOptions } = options;
+ return request(`/cos/mind/visibility${refresh ? '?refresh=true' : ''}`, requestOptions);
+};
export const sendPersistentMindMessage = (body, options = {}) =>
request('/cos/mind/messages', { method: 'POST', body: JSON.stringify(body), ...options });
export const addPersistentMindAnnotation = (body, options = {}) =>
diff --git a/server/lib/persistentMindCapabilities.js b/server/lib/persistentMindCapabilities.js
index bcc71edf3f..904389a339 100644
--- a/server/lib/persistentMindCapabilities.js
+++ b/server/lib/persistentMindCapabilities.js
@@ -47,6 +47,17 @@ export const PERSISTENT_MIND_TASK_LIMITS = Object.freeze({
modelChars: 200,
});
+// These are the only workspace facts a task may promote from advisory
+// visibility into a queueing gate. An omitted or empty list keeps the
+// preflight informative without blocking docs-only/read-only work.
+export const PERSISTENT_MIND_VALIDATION_CHECKS = Object.freeze([
+ 'dependencies',
+ 'engines',
+ 'submodules',
+ 'forge',
+ 'reviewers',
+]);
+
export const persistentMindCapabilitiesSchema = z.object({
schemaVersion: z.literal(PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION).optional(),
createTasks: z.boolean().optional(),
@@ -71,6 +82,10 @@ export const persistentMindTaskRequestSchema = z.object({
// and could queue it twice after an install upgrades.
planOnly: z.boolean().optional(),
prCompletion: z.enum(PR_COMPLETION_VALUES).optional(),
+ // Advisory by default. A task declares only the checks its acceptance
+ // criteria require; this lets docs-only work proceed when code dependencies
+ // are absent while still failing closed for required validation.
+ requiredValidation: z.array(z.enum(PERSISTENT_MIND_VALIDATION_CHECKS)).max(PERSISTENT_MIND_VALIDATION_CHECKS.length).optional(),
}).strict().superRefine((value, context) => {
if (!value.planOnly && !value.prCompletion) {
context.addIssue({
diff --git a/server/lib/persistentMindCapabilities.test.js b/server/lib/persistentMindCapabilities.test.js
index fb0fbb7c87..5407513124 100644
--- a/server/lib/persistentMindCapabilities.test.js
+++ b/server/lib/persistentMindCapabilities.test.js
@@ -40,6 +40,8 @@ describe('persistent mind capabilities', () => {
prCompletion: 'review-then-merge',
};
expect(persistentMindTaskRequestSchema.safeParse(task).success).toBe(true);
+ expect(persistentMindTaskRequestSchema.safeParse({ ...task, requiredValidation: ['dependencies', 'reviewers'] }).success).toBe(true);
+ expect(persistentMindTaskRequestSchema.safeParse({ ...task, requiredValidation: ['shell'] }).success).toBe(false);
expect(persistentMindTaskRequestSchema.safeParse({ ...task, prCompletion: 'merge-now' }).success).toBe(false);
expect(persistentMindTaskRequestSchema.safeParse({ ...task, priority: 'URGENT' }).success).toBe(false);
});
diff --git a/server/routes/cosMindRoutes.js b/server/routes/cosMindRoutes.js
index 588a1da945..80ed2b8cea 100644
--- a/server/routes/cosMindRoutes.js
+++ b/server/routes/cosMindRoutes.js
@@ -35,6 +35,7 @@ import { getProviderById } from '../services/providers.js';
import { persistentMindHarnessInfo } from '../services/persistentMindAdapter.js';
import { readPersistentMindTaskCatalog } from '../services/persistentMindTaskCapability.js';
import { inspectPersistentMindRuntime } from '../services/persistentMindRuntime.js';
+import { readPersistentMindVisibility } from '../services/persistentMindVisibility.js';
import {
enqueuePersistentMindMessage,
getPersistentMindState,
@@ -53,6 +54,9 @@ const mindReadSchema = z.object({
cursor: z.string().max(260).refine((value) => parsePersistentMindCursor(value) !== null, 'Invalid cursor').optional(),
limit: z.coerce.number().int().positive().max(PERSISTENT_MIND_TRAJECTORY_LIMITS.maxPageSize).optional(),
}).strict();
+const visibilityReadSchema = z.object({
+ refresh: z.enum(['true', 'false']).transform((value) => value === 'true').optional(),
+}).strict();
const messageSchema = z.object({ id: idempotencyId, text }).strict();
const annotationSchema = z.object({
id: idempotencyId,
@@ -188,6 +192,16 @@ router.get('/mind/runtime', asyncHandler(async (_req, res) => {
res.json(await inspectPersistentMindRuntime({ state, profile, prompt, provider }));
}));
+router.get('/mind/visibility', asyncHandler(async (req, res) => {
+ const { refresh = false } = validateRequest(visibilityReadSchema, req.query);
+ const [root, state] = await Promise.all([loadState(), getPersistentMindState()]);
+ const prompt = normalizePersistentMindPrompt(root.config?.persistentMindPrompt);
+ const profile = normalizePersistentMindProfile(root.config?.persistentMindProfile);
+ const providerId = state.activeTurn?.providerId || profile.providerId;
+ const provider = providerId ? await getProviderById(providerId) : null;
+ res.json(await readPersistentMindVisibility({ root, state, profile, prompt, provider, force: refresh }));
+}));
+
router.post('/mind/memories', asyncHandler(async (req, res) => {
const input = validateRequest(memoryInputSchema, req.body);
const memory = await createPersistentMindMemory(input);
diff --git a/server/routes/cosMindRoutes.test.js b/server/routes/cosMindRoutes.test.js
index ab3ed67909..58f2610fc5 100644
--- a/server/routes/cosMindRoutes.test.js
+++ b/server/routes/cosMindRoutes.test.js
@@ -22,6 +22,7 @@ const mocks = vi.hoisted(() => ({
resumePersistentMind: vi.fn(),
stopPersistentMind: vi.fn(),
inspectPersistentMindRuntime: vi.fn(),
+ readPersistentMindVisibility: vi.fn(),
readPersistentMindTaskCatalog: vi.fn(),
}));
@@ -62,6 +63,9 @@ vi.mock('../services/persistentMindSupervisor.js', () => ({
vi.mock('../services/persistentMindRuntime.js', () => ({
inspectPersistentMindRuntime: mocks.inspectPersistentMindRuntime,
}));
+vi.mock('../services/persistentMindVisibility.js', () => ({
+ readPersistentMindVisibility: mocks.readPersistentMindVisibility,
+}));
import cosMindRoutes from './cosMindRoutes.js';
@@ -117,6 +121,14 @@ describe('persistent mind routes', () => {
context: { chars: 9, maxChars: 32000, approximateTokens: 3, summaryState: 'empty', memoryCount: 1 },
system: { memory: { total: 100, used: 40, free: 60, usagePercent: 40 } },
});
+ mocks.readPersistentMindVisibility.mockResolvedValue({
+ schemaVersion: 1,
+ capturedAt: '2026-08-27T12:00:00.000Z',
+ freshness: { state: 'fresh', ageMs: 0, ttlMs: 30_000 },
+ readiness: 'degraded',
+ truncated: false,
+ workspaces: [{ appId: 'demo-app', appName: 'Demo App', readiness: 'degraded', preflight: { warnings: [] } }],
+ });
mocks.readPersistentMindTaskCatalog.mockResolvedValue({
apps: [{ id: 'demo-app', name: 'Demo App', planOnly: true }],
providers: [{ id: 'codex', name: 'Codex', type: 'cli', models: [{ id: 'gpt-5', efforts: ['low', 'high'] }] }],
@@ -206,6 +218,23 @@ describe('persistent mind routes', () => {
expect(mocks.getProviderById).toHaveBeenCalledWith('ollama');
});
+ it('serves the shared environment visibility projection and accepts an explicit refresh', async () => {
+ const res = await get('/mind/visibility?refresh=true');
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({
+ schemaVersion: 1,
+ readiness: 'degraded',
+ freshness: { state: 'fresh' },
+ workspaces: [{ appId: 'demo-app', readiness: 'degraded' }],
+ });
+ expect(mocks.readPersistentMindVisibility).toHaveBeenCalledWith(expect.objectContaining({
+ force: true,
+ state: expect.objectContaining({ status: 'idle' }),
+ profile: expect.objectContaining({ providerId: 'demo' }),
+ provider: expect.objectContaining({ id: 'demo' }),
+ }));
+ });
+
it('creates and edits only validated persistent-mind memories', async () => {
const created = await post('/mind/memories', { content: 'A new fact' });
expect(created.status).toBe(201);
diff --git a/server/services/persistentMindAdapter.js b/server/services/persistentMindAdapter.js
index c83b756964..6583cf9d12 100644
--- a/server/services/persistentMindAdapter.js
+++ b/server/services/persistentMindAdapter.js
@@ -29,6 +29,10 @@ import {
executePersistentMindTaskRequests,
readPersistentMindTaskCatalog,
} from './persistentMindTaskCapability.js';
+import {
+ buildPersistentMindVisibilityPrompt,
+ readPersistentMindVisibility,
+} from './persistentMindVisibility.js';
const HEARTBEAT_INTERVAL_MS = 60_000;
@@ -95,9 +99,11 @@ const currentWakeText = (wake) => {
return `This is a self-directed wake. Continue one worthwhile thread from the trajectory.\nreason=${wake?.reason || 'scheduled reflection'}`;
};
-export function buildPersistentMindTurnPrompt({ context, wake, taskCapabilityPrompt }) {
+export function buildPersistentMindTurnPrompt({ context, wake, taskCapabilityPrompt, visibilityPrompt = '# Persistent Mind environment visibility\nWorkspace and runtime visibility is unknown.' }) {
return `${context.text}
+${visibilityPrompt}
+
# Current wake
${currentWakeText(wake)}
@@ -109,7 +115,7 @@ Return ONLY one JSON object with this shape:
"thinkingSummary": "A concise, user-visible working note explaining what you considered and why. Do not reveal hidden chain-of-thought.",
"message": "The conversational reply. Required for a human message; optional for a self-directed wake.",
"memoryCandidates": [{ "content": "A durable fact worth remembering", "summary": "Short label", "type": "fact", "category": "other", "tags": ["optional"] }],
- "taskRequests": [{ "description": "Concise queue label", "prompt": "Complete instructions for the agent", "priority": "MEDIUM", "appId": "configured-app-id", "providerId": "configured-provider-id", "model": "configured-model-id-or-empty-for-default", "effort": "high", "planOnly": false, "prCompletion": "review-then-merge" }],
+ "taskRequests": [{ "description": "Concise queue label", "prompt": "Complete instructions for the agent", "priority": "MEDIUM", "appId": "configured-app-id", "providerId": "configured-provider-id", "model": "configured-model-id-or-empty-for-default", "effort": "high", "planOnly": false, "prCompletion": "review-then-merge", "requiredValidation": ["dependencies"] }],
"selfWake": { "reason": "Why another wake would be useful", "delayMinutes": 60 }
}
Use empty arrays when there is no durable memory candidate or task request, and null when no earlier follow-up is needed. Memory candidates are durable memories to save automatically; only include information that is worth retaining. Typed CoS task creation is the only action capability in this lane and is available only when the capability section says ON. This lane still cannot mutate files directly, call arbitrary tools, contact people, or perform other external actions.`;
@@ -197,18 +203,26 @@ export function createPersistentMindTurnAdapter() {
async run({ turnId, wake, provider, model, effort, signal, context, heartbeat, recordCapabilityEvent }) {
const root = await loadState();
const taskAccess = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities);
+ const prompt = normalizePersistentMindPrompt(root.config?.persistentMindPrompt);
+ const visibility = await readPersistentMindVisibility({
+ root,
+ profile: { providerId: provider?.id || null, model: model || null, effort: effort || null },
+ prompt,
+ provider,
+ });
const taskCatalog = taskAccess.createTasks ? await readPersistentMindTaskCatalog() : undefined;
const taskCapabilityPrompt = buildPersistentMindTaskCapabilityPrompt({
enabled: taskAccess.createTasks,
catalog: taskCatalog,
});
+ const visibilityPrompt = buildPersistentMindVisibilityPrompt(visibility);
const result = await runPinnedPrompt({
provider,
model,
effort,
signal,
heartbeat,
- prompt: buildPersistentMindTurnPrompt({ context, wake, taskCapabilityPrompt }),
+ prompt: buildPersistentMindTurnPrompt({ context, wake, taskCapabilityPrompt, visibilityPrompt }),
responseSchema: persistentMindResponseSchema,
});
const parsed = persistentMindResponseSchema.parse(parseLLMJSON(result.text));
diff --git a/server/services/persistentMindAdapter.test.js b/server/services/persistentMindAdapter.test.js
index 57eebecfb7..34ba300ec1 100644
--- a/server/services/persistentMindAdapter.test.js
+++ b/server/services/persistentMindAdapter.test.js
@@ -7,6 +7,7 @@ const mock = vi.hoisted(() => ({
stopRun: vi.fn(),
readTaskCatalog: vi.fn(),
executeTaskRequests: vi.fn(),
+ readVisibility: vi.fn(),
createPersistentMindMemoryFromCandidate: vi.fn(async ({ candidateId, ...candidate }) => ({
success: true,
duplicate: false,
@@ -26,6 +27,10 @@ vi.mock('./persistentMindTaskCapability.js', () => ({
readPersistentMindTaskCatalog: (...args) => mock.readTaskCatalog(...args),
executePersistentMindTaskRequests: (...args) => mock.executeTaskRequests(...args),
}));
+vi.mock('./persistentMindVisibility.js', () => ({
+ readPersistentMindVisibility: (...args) => mock.readVisibility(...args),
+ buildPersistentMindVisibilityPrompt: () => 'Environment visibility: READY',
+}));
const { createPersistentMindTurnAdapter, persistentMindHarnessInfo } = await import('./persistentMindAdapter.js');
@@ -35,6 +40,7 @@ beforeEach(() => {
vi.clearAllMocks();
mock.root.config.persistentMindCapabilities = { createTasks: true };
mock.readTaskCatalog.mockResolvedValue({ apps: [{ id: 'portos' }], providers: [{ id: 'codex' }] });
+ mock.readVisibility.mockResolvedValue({ readiness: 'ready', workspaces: [] });
mock.executeTaskRequests.mockResolvedValue([]);
mock.runPrompt.mockResolvedValue({ text: JSON.stringify({
thinkingSummary: 'I connected the new request to the durable fact.',
@@ -83,6 +89,7 @@ describe('persistent mind adapter', () => {
candidateId: 'turn-1:0', turnId: 'turn-1',
});
expect(mock.runPrompt.mock.calls[0][0].prompt).toContain('Task access: ON');
+ expect(mock.runPrompt.mock.calls[0][0].prompt).toContain('Environment visibility: READY');
});
it('executes bounded typed task requests through the supervised capability', async () => {
diff --git a/server/services/persistentMindTaskCapability.js b/server/services/persistentMindTaskCapability.js
index 8f2112d29a..14ae4966df 100644
--- a/server/services/persistentMindTaskCapability.js
+++ b/server/services/persistentMindTaskCapability.js
@@ -23,6 +23,10 @@ import { loadState } from './cosState.js';
import { addTask, getTaskById } from './cosTaskStore.js';
import { getProviderPrerequisiteReadinessMap } from './providerPrerequisites.js';
import { listProviders } from './providers.js';
+import {
+ assessPersistentMindWorkspaceReadiness,
+ readPersistentMindWorkspacePreflight,
+} from './persistentMindWorkspacePreflight.js';
const MAX_CATALOG_APPS = 50;
const MAX_CATALOG_PROVIDERS = 50;
@@ -111,7 +115,10 @@ const appCatalogEntry = async (app) => {
};
export async function readPersistentMindTaskCatalog() {
- const [apps, providers] = await Promise.all([getActiveApps(), listProviders()]);
+ const [apps, providers] = await Promise.all([
+ Array.isArray(suppliedApps) ? suppliedApps : getActiveApps(),
+ Array.isArray(suppliedProviders) ? suppliedProviders : listProviders(),
+ ]);
const runnableApps = apps
.filter((app) => isRunnableApp(app) && typeof app?.id === 'string' && app.id
&& app.id.length <= PERSISTENT_MIND_TASK_LIMITS.appIdChars)
@@ -188,6 +195,10 @@ for an app whose catalog entry has 'planOnly: true'; that mode investigates the
repository and files one GitHub/GitLab issue without editing code or opening a
PR. In plan-only mode, 'prCompletion' may be omitted. Otherwise set
'planOnly' to false and choose one PR completion policy.
+Use 'requiredValidation' only when the task's acceptance criteria require those
+workspace checks before queueing. Supported checks are 'dependencies',
+'engines', 'submodules', 'forge', and 'reviewers'. An omitted or empty list
+keeps absent dependencies advisory, which is appropriate for docs-only work.
Configured choices (ids are authoritative; do not invent ids):
${JSON.stringify(promptCatalog)}
@@ -241,7 +252,16 @@ const validateChoice = async (request, apps, providers) => {
return { error: `Plan-and-file tasks require a GitHub or GitLab issue tracker for app '${request.appId}'` };
}
}
- return { app, provider };
+ const preflight = await readPersistentMindWorkspacePreflight(app);
+ const readiness = assessPersistentMindWorkspaceReadiness(preflight, request.requiredValidation);
+ if (readiness.blockers.length) {
+ return {
+ error: `Workspace preflight blocked task '${request.description}': ${readiness.blockers.map((blocker) => blocker.message).join(' ')}`,
+ preflight,
+ readiness,
+ };
+ }
+ return { app, provider, preflight, readiness };
};
async function queueOneTask({ request, taskId, apps }) {
@@ -282,6 +302,7 @@ const eventDataFor = (request, outcome, displayText) => ({
effort: request.effort || null,
planOnly: request.planOnly === true,
prCompletion: request.prCompletion || null,
+ requiredValidation: request.requiredValidation || [],
...(outcome ? {
success: outcome.success === true,
duplicate: outcome.duplicate === true,
diff --git a/server/services/persistentMindTaskCapability.test.js b/server/services/persistentMindTaskCapability.test.js
index 1d0eb52fa8..26a36620cd 100644
--- a/server/services/persistentMindTaskCapability.test.js
+++ b/server/services/persistentMindTaskCapability.test.js
@@ -13,6 +13,8 @@ const mocks = vi.hoisted(() => ({
getAppWorkTracker: vi.fn(),
resolveAppWorkTracker: vi.fn(),
getProviderPrerequisiteReadinessMap: vi.fn(),
+ workspacePreflight: vi.fn(),
+ assessWorkspaceReadiness: vi.fn(),
}));
vi.mock('./apps.js', () => ({
@@ -31,6 +33,10 @@ vi.mock('./providerPrerequisites.js', () => ({
vi.mock('../lib/workTracker.js', () => ({
resolveAppWorkTracker: (...args) => mocks.resolveAppWorkTracker(...args),
}));
+vi.mock('./persistentMindWorkspacePreflight.js', () => ({
+ readPersistentMindWorkspacePreflight: (...args) => mocks.workspacePreflight(...args),
+ assessPersistentMindWorkspaceReadiness: (...args) => mocks.assessWorkspaceReadiness(...args),
+}));
const {
buildPersistentMindTaskCapabilityPrompt,
@@ -66,6 +72,13 @@ beforeEach(() => {
mocks.getProviderPrerequisiteReadinessMap.mockImplementation((providers) => Object.fromEntries(
providers.map((provider) => [provider.id, { status: 'ready', reasonCodes: [] }]),
));
+ mocks.workspacePreflight.mockResolvedValue({ readiness: 'ready', warnings: [] });
+ mocks.assessWorkspaceReadiness.mockImplementation((preflight, requiredValidation) => ({
+ readiness: preflight.readiness,
+ requiredValidation: requiredValidation || [],
+ blockers: [],
+ warnings: preflight.warnings,
+ }));
});
describe('persistent mind CoS-task capability', () => {
@@ -169,6 +182,25 @@ describe('persistent mind CoS-task capability', () => {
expect(recordCapabilityEvent.mock.calls.map(([event]) => event.kind)).toEqual(['request', 'result']);
});
+ it('blocks only the validation checks a task explicitly requires', async () => {
+ mocks.workspacePreflight.mockResolvedValue({ readiness: 'degraded', warnings: [] });
+ mocks.assessWorkspaceReadiness.mockReturnValue({
+ readiness: 'blocked',
+ requiredValidation: ['dependencies'],
+ blockers: [{ check: 'dependencies', status: 'unavailable', message: 'Dependencies are absent.' }],
+ warnings: [],
+ });
+
+ const [result] = await executePersistentMindTaskRequests({
+ taskRequests: [taskRequest({ requiredValidation: ['dependencies'] })],
+ turnId: 'turn-required-validation',
+ wake: { kind: 'message', message: { id: 'message-required-validation' } },
+ });
+
+ expect(result).toMatchObject({ success: false, error: expect.stringContaining('Dependencies are absent') });
+ expect(mocks.addTask).not.toHaveBeenCalled();
+ });
+
it('queues plan-and-file mode only for an app with an issue tracker', async () => {
mocks.getAppWorkTracker.mockResolvedValue({ resolved: 'github' });
const results = await executePersistentMindTaskRequests({
diff --git a/server/services/persistentMindVisibility.js b/server/services/persistentMindVisibility.js
new file mode 100644
index 0000000000..6888226689
--- /dev/null
+++ b/server/services/persistentMindVisibility.js
@@ -0,0 +1,261 @@
+/**
+ * Shared privacy-safe visibility projection for the persistent mind.
+ *
+ * The projection is intentionally narrower than the underlying services. It
+ * is the one object used by the mind prompt and the authenticated visibility
+ * endpoint; the UI consumes that endpoint rather than rebuilding readiness
+ * from unrelated health APIs.
+ */
+
+import { getDomainMode } from '../lib/domainAutonomy.js';
+import {
+ normalizePersistentMindCapabilities,
+ PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION,
+ PERSISTENT_MIND_TOOL_CATALOG,
+} from '../lib/persistentMindCapabilities.js';
+import { getActiveApps } from './apps.js';
+import { inspectPersistentMindRuntime } from './persistentMindRuntime.js';
+import { readPersistentMindWorkspacePreflights, PERSISTENT_MIND_WORKSPACE_PREFLIGHT_TTL_MS } from './persistentMindWorkspacePreflight.js';
+
+export const PERSISTENT_MIND_VISIBILITY_SCHEMA_VERSION = 1;
+export const PERSISTENT_MIND_VISIBILITY_LIMITS = Object.freeze({
+ maxApps: 25,
+ maxPromptChars: 20_000,
+});
+
+const safePromise = (promise) => Promise.resolve(promise)
+ .then((value) => ({ value, ok: true }), () => ({ value: null, ok: false }));
+
+const contextPressure = (context) => {
+ const chars = Number(context?.chars);
+ const maxChars = Number(context?.maxChars);
+ if (!Number.isFinite(chars) || !Number.isFinite(maxChars) || maxChars <= 0) return 'unknown';
+ const ratio = chars / maxChars;
+ return ratio >= 0.9 ? 'critical' : ratio >= 0.75 ? 'elevated' : 'nominal';
+};
+
+const memoryPressure = (memory) => {
+ const usage = Number(memory?.usagePercent);
+ if (!Number.isFinite(usage)) return 'unknown';
+ return usage >= 95 ? 'critical' : usage >= 80 ? 'elevated' : 'nominal';
+};
+
+const harnessProjection = (provider) => ({
+ type: provider?.type || null,
+ configured: Boolean(provider),
+ readiness: provider ? 'configured' : 'unknown',
+});
+
+const activeAgentCount = (state) => Object.values(state?.agents || {})
+ .filter((agent) => ['starting', 'running', 'thinking', 'working'].includes(agent?.status))
+ .length;
+
+const schedulerProjection = (root, state) => {
+ const config = root?.config || {};
+ const limit = Number.isInteger(config.maxConcurrentAgents) ? config.maxConcurrentAgents : null;
+ const active = activeAgentCount(state);
+ return {
+ autonomy: getDomainMode(config, 'cos'),
+ capacity: {
+ active,
+ limit,
+ status: limit === null ? 'unknown' : active < limit ? 'available' : 'full',
+ },
+ budget: {
+ configured: Boolean(config.domainBudgets?.cos),
+ status: config.domainBudgets?.cos ? 'configured' : 'unlimited',
+ },
+ };
+};
+
+const actionProjection = (root) => {
+ const capabilities = normalizePersistentMindCapabilities(root?.config?.persistentMindCapabilities);
+ return {
+ schemaVersion: PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION,
+ grants: capabilities,
+ tools: PERSISTENT_MIND_TOOL_CATALOG.map((tool) => ({
+ id: tool.id,
+ name: tool.name,
+ kind: tool.kind,
+ granted: capabilities[tool.capability] === true,
+ })),
+ };
+};
+
+const runtimeProjection = (result) => {
+ if (!result) {
+ return {
+ status: 'unknown',
+ harness: { type: null, configured: false, readiness: 'unknown' },
+ context: { pressure: 'unknown', summaryState: 'unknown' },
+ model: { active: null, residency: 'unknown' },
+ system: { memory: 'unknown', cpu: 'unknown' },
+ };
+ }
+ return {
+ status: 'ready',
+ harness: null,
+ context: {
+ pressure: contextPressure(result.context),
+ summaryState: result.context?.summaryState || 'unknown',
+ approximateTokens: Number.isFinite(result.context?.approximateTokens) ? result.context.approximateTokens : null,
+ maxChars: Number.isFinite(result.context?.maxChars) ? result.context.maxChars : null,
+ },
+ model: {
+ active: result.inference?.active === true,
+ residency: result.inference?.residency?.status || 'unknown',
+ },
+ system: {
+ memory: memoryPressure(result.system?.memory),
+ cpu: result.system?.cpu ? 'available' : 'unknown',
+ },
+ };
+};
+
+const providerProjection = (provider, runtime) => ({
+ status: provider ? 'configured' : 'unknown',
+ type: provider?.type || null,
+ harness: harnessProjection(provider),
+ runtime: runtime?.inference?.residency?.status || 'unknown',
+});
+
+const forgeStatus = (entries) => {
+ const statuses = entries.map((entry) => entry.preflight?.forge?.status).filter(Boolean);
+ if (!statuses.length) return 'unknown';
+ if (statuses.includes('ready')) return 'ready';
+ if (statuses.includes('unavailable')) return 'unavailable';
+ if (statuses.includes('unknown')) return 'unknown';
+ return 'not-configured';
+};
+
+const workspaceProjection = (entries) => entries.map((entry) => ({
+ appId: entry.appId,
+ appName: entry.appName,
+ readiness: entry.preflight.readiness,
+ preflight: entry.preflight,
+}));
+
+const boundWorkspaces = (visibility, maxChars = PERSISTENT_MIND_VISIBILITY_LIMITS.maxPromptChars) => {
+ const sourceVisibility = visibility && typeof visibility === 'object' && !Array.isArray(visibility) ? visibility : {};
+ const source = Array.isArray(sourceVisibility.workspaces) ? sourceVisibility.workspaces : [];
+ const base = { ...sourceVisibility, workspaces: [], truncated: Boolean(sourceVisibility.truncated) };
+ delete base.characterBudget;
+ const buildCandidate = (workspaces, truncated) => {
+ const candidate = {
+ ...base,
+ workspaces,
+ truncated,
+ characterBudget: { maxChars, chars: 0, truncated },
+ };
+ const chars = JSON.stringify(candidate).length;
+ return {
+ ...candidate,
+ characterBudget: { maxChars, chars, truncated },
+ };
+ };
+ let workspaces = [];
+ let truncated = Boolean(sourceVisibility.truncated);
+ let result = buildCandidate(workspaces, truncated);
+ for (const workspace of source) {
+ const candidateWorkspaces = [...workspaces, workspace];
+ const candidate = buildCandidate(candidateWorkspaces, truncated);
+ if (JSON.stringify(candidate).length > maxChars) {
+ truncated = true;
+ break;
+ }
+ workspaces = candidateWorkspaces;
+ result = candidate;
+ }
+ result = buildCandidate(workspaces, truncated);
+ while (JSON.stringify(result).length > maxChars && workspaces.length > 0) {
+ workspaces = workspaces.slice(0, -1);
+ truncated = true;
+ result = buildCandidate(workspaces, truncated);
+ }
+ return result;
+};
+
+const reasonCodes = (visibility) => [
+ ...(Array.isArray(visibility?.workspaces) ? visibility.workspaces.flatMap((entry) => (
+ Array.isArray(entry.preflight?.warnings) ? entry.preflight.warnings.map((warning) => warning.code) : []
+ )) : []),
+ ...(visibility?.runtime?.status === 'unknown' ? ['runtime-unknown'] : []),
+ ...(visibility?.sections?.workspace?.freshness === 'unknown' ? ['workspace-unknown'] : []),
+].filter((code, index, codes) => typeof code === 'string' && codes.indexOf(code) === index).slice(0, 50);
+
+/**
+ * Build the shared visibility object. `apps` and `providers` are injectable so
+ * callers can reuse one registry snapshot; omitted values are read normally.
+ */
+export async function readPersistentMindVisibility({
+ root = {},
+ state = null,
+ profile = null,
+ prompt = null,
+ provider = null,
+ apps,
+ force = false,
+ now = Date.now,
+ dependencies,
+} = {}) {
+ const timestamp = typeof now === 'function' ? now() : now;
+ const capturedAt = new Date(Number.isFinite(timestamp) ? timestamp : Date.now()).toISOString();
+ const appsResult = Array.isArray(apps) ? { value: apps, ok: true } : await safePromise(getActiveApps());
+ const runtimeResult = await safePromise(inspectPersistentMindRuntime({ state, profile, prompt, provider }));
+ const candidates = appsResult.ok ? appsResult.value : [];
+ const workspaceResult = await safePromise(readPersistentMindWorkspacePreflights(candidates, {
+ force,
+ now: timestamp,
+ dependencies,
+ }));
+ const workspaceEntries = workspaceResult.ok && Array.isArray(workspaceResult.value) ? workspaceResult.value : [];
+ const workspaces = workspaceProjection(workspaceEntries);
+ const runtime = runtimeResult.value;
+ const projectedRuntime = runtimeProjection(runtime);
+ const visibility = {
+ schemaVersion: PERSISTENT_MIND_VISIBILITY_SCHEMA_VERSION,
+ capturedAt,
+ freshness: {
+ state: 'fresh',
+ capturedAt,
+ ageMs: 0,
+ ttlMs: PERSISTENT_MIND_WORKSPACE_PREFLIGHT_TTL_MS,
+ },
+ truncated: candidates.length > PERSISTENT_MIND_VISIBILITY_LIMITS.maxApps
+ || workspaceEntries.some((entry) => entry.preflight.truncated),
+ readiness: appsResult.ok && workspaceResult.ok && runtimeResult.ok && workspaces.every((workspace) => workspace.readiness !== 'blocked')
+ ? workspaces.some((workspace) => workspace.readiness === 'unknown') ? 'unknown'
+ : workspaces.some((workspace) => workspace.readiness === 'degraded') ? 'degraded' : 'ready'
+ : appsResult.ok && workspaceResult.ok && runtimeResult.ok ? 'blocked' : 'unknown',
+ sections: {
+ runtime: { freshness: runtimeResult.ok ? 'fresh' : 'unknown' },
+ workspace: {
+ freshness: !appsResult.ok || !workspaceResult.ok ? 'unknown'
+ : workspaces.some((workspace) => workspace.preflight.freshness.state === 'stale') ? 'stale' : 'fresh',
+ },
+ },
+ runtime: projectedRuntime,
+ harness: projectedRuntime.harness || harnessProjection(provider),
+ provider: providerProjection(provider, runtime),
+ actions: actionProjection(root),
+ scheduler: schedulerProjection(root, state),
+ workspaces,
+ health: {
+ system: runtimeResult.ok ? 'available' : 'unknown',
+ provider: provider ? 'configured' : 'unknown',
+ database: runtimeResult.ok ? 'available' : 'unknown',
+ forge: workspaceResult.ok ? forgeStatus(workspaceEntries) : 'unknown',
+ },
+ surfaces: ['mind/context', 'mind/runtime', 'mind/tools', 'mind/visibility', 'workspace-preflight'],
+ reasonCodes: [],
+ };
+ visibility.reasonCodes = reasonCodes(visibility);
+ return boundWorkspaces(visibility);
+}
+
+/** Render the exact bounded projection sent to the persistent-mind prompt. */
+export function buildPersistentMindVisibilityPrompt(visibility) {
+ return `# Persistent Mind environment visibility
+The following is a read-only, bounded semantic snapshot. It contains no repository paths, remotes, branch names, command output, credentials, usernames, or repository contents. Treat unknown and unavailable values as real constraints; do not invent a successful probe.
+${JSON.stringify(boundWorkspaces(visibility || {}, Math.max(0, PERSISTENT_MIND_VISIBILITY_LIMITS.maxPromptChars - 350)))}`;
+}
diff --git a/server/services/persistentMindVisibility.test.js b/server/services/persistentMindVisibility.test.js
new file mode 100644
index 0000000000..2742a92025
--- /dev/null
+++ b/server/services/persistentMindVisibility.test.js
@@ -0,0 +1,105 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ getActiveApps: vi.fn(),
+ inspectRuntime: vi.fn(),
+ readPreflights: vi.fn(),
+}));
+
+vi.mock('./apps.js', () => ({ getActiveApps: mocks.getActiveApps }));
+vi.mock('./persistentMindRuntime.js', () => ({ inspectPersistentMindRuntime: mocks.inspectRuntime }));
+vi.mock('./persistentMindWorkspacePreflight.js', () => ({
+ PERSISTENT_MIND_WORKSPACE_PREFLIGHT_TTL_MS: 30_000,
+ readPersistentMindWorkspacePreflights: (...args) => mocks.readPreflights(...args),
+}));
+
+const { buildPersistentMindVisibilityPrompt, readPersistentMindVisibility } = await import('./persistentMindVisibility.js');
+
+const preflight = {
+ schemaVersion: 1,
+ capturedAt: '2026-08-27T12:00:00.000Z',
+ freshness: { state: 'fresh', capturedAt: '2026-08-27T12:00:00.000Z', ageMs: 0, ttlMs: 30_000 },
+ truncated: false,
+ workspaceDiscovery: 'ready',
+ readiness: 'degraded',
+ repository: { configured: true, reachable: true },
+ checkout: { state: 'clean' },
+ workspaces: [{
+ id: 'root',
+ manifest: 'ready',
+ lockfile: { status: 'present', type: 'npm', scope: 'workspace' },
+ dependencies: { status: 'absent', source: null },
+ engines: { node: { required: '>=22.12.0', actual: '24.0.0', status: 'compatible' }, packageManager: null },
+ scripts: { test: ['test'], build: ['build'] },
+ }],
+ submodules: { configured: false, status: 'not-configured', initialized: null },
+ forge: { provider: 'github', cli: 'gh', installed: true, authenticated: true, status: 'ready' },
+ reviewers: {
+ configured: 1,
+ required: { configured: 1, available: 1, unavailable: 0, unknown: 0, status: 'ready' },
+ optional: { configured: 0, available: 0, unavailable: 0, unknown: 0, status: 'not-configured' },
+ status: 'ready',
+ },
+ warnings: [{ code: 'workspace-dependencies-unavailable', check: 'dependencies', severity: 'warning', message: 'Dependencies are absent.' }],
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getActiveApps.mockResolvedValue([{ id: 'example-app', name: 'Example App', repoPath: '/private/example-app' }]);
+ mocks.inspectRuntime.mockResolvedValue({
+ inference: { active: false, residency: { status: 'provider-managed' } },
+ context: { chars: 100, maxChars: 1_000, approximateTokens: 25, summaryState: 'current' },
+ system: { memory: { usagePercent: 40 } },
+ });
+ mocks.readPreflights.mockResolvedValue([{ appId: 'example-app', appName: 'Example App', preflight }]);
+});
+
+describe('persistent mind visibility', () => {
+ it('projects shared runtime, actions, scheduler, health, and workspace facts', async () => {
+ const visibility = await readPersistentMindVisibility({
+ root: { config: { persistentMindCapabilities: { createTasks: true }, domainAutonomy: { cos: 'execute' } } },
+ state: { agents: {}, status: 'idle' },
+ profile: { providerId: 'example-provider' },
+ prompt: { identity: 'Example identity' },
+ provider: { id: 'example-provider', type: 'api' },
+ apps: [{ id: 'example-app', name: 'Example App', repoPath: '/private/example-app' }],
+ now: 1_000,
+ });
+
+ expect(visibility).toMatchObject({
+ schemaVersion: 1,
+ readiness: 'degraded',
+ runtime: { status: 'ready', context: { pressure: 'nominal' } },
+ provider: { status: 'configured', type: 'api' },
+ actions: { grants: { createTasks: true }, tools: [expect.objectContaining({ id: 'cos.create-task', granted: true })] },
+ scheduler: { autonomy: 'execute', capacity: { status: 'unknown' } },
+ health: { system: 'available', provider: 'configured', database: 'available', forge: 'ready' },
+ workspaces: [{ appId: 'example-app', readiness: 'degraded', preflight: { repository: { reachable: true } } }],
+ surfaces: expect.arrayContaining(['mind/visibility', 'workspace-preflight']),
+ });
+
+ const prompt = buildPersistentMindVisibilityPrompt(visibility);
+ expect(prompt).toContain('workspace-dependencies-unavailable');
+ expect(prompt).not.toContain('/private/example-app');
+ expect(prompt).not.toContain('git@');
+ expect(JSON.stringify(visibility)).not.toContain('/private/example-app');
+ });
+
+ it('bounds large workspace projections while retaining an explicit truncation signal', async () => {
+ const apps = Array.from({ length: 30 }, (_, index) => ({
+ id: `example-${index}`,
+ name: `Example App ${index}`,
+ repoPath: `/private/example-${index}`,
+ }));
+ mocks.readPreflights.mockResolvedValue(apps.map((app) => ({
+ appId: app.id,
+ appName: app.name,
+ preflight: { ...preflight, warnings: [] },
+ })));
+
+ const visibility = await readPersistentMindVisibility({ apps, now: 2_000 });
+ expect(visibility.truncated).toBe(true);
+ expect(visibility.characterBudget).toMatchObject({ maxChars: 20_000, truncated: true });
+ expect(JSON.stringify(visibility).length).toBeLessThanOrEqual(21_000);
+ });
+});
diff --git a/server/services/persistentMindWorkspacePreflight.js b/server/services/persistentMindWorkspacePreflight.js
new file mode 100644
index 0000000000..873ea6601c
--- /dev/null
+++ b/server/services/persistentMindWorkspacePreflight.js
@@ -0,0 +1,851 @@
+/**
+ * Read-only, bounded workspace readiness probes for the persistent mind.
+ *
+ * This module deliberately returns semantic facts only. Probe output, paths,
+ * branch names, remotes, and arbitrary configuration values never cross the
+ * service boundary. The in-memory cache is per PortOS process and is a
+ * diagnostic freshness aid, not a persisted source of truth.
+ */
+
+import { opendir, readFile, readdir, stat } from 'fs/promises';
+import { isAbsolute, join, relative, resolve } from 'path';
+import { promisify } from 'util';
+import { execFile } from '../lib/childProcess.js';
+import { commandExists } from '../lib/commandExists.js';
+import { execGit } from '../lib/execGit.js';
+import { parseGitRemote } from '../lib/gitForge.js';
+import { readOriginRemoteUrl } from '../lib/gitRemote.js';
+import { withSpawnCwdEnv } from '../lib/spawnCwd.js';
+import {
+ PERSISTENT_MIND_VALIDATION_CHECKS,
+} from '../lib/persistentMindCapabilities.js';
+import {
+ isCliReviewer,
+ REVIEWER_VALUES,
+} from '../lib/validation.js';
+import { compareVersions } from '../../scripts/checkNodeVersion.js';
+import * as codeReview from './codeReview.js';
+
+const execFileAsync = promisify(execFile);
+
+export const PERSISTENT_MIND_WORKSPACE_PREFLIGHT_SCHEMA_VERSION = 1;
+export const PERSISTENT_MIND_WORKSPACE_PREFLIGHT_TTL_MS = 30_000;
+export const PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS = Object.freeze({
+ maxApps: 25,
+ maxAppIdChars: 128,
+ maxAppNameChars: 100,
+ maxWorkspaces: 20,
+ maxDirectoryEntries: 100,
+ maxPackageManifestBytes: 256 * 1024,
+ maxScriptNames: 20,
+ maxScriptNameChars: 100,
+ maxWorkspaceIdChars: 200,
+ maxEngineRequirementChars: 200,
+ maxGitOutputBytes: 64 * 1024,
+ probeTimeoutMs: 5_000,
+});
+
+const LOCKFILES = Object.freeze([
+ { filename: 'package-lock.json', type: 'npm' },
+ { filename: 'npm-shrinkwrap.json', type: 'npm-shrinkwrap' },
+ { filename: 'pnpm-lock.yaml', type: 'pnpm' },
+ { filename: 'yarn.lock', type: 'yarn' },
+ { filename: 'bun.lockb', type: 'bun' },
+ { filename: 'bun.lock', type: 'bun' },
+]);
+
+const PACKAGE_MANAGER_COMMANDS = Object.freeze({ npm: 'npm', pnpm: 'pnpm', yarn: 'yarn', bun: 'bun' });
+const FORGE_COMMANDS = Object.freeze({ github: 'gh', gitlab: 'glab' });
+const FORGE_AUTH_ARGS = Object.freeze({
+ github: ['auth', 'status'],
+ gitlab: ['auth', 'status'],
+});
+const FORGE_TRACKERS = new Set(['github', 'gitlab']);
+const NON_FORGE_TRACKERS = new Set(['plan', 'jira']);
+
+const defaultDependencies = {
+ readFile,
+ readdir,
+ opendir,
+ stat,
+ execGit,
+ commandExists,
+ execFile: execFileAsync,
+ readOriginRemoteUrl,
+ getCodeReviewDefaults: (...args) => typeof codeReview.getCodeReviewDefaults === 'function'
+ ? codeReview.getCodeReviewDefaults(...args)
+ : Promise.resolve(null),
+ getReviewerCliInstalled: (...args) => typeof codeReview.getReviewerCliInstalled === 'function'
+ ? codeReview.getReviewerCliInstalled(...args)
+ : Promise.resolve(null),
+};
+
+const cache = new Map();
+
+const isRecord = (value) => value && typeof value === 'object' && !Array.isArray(value);
+
+const nowValue = (clock) => {
+ const value = typeof clock === 'function' ? clock() : clock;
+ return Number.isFinite(value) ? value : Date.now();
+};
+
+const isMissing = (error) => error?.code === 'ENOENT';
+
+const isPathLike = (value) => typeof value === 'string' && (
+ isAbsolute(value)
+ || /^[A-Za-z]:[\\/]/.test(value)
+ || /^~[\\/]/.test(value)
+);
+
+const isTimeout = (error) => Boolean(
+ error?.code === 'ETIMEDOUT'
+ || error?.killed === true
+ || error?.signal === 'SIGTERM'
+);
+
+const normalizeRelativePath = (value) => {
+ if (typeof value !== 'string') return null;
+ const normalized = value.trim().replaceAll('\\', '/');
+ if (!normalized || normalized === '.') return '.';
+ if (normalized.length > PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS.maxWorkspaceIdChars) return null;
+ if (normalized.startsWith('/') || /^[A-Za-z]:\//.test(normalized) || isAbsolute(normalized)) return null;
+ const parts = normalized.split('/').filter(Boolean);
+ if (parts.some((part) => part === '..' || part === '.')) return null;
+ return parts.join('/');
+};
+
+const relativeWorkspaceId = (repoPath, workspacePath) => {
+ const value = relative(repoPath, workspacePath).replaceAll('\\', '/');
+ return (value || 'root').slice(0, PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS.maxWorkspaceIdChars);
+};
+
+const pathForWorkspace = (repoPath, workspaceId) => resolve(repoPath, workspaceId === 'root' ? '.' : workspaceId);
+
+const readPathState = (filePath, dependencies) => dependencies.stat(filePath)
+ .then((info) => ({
+ state: 'present',
+ isDirectory: typeof info?.isDirectory === 'function' ? info.isDirectory() : null,
+ size: Number.isFinite(info?.size) ? Number(info.size) : null,
+ }))
+ .catch((error) => ({ state: isMissing(error) ? 'missing' : 'unknown' }));
+
+const readPackageManifest = (filePath, dependencies) => dependencies.stat(filePath)
+ .then((info) => {
+ if (Number.isFinite(info?.size) && info.size > PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS.maxPackageManifestBytes) {
+ return { state: 'truncated', value: null };
+ }
+ return dependencies.readFile(filePath, 'utf8')
+ .then((content) => Promise.resolve().then(() => JSON.parse(String(content))))
+ .then((value) => ({ state: isRecord(value) ? 'ready' : 'unknown', value: isRecord(value) ? value : null }))
+ .catch((error) => ({
+ state: isMissing(error) ? 'missing' : 'unknown',
+ value: null,
+ }));
+ })
+ .catch((error) => ({ state: isMissing(error) ? 'missing' : 'unknown', value: null }));
+
+const readDirectoryEntries = async (directoryPath, dependencies) => {
+ // Keep an injected array reader useful for fixture tests, while the real
+ // probe streams directory entries and stops after the safety bound plus one
+ // sentinel. `readdir()` materializes an arbitrarily large directory before
+ // the slice can be applied.
+ if (dependencies.readdir !== readdir) return dependencies.readdir(directoryPath, { withFileTypes: true });
+ const directory = await dependencies.opendir(directoryPath);
+ const entries = [];
+ for await (const entry of directory) {
+ entries.push(entry);
+ if (entries.length > PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS.maxDirectoryEntries) break;
+ }
+ return entries;
+};
+
+const readDirectoryNames = (directoryPath, dependencies) => Promise.resolve()
+ .then(() => readDirectoryEntries(directoryPath, dependencies))
+ .then((entries) => {
+ const bounded = Array.isArray(entries) ? entries.slice(0, PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS.maxDirectoryEntries) : [];
+ return {
+ names: bounded
+ .filter((entry) => typeof entry?.name === 'string' && (typeof entry.isDirectory !== 'function' || entry.isDirectory()))
+ .map((entry) => entry.name)
+ .sort(),
+ truncated: Array.isArray(entries) && entries.length > bounded.length,
+ unknown: false,
+ };
+ })
+ .catch(() => ({ names: [], truncated: false, unknown: true }));
+
+const workspacePatterns = (manifest) => {
+ const raw = manifest?.workspaces;
+ if (Array.isArray(raw)) return raw;
+ if (isRecord(raw) && Array.isArray(raw.packages)) return raw.packages;
+ return [];
+};
+
+const safeEngineRequirement = (value) => {
+ if (typeof value !== 'string' || !value.trim()) return null;
+ const normalized = value.trim();
+ return /^[vV0-9xX*<>=~^|.,\s-]+$/.test(normalized)
+ ? normalized.slice(0, PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS.maxEngineRequirementChars)
+ : 'unknown';
+};
+
+const expandWorkspacePattern = (repoPath, pattern, dependencies) => {
+ const normalized = normalizeRelativePath(pattern);
+ if (!normalized) return Promise.resolve({ paths: [], truncated: true });
+ const segments = normalized.split('/');
+ const hasGlob = segments.some((segment) => segment === '*');
+ if (!hasGlob) return Promise.resolve({ paths: [pathForWorkspace(repoPath, normalized)], truncated: false });
+ if (segments.some((segment) => segment !== '*' && /[*?\[\]]/.test(segment))) {
+ return Promise.resolve({ paths: [], truncated: true });
+ }
+
+ const walk = (basePath, index) => {
+ if (index >= segments.length) return Promise.resolve([basePath]);
+ const segment = segments[index];
+ if (segment !== '*') return walk(join(basePath, segment), index + 1);
+ return readDirectoryNames(basePath, dependencies).then(({ names, truncated, unknown }) => (
+ Promise.all(names.map((name) => walk(join(basePath, name), index + 1)))
+ .then((groups) => ({ paths: groups.flat(), truncated, unknown }))
+ ));
+ };
+
+ return walk(repoPath, 0).then((result) => Array.isArray(result) ? { paths: result, truncated: false } : result);
+};
+
+const discoverWorkspacePaths = async (repoPath, manifest, dependencies) => {
+ const patterns = workspacePatterns(manifest);
+ if (!patterns.length) return { paths: [repoPath], truncated: false };
+ const expanded = await Promise.all(patterns.slice(0, PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS.maxWorkspaces).map(
+ (pattern) => expandWorkspacePattern(repoPath, pattern, dependencies)
+ ));
+ const paths = [repoPath, ...expanded.flatMap((item) => item.paths || [])];
+ const unique = [...new Set(paths)].slice(0, PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS.maxWorkspaces);
+ return {
+ paths: unique,
+ truncated: patterns.length > PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS.maxWorkspaces
+ || expanded.some((item) => item.truncated)
+ || paths.length > unique.length,
+ unknown: expanded.some((item) => item.unknown),
+ };
+};
+
+const scriptNames = (manifest) => {
+ const scripts = isRecord(manifest?.scripts) ? Object.keys(manifest.scripts) : [];
+ const pick = (prefix) => scripts
+ .filter((name) => name === prefix || name.startsWith(`${prefix}:`) || name.startsWith(`${prefix}-`))
+ .sort()
+ .slice(0, PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS.maxScriptNames);
+ const bound = (names) => names.map((name) => name.slice(0, PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS.maxScriptNameChars));
+ return { test: bound(pick('test')), build: bound(pick('build')) };
+};
+
+const engineRequirements = (manifest) => {
+ const engines = isRecord(manifest?.engines) ? manifest.engines : {};
+ const manager = Object.keys(PACKAGE_MANAGER_COMMANDS).find((name) => typeof engines[name] === 'string' && engines[name].trim());
+ const packageManager = typeof manifest?.packageManager === 'string'
+ ? manifest.packageManager.trim().match(/^([a-z]+)@(.+)$/i)
+ : null;
+ const packageManagerName = packageManager && PACKAGE_MANAGER_COMMANDS[packageManager[1].toLowerCase()]
+ ? packageManager[1].toLowerCase()
+ : manager || null;
+ const packageManagerRequirement = packageManagerName
+ ? (safeEngineRequirement(engines[packageManagerName])
+ || (packageManager?.[2] ? /^v?\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?$/.test(packageManager[2].trim())
+ ? `=${packageManager[2].trim().slice(0, PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS.maxEngineRequirementChars - 1)}`
+ : 'unknown' : null))
+ : null;
+ return {
+ node: safeEngineRequirement(engines.node),
+ packageManager: packageManagerName ? {
+ name: packageManagerName,
+ required: packageManagerRequirement,
+ } : null,
+ };
+};
+
+/**
+ * Compare a tool version against the small, portable subset of npm engine
+ * ranges used by PortOS manifests. It intentionally does not pretend to be a
+ * complete semver implementation; unsupported syntax is unknown to callers.
+ */
+export function satisfiesVersionRequirement(version, requirement) {
+ if (typeof version !== 'string' || !version.trim() || typeof requirement !== 'string' || !requirement.trim()) return null;
+ if (!/^v?\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?$/.test(version.trim())) return null;
+ const alternatives = requirement.split('||').map((part) => part.trim()).filter(Boolean);
+ if (!alternatives.length) return null;
+
+ const satisfiesComparator = (candidate, comparator) => {
+ const token = comparator.trim();
+ if (!token || token === '*' || /^x$/i.test(token)) return true;
+ const match = token.match(/^(>=|<=|>|<|=|\^|~)?\s*(v?\d+(?:\.\d+){0,2})(?:\.[xX*])?$/);
+ if (!match) return null;
+ const operator = match[1] || '=';
+ const target = match[2];
+ const comparison = compareVersions(candidate, target);
+ const numericParts = target.replace(/^v/, '').split('.').map((part) => Number(part));
+ const major = numericParts[0];
+ const minor = numericParts[1] || 0;
+ const patch = numericParts[2] || 0;
+ const isPartial = numericParts.length < 3 || /(?:^|\.)[xX*]$/.test(token);
+ const partialUpper = numericParts.length < 2
+ ? `${major + 1}.0.0`
+ : `${major}.${minor + 1}.0`;
+ if (operator === '=' && isPartial) {
+ return comparison >= 0 && compareVersions(candidate, partialUpper) < 0;
+ }
+ if (operator === '>=') return comparison >= 0;
+ if (operator === '<=') return isPartial
+ ? compareVersions(candidate, partialUpper) < 0
+ : comparison <= 0;
+ if (operator === '>') return comparison > 0;
+ if (operator === '<') return comparison < 0;
+ if (operator === '^') {
+ const upper = major > 0
+ ? `${major + 1}.0.0`
+ : minor > 0
+ ? `0.${minor + 1}.0`
+ : numericParts.length < 3 ? '1.0.0' : `0.0.${patch + 1}`;
+ return comparison >= 0 && compareVersions(candidate, upper) < 0;
+ }
+ if (operator === '=') return comparison === 0;
+ const upper = numericParts.length < 2 ? `${major + 1}.0.0` : `${major}.${minor + 1}.0`;
+ return comparison >= 0 && compareVersions(candidate, upper) < 0;
+ };
+
+ const results = alternatives.map((alternative) => {
+ const comparators = alternative.replaceAll(',', ' ').split(/\s+/).filter(Boolean);
+ const values = comparators.map((comparator) => satisfiesComparator(version, comparator));
+ if (values.some((value) => value === null)) return null;
+ return values.every(Boolean);
+ });
+ if (results.some(Boolean)) return true;
+ if (results.every((value) => value === false)) return false;
+ return null;
+}
+
+const normalizeVersion = (value) => {
+ const match = String(value || '').trim().match(/^v?\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?$/);
+ return match ? match[0].replace(/^v/, '') : null;
+};
+
+const actualVersion = (output) => {
+ const match = String(output || '').match(/\bv?\d+(?:\.\d+){1,2}(?:-[0-9A-Za-z.-]+)?\b/);
+ return normalizeVersion(match?.[0]);
+};
+
+const compatibility = (actual, required) => {
+ const normalizedActual = normalizeVersion(actual);
+ if (!required) return { required: null, actual: normalizedActual, status: 'not-declared' };
+ const result = satisfiesVersionRequirement(normalizedActual, required);
+ return {
+ required,
+ actual: normalizedActual,
+ status: result === true ? 'compatible' : result === false ? 'incompatible' : 'unknown',
+ };
+};
+
+const safeGit = (args, cwd, dependencies) => dependencies.execGit(args, cwd, {
+ ignoreExitCode: true,
+ maxBuffer: PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS.maxGitOutputBytes,
+ timeout: PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS.probeTimeoutMs,
+}).then((result) => result).catch(() => null);
+
+const inspectRepository = async (app, dependencies) => {
+ const repoPath = typeof app?.repoPath === 'string' ? app.repoPath.trim() : '';
+ if (!repoPath) {
+ return {
+ repository: { configured: false, reachable: false },
+ checkout: { state: 'unknown' },
+ origin: null,
+ };
+ }
+ const pathState = await readPathState(repoPath, dependencies);
+ if (pathState.state === 'missing' || pathState.isDirectory === false) {
+ return {
+ repository: { configured: true, reachable: false },
+ checkout: { state: 'unknown' },
+ origin: null,
+ };
+ }
+ if (pathState.state !== 'present') {
+ return {
+ repository: { configured: true, reachable: null },
+ checkout: { state: 'unknown' },
+ origin: null,
+ };
+ }
+ const reachableProbe = await safeGit(['rev-parse', '--is-inside-work-tree'], repoPath, dependencies);
+ if (!reachableProbe) {
+ return {
+ repository: { configured: true, reachable: null },
+ checkout: { state: 'unknown' },
+ origin: null,
+ };
+ }
+ if (reachableProbe.exitCode !== 0 || String(reachableProbe.stdout || '').trim() !== 'true') {
+ return {
+ repository: { configured: true, reachable: false },
+ checkout: { state: 'unknown' },
+ origin: null,
+ };
+ }
+ const [statusProbe, originUrl] = await Promise.all([
+ safeGit(['status', '--porcelain', '--untracked-files=all'], repoPath, dependencies),
+ dependencies.readOriginRemoteUrl(repoPath).catch(() => null),
+ ]);
+ const origin = parseGitRemote(originUrl);
+ return {
+ repository: { configured: true, reachable: true },
+ checkout: {
+ state: statusProbe && statusProbe.exitCode === 0
+ ? String(statusProbe.stdout || '').trim() ? 'dirty' : 'clean'
+ : 'unknown',
+ },
+ origin,
+ };
+};
+
+const inspectLockfile = async (workspacePath, repoPath, dependencies) => {
+ const localChecks = await Promise.all(LOCKFILES.map(async (candidate) => ({
+ ...candidate,
+ result: await readPathState(join(workspacePath, candidate.filename), dependencies),
+ })));
+ const localPresent = localChecks.find((candidate) => candidate.result.state === 'present');
+ if (localPresent) return { status: 'present', type: localPresent.type, scope: 'workspace' };
+ if (localChecks.some((candidate) => candidate.result.state === 'unknown')) {
+ return { status: 'unknown', type: null, scope: null };
+ }
+ if (workspacePath === repoPath) return { status: 'absent', type: null, scope: null };
+ const rootChecks = await Promise.all(LOCKFILES.map(async (candidate) => ({
+ ...candidate,
+ result: await readPathState(join(repoPath, candidate.filename), dependencies),
+ })));
+ const rootPresent = rootChecks.find((candidate) => candidate.result.state === 'present');
+ if (rootPresent) return { status: 'present', type: rootPresent.type, scope: 'root' };
+ if (rootChecks.some((candidate) => candidate.result.state === 'unknown')) {
+ return { status: 'unknown', type: null, scope: null };
+ }
+ return { status: 'absent', type: null, scope: null };
+};
+
+const inspectDependencies = async (workspacePath, repoPath, dependencies) => {
+ const local = await readPathState(join(workspacePath, 'node_modules'), dependencies);
+ if (local.state === 'present' && local.isDirectory !== false) return { status: 'installed', source: 'workspace' };
+ if (local.state === 'unknown') return { status: 'unknown', source: null };
+ if (workspacePath === repoPath) return { status: 'absent', source: null };
+ const root = await readPathState(join(repoPath, 'node_modules'), dependencies);
+ if (root.state === 'present' && root.isDirectory !== false) return { status: 'installed', source: 'root' };
+ if (root.state === 'unknown') return { status: 'unknown', source: null };
+ return { status: 'absent', source: null };
+};
+
+const readManagerVersions = async (names, repoPath, dependencies, runtime) => {
+ const configured = isRecord(runtime?.packageManagerVersions) ? runtime.packageManagerVersions : {};
+ const entries = await Promise.all([...names].map(async (name) => {
+ if (typeof configured[name] === 'string' && configured[name].trim()) return [name, actualVersion(configured[name])];
+ const command = PACKAGE_MANAGER_COMMANDS[name];
+ if (!command) return [name, null];
+ const result = await dependencies.execFile(command, ['--version'], {
+ cwd: repoPath,
+ env: withSpawnCwdEnv(process.env, repoPath),
+ timeout: PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS.probeTimeoutMs,
+ maxBuffer: 4 * 1024,
+ }).catch(() => null);
+ return [name, result ? actualVersion(result.stdout ?? result) : null];
+ }));
+ return Object.fromEntries(entries);
+};
+
+const inspectSubmodules = async (repoPath, dependencies) => {
+ const gitmodules = await readPathState(join(repoPath, '.gitmodules'), dependencies);
+ if (gitmodules.state === 'missing') return { configured: false, status: 'not-configured', initialized: null };
+ if (gitmodules.state !== 'present') return { configured: null, status: 'unknown', initialized: null };
+ const result = await safeGit(['submodule', 'status', '--recursive'], repoPath, dependencies);
+ if (!result || result.exitCode !== 0) return { configured: true, status: 'unknown', initialized: null };
+ const lines = String(result.stdout || '').split(/\r?\n/).filter(Boolean);
+ const uninitialized = lines.some((line) => line.startsWith('-'));
+ return {
+ configured: true,
+ status: uninitialized ? 'uninitialized' : 'initialized',
+ initialized: !uninitialized,
+ };
+};
+
+const forgeTracker = (app, origin) => {
+ if (FORGE_TRACKERS.has(app?.workTracker)) return app.workTracker;
+ if (NON_FORGE_TRACKERS.has(app?.workTracker)) return null;
+ if (origin?.host) {
+ const host = origin.host.toLowerCase();
+ if (host === 'github.com' || /(^|\.)github\./.test(host)) return 'github';
+ if (host === 'gitlab.com' || /(^|\.)gitlab\./.test(host)) return 'gitlab';
+ return 'unknown';
+ }
+ return 'unknown';
+};
+
+const inspectForge = async (app, repository, dependencies) => {
+ const tracker = forgeTracker(app, repository.origin);
+ if (tracker === null) {
+ return { provider: 'none', cli: null, installed: null, authenticated: null, status: 'not-configured' };
+ }
+ if (!FORGE_COMMANDS[tracker]) {
+ return { provider: 'unknown', cli: null, installed: null, authenticated: null, status: 'unknown' };
+ }
+ if (repository.reachable !== true) {
+ return { provider: tracker, cli: FORGE_COMMANDS[tracker], installed: null, authenticated: null, status: 'unknown' };
+ }
+ const cli = FORGE_COMMANDS[tracker];
+ const installed = await dependencies.commandExists(cli, ['--version'], {
+ cwd: typeof app.repoPath === 'string' ? app.repoPath : undefined,
+ timeoutMs: PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS.probeTimeoutMs,
+ }).catch(() => false);
+ if (!installed) return { provider: tracker, cli, installed: false, authenticated: false, status: 'unavailable' };
+ const authResult = await dependencies.execFile(cli, FORGE_AUTH_ARGS[tracker], {
+ cwd: app.repoPath,
+ env: withSpawnCwdEnv(process.env, app.repoPath),
+ timeout: PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS.probeTimeoutMs,
+ maxBuffer: 8 * 1024,
+ }).then(() => true).catch((error) => isTimeout(error) ? null : false);
+ return {
+ provider: tracker,
+ cli,
+ installed: true,
+ authenticated: authResult,
+ status: authResult === true ? 'ready' : authResult === false ? 'unavailable' : 'unknown',
+ };
+};
+
+const reviewerAvailability = (reviewer, forge, installed) => {
+ if (isCliReviewer(reviewer)) return installed && Object.hasOwn(installed, reviewer) ? installed[reviewer] : null;
+ if (reviewer === 'copilot') return forge?.authenticated === true ? true : forge?.authenticated === false ? false : null;
+ return null;
+};
+
+const emptyReviewerSummary = (status = 'unknown') => ({
+ configured: 0,
+ available: 0,
+ unavailable: 0,
+ unknown: 0,
+ status,
+});
+
+const summarizeReviewers = (entries) => {
+ const summary = emptyReviewerSummary(entries.length ? 'unknown' : 'not-configured');
+ summary.configured = entries.length;
+ if (!entries.length) return summary;
+ entries.forEach((entry) => {
+ if (entry.available === true) summary.available += 1;
+ else if (entry.available === false) summary.unavailable += 1;
+ else summary.unknown += 1;
+ });
+ summary.status = summary.unavailable > 0 ? 'unavailable' : summary.unknown > 0 ? 'unknown' : 'ready';
+ return summary;
+};
+
+const inspectReviewers = async (forge, dependencies) => {
+ const [defaults, installed] = await Promise.all([
+ dependencies.getCodeReviewDefaults().catch(() => null),
+ dependencies.getReviewerCliInstalled().catch(() => null),
+ ]);
+ if (!defaults) {
+ return {
+ configured: null,
+ required: emptyReviewerSummary(),
+ optional: emptyReviewerSummary(),
+ status: 'unknown',
+ };
+ }
+ const fixedReviewers = Array.isArray(defaults.reviewers) ? defaults.reviewers.filter((value) => REVIEWER_VALUES.includes(value)) : [];
+ const usernames = Array.isArray(defaults.usernames) ? defaults.usernames.filter((value) => typeof value === 'string' && value.trim()) : [];
+ const optional = new Set(Array.isArray(defaults.optionalReviewers) ? defaults.optionalReviewers : []);
+ const requiredEntries = fixedReviewers
+ .filter((reviewer) => !optional.has(reviewer))
+ .map((reviewer) => ({ available: reviewerAvailability(reviewer, forge, installed) }));
+ const optionalEntries = fixedReviewers
+ .filter((reviewer) => optional.has(reviewer))
+ .map((reviewer) => ({ available: reviewerAvailability(reviewer, forge, installed) }));
+ const usernameAvailability = forge?.authenticated === true ? true : forge?.authenticated === false ? false : null;
+ usernames.forEach((username) => {
+ const identity = `@${username.replace(/^@/, '')}`;
+ const entry = { available: usernameAvailability };
+ if (optional.has(identity)) optionalEntries.push(entry);
+ else requiredEntries.push(entry);
+ });
+ const required = summarizeReviewers(requiredEntries);
+ const optionalSummary = summarizeReviewers(optionalEntries);
+ return {
+ configured: required.configured + optionalSummary.configured,
+ required,
+ optional: optionalSummary,
+ status: required.status === 'unavailable'
+ ? 'unavailable'
+ : required.status === 'unknown'
+ ? 'unknown'
+ : optionalSummary.status === 'unavailable' || optionalSummary.status === 'unknown' ? 'degraded' : 'ready',
+ };
+};
+
+const engineStatus = (workspaces) => workspaces.flatMap((workspace) => [
+ workspace.engines?.node?.status,
+ workspace.engines?.packageManager?.status,
+]).filter(Boolean);
+
+const dependencyStatus = (workspaces) => workspaces.map((workspace) => workspace.dependencies?.status).filter(Boolean);
+
+const checkStatus = (preflight, check) => {
+ if (check === 'dependencies') {
+ const statuses = dependencyStatus(Array.isArray(preflight?.workspaces) ? preflight.workspaces : []);
+ if (preflight?.workspaceDiscovery !== 'ready' || !statuses.length) return 'unknown';
+ return statuses.some((status) => status === 'unknown') ? 'unknown' : statuses.some((status) => status !== 'installed') ? 'unavailable' : 'ready';
+ }
+ if (check === 'engines') {
+ const statuses = engineStatus(Array.isArray(preflight?.workspaces) ? preflight.workspaces : []).filter((status) => status !== 'not-declared');
+ if (preflight?.workspaceDiscovery !== 'ready' || !Array.isArray(preflight?.workspaces) || !preflight.workspaces.every((workspace) => workspace.manifest === 'ready')) return 'unknown';
+ return statuses.some((status) => status === 'unknown') ? 'unknown' : statuses.some((status) => status === 'incompatible') ? 'unavailable' : 'ready';
+ }
+ if (check === 'submodules') {
+ if (preflight?.submodules?.status === 'not-configured') return 'ready';
+ return preflight?.submodules?.status === 'initialized' ? 'ready' : preflight?.submodules?.status === 'uninitialized' ? 'unavailable' : 'unknown';
+ }
+ if (check === 'forge') return ['ready', 'not-configured'].includes(preflight?.forge?.status) ? 'ready' : preflight?.forge?.status === 'unavailable' ? 'unavailable' : 'unknown';
+ if (check === 'reviewers') return ['ready', 'not-configured'].includes(preflight?.reviewers?.required?.status) ? 'ready' : preflight?.reviewers?.required?.status === 'unavailable' ? 'unavailable' : 'unknown';
+ return 'unknown';
+};
+
+const CHECK_MESSAGES = Object.freeze({
+ dependencies: 'Dependencies are absent or could not be verified for a declared workspace.',
+ engines: 'The required Node.js or package-manager engine is incompatible or could not be verified.',
+ submodules: 'One or more configured submodules are not initialized or could not be verified.',
+ forge: 'The configured forge CLI is unavailable or is not authenticated.',
+ reviewers: 'One or more required reviewers are unavailable or could not be verified.',
+});
+
+const buildWarnings = (preflight) => {
+ const warnings = [];
+ if (preflight.checkout?.state === 'dirty') {
+ warnings.push({
+ code: 'workspace-checkout-dirty',
+ check: 'checkout',
+ severity: 'advisory',
+ message: 'The workspace has local changes; delegated work should preserve them.',
+ });
+ }
+ PERSISTENT_MIND_VALIDATION_CHECKS.forEach((check) => {
+ const status = checkStatus(preflight, check);
+ if (status !== 'ready') warnings.push({ code: `workspace-${check}-${status}`, check, severity: 'warning', message: CHECK_MESSAGES[check] });
+ });
+ if (preflight.reviewers.optional.status === 'unavailable' || preflight.reviewers.optional.status === 'unknown') {
+ warnings.push({
+ code: `workspace-reviewers-optional-${preflight.reviewers.optional.status}`,
+ check: 'reviewers',
+ severity: 'advisory',
+ message: 'Optional reviewers are unavailable or could not be verified; they do not block the task.',
+ });
+ }
+ if (preflight.truncated) warnings.push({ code: 'workspace-preflight-truncated', check: 'preflight', severity: 'advisory', message: 'Workspace preflight reached a safety bound; some facts may be unknown.' });
+ return warnings;
+};
+
+const readinessForSnapshot = (repository, checkout, workspaces, submodules, forge, reviewers) => {
+ if (repository.reachable === false) return 'blocked';
+ if (workspaces.some((workspace) => workspace.manifest !== 'ready')) return 'unknown';
+ const engines = engineStatus(workspaces);
+ if (engines.includes('incompatible')) return 'blocked';
+ if (repository.reachable === null || checkout.state === 'unknown' || engines.includes('unknown')) return 'unknown';
+ const degraded = checkout.state === 'dirty'
+ || dependencyStatus(workspaces).some((status) => status !== 'installed')
+ || submodules.status === 'uninitialized'
+ || submodules.status === 'unknown'
+ || forge.status === 'unavailable'
+ || forge.status === 'unknown'
+ || ['unavailable', 'unknown'].includes(reviewers.required.status)
+ || ['unavailable', 'unknown'].includes(reviewers.optional.status);
+ return degraded ? 'degraded' : 'ready';
+};
+
+const unknownSnapshot = (app, capturedAt) => ({
+ schemaVersion: PERSISTENT_MIND_WORKSPACE_PREFLIGHT_SCHEMA_VERSION,
+ capturedAt,
+ freshness: { state: 'fresh', capturedAt, ageMs: 0, ttlMs: PERSISTENT_MIND_WORKSPACE_PREFLIGHT_TTL_MS },
+ truncated: false,
+ workspaceDiscovery: 'unknown',
+ readiness: 'unknown',
+ repository: { configured: Boolean(typeof app?.repoPath === 'string' && app.repoPath.trim()), reachable: null },
+ checkout: { state: 'unknown' },
+ workspaces: [],
+ submodules: { configured: null, status: 'unknown', initialized: null },
+ forge: { provider: 'unknown', cli: null, installed: null, authenticated: null, status: 'unknown' },
+ reviewers: { configured: null, required: emptyReviewerSummary(), optional: emptyReviewerSummary(), status: 'unknown' },
+ warnings: [{ code: 'workspace-preflight-unknown', check: 'preflight', severity: 'warning', message: 'Workspace readiness could not be verified.' }],
+});
+
+const collectPreflight = async (app, options) => {
+ const dependencies = { ...defaultDependencies, ...(options.dependencies || {}) };
+ const timestamp = nowValue(options.now);
+ const capturedAt = new Date(timestamp).toISOString();
+ const repoPath = typeof app?.repoPath === 'string' ? app.repoPath.trim() : '';
+ const normalizedApp = repoPath ? { ...app, repoPath } : app;
+ const repository = await inspectRepository(normalizedApp, dependencies);
+ if (repository.repository.reachable !== true) {
+ const submodules = { configured: null, status: 'unknown', initialized: null };
+ const forge = await inspectForge(normalizedApp, repository.repository, dependencies);
+ const reviewers = await inspectReviewers(forge, dependencies);
+ const snapshot = {
+ schemaVersion: PERSISTENT_MIND_WORKSPACE_PREFLIGHT_SCHEMA_VERSION,
+ capturedAt,
+ freshness: { state: 'fresh', capturedAt, ageMs: 0, ttlMs: PERSISTENT_MIND_WORKSPACE_PREFLIGHT_TTL_MS },
+ truncated: false,
+ workspaceDiscovery: 'unknown',
+ readiness: repository.repository.reachable === false ? 'blocked' : 'unknown',
+ repository: repository.repository,
+ checkout: repository.checkout,
+ workspaces: [],
+ submodules,
+ forge,
+ reviewers,
+ warnings: [],
+ };
+ snapshot.warnings = buildWarnings(snapshot);
+ return snapshot;
+ }
+
+ const rootManifest = await readPackageManifest(join(repoPath, 'package.json'), dependencies);
+ const discovered = await discoverWorkspacePaths(repoPath, rootManifest.value, dependencies);
+ const workspacePaths = discovered.paths.slice(0, PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS.maxWorkspaces);
+ const managerNames = new Set();
+ const manifests = await Promise.all(workspacePaths.map((workspacePath) => (
+ workspacePath === repoPath ? Promise.resolve(rootManifest) : readPackageManifest(join(workspacePath, 'package.json'), dependencies)
+ )));
+ const workspaceFacts = manifests.map((manifest, index) => {
+ const workspacePath = workspacePaths[index];
+ const requirements = engineRequirements(manifest.value);
+ if (requirements.packageManager?.name) managerNames.add(requirements.packageManager.name);
+ return { workspacePath, manifest, requirements };
+ });
+ const managerVersions = await readManagerVersions(managerNames, repoPath, dependencies, options.runtime || {});
+ const nodeVersion = options.runtime?.nodeVersion || process.versions.node || null;
+ const workspaces = await Promise.all(workspaceFacts.map(async ({ workspacePath, manifest, requirements }) => {
+ const manager = requirements.packageManager;
+ return {
+ id: relativeWorkspaceId(repoPath, workspacePath),
+ manifest: manifest.state,
+ lockfile: await inspectLockfile(workspacePath, repoPath, dependencies),
+ dependencies: await inspectDependencies(workspacePath, repoPath, dependencies),
+ engines: {
+ node: compatibility(nodeVersion, requirements.node),
+ packageManager: manager ? {
+ name: manager.name,
+ ...compatibility(managerVersions[manager.name], manager.required),
+ } : null,
+ },
+ scripts: scriptNames(manifest.value),
+ };
+ }));
+ const submodules = await inspectSubmodules(app.repoPath, dependencies);
+ const forge = await inspectForge(normalizedApp, repository.repository, dependencies);
+ const reviewers = await inspectReviewers(forge, dependencies);
+ const snapshot = {
+ schemaVersion: PERSISTENT_MIND_WORKSPACE_PREFLIGHT_SCHEMA_VERSION,
+ capturedAt,
+ freshness: { state: 'fresh', capturedAt, ageMs: 0, ttlMs: PERSISTENT_MIND_WORKSPACE_PREFLIGHT_TTL_MS },
+ truncated: discovered.truncated || workspaceFacts.some(({ manifest }) => manifest.state === 'truncated'),
+ workspaceDiscovery: discovered.unknown ? 'unknown' : discovered.truncated ? 'truncated' : 'ready',
+ readiness: null,
+ repository: repository.repository,
+ checkout: repository.checkout,
+ workspaces,
+ submodules,
+ forge,
+ reviewers,
+ warnings: [],
+ };
+ snapshot.readiness = discovered.unknown || discovered.truncated
+ ? 'unknown'
+ : readinessForSnapshot(repository.repository, repository.checkout, workspaces, submodules, forge, reviewers);
+ snapshot.warnings = buildWarnings(snapshot);
+ return snapshot;
+};
+
+const cacheKeyFor = (app) => `${app?.id || ''}\0${app?.repoPath || ''}\0${app?.workTracker || 'auto'}`;
+
+const withFreshness = (snapshot, timestamp) => {
+ const captured = Date.parse(snapshot.capturedAt);
+ const ageMs = Number.isFinite(captured) ? Math.max(0, timestamp - captured) : null;
+ return {
+ ...snapshot,
+ freshness: {
+ state: ageMs !== null && ageMs <= PERSISTENT_MIND_WORKSPACE_PREFLIGHT_TTL_MS ? 'fresh' : 'stale',
+ capturedAt: snapshot.capturedAt,
+ ageMs,
+ ttlMs: PERSISTENT_MIND_WORKSPACE_PREFLIGHT_TTL_MS,
+ },
+ };
+};
+
+/** Clear the process-local cache; intended for tests and explicit diagnostics. */
+export function resetPersistentMindWorkspacePreflightCache() {
+ cache.clear();
+}
+
+/**
+ * Inspect one configured app. A repeated read within the freshness window does
+ * not re-run git, filesystem, forge, or reviewer probes.
+ */
+export function readPersistentMindWorkspacePreflight(app, { force = false, now = Date.now, dependencies, runtime } = {}) {
+ const timestamp = nowValue(now);
+ const key = cacheKeyFor(app);
+ const cached = cache.get(key);
+ if (!force && cached && cached.expiresAt > timestamp) {
+ return cached.promise.then((snapshot) => withFreshness(snapshot, timestamp));
+ }
+ const promise = collectPreflight(app, { now: timestamp, dependencies, runtime })
+ .catch(() => unknownSnapshot(app, new Date(timestamp).toISOString()));
+ cache.set(key, { promise, expiresAt: timestamp + PERSISTENT_MIND_WORKSPACE_PREFLIGHT_TTL_MS });
+ return promise.then((snapshot) => withFreshness(snapshot, timestamp));
+}
+
+/** Read a bounded set of app preflights, retaining app identity but no paths. */
+export async function readPersistentMindWorkspacePreflights(apps, options = {}) {
+ const candidates = (Array.isArray(apps) ? apps : [])
+ .filter((app) => typeof app?.id === 'string' && app.id.trim()
+ && !isPathLike(app.id.trim())
+ && app.id.length <= PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS.maxAppIdChars)
+ .slice(0, PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS.maxApps);
+ return Promise.all(candidates.map(async (app) => ({
+ appId: app.id.trim(),
+ appName: typeof app.name === 'string' && app.name.trim() && !isPathLike(app.name.trim())
+ ? app.name.trim().slice(0, PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS.maxAppNameChars)
+ : app.id.trim(),
+ preflight: await readPersistentMindWorkspacePreflight(app, options),
+ })));
+}
+
+/**
+ * Apply task-declared validation requirements to a cached preflight. Missing
+ * dependencies remain advisory for tasks that do not declare them, so a
+ * docs-only/read-only task is not incorrectly blocked.
+ */
+export function assessPersistentMindWorkspaceReadiness(preflight, requiredValidation = []) {
+ const required = [...new Set((Array.isArray(requiredValidation) ? requiredValidation : [])
+ .filter((check) => PERSISTENT_MIND_VALIDATION_CHECKS.includes(check)))];
+ const blockers = required
+ .map((check) => ({ check, status: checkStatus(preflight || {}, check) }))
+ .filter(({ status }) => status !== 'ready')
+ .map(({ check, status }) => ({
+ code: `workspace-${check}-${status}`,
+ check,
+ status,
+ message: CHECK_MESSAGES[check],
+ }));
+ const readiness = blockers.length > 0
+ ? 'blocked'
+ : preflight?.readiness || 'unknown';
+ return {
+ readiness,
+ requiredValidation: required,
+ blockers,
+ warnings: Array.isArray(preflight?.warnings) ? preflight.warnings : [],
+ };
+}
+
+export const PERSISTENT_MIND_WORKSPACE_PREFLIGHT_CHECKS = PERSISTENT_MIND_VALIDATION_CHECKS;
diff --git a/server/services/persistentMindWorkspacePreflight.test.js b/server/services/persistentMindWorkspacePreflight.test.js
new file mode 100644
index 0000000000..3d50dfd2d7
--- /dev/null
+++ b/server/services/persistentMindWorkspacePreflight.test.js
@@ -0,0 +1,243 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdir, mkdtemp, rm, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { tmpdir } from 'os';
+
+import {
+ assessPersistentMindWorkspaceReadiness,
+ PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS,
+ PERSISTENT_MIND_WORKSPACE_PREFLIGHT_TTL_MS,
+ readPersistentMindWorkspacePreflight,
+ readPersistentMindWorkspacePreflights,
+ resetPersistentMindWorkspacePreflightCache,
+ satisfiesVersionRequirement,
+} from './persistentMindWorkspacePreflight.js';
+
+const appFor = (repoPath, overrides = {}) => ({
+ id: 'fixture-app',
+ name: 'Fixture App',
+ repoPath,
+ workTracker: 'github',
+ ...overrides,
+});
+
+const createDependencies = ({ git, origin = '[email protected]:example/fixture.git', installed = true, auth = true } = {}) => ({
+ execGit: vi.fn(git || (async (args) => ({
+ stdout: args[0] === 'rev-parse' ? 'true\n' : '',
+ stderr: '',
+ exitCode: 0,
+ }))),
+ readOriginRemoteUrl: vi.fn(async () => origin),
+ commandExists: vi.fn(async () => installed),
+ execFile: vi.fn(async (command, args) => {
+ if (args[0] === 'auth') {
+ if (auth === true) return { stdout: 'authenticated as example-user\n' };
+ if (auth === null) throw Object.assign(new Error('probe timed out'), { code: 'ETIMEDOUT', killed: true });
+ throw Object.assign(new Error('not authenticated'), { code: 'AUTH_REQUIRED' });
+ }
+ return { stdout: command === 'npm' ? '12.0.0\n' : '1.0.0\n' };
+ }),
+ getCodeReviewDefaults: vi.fn(async () => ({
+ reviewers: ['codex'],
+ usernames: ['example-reviewer'],
+ optionalReviewers: [],
+ })),
+ getReviewerCliInstalled: vi.fn(async () => ({ codex: installed })),
+});
+
+const writeManifest = (repoPath, relativePath, manifest) => writeFile(
+ join(repoPath, relativePath),
+ JSON.stringify(manifest),
+);
+
+describe('persistent mind workspace preflight', () => {
+ let repoPath;
+
+ beforeEach(async () => {
+ resetPersistentMindWorkspacePreflightCache();
+ repoPath = await mkdtemp(join(tmpdir(), 'portos-preflight-fixture-'));
+ });
+
+ afterEach(async () => {
+ resetPersistentMindWorkspacePreflightCache();
+ await rm(repoPath, { recursive: true, force: true });
+ });
+
+ it('supports portable engine ranges without copying the Node floor', () => {
+ expect(satisfiesVersionRequirement('24.1.0', '>=22.12.0')).toBe(true);
+ expect(satisfiesVersionRequirement('22.11.9', '>=22.12.0')).toBe(false);
+ expect(satisfiesVersionRequirement('20.19.0', '>=22.12.0 || ^18.20.0')).toBe(false);
+ expect(satisfiesVersionRequirement('22.12.3', '^22.12.0')).toBe(true);
+ expect(satisfiesVersionRequirement('23.0.0', '^22.12.0')).toBe(false);
+ expect(satisfiesVersionRequirement('22.12.3', '22.12.x')).toBe(true);
+ expect(satisfiesVersionRequirement('22.13.0', '22.12.x')).toBe(false);
+ expect(satisfiesVersionRequirement('22.12.3', '~22.12')).toBe(true);
+ expect(satisfiesVersionRequirement('not-a-version', '>=22.12.0')).toBe(null);
+ });
+
+ it('reports npm workspaces, absent dependencies, submodules, engines, forge auth, and reviewers as semantic facts', async () => {
+ await mkdir(join(repoPath, 'packages', 'client'), { recursive: true });
+ await writeManifest(repoPath, 'package.json', {
+ name: 'fixture-root',
+ workspaces: ['packages/*'],
+ packageManager: '[email protected]',
+ engines: { node: '>=22.12.0', npm: '>=12.0.0' },
+ scripts: { test: 'node test.js', build: 'node build.js', lint: 'node lint.js' },
+ });
+ await writeFile(join(repoPath, 'package-lock.json'), '{}');
+ await writeManifest(repoPath, 'packages/client/package.json', {
+ name: 'fixture-client',
+ engines: { node: '>=25.0.0' },
+ scripts: { 'test:unit': 'node test.js', 'build:client': 'node build.js' },
+ });
+ await writeFile(join(repoPath, '.gitmodules'), '[submodule "fixture"]\n\tpath = vendor/fixture\n');
+
+ const dependencies = createDependencies({
+ git: async (args) => ({
+ stdout: args[0] === 'rev-parse' ? 'true\n' : args[0] === 'submodule' ? '-abc123 vendor/fixture\n' : '',
+ stderr: '',
+ exitCode: 0,
+ }),
+ installed: true,
+ auth: false,
+ });
+ const preflight = await readPersistentMindWorkspacePreflight(appFor(repoPath), {
+ now: 1_000,
+ runtime: { nodeVersion: '24.1.0' },
+ dependencies,
+ });
+
+ expect(preflight).toMatchObject({
+ schemaVersion: 1,
+ capturedAt: '1970-01-01T00:00:01.000Z',
+ readiness: 'blocked',
+ repository: { configured: true, reachable: true },
+ checkout: { state: 'clean' },
+ submodules: { configured: true, initialized: false, status: 'uninitialized' },
+ forge: { provider: 'github', cli: 'gh', installed: true, authenticated: false, status: 'unavailable' },
+ reviewers: {
+ required: { configured: 2, available: 1, unavailable: 1, unknown: 0, status: 'unavailable' },
+ optional: { configured: 0, status: 'not-configured' },
+ },
+ });
+ expect(preflight.workspaces.map((workspace) => workspace.id)).toEqual(['root', 'packages/client']);
+ expect(preflight.workspaces[0]).toMatchObject({
+ manifest: 'ready',
+ lockfile: { status: 'present', type: 'npm', scope: 'workspace' },
+ dependencies: { status: 'absent' },
+ engines: {
+ node: { required: '>=22.12.0', actual: '24.1.0', status: 'compatible' },
+ packageManager: { name: 'npm', required: '>=12.0.0', actual: '12.0.0', status: 'compatible' },
+ },
+ scripts: { test: ['test'], build: ['build'] },
+ });
+ expect(preflight.workspaces[1]).toMatchObject({
+ lockfile: { status: 'present', type: 'npm', scope: 'root' },
+ dependencies: { status: 'absent' },
+ engines: { node: { status: 'incompatible' }, packageManager: null },
+ scripts: { test: ['test:unit'], build: ['build:client'] },
+ });
+ const serialized = JSON.stringify(preflight);
+ expect(serialized).not.toContain(repoPath);
+ expect(serialized).not.toContain('fixture.git');
+ expect(serialized).not.toContain('example-reviewer');
+ expect(dependencies.execFile.mock.calls.every(([, args]) => !args.includes('install'))).toBe(true);
+ expect(dependencies.execGit.mock.calls.every(([args]) => !args.includes('init'))).toBe(true);
+ });
+
+ it('keeps missing dependencies advisory for docs-only work but blocks declared validation', async () => {
+ await writeManifest(repoPath, 'package.json', {
+ name: 'fixture-root',
+ engines: { node: '>=22.12.0', npm: '>=12.0.0' },
+ scripts: { test: 'node test.js' },
+ });
+ const preflight = await readPersistentMindWorkspacePreflight(appFor(repoPath, { workTracker: 'plan' }), {
+ now: 2_000,
+ runtime: { nodeVersion: '24.1.0', packageManagerVersions: { npm: '12.0.0' } },
+ dependencies: createDependencies({ origin: null, installed: true, auth: true }),
+ });
+
+ expect(preflight.readiness).toBe('degraded');
+ expect(assessPersistentMindWorkspaceReadiness(preflight, [])).toMatchObject({ readiness: 'degraded', blockers: [] });
+ expect(assessPersistentMindWorkspaceReadiness(preflight, ['dependencies'])).toMatchObject({
+ readiness: 'blocked',
+ blockers: [{ check: 'dependencies', status: 'unavailable' }],
+ });
+ });
+
+ it('reports an unconfigured app and does not claim truncated workspace discovery is ready', async () => {
+ const entries = await readPersistentMindWorkspacePreflights([
+ { id: 'unconfigured-app', name: 'Unconfigured App' },
+ ], {
+ now: 2_500,
+ dependencies: createDependencies(),
+ });
+
+ expect(entries).toHaveLength(1);
+ expect(entries[0]).toMatchObject({
+ appId: 'unconfigured-app',
+ appName: 'Unconfigured App',
+ preflight: {
+ readiness: 'blocked',
+ repository: { configured: false, reachable: false },
+ },
+ });
+ expect(assessPersistentMindWorkspaceReadiness({
+ workspaceDiscovery: 'truncated',
+ workspaces: [{ manifest: 'ready', dependencies: { status: 'installed' } }],
+ }, ['dependencies'])).toMatchObject({
+ readiness: 'blocked',
+ blockers: [{ check: 'dependencies', status: 'unknown' }],
+ });
+ });
+
+ it('keeps unavailable optional reviewers advisory', async () => {
+ await writeManifest(repoPath, 'package.json', { name: 'fixture-root' });
+ const dependencies = createDependencies({ installed: false });
+ dependencies.getCodeReviewDefaults.mockResolvedValue({
+ reviewers: ['codex'],
+ usernames: [],
+ optionalReviewers: ['codex'],
+ });
+ const preflight = await readPersistentMindWorkspacePreflight(appFor(repoPath), {
+ now: 2_750,
+ dependencies,
+ });
+
+ expect(preflight.reviewers).toMatchObject({
+ required: { configured: 0, status: 'not-configured' },
+ optional: { configured: 1, unavailable: 1, status: 'unavailable' },
+ status: 'degraded',
+ });
+ expect(preflight.warnings).toEqual(expect.arrayContaining([
+ expect.objectContaining({ code: 'workspace-reviewers-optional-unavailable', severity: 'advisory' }),
+ ]));
+ expect(assessPersistentMindWorkspaceReadiness(preflight, ['reviewers']).blockers).toEqual([]);
+ });
+
+ it('preserves unknown probe state, cache freshness, and explicit truncation', async () => {
+ await writeManifest(repoPath, 'package.json', { name: 'fixture-root' });
+ const dependencies = createDependencies({
+ git: vi.fn(async () => { throw Object.assign(new Error('unavailable'), { code: 'EIO' }); }),
+ auth: null,
+ });
+ const first = await readPersistentMindWorkspacePreflight(appFor(repoPath), { now: 3_000, dependencies });
+ const cached = await readPersistentMindWorkspacePreflight(appFor(repoPath), { now: 3_000 + PERSISTENT_MIND_WORKSPACE_PREFLIGHT_TTL_MS - 1, dependencies });
+ const refreshed = await readPersistentMindWorkspacePreflight(appFor(repoPath), { now: 3_000 + PERSISTENT_MIND_WORKSPACE_PREFLIGHT_TTL_MS + 1, dependencies });
+
+ expect(first.repository.reachable).toBe(null);
+ expect(first.readiness).toBe('unknown');
+ expect(cached.freshness.state).toBe('fresh');
+ expect(refreshed.freshness.state).toBe('fresh');
+ expect(dependencies.execGit).toHaveBeenCalledTimes(2);
+
+ resetPersistentMindWorkspacePreflightCache();
+ await writeFile(join(repoPath, 'package.json'), 'x'.repeat(PERSISTENT_MIND_WORKSPACE_PREFLIGHT_LIMITS.maxPackageManifestBytes + 1));
+ const truncated = await readPersistentMindWorkspacePreflight(appFor(repoPath), {
+ now: 4_000,
+ dependencies: createDependencies(),
+ });
+ expect(truncated.truncated).toBe(true);
+ expect(truncated.workspaces[0].manifest).toBe('truncated');
+ });
+});