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(reference-repos): queue CoS analysis task on Check (#437)

[._.]/ Adam Eivy4ea8e72a785f
diff --git a/client/src/components/apps/ReferenceReposPanel.jsx b/client/src/components/apps/ReferenceReposPanel.jsx
index ff0a1a0eff..daa85db4ed 100644
--- a/client/src/components/apps/ReferenceReposPanel.jsx
+++ b/client/src/components/apps/ReferenceReposPanel.jsx
@@ -107,7 +107,17 @@ export default function ReferenceReposPanel({ appId, appName, compact = false, i
return;
}
setSnapshots((prev) => ({ ...prev, [ref.id]: snap }));
- toast.success(`${ref.name}: ${snap.commitCount} new commit${snap.commitCount === 1 ? '' : 's'}`);
+ const commitMsg = `${ref.name}: ${snap.commitCount} new commit${snap.commitCount === 1 ? '' : 's'}`;
+ if (snap.analysis?.queued) {
+ toast.success(`${commitMsg} — analysis task queued`);
+ } else if (snap.analysis?.reason === 'duplicate') {
+ toast.success(`${commitMsg} — analysis already queued`);
+ } else if (snap.analysis?.reason === 'analysis-trigger-failed') {
+ toast.success(commitMsg);
+ toast.error(`${ref.name}: failed to queue analysis task`);
+ } else {
+ toast.success(commitMsg);
+ }
fetch();
};
diff --git a/server/routes/referenceRepos.js b/server/routes/referenceRepos.js
index dabb5d87ba..ca88e8cef7 100644
--- a/server/routes/referenceRepos.js
+++ b/server/routes/referenceRepos.js
@@ -20,7 +20,9 @@ import {
deleteReferenceRepo,
checkReferenceRepo,
markReferenceRepoReviewed,
+ triggerReferenceAnalysis,
} from '../services/referenceRepos.js';
+import { getAppById } from '../services/apps.js';
const router = Router({ mergeParams: true });
@@ -48,13 +50,30 @@ router.delete('/:refId', asyncHandler(async (req, res) => {
res.json({ ok: true });
}));
-// Run a check now — fetches the upstream repo and returns the commit list
-// since lastReviewedSha. Does NOT advance lastReviewedSha; that happens
-// via the explicit /reviewed endpoint after the user / agent has actually
-// processed the changes.
+// Run a check now — fetches the upstream repo, returns the commit list since
+// lastReviewedSha, and queues a CoS analysis task when new commits exist.
+// Does NOT advance lastReviewedSha; that happens via the explicit /reviewed
+// endpoint after the user / agent has actually processed the changes.
router.post('/:refId/check', asyncHandler(async (req, res) => {
- const snapshot = await checkReferenceRepo(req.params.appId, req.params.refId);
- res.json(snapshot);
+ const { appId, refId } = req.params;
+ const snapshot = await checkReferenceRepo(appId, refId);
+ let analysis = { queued: false, reason: 'no-new-commits' };
+ if (snapshot.commitCount > 0) {
+ const app = await getAppById(appId);
+ const ref = app?.referenceRepos?.find((r) => r.id === refId);
+ if (!app) {
+ analysis = { queued: false, reason: 'app-not-found' };
+ } else if (!ref) {
+ analysis = { queued: false, reason: 'ref-not-found' };
+ } else {
+ analysis = await triggerReferenceAnalysis(app, ref, snapshot)
+ .catch((err) => {
+ console.error(`❌ Analysis trigger failed for ${refId}: ${err instanceof Error ? err.message : String(err)}`);
+ return { queued: false, reason: 'analysis-trigger-failed' };
+ });
+ }
+ }
+ res.json({ ...snapshot, analysis });
}));
router.post('/:refId/reviewed', asyncHandler(async (req, res) => {
diff --git a/server/routes/referenceRepos.test.js b/server/routes/referenceRepos.test.js
index cd6a2fb83c..7a7b47675c 100644
--- a/server/routes/referenceRepos.test.js
+++ b/server/routes/referenceRepos.test.js
@@ -12,6 +12,16 @@ vi.mock('../services/referenceRepos.js', () => ({
deleteReferenceRepo: vi.fn(async () => ({ ok: true })),
checkReferenceRepo: vi.fn(async () => ({ head: 'a'.repeat(40), commitCount: 2, commits: [] })),
markReferenceRepoReviewed: vi.fn(async (_appId, refId, sha) => ({ id: refId, lastReviewedSha: sha })),
+ triggerReferenceAnalysis: vi.fn(async () => ({ queued: true, taskId: 'ref-analysis-1' })),
+}));
+
+vi.mock('../services/apps.js', () => ({
+ getAppById: vi.fn(async () => ({
+ id: 'app-1',
+ name: 'TestApp',
+ repoPath: '/mock/repo',
+ referenceRepos: [{ id: 'r1', name: 'phosphene', repoUrl: 'https://github.com/x/y.git' }],
+ })),
}));
import * as svc from '../services/referenceRepos.js';
@@ -116,6 +126,32 @@ describe('reference repos routes', () => {
expect(r.body).toMatchObject({ commitCount: 2 });
expect(svc.checkReferenceRepo).toHaveBeenCalledWith('app-1', 'r1');
});
+
+ it('triggers analysis when new commits exist', async () => {
+ const r = await request(app).post('/api/apps/app-1/reference-repos/r1/check');
+ expect(r.status).toBe(200);
+ expect(r.body.analysis).toEqual({ queued: true, taskId: 'ref-analysis-1' });
+ expect(svc.triggerReferenceAnalysis).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'app-1', name: 'TestApp' }),
+ expect.objectContaining({ id: 'r1' }),
+ expect.objectContaining({ commitCount: 2 }),
+ );
+ });
+
+ it('returns stable reason code when analysis trigger throws', async () => {
+ svc.triggerReferenceAnalysis.mockRejectedValueOnce(new Error('something internal'));
+ const r = await request(app).post('/api/apps/app-1/reference-repos/r1/check');
+ expect(r.status).toBe(200);
+ expect(r.body.analysis).toEqual({ queued: false, reason: 'analysis-trigger-failed' });
+ });
+
+ it('skips analysis when no new commits', async () => {
+ svc.checkReferenceRepo.mockResolvedValueOnce({ head: 'a'.repeat(40), commitCount: 0, commits: [] });
+ const r = await request(app).post('/api/apps/app-1/reference-repos/r1/check');
+ expect(r.status).toBe(200);
+ expect(r.body.analysis).toEqual({ queued: false, reason: 'no-new-commits' });
+ expect(svc.triggerReferenceAnalysis).not.toHaveBeenCalled();
+ });
});
describe('POST /:refId/reviewed', () => {
diff --git a/server/services/referenceRepos.js b/server/services/referenceRepos.js
index 62352c915b..0ac4863eb1 100644
--- a/server/services/referenceRepos.js
+++ b/server/services/referenceRepos.js
@@ -29,6 +29,7 @@ import {
getAppById,
updateApp,
} from './apps.js';
+import { DEFAULT_REVIEWER } from '../lib/validation.js';
// `path.join(homedir(), '/.foo')` discards the homedir because of the leading
// slash, so we strip the `~/` prefix (or `~`) before joining. Same shape as
@@ -579,6 +580,59 @@ export function formatReferenceForPrompt(ref, snapshot) {
return lines.join('\n');
}
+/**
+ * Trigger a CoS analysis task for a single reference repo after a successful
+ * check found new commits. Builds the reference-watch prompt with the snapshot
+ * data and queues it as an internal task for the next available agent slot.
+ *
+ * Returns `{ queued: true, taskId }` on success, or `{ queued: false, reason }`
+ * when the task can't be created (e.g. no commits, app not found).
+ */
+export async function triggerReferenceAnalysis(app, ref, snapshot) {
+ if (!snapshot || snapshot.commitCount === 0) {
+ return { queued: false, reason: 'no-new-commits' };
+ }
+ if (!app) return { queued: false, reason: 'app-not-found' };
+
+ const { addTask } = await import('./cos.js');
+ const taskSchedule = await import('./taskSchedule.js');
+
+ const referenceDataBlock = formatReferenceForPrompt(ref, snapshot);
+ const promptTemplate = await taskSchedule.getTaskPrompt('reference-watch');
+ // Use arrow replacers to avoid $& / $1 interpretation in replacement strings
+ const fullPrompt = promptTemplate
+ .replace(/\{appName\}/g, () => app.name)
+ .replace(/\{repoPath\}/g, () => app.repoPath)
+ .replace(/\{appId\}/g, () => app.id)
+ .replace(/\{reviewer\}/g, () => DEFAULT_REVIEWER)
+ .replace(/\{referenceData\}/g, () => referenceDataBlock)
+ .replace(/\{planConstraint\}/g, () => '');
+
+ const task = await addTask({
+ id: `sys-ref-analysis-${app.id}-${ref.id}-${Date.now().toString(36)}`,
+ status: 'pending',
+ priority: 'MEDIUM',
+ priorityValue: 2,
+ description: `Reference-watch analysis: ${ref.name} (${redactUrlCreds(ref.repoUrl)}) for ${app.name}`,
+ metadata: {
+ app: app.id,
+ appName: app.name,
+ repoPath: app.repoPath,
+ analysisType: 'reference-watch',
+ autoGenerated: true,
+ readOnly: true,
+ context: fullPrompt,
+ },
+ autoApproved: true,
+ section: 'pending',
+ }, 'internal', { raw: true });
+
+ if (task?.duplicate) {
+ return { queued: false, reason: 'duplicate', taskId: task.id };
+ }
+ return { queued: true, taskId: task.id };
+}
+
// Exported for tests + reference-watch task type lookup.
export const __test = {
REFERENCE_REPOS_ROOT,
diff --git a/server/services/referenceRepos.test.js b/server/services/referenceRepos.test.js
index fa17fa26a2..4dbb1c8793 100644
--- a/server/services/referenceRepos.test.js
+++ b/server/services/referenceRepos.test.js
@@ -39,6 +39,16 @@ vi.mock('../lib/execGit.js', () => ({
},
}));
+// Stubs for CoS task queuing — used by triggerReferenceAnalysis.
+const addTaskMock = vi.fn(async (task) => task);
+vi.mock('./cos.js', () => ({
+ addTask: (...args) => addTaskMock(...args),
+}));
+const getTaskPromptMock = vi.fn(async () => 'Analyze {appName} at {repoPath} for {appId} reviewer={reviewer}\n{referenceData}\n{planConstraint}');
+vi.mock('./taskSchedule.js', () => ({
+ getTaskPrompt: (...args) => getTaskPromptMock(...args),
+}));
+
// existsSync is hit when the service decides whether the managed clone
// already exists. Default to false so first-touch goes through clone path;
// individual tests override.
@@ -56,6 +66,10 @@ beforeEach(async () => {
vi.resetModules();
mockApps.clear();
execGitMock.mockReset();
+ addTaskMock.mockReset();
+ addTaskMock.mockImplementation(async (task) => task);
+ getTaskPromptMock.mockReset();
+ getTaskPromptMock.mockImplementation(async () => 'Analyze {appName} at {repoPath} for {appId} reviewer={reviewer}\n{referenceData}\n{planConstraint}');
existsMock.mockReset();
existsMock.mockReturnValue(false);
svc = await import('./referenceRepos.js');
@@ -336,3 +350,55 @@ describe('markReferenceRepoReviewed', () => {
expect(mockApps.get('app-1').referenceRepos[0].lastReviewedSha).toBeNull();
});
});
+
+describe('triggerReferenceAnalysis', () => {
+ const app = { id: 'app-1', name: 'TestApp', repoPath: '/mock/repo' };
+ const ref = { id: 'r1', name: 'phosphene', repoUrl: 'https://github.com/x/y.git', branch: 'main' };
+ const snapshot = { head: 'a'.repeat(40), headShort: 'aaaaaaaa', commitCount: 3, commits: [], cwd: '/mock/clone', branch: 'main' };
+
+ it('skips when snapshot has no new commits', async () => {
+ const result = await svc.triggerReferenceAnalysis(app, ref, { ...snapshot, commitCount: 0 });
+ expect(result).toEqual({ queued: false, reason: 'no-new-commits' });
+ expect(addTaskMock).not.toHaveBeenCalled();
+ });
+
+ it('skips when snapshot is null', async () => {
+ const result = await svc.triggerReferenceAnalysis(app, ref, null);
+ expect(result).toEqual({ queued: false, reason: 'no-new-commits' });
+ });
+
+ it('skips when app is null', async () => {
+ const result = await svc.triggerReferenceAnalysis(null, ref, snapshot);
+ expect(result).toEqual({ queued: false, reason: 'app-not-found' });
+ });
+
+ it('queues a task with single-line description and full prompt in metadata.context', async () => {
+ const result = await svc.triggerReferenceAnalysis(app, ref, snapshot);
+ expect(result.queued).toBe(true);
+ expect(result.taskId).toBeTruthy();
+ expect(addTaskMock).toHaveBeenCalledTimes(1);
+ const taskArg = addTaskMock.mock.calls[0][0];
+ // Task ID must use a known internal prefix so taskParser doesn't rewrite it
+ expect(taskArg.id).toMatch(/^sys-ref-analysis-/);
+ // Description must be single-line and contain ref + app identifiers
+ expect(taskArg.description).not.toContain('\n');
+ expect(taskArg.description).toContain('phosphene');
+ expect(taskArg.description).toContain('TestApp');
+ expect(taskArg.description).toContain('github.com/x/y.git');
+ // Full prompt stored in metadata.context for COS-TASKS.md round-trip safety
+ expect(taskArg.metadata.context).toContain('Analyze TestApp');
+ expect(taskArg.metadata.context).toContain('/mock/repo');
+ // Must set autoApproved so CoS dequeues automatically
+ expect(taskArg.autoApproved).toBe(true);
+ expect(taskArg.section).toBe('pending');
+ // Task type markers
+ expect(addTaskMock.mock.calls[0][1]).toBe('internal');
+ expect(addTaskMock.mock.calls[0][2]).toEqual({ raw: true });
+ });
+
+ it('returns duplicate when addTask signals a duplicate', async () => {
+ addTaskMock.mockResolvedValueOnce({ id: 'dup-1', duplicate: true });
+ const result = await svc.triggerReferenceAnalysis(app, ref, snapshot);
+ expect(result).toEqual({ queued: false, reason: 'duplicate', taskId: 'dup-1' });
+ });
+});