-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.mjs
More file actions
2616 lines (2351 loc) · 107 KB
/
server.mjs
File metadata and controls
2616 lines (2351 loc) · 107 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createServer } from 'http';
import { WebSocketServer, WebSocket } from 'ws';
import { watch, readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import next from 'next';
// Load .env.local so server.mjs has the same env vars as Next.js route handlers
// (notably ORG_STUDIO_API_KEY for self-calls to /api/scheduler)
const __envDir = dirname(fileURLToPath(import.meta.url));
try {
const envPath = join(__envDir, '.env.local');
if (existsSync(envPath)) {
const envContent = readFileSync(envPath, 'utf-8');
for (const line of envContent.split('\n')) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
const eqIdx = trimmed.indexOf('=');
if (eqIdx < 0) continue;
const key = trimmed.slice(0, eqIdx).trim();
const val = trimmed.slice(eqIdx + 1).trim();
if (!process.env[key]) process.env[key] = val; // don't override existing
}
}
} catch {} // best-effort
import { getRuntimeRegistry } from './lib/runtimes.mjs';
import { ensureHeartbeatSchema, startLoopWatchdog, logIncident } from './lib/heartbeats.mjs';
import { ensureOutboxSchema, startOutboxWorker } from './lib/outbox.mjs';
import { ensureSkillInstallsSchema, runDriftCheck } from './lib/skill-installs.mjs';
import { initHealthAlerts, sendHealthAlert, isHealthAlertsEnabled } from './lib/health-alerts.mjs';
const __dirname = dirname(fileURLToPath(import.meta.url));
const port = parseInt(process.env.PORT || '4501');
const dev = false;
// --- Telegram comms guard (v0.15) ---
const ENABLE_TELEGRAM_COMMS = (() => {
const val = (process.env.ENABLE_TELEGRAM_COMMS || 'false').toLowerCase().trim();
return val === 'true' || val === '1' || val === 'yes';
})();
// --- Telegram notification helper ---
const TG_BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN || '';
const TG_CHAT_ID = process.env.TELEGRAM_CHAT_ID || process.env.NOTIFY_CHAT_ID || '';
function sendTelegramNotification(message) {
if (!ENABLE_TELEGRAM_COMMS) return; // v0.15: comms relay disabled by default
if (!TG_BOT_TOKEN || !TG_CHAT_ID) return;
fetch(`https://api.telegram.org/bot${TG_BOT_TOKEN}/sendMessage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ chat_id: TG_CHAT_ID, text: message, parse_mode: 'Markdown' }),
}).catch(err => console.error('[Telegram] Send failed:', err.message));
}
// --- Activity Feed (in-memory ring buffer) ---
const ACTIVITY_FEED_MAX = 200;
const activityFeed = [];
function addActivityEvent(event) {
const entry = {
id: `evt-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
timestamp: Date.now(),
...event,
};
activityFeed.unshift(entry);
if (activityFeed.length > ACTIVITY_FEED_MAX) activityFeed.length = ACTIVITY_FEED_MAX;
broadcast('activity-feed', activityFeed.slice(0, 50)); // send latest 50 to clients
return entry;
}
// Export for use by API routes
globalThis.__orgStudioActivityFeed = {
add: addActivityEvent,
get: () => activityFeed.slice(0, 50),
};
// Seed the activity feed from recent task statusHistory (survives restarts)
function seedActivityFeedFromStore(store) {
if (!store?.tasks?.length) return;
const projects = store.projects || [];
const projectMap = {};
for (const p of projects) projectMap[p.id] = p.name;
const statusEmoji = { 'in-progress': '⚙️', 'review': '👀', 'done': '✅', 'blocked': '🚫', 'qa': '🧪' };
const recentEvents = [];
const oneDayAgo = Date.now() - 24 * 60 * 60 * 1000;
for (const task of store.tasks) {
if (!task.statusHistory?.length) continue;
for (const entry of task.statusHistory) {
if (!entry.timestamp || entry.timestamp < oneDayAgo) continue;
recentEvents.push({
id: `seed-${task.id}-${entry.status}-${entry.timestamp}`,
timestamp: entry.timestamp,
type: 'task-status',
emoji: statusEmoji[entry.status] || '📋',
agent: entry.by || task.assignee || 'Unknown',
project: projectMap[task.projectId] || '',
taskId: task.id,
message: `${entry.by || task.assignee || 'Unknown'} moved "${task.title}" to ${entry.status}`,
});
}
}
// Sort by timestamp descending and take latest 50
recentEvents.sort((a, b) => b.timestamp - a.timestamp);
for (const evt of recentEvents.slice(0, 50)) {
activityFeed.push(evt);
}
if (activityFeed.length > 0) {
console.log(`[Activity Feed] Seeded ${activityFeed.length} events from task history`);
}
}
// --- Next.js ---
const app = next({ dev, dir: __dirname, port });
const handle = app.getRequestHandler();
await app.prepare();
const server = createServer((req, res) => {
// Activity feed REST endpoint
// Debug: confirm server.mjs is running (not standalone server.js)
if (req.url === "/api/debug-server" && req.method === "GET") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ server: "server.mjs", feedSize: activityFeed.length, uptime: process.uptime() }));
return;
}
if (req.url === '/api/activity-feed' && req.method === 'GET') {
const feed = globalThis.__orgStudioActivityFeed?.get() || [];
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ events: feed }));
return;
}
// --- Health-alerts webhook (v0.15) ---
if (req.url === '/api/webhooks/health-alerts' && req.method === 'POST') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', async () => {
try {
const data = JSON.parse(body);
const { agentId, metric, value, threshold, status } = data;
if (!agentId || !metric) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Missing required fields: agentId, metric' }));
return;
}
const alertType = `webhook_${metric}_${agentId}`;
const emoji = status === 'critical' ? '🚨' : status === 'warning' ? '⚠️' : '📊';
const title = `Health Alert: ${metric}`;
const context = `Agent: ${agentId} | ${metric}: ${value} (threshold: ${threshold}) | Status: ${status || 'unknown'}`;
// 1. Forward to external webhook URL if configured
const webhookUrl = process.env.TELEGRAM_HEALTH_ALERTS_WEBHOOK_URL;
if (webhookUrl) {
fetch(webhookUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ agentId, metric, value, threshold, status, timestamp: Date.now() }),
}).catch(err => console.error('[HealthWebhook] Forward failed:', err.message));
}
// 2. Forward to Telegram health bot if configured (independent of ENABLE_TELEGRAM_COMMS)
const sent = await sendHealthAlert({ type: alertType, emoji, title, context });
// 3. Add to activity feed
const feedApi = globalThis.__orgStudioActivityFeed;
if (feedApi?.add) {
feedApi.add({
type: 'health-alert',
emoji,
agent: agentId,
message: `${emoji} ${title}: ${context}`,
});
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ ok: true, telegramSent: sent, webhookForwarded: !!webhookUrl }));
} catch (err) {
console.error('[HealthWebhook] Parse error:', err.message);
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON body' }));
}
});
return;
}
handle(req, res);
});
// --- WebSocket server on /ws ---
const wss = new WebSocketServer({ server, path: '/ws' });
const DATA_DIR = join(__dirname, 'data');
const STORE_PATH = join(DATA_DIR, 'store.json');
const STATUS_PATH = join(DATA_DIR, 'activity-status.json');
function safeRead(path) {
try {
if (!existsSync(path)) return null;
return JSON.parse(readFileSync(path, 'utf-8'));
} catch { return null; }
}
// --- Broadcast ---
function broadcast(type, data) {
const msg = JSON.stringify({ type, data, ts: Date.now() });
for (const client of wss.clients) {
if (client.readyState === WebSocket.OPEN) {
client.send(msg);
}
}
}
// --- File watchers (debounced) ---
const usePostgres = !!process.env.DATABASE_URL;
function watchDataFile(path, type) {
if (!existsSync(path)) return;
let timer = null;
watch(path, () => {
if (timer) clearTimeout(timer);
timer = setTimeout(async () => {
if (type === 'store' && usePostgres) {
// Postgres is source of truth — fetch from API, not stale file
await refreshCachedStore();
if (cachedStore) broadcast('store', cachedStore);
} else {
const data = safeRead(path);
if (data) {
if (type === 'store') cachedStore = data;
broadcast(type, data);
}
}
}, 150);
});
}
// --- ORG.md sync — write to agent workspaces on store change ---
let WORKSPACE_BASE = null;
// Initialize WORKSPACE_BASE intelligently
function initWorkspaceBase() {
if (process.env.WORKSPACE_BASE) {
WORKSPACE_BASE = process.env.WORKSPACE_BASE;
console.log(`Using WORKSPACE_BASE from env: ${WORKSPACE_BASE}`);
return;
}
// Try ~/.openclaw
const homeOCL = join(process.env.HOME || '/tmp', '.openclaw');
if (existsSync(homeOCL)) {
WORKSPACE_BASE = homeOCL;
console.log(`Found ~/.openclaw, using for ORG.md sync: ${WORKSPACE_BASE}`);
return;
}
console.log('WORKSPACE_BASE not found, skipping ORG.md sync. Set WORKSPACE_BASE env var to enable.');
}
function generateOrgMd(store, forAgentId) {
const settings = store?.settings || {};
const mission = settings.missionStatement || 'No mission defined.';
const values = settings.values;
const teammates = settings.teammates || [];
const lines = [];
lines.push('# Org Context');
lines.push('> Auto-generated by Org Studio. Do not edit — changes will be overwritten.');
lines.push('');
lines.push('## Mission');
lines.push(mission);
lines.push('');
if (values?.items?.length) {
lines.push(`## Values — ${values.name || 'Values'}`);
for (const v of values.items) {
lines.push(`- **${v.title}** ${v.icon}: ${v.description}`);
}
lines.push('');
}
if (forAgentId) {
const me = teammates.find(t => t.agentId === forAgentId || t.id === forAgentId);
if (me) {
lines.push(`## Your Domain: ${me.domain || 'Unassigned'}`);
lines.push(`**Role:** ${me.title || 'Team Member'}`);
if (me.owns) lines.push(`**Owns (autonomous decisions):** ${me.owns}`);
if (me.defers) lines.push(`**Defers (needs confirmation):** ${me.defers}`);
if (me.description) lines.push(`**Description:** ${me.description}`);
if (me.context) {
lines.push('');
lines.push('### Context');
lines.push(me.context);
}
lines.push('');
}
}
lines.push('## Team');
for (const t of teammates) {
const type = t.isHuman ? 'Human' : 'Agent';
const owns = t.owns ? ` | Owns: ${t.owns}` : '';
lines.push(`- **${t.name}** ${t.emoji} (${type}) — ${t.domain || 'Unassigned'}${owns}`);
}
lines.push('');
// Team-level shared protocols — same for every agent
lines.push('## How the Team Works');
lines.push('- **Own your domain.** You don\'t report status to a manager — the Org Studio board is your status. Update it, don\'t narrate it.');
lines.push('- **Humans task you directly.** Their word is final. When a human and another agent conflict, the human wins.');
lines.push('- **Coordinators don\'t manage you.** Agents tagged as cross-cutting coordinators handle work that spans domains (email, calendar, onboarding). They don\'t approve your domain work.');
lines.push('- **Go direct when it makes sense.** Need to sync with another agent on shared code or a blocker? Ping them directly. Don\'t route through a coordinator.');
lines.push('- **Ask for help when you\'re stuck.** Missing context that spans domains? Need something from email or calendar? That\'s when you ping a coordinator.');
lines.push('');
lines.push('### What NOT to do');
lines.push('- ❌ Send teammates status updates about your work (update the board instead)');
lines.push('- ❌ Ask permission to do things in your own domain (just do them)');
lines.push('- ❌ Route messages through coordinators when you can talk to the other agent directly');
lines.push('');
lines.push('## Inter-Agent Communication');
lines.push('You can reach other agents directly. Use the `wake-agent` command to send a message that will wake the target even if they\'re idle:');
lines.push('```bash');
lines.push('wake-agent <agentId> "<message>"');
lines.push('```');
lines.push('Valid agent IDs are listed in the Team roster above (use the lowercase name, e.g. `henry`, `ana`, `mikey`).');
lines.push('');
lines.push('**Cross-runtime mentions.** @mention another agent in a task comment (e.g. `@Ana please check this`) and the notification routes cross-runtime (OpenClaw ↔ Hermes) automatically. Preferred for task-specific coordination.');
lines.push('');
lines.push('## Cross-Agent Delivery Rule (MANDATORY)');
lines.push('When another agent routes work to you (via wake event, cross-session message, or cron) and the result needs to reach a human:');
lines.push('1. **ALWAYS** deliver the result via the messaging tool (e.g. `message(action=send, channel=telegram, target=<humanId>)`) — do NOT rely on normal reply routing.');
lines.push('2. After sending, reply `NO_REPLY` to avoid duplicates.');
lines.push('3. **Why:** Wake events and cross-agent sessions have `channel: "unknown"` — normal replies go nowhere.');
lines.push('');
lines.push('## Sub-Agent Model Selection');
lines.push('For code sub-agents use **Codex** (`foundry-openai-responses/gpt-5.3-codex`) — zero cost on Foundry, purpose-built for code. For research/analysis sub-agents use `foundry-openai/gpt-5.4`. Keep your main session on your primary model for orchestration.');
lines.push('');
lines.push('**Rule of thumb:** task ends with a code commit → Codex. Task ends with a report or decision → 5.4.');
lines.push('');
// Vision docs summary — fetch from API (Postgres) with local file fallback
const projects = store?.projects || [];
const activeProjects = projects.filter(p => p.phase === 'active' || p.lifecycle === 'building' || p.lifecycle === 'mature');
if (activeProjects.length > 0) {
lines.push('## Active Projects');
lines.push('');
for (const p of activeProjects) {
const versionStr = p.currentVersion ? ` v${p.currentVersion}` : '';
const devStr = p.devOwner ? ` | Dev: ${p.devOwner}` : '';
const qaStr = p.qaOwner ? ` | QA: ${p.qaOwner}` : '';
lines.push(`- **${p.name}**${versionStr}${devStr}${qaStr}`);
}
lines.push('');
lines.push('Read full vision docs: `GET /api/vision/{projectId}/doc`');
lines.push('');
}
lines.push('## Reference');
lines.push('For Org Studio workflows and usage, see docs/guide.md in your workspace.');
lines.push('For the full API reference, see the org-studio-api skill: skills/org-studio-api/SKILL.md');
lines.push('');
// API quick reference — so agents can interact with Org Studio immediately
const port = process.env.PORT || 4501;
const baseUrl = `http://localhost:${port}`;
const apiKey = process.env.ORG_STUDIO_API_KEY;
lines.push('## Org Studio API');
lines.push(`Dashboard: ${baseUrl}`);
if (apiKey) {
lines.push(`Auth: All writes require header \`Authorization: Bearer ${apiKey}\``);
} else {
lines.push('Auth: All writes require header `Authorization: Bearer <key>` (set ORG_STUDIO_API_KEY in .env.local)');
}
lines.push('');
lines.push('**Quick reference:**');
lines.push('```');
lines.push(`GET ${baseUrl}/api/store — fetch tasks, projects, team`);
lines.push(`POST ${baseUrl}/api/store — create/update tasks, add comments`);
lines.push(`GET ${baseUrl}/api/vision/{projectId}/doc — read project vision doc`);
lines.push(`POST ${baseUrl}/api/roadmap/{projectId} — create/update roadmap versions`);
lines.push(`GET ${baseUrl}/api/stats/{agentId} — your delivery metrics`);
lines.push('```');
lines.push('');
// Work loop — canonical workflow. Full work contract is in the org-studio-api skill.
lines.push('## Work Loop');
lines.push('1. Scan **in-progress** for tasks assigned to you. Resume the highest priority one.');
lines.push('2. If nothing in-progress, scan **backlog**. Pick the highest priority task.');
lines.push(' - Read the full task description and comments FIRST.');
lines.push(' - Only move to in-progress AFTER actual work starts. Do NOT claim tasks speculatively.');
lines.push('3. Before moving any task out of in-progress, check `testType`:');
lines.push(' - `self` (default): self-test, document results in a comment or `reviewNotes`, move to **done** (or **review** if `needsReview: true`).');
lines.push(' - `qa`: self-test first, write a test plan, move to QA column.');
lines.push('4. **When complete:** move to **done** by default. Move to **review** ONLY when `needsReview: true` — set this flag when the work is:');
lines.push(' - **(a) Irreversible** — DB migrations, deletions, money/billing, external API writes with cost');
lines.push(' - **(b) Cross-domain** — touching another agent\'s owned code');
lines.push(' - **(c) Mission/vision/roadmap** direction changes');
lines.push(' - **(d) Security-sensitive**');
lines.push(' When in doubt about reversibility, set needsReview=true. Include `reviewReason` when you do.');
lines.push('5. `reviewNotes` required ONLY when moving to review. For direct-to-done, the commit message + a final summary comment is sufficient.');
lines.push('6. Clear activity status when done. If more backlog tasks remain, continue with the next one. If you run out of time mid-task, leave it where it is.');
lines.push('');
lines.push('**Planning column:** You ARE encouraged to pull from planning — scope the task (acceptance criteria, constraints, context), then move to backlog when ready for execution. If the task lacks context to scope, post a comment asking instead of guessing.');
lines.push('');
lines.push('**Primary directive:** Org Studio exists to unlock continuous agent delivery. After mission/vision/domain/boundaries are set, deliver autonomously. Human involvement is for blockers, irreversible decisions, and cross-domain changes — not routine work in your owned domain.');
lines.push('');
lines.push('**Default task lifecycle:** `backlog → in-progress → done`');
lines.push('**Review lifecycle (opt-in, when `needsReview: true`):** `backlog → in-progress → review → done`');
lines.push('**With QA:** insert `qa` after in-progress when `testType: qa`.');
lines.push('Always include `version` when creating tasks for a sprint.');
lines.push('');
lines.push('**Full work contract** (columns, testing details, handoffs, examples) lives in the `org-studio-api` skill at `skills/org-studio-api/SKILL.md`. Read it when in doubt.');
lines.push('');
lines.push('## Cross-Project Blockers');
lines.push('When you hit a blocker caused by another project:');
lines.push('1. **Mark your task as blocked** (status = blocked) with a comment explaining the issue.');
lines.push('2. **Create a new task** in the blocking project, assigned to that project\'s dev owner.');
lines.push(' - Reference your blocked task ID in the description.');
lines.push('3. The other dev owner fixes the issue and uses `addHandoff` to inject context back.');
lines.push('4. Your task auto-unblocks and you get dispatched to continue.');
lines.push('');
lines.push('**Do NOT** reassign your own task to another project\'s dev owner. Keep tasks in their project.');
lines.push('**Do NOT** fix issues in codebases you don\'t own - create a task for the owner instead.');
lines.push('');
// Activity status — so agents can report what they're doing
lines.push('## Activity Status');
lines.push('Report your status (visible in Mission Control Live Activity feed):');
lines.push('```');
lines.push(`POST ${baseUrl}/api/activity-status`);
lines.push(` {"agent":"<your-agentId>","status":"<what you are doing>","detail":"<optional>"}`);
lines.push('');
lines.push(`DELETE ${baseUrl}/api/activity-status`);
lines.push(` {"agent":"<your-agentId>"}`);
lines.push('```');
lines.push('');
// Comments — how to communicate about tasks
lines.push('## Task Comments');
lines.push('Use comments to communicate about a task (questions, updates, findings):');
lines.push('```');
lines.push(`POST ${baseUrl}/api/store`);
lines.push(` {"action":"addComment","taskId":"<id>","comment":{"author":"<Your Name>","content":"<message>","type":"comment"}}`);
lines.push('```');
lines.push('- When a task is sent back (review → in-progress), check comments for feedback.');
lines.push('- Post questions as comments instead of guessing.');
lines.push('');
return lines.join('\n');
}
function resolveWorkspaceDir(agentId) {
// Hermes agents: check ~/.hermes/profiles/{profileName}/workspace/ first
if (agentId.startsWith('hermes-')) {
const profileName = agentId.replace('hermes-', '');
const hermesWorkspace = join(process.env.HOME || '/tmp', '.hermes', 'profiles', profileName, 'workspace');
// Create workspace dir if it doesn't exist (Hermes profiles don't always have one)
if (!existsSync(hermesWorkspace)) {
try { mkdirSync(hermesWorkspace, { recursive: true }); } catch {}
}
if (existsSync(hermesWorkspace)) return hermesWorkspace;
}
// Default agent id is 'main' but workspace is the bare 'workspace' dir
if (agentId === 'main') {
const bare = join(WORKSPACE_BASE, 'workspace');
if (existsSync(bare)) return bare;
}
// Standard OpenClaw path: workspace-{agentId}
const suffixed = join(WORKSPACE_BASE, `workspace-${agentId}`);
if (existsSync(suffixed)) return suffixed;
return null;
}
function syncOrgFiles(store) {
if (!WORKSPACE_BASE) return; // Skip if WORKSPACE_BASE is null
const teammates = store?.settings?.teammates || [];
const agents = teammates.filter(t => !t.isHuman && t.agentId);
let synced = 0;
// Copy docs/guide.md and skills/org-studio-api/ to each workspace if they exist
const guideSrc = join(process.cwd(), 'docs', 'guide.md');
const guideContent = existsSync(guideSrc) ? readFileSync(guideSrc, 'utf-8') : null;
// Sync the org-studio-api skill (SKILL.md + references/) as the canonical API reference
const skillDir = join(process.cwd(), 'skills', 'org-studio-api');
const skillContent = existsSync(join(skillDir, 'SKILL.md')) ? readFileSync(join(skillDir, 'SKILL.md'), 'utf-8') : null;
const apiRefContent = existsSync(join(skillDir, 'references', 'api-reference.md')) ? readFileSync(join(skillDir, 'references', 'api-reference.md'), 'utf-8') : null;
const metricsRefContent = existsSync(join(skillDir, 'references', 'metrics-reference.md')) ? readFileSync(join(skillDir, 'references', 'metrics-reference.md'), 'utf-8') : null;
for (const agent of agents) {
const workspaceDir = resolveWorkspaceDir(agent.agentId);
if (!workspaceDir) continue;
const orgPath = join(workspaceDir, 'ORG.md');
const content = generateOrgMd(store, agent.agentId);
try {
writeFileSync(orgPath, content);
// Sync docs/guide.md and org-studio-api skill alongside ORG.md
if (guideContent || skillContent) {
const docsDir = join(workspaceDir, 'docs');
mkdirSync(docsDir, { recursive: true });
if (guideContent) {
writeFileSync(join(docsDir, 'guide.md'), guideContent);
}
if (skillContent) {
const skillOutDir = join(workspaceDir, 'skills', 'org-studio-api', 'references');
mkdirSync(skillOutDir, { recursive: true });
writeFileSync(join(workspaceDir, 'skills', 'org-studio-api', 'SKILL.md'), skillContent);
if (apiRefContent) writeFileSync(join(skillOutDir, 'api-reference.md'), apiRefContent);
if (metricsRefContent) writeFileSync(join(skillOutDir, 'metrics-reference.md'), metricsRefContent);
}
}
synced++;
} catch {}
}
if (synced > 0) console.log(` ORG.md + docs/guide.md + skills/org-studio-api synced to ${synced} agent workspace(s)`);
// Async: fetch performance data and append to ORG.md for each agent
appendPerformanceToOrgFiles(agents).catch(e => {
console.warn('[Performance] Failed to append performance data:', e.message);
});
}
/**
* Fetch kudos + stats for each agent and append a tiered Performance section to their ORG.md.
* Three tiers: Core Identity (all-time), Recent Feedback (30 days), Operating Principles (patterns)
* Target: <400 tokens total regardless of volume.
* Runs async after the initial sync so it doesn't block.
*/
async function appendPerformanceToOrgFiles(agents) {
if (!WORKSPACE_BASE) return;
for (const agent of agents) {
const workspaceDir = resolveWorkspaceDir(agent.agentId);
if (!workspaceDir) continue;
const orgPath = join(workspaceDir, 'ORG.md');
if (!existsSync(orgPath)) continue;
try {
// Fetch all kudos for this agent (all-time)
const kudosRes = await fetch(`http://127.0.0.1:${port}/api/kudos?agentId=${agent.agentId}&limit=100`);
const kudosData = kudosRes.ok ? await kudosRes.json() : { kudos: [] };
const allKudos = kudosData.kudos || [];
// Separate kudos and flags, convert createdAt
const kudos = allKudos.filter(k => k.type === 'kudos').map(k => ({
...k,
createdAt: new Date(k.createdAt || k.created_at || Date.now())
}));
const flags = allKudos.filter(k => k.type === 'flag').map(k => ({
...k,
createdAt: new Date(k.createdAt || k.created_at || Date.now())
}));
const now = new Date();
const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
const ninetyDaysAgo = new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000);
// Build tiered performance section
const lines = [];
lines.push('');
lines.push('## Your Performance');
lines.push('');
// TIER 1: Core Identity (all-time, compressed)
const coreIdentity = buildCoreIdentity(kudos, flags, ninetyDaysAgo);
if (coreIdentity.length > 0) {
lines.push('### Core Identity');
lines.push(...coreIdentity);
lines.push('');
}
// TIER 2: Recent Feedback (last 30 days, specific)
const recentFeedback = buildRecentFeedback(kudos, flags, thirtyDaysAgo);
if (recentFeedback.length > 0) {
lines.push('### Recent Feedback (last 30 days)');
lines.push(...recentFeedback);
lines.push('');
}
// TIER 3: Operating Principles (derived from patterns, enhanced)
const principles = generateOperatingPrinciples(kudos, flags, ninetyDaysAgo);
if (principles.length > 0) {
lines.push('### Operating Principles');
lines.push(...principles);
lines.push('');
}
// Append to ORG.md, respecting 400-token budget
if (lines.length > 3) {
const existing = readFileSync(orgPath, 'utf-8');
const cleaned = existing.replace(/\n## Your Performance[\s\S]*$/, '');
const perfSection = lines.join('\n');
writeFileSync(orgPath, cleaned + perfSection);
}
} catch (e) {
console.warn(`[Performance] Failed for ${agent.agentId}:`, e.message);
}
}
}
/**
* TIER 1: Core Identity — Aggregated from all-time kudos/flags
* Returns array of markdown lines (compressed themes).
*/
function buildCoreIdentity(kudos, flags, ninetyDaysAgo) {
const lines = [];
// Count all-time kudos by value tag
const kudosValueCounts = {};
const kudosExamples = {};
for (const k of kudos) {
const values = parseValueTags(k.value_tags || k.values || '[]');
for (const v of values) {
kudosValueCounts[v] = (kudosValueCounts[v] || 0) + 1;
if (!kudosExamples[v]) kudosExamples[v] = k;
}
}
// Count all-time flags by value tag
const flagValueCounts = {};
const flagExamples = {};
const flagLastSeen = {}; // Track last flag date per value
for (const f of flags) {
const values = parseValueTags(f.value_tags || f.values || '[]');
for (const v of values) {
flagValueCounts[v] = (flagValueCounts[v] || 0) + 1;
if (!flagExamples[v]) flagExamples[v] = f;
flagLastSeen[v] = f.createdAt; // Keep latest
}
}
// Top 3 recognized strengths (kudos)
const topKudos = Object.entries(kudosValueCounts)
.sort((a, b) => b[1] - a[1])
.slice(0, 3);
for (const [value, count] of topKudos) {
lines.push(`- Recognized strength: ${sanitizeValue(value)} (${count} kudos all-time, #${value})`);
}
// Growth areas (flags with 2+ occurrences)
const growthAreas = Object.entries(flagValueCounts)
.filter(([_, count]) => count >= 2)
.sort((a, b) => b[1] - a[1]);
for (const [value, count] of growthAreas) {
const lastFlagDate = flagLastSeen[value] || new Date();
const daysAgo = Math.floor((Date.now() - lastFlagDate.getTime()) / (24 * 60 * 60 * 1000));
let daysStr = `${daysAgo} days ago`;
if (daysAgo < 1) daysStr = 'today';
else if (daysAgo === 1) daysStr = 'yesterday';
else if (daysAgo >= 90) daysStr = 'improving';
if (daysAgo >= 90) {
lines.push(`- Growth area: ${sanitizeValue(value)} (${count} flags, last ${daysAgo} days ago — improving, #${value})`);
} else {
lines.push(`- Growth area: ${sanitizeValue(value)} (${count} flags, last ${daysStr}, #${value})`);
}
}
return lines;
}
/**
* TIER 2: Recent Feedback — Specific kudos/flags from last 30 days
* Returns array of markdown lines (up to 5 recent items).
*/
function buildRecentFeedback(kudos, flags, thirtyDaysAgo) {
const lines = [];
const recent = [];
// Combine and filter to last 30 days
for (const k of kudos) {
if (k.createdAt >= thirtyDaysAgo) {
recent.push({ type: 'kudos', ...k });
}
}
for (const f of flags) {
if (f.createdAt >= thirtyDaysAgo) {
recent.push({ type: 'flag', ...f });
}
}
// Sort by date, most recent first
recent.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
// Take top 5
for (const item of recent.slice(0, 5)) {
const emoji = item.type === 'kudos' ? '⭐' : '🚩';
const givenBy = item.given_by || item.givenBy || 'team';
lines.push(`- ${emoji} "${item.note}" — ${givenBy}`);
}
return lines;
}
/**
* TIER 3: Operating Principles — Derived from feedback patterns
* Enhanced to soften principles when underlying pattern improves (no flags in 90+ days).
* Returns array of markdown lines.
*/
function generateOperatingPrinciples(kudos, flags, ninetyDaysAgo) {
const principles = [];
// Count flag values (for pattern detection)
const flagValueCounts = {};
const flagLastSeen = {};
for (const f of flags) {
const values = parseValueTags(f.value_tags || f.values || '[]');
for (const v of values) {
flagValueCounts[v] = (flagValueCounts[v] || 0) + 1;
flagLastSeen[v] = f.createdAt;
}
}
// Count kudos values
const kudosValueCounts = {};
for (const k of kudos) {
const values = parseValueTags(k.value_tags || k.values || '[]');
for (const v of values) {
kudosValueCounts[v] = (kudosValueCounts[v] || 0) + 1;
}
}
// Generate principles dynamically from ANY value tags (not hardcoded to specific values)
// Flag-based principles (areas to improve)
for (const [value, count] of Object.entries(flagValueCounts)) {
const valueName = sanitizeValue(value);
if (count >= 2) {
if (flagLastSeen[value] >= ninetyDaysAgo) {
principles.push(`Area for growth: "${valueName}" has been flagged ${count} times. Focus on improving this deliberately.`);
} else {
principles.push(`You've shown improvement in "${valueName}". Keep it up — no flags in over 90 days.`);
}
} else if (count === 1) {
principles.push(`Reminder: "${valueName}" was flagged once. Stay mindful of this area.`);
}
}
// Kudos-based principles (strengths to reinforce)
for (const [value, count] of Object.entries(kudosValueCounts)) {
const valueName = sanitizeValue(value);
if (count >= 3) {
principles.push(`Recognized strength: "${valueName}" (${count} kudos). This is core to your identity — keep leading with it.`);
} else if (count >= 2) {
principles.push(`Emerging strength: "${valueName}" (${count} kudos). Your work here is being noticed.`);
}
}
return principles.map(p => `- ${p}`);
}
/**
* Parse value tags from stored format (string, array, or JSON).
*/
function parseValueTags(rawTags) {
if (Array.isArray(rawTags)) return rawTags;
if (typeof rawTags === 'string') {
if (rawTags === '[]') return [];
try {
const parsed = JSON.parse(rawTags);
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
return [];
}
/**
* Sanitize a value tag for display (convert 'people-first' to 'People-First', etc.).
*/
function sanitizeValue(value) {
return value
.split('-')
.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join('-');
}
watchDataFile(STORE_PATH, 'store');
watchDataFile(STATUS_PATH, 'activity-status');
// --- Intent Router ---
// Processes intents written to Postgres by remote Org Studio instances.
// Bridges remote writes to local Gateway execution.
/**
* Process a change event from Postgres NOTIFY and execute any pending intents.
* Intents are signaled via special values in the data (e.g. pendingVersion: 'needs_launch').
*/
async function processIntent(changeEvent) {
try {
// --- Vision Launch Intent ---
if (changeEvent.action === 'updateProject' && changeEvent.updates?.autonomy?.pendingVersion === 'needs_launch') {
const projectId = changeEvent.projectId;
const intent = changeEvent.updates.autonomy._launchIntent;
console.log(`[Intent] Vision launch detected for project ${projectId}`);
// Fetch the project and build the launch message
try {
const storeRes = await fetch(`http://127.0.0.1:${port}/api/store`);
const store = await storeRes.json();
const project = store.projects?.find(p => p.id === projectId);
if (!project) {
console.error(`[Intent] Project ${projectId} not found in store`);
return;
}
// Build the launch message by calling the launch endpoint in direct mode
// We call the propose endpoint to get the message, then fire via scheduler
const agentId = intent?.agentId || 'main';
// Fire the vision launch via the local scheduler/api
const launchRes = await fetch(`http://127.0.0.1:${port}/api/vision/${projectId}/launch`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
});
const launchData = await launchRes.json();
if (launchData.ok) {
console.log(`[Intent] Vision launch executed for ${project.name} (mode: ${launchData.mode})`);
} else {
console.error(`[Intent] Vision launch failed for ${project.name}:`, launchData.error);
// Revert state on failure
await fetch(`http://127.0.0.1:${port}/api/store`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
action: 'updateProject',
id: projectId,
updates: {
autonomy: {
...(project.autonomy || {}),
pendingVersion: null,
_launchIntent: undefined,
},
},
}),
});
}
} catch (e) {
console.error(`[Intent] Vision launch error for ${projectId}:`, e.message);
}
return; // Don't process other intents for this event
}
// --- Task-based Agent Triggers ---
// When a task moves to backlog or QA via remote write, trigger the local scheduler
if (changeEvent.type === 'task_updated' && changeEvent.updates?.status) {
const newStatus = changeEvent.updates.status;
// Use task-level assignee (always present), fall back to updates.assignee
const assignee = changeEvent.assignee || changeEvent.updates.assignee;
if ((newStatus === 'backlog' || newStatus === 'qa') && assignee) {
console.log(`[Intent] Task ${changeEvent.taskId} moved to ${newStatus}, triggering agent for ${assignee}`);
// Resolve assignee → agentId from store
try {
const storeRes = await fetch(`http://127.0.0.1:${port}/api/store`);
const store = await storeRes.json();
const teammates = store.settings?.teammates || [];
const match = teammates.find(t =>
t.name?.toLowerCase() === assignee.toLowerCase() ||
t.agentId === assignee?.toLowerCase()
);
const agentId = match?.agentId;
if (agentId) {
const triggerRes = await fetch(`http://127.0.0.1:${port}/api/scheduler`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'trigger', agentId }),
});
if (triggerRes.ok) {
console.log(`[Intent] Scheduler triggered for ${agentId}`);
} else {
console.warn(`[Intent] Scheduler trigger failed: HTTP ${triggerRes.status}`);
}
}
} catch (e) {
console.warn(`[Intent] Scheduler trigger error:`, e.message);
}
}
}
} catch (e) {
console.warn(`[Intent] Processing error:`, e.message);
}
}
// --- PostgreSQL LISTEN for bidirectional sync ---
// When remote server makes changes via /api/store, they trigger NOTIFY events
// that the local server receives and broadcasts to all WebSocket clients.
// PubSub health state (exported via /api/health/pubsub and MC dashboard)
const pubsubHealth = {
connected: false,
lastHeartbeatAt: null, // ISO string
reconnectCount: 0,
lastError: null, // string
lastConnectedAt: null, // ISO string
};
// Expose for health endpoint
globalThis.__pubsubHealth = pubsubHealth;
let _pubsubHeartbeatTimer = null;
let _pubsubReconnectAttempt = 0;
const PUBSUB_HEARTBEAT_INTERVAL_MS = 30_000; // 30s
const PUBSUB_RECONNECT_DELAYS = [5000, 10000, 20000, 60000]; // exponential backoff, cap at 60s
function getPubsubReconnectDelay() {
const idx = Math.min(_pubsubReconnectAttempt, PUBSUB_RECONNECT_DELAYS.length - 1);
return PUBSUB_RECONNECT_DELAYS[idx];
}
async function initializePostgresListener() {
const dbUrl = process.env.DATABASE_URL;
if (!dbUrl) {
console.log('[LISTEN] DATABASE_URL not set — skipping PostgreSQL listener');
return;
}
// Clear any existing heartbeat timer
if (_pubsubHeartbeatTimer) {
clearInterval(_pubsubHeartbeatTimer);
_pubsubHeartbeatTimer = null;
}
try {
const pg = await import('pg');
const Client = pg.default?.Client || pg.Client;
const listener = new Client({ connectionString: dbUrl });
function scheduleReconnect(reason) {
pubsubHealth.connected = false;
pubsubHealth.lastError = reason;
if (_pubsubHeartbeatTimer) {
clearInterval(_pubsubHeartbeatTimer);
_pubsubHeartbeatTimer = null;
}
const delay = getPubsubReconnectDelay();
_pubsubReconnectAttempt++;
pubsubHealth.reconnectCount++;
console.warn(`[LISTEN] ${reason}. Reconnecting in ${delay / 1000}s (attempt #${_pubsubReconnectAttempt})`);
setTimeout(() => initializePostgresListener(), delay);
}
listener.on('error', (err) => {
scheduleReconnect(`Connection error: ${err.message}`);
});
listener.on('end', () => {
scheduleReconnect('Connection closed');
});
// Listen for store update events + heartbeat
listener.on('notification', async (msg) => {
try {
// Heartbeat channel — just update timestamp, don't process further
if (msg.channel === 'org_studio_heartbeat') {
pubsubHealth.lastHeartbeatAt = new Date().toISOString();
return;
}
// msg.channel is the event name, msg.payload is the JSON data
if (msg.channel === 'org_studio_change') {
const changeEvent = JSON.parse(msg.payload);
// Ensure workspace_id is present; default to 'default-workspace' if missing
if (!changeEvent.workspace_id) {
changeEvent.workspace_id = 'default-workspace';
// Only warn once per server lifetime for missing workspace_id
if (!globalThis.__wsIdWarnLogged) {
console.warn('[LISTEN] Notification missing workspace_id — defaulting to default-workspace');
globalThis.__wsIdWarnLogged = true;
}
}
console.log(`[LISTEN] Received ${changeEvent.type} event:`, changeEvent.action || '');
// --- Intent Router ---
// Process intents BEFORE refreshing the store cache, so we can act on the intent
// and update state in the same cycle
await processIntent(changeEvent);
// Process @mentions from comments added via remote (staging) UI
if (changeEvent.type === 'comment_added' && changeEvent.taskId) {
console.log(`[LISTEN] comment_added taskId=${changeEvent.taskId} commentId=${changeEvent.commentId || 'none'}`);
try {
const freshStore = await refreshCachedStore();
if (freshStore) {
const task = freshStore.tasks?.find(t => t.id === changeEvent.taskId);
// Look up by commentId if available, fall back to last comment
let comment;
if (changeEvent.commentId && task?.comments) {
comment = task.comments.find(c => c.id === changeEvent.commentId);
}