@maximalabs/dev-mcp-suite 0.0.0-stage → 3.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/.env.example +69 -0
  2. package/CHANGELOG.md +271 -0
  3. package/CODEX_DEV_MCP_GUIDE.md +297 -0
  4. package/LICENSE +21 -0
  5. package/README.md +193 -2
  6. package/armada/package.json +14 -0
  7. package/armada/server.js +329 -0
  8. package/backfill-sessions-v2.mjs +288 -0
  9. package/bin/_meta.mjs +73 -0
  10. package/bin/armada-mcp.mjs +12 -0
  11. package/bin/checkpoint.mjs +9 -0
  12. package/bin/context-pack.mjs +9 -0
  13. package/bin/devjournal.mjs +9 -0
  14. package/bin/init.mjs +25 -0
  15. package/bin/project-memory.mjs +10 -0
  16. package/bin/provider-smoke.mjs +278 -0
  17. package/bin/prune.mjs +158 -0
  18. package/bin/stats.mjs +101 -0
  19. package/bin/ui.mjs +5 -0
  20. package/checkpoint/package.json +14 -0
  21. package/checkpoint/server.js +318 -0
  22. package/context-pack/package.json +14 -0
  23. package/context-pack/server.js +747 -0
  24. package/devjournal/compress.js +75 -0
  25. package/devjournal/env.js +3 -0
  26. package/devjournal/package.json +14 -0
  27. package/devjournal/provider-chain.js +109 -0
  28. package/devjournal/rerank.js +120 -0
  29. package/devjournal/server.js +415 -0
  30. package/docs/ROADMAP.md +77 -0
  31. package/docs/clients/antigravity.md +52 -0
  32. package/docs/clients/claude-code.md +46 -0
  33. package/docs/clients/codex.md +39 -0
  34. package/docs/clients/generic-mcp.md +45 -0
  35. package/docs/clients/hermes.md +48 -0
  36. package/docs/configuration.md +123 -0
  37. package/docs/privacy.md +39 -0
  38. package/docs/providers.md +13 -0
  39. package/docs/superpowers/plans/2026-06-15-hardening-v1-2-implementation.md +60 -0
  40. package/docs/superpowers/plans/2026-06-15-provider-chain-v1-1-implementation.md +65 -0
  41. package/docs/superpowers/plans/2026-06-15-provider-client-agnostic-config.md +41 -0
  42. package/docs/superpowers/plans/2026-06-15-trust-release-implementation.md +62 -0
  43. package/docs/superpowers/plans/2026-06-18-v1-5-0-knowledge-graph.md +792 -0
  44. package/docs/superpowers/specs/2026-06-15-provider-chain-v1-1-design.md +89 -0
  45. package/docs/superpowers/specs/2026-06-15-trust-release-design.md +164 -0
  46. package/docs/superpowers/specs/2026-06-18-dev-mcp-suite-v1-5-0-knowledge-graph-design.md +386 -0
  47. package/docs/superpowers/specs/2026-07-22-v2-0-0-peak-intelligence.md +50 -0
  48. package/docs/superpowers/specs/2026-07-22-v3-0-0-god-tier.md +32 -0
  49. package/lib/init-wizard.js +120 -0
  50. package/lib/provider-smoke.js +234 -0
  51. package/lib/prune.js +114 -0
  52. package/lib/stats.js +269 -0
  53. package/lib/ui-server.js +151 -0
  54. package/lib/update-check.js +125 -0
  55. package/package.json +71 -4
  56. package/project-memory/auto-indexer.js +152 -0
  57. package/project-memory/dedup.js +49 -0
  58. package/project-memory/embedding.js +174 -0
  59. package/project-memory/env.js +3 -0
  60. package/project-memory/global-index.js +46 -0
  61. package/project-memory/graph.js +93 -0
  62. package/project-memory/local-embed.js +92 -0
  63. package/project-memory/package.json +14 -0
  64. package/project-memory/provider-chain.js +109 -0
  65. package/project-memory/rerank.js +120 -0
  66. package/project-memory/server.js +931 -0
  67. package/project-memory/swarm.js +56 -0
  68. package/run-tests.mjs +54 -0
package/README.md CHANGED
@@ -1,3 +1,194 @@
1
- # Temporary Holding Version
1
+ # Dev MCP Suite 🚀
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > **Give your AI Coding Assistant Permanent Brain Power & Zero Memory Loss.**
4
+
5
+ [![CI](https://github.com/MaximaLabs/dev-mcp-suite/actions/workflows/ci.yml/badge.svg)](https://github.com/MaximaLabs/dev-mcp-suite/actions/workflows/ci.yml)
6
+ [![npm version](https://img.shields.io/npm/v/@maximalabs/dev-mcp-suite.svg)](https://www.npmjs.com/package/@maximalabs/dev-mcp-suite)
7
+ [![npm downloads](https://img.shields.io/npm/dm/@maximalabs/dev-mcp-suite.svg)](https://www.npmjs.com/package/@maximalabs/dev-mcp-suite)
8
+ [![license](https://img.shields.io/npm/l/@maximalabs/dev-mcp-suite.svg)](./LICENSE)
9
+ [![node](https://img.shields.io/node/v/@maximalabs/dev-mcp-suite.svg)](https://nodejs.org)
10
+ [![Saweria](https://img.shields.io/badge/Saweria-Dukung%20Proyek-FAAE2B?style=flat&logo=saweria&logoColor=black)](https://saweria.co/sijuling)
11
+
12
+ Published on npm as `@maximalabs/dev-mcp-suite`.
13
+
14
+ ---
15
+
16
+ ### 😩 Sound Familiar?
17
+
18
+ > *"You spent 45 minutes explaining your database schema and architecture to your AI agent. Then... **'Context window compacted'** or session restarted. Boom. Your AI forgot everything and started hallucinating variable names."*
19
+
20
+ **Stop re-pasting context over and over.**
21
+
22
+ **Dev MCP Suite** is a suite of four local, zero-telemetry MCP (Model Context Protocol) servers built for solo developers and vibe coders. It equips your favorite AI agent (**Codex CLI, Hermes Agent, Google Antigravity, Claude Code, Cursor, Windsurf**) with permanent memory, anti-compaction handoffs, git-safe checkpoints, and offline vector search.
23
+
24
+ ---
25
+
26
+ ### ⚡ Before & After Dev MCP Suite
27
+
28
+ | Without Dev MCP Suite 🥱 | With Dev MCP Suite ⚡ |
29
+ |---|---|
30
+ | Re-explaining project setup every time session resets | One-command `journal_resume` recovers context instantly |
31
+ | AI forgets architectural decisions and preferences | Obsidian-compatible Markdown vault retains knowledge permanently |
32
+ | Wasted git commits just to save temporary experiments | Git-independent `checkpoint_create` & instant rollback |
33
+ | Accidental secret/API key leaks committed to GitHub | Built-in `pack_audit` flags missing `.gitignore` & leaked keys |
34
+ | Locked into a proprietary hosted backend | 100% Local-first, zero cloud lock-in, zero telemetry |
35
+
36
+ ---
37
+
38
+ ### ⚡ 10-Second Quickstart
39
+
40
+ Automatically configure all installed AI tools (Codex CLI, Claude Code, Cursor, Windsurf, Hermes, Antigravity) with 1 command:
41
+
42
+ ```bash
43
+ npx -y @maximalabs/dev-mcp-suite init
44
+ ```
45
+
46
+ Or test a single server right now without installing:
47
+
48
+ ```bash
49
+ npx -y -p @maximalabs/dev-mcp-suite project-memory-mcp --help
50
+ ```
51
+
52
+ ---
53
+
54
+ ### 🛠️ The 4 Superpowers (MCP Servers)
55
+
56
+ | Server | Superpower | Key Tools |
57
+ |---|---|---|
58
+ | 🧠 **`project-memory`** | **Obsidian-Grade Knowledge Vault**: Persistent Markdown notes, wiki-links (`[[note]]`), MOC generation, zero-dependency local 384-d vector search (`MCP_LOCAL_EMBED=true`), multi-agent swarm stream, and autonomous background git observer (`memory_auto_index`). | `memory_save`, `memory_recall`, `memory_list`, `memory_get`, `memory_link`, `memory_moc`, `memory_graph`, `memory_dedup`, `memory_broadcast`, `memory_swarm_timeline`, `memory_auto_index` |
59
+ | 📜 **`devjournal`** | **Anti-Compaction Session Timeline**: Logs progress, saves handoffs, restores full context, and compresses session logs to cut token costs ~90%. | `journal_log`, `journal_handoff`, `journal_resume`, `journal_timeline`, `journal_search`, `journal_compress`, `journal_clear_handoff` |
60
+ | 🛡️ **`checkpoint`** | **Git-Independent Snapshots**: Take 1-second file snapshots before risky AI refactors. Compare diffs and revert instantly without touching your git tree. | `checkpoint_create`, `checkpoint_list`, `checkpoint_diff`, `checkpoint_restore`, `checkpoint_delete` |
61
+ | 🔍 **`context-pack`** | **Autonomous Agent OS**: Token-efficient briefings, dependency blast-radius analysis (`pack_impact`), self-healing preflight checks (`pack_guard`), live log telemetry (`pack_telemetry`), predictive contract diff simulation (`pack_predictive_diff`), and security auditing (`pack_audit`). | `pack_overview`, `pack_tree`, `pack_outline`, `pack_search`, `pack_audit`, `pack_impact`, `pack_guard`, `pack_telemetry`, `pack_predictive_diff` |
62
+ | 🛰️ **`armada`** *(opsional)* | **Fleet Ops Control Plane**: Watch heartbeats and enqueue policy-gated jobs on many hosts through an [Armada bus](https://github.com/verrysimatupang99/armada) — outbound-only, no SSH fan-in. Host policy grants/denies every job (allowlist → user → root → docker sandbox). *Needs `ARMADA_BUS_URL` + `ARMADA_BUS_TOKEN`; not auto-wired by `init` since it points at YOUR fleet.* | `fleet_health`, `fleet_jobs`, `job_post`, `job_status`, `job_watch`, `job_tail`, `job_cancel`, `bus_note`, `bus_read` |
63
+
64
+ ---
65
+
66
+ ### 🧠 Intelligent Local-First Semantic Search
67
+
68
+ `memory_recall` automatically selects the best available search engine on your machine:
69
+
70
+ 1. **Local Offline Vector Search (`v1.8.0`)** — Set `MCP_LOCAL_EMBED=true` to use the built-in, zero-dependency 384-dimensional term-frequency hashing vector engine. Sub-millisecond execution, zero network requests, 100% private.
71
+ 2. **Remote Embeddings (Optional)** — Connect any OpenAI-compatible `/v1/embeddings` endpoint (OpenAI, Cloudflare Workers AI, Ollama, LM Studio, 9router, OpenRouter).
72
+ 3. **LLM Reranking (Optional)** — Hybrid keyword pre-filter followed by LLM reranking for high-precision recall.
73
+ 4. **Keyword Fallback** — Always-available offline fallback if no network or API keys exist.
74
+
75
+ ---
76
+
77
+ ### 🔌 Plug & Play with Any MCP Client
78
+
79
+ #### 1. Codex CLI (`~/.codex/config.toml`)
80
+ ```toml
81
+ [mcp_servers.project-memory]
82
+ command = "npx"
83
+ args = ["-y", "-p", "@maximalabs/dev-mcp-suite", "project-memory-mcp"]
84
+
85
+ [mcp_servers.devjournal]
86
+ command = "npx"
87
+ args = ["-y", "-p", "@maximalabs/dev-mcp-suite", "devjournal-mcp"]
88
+
89
+ [mcp_servers.checkpoint]
90
+ command = "npx"
91
+ args = ["-y", "-p", "@maximalabs/dev-mcp-suite", "checkpoint-mcp"]
92
+
93
+ [mcp_servers.context-pack]
94
+ command = "npx"
95
+ args = ["-y", "-p", "@maximalabs/dev-mcp-suite", "context-pack-mcp"]
96
+ ```
97
+
98
+ #### 2. Hermes Agent (`~/.hermes/config.yaml`)
99
+ ```yaml
100
+ mcp_servers:
101
+ project-memory:
102
+ command: project-memory-mcp
103
+ env:
104
+ MCP_LOCAL_EMBED: "true"
105
+ devjournal:
106
+ command: devjournal-mcp
107
+ checkpoint:
108
+ command: checkpoint-mcp
109
+ context-pack:
110
+ command: context-pack-mcp
111
+ ```
112
+
113
+ #### 3. Google Antigravity CLI / Cursor / Claude Code (`mcp.json`)
114
+ ```json
115
+ {
116
+ "mcpServers": {
117
+ "project-memory": { "command": "project-memory-mcp", "env": { "MCP_LOCAL_EMBED": "true" } },
118
+ "devjournal": { "command": "devjournal-mcp" },
119
+ "checkpoint": { "command": "checkpoint-mcp" },
120
+ "context-pack": { "command": "context-pack-mcp" }
121
+ }
122
+ }
123
+ ```
124
+
125
+ #### 4. Armada Fleet MCP *(opsional — butuh fleet Armada sendiri)*
126
+
127
+ `armada-mcp` tidak dipasang otomatis oleh `init` karena ia menunjuk ke bus
128
+ milikmu. Tambahkan manual ke klien yang perlu akses fleet:
129
+
130
+ ```json
131
+ {
132
+ "mcpServers": {
133
+ "armada": {
134
+ "command": "npx",
135
+ "args": ["-y", "-p", "@maximalabs/dev-mcp-suite", "armada-mcp"],
136
+ "env": {
137
+ "ARMADA_BUS_URL": "https://bus.example.com",
138
+ "ARMADA_BUS_TOKEN": "<token-agen>",
139
+ "ARMADA_AGENT": "claude-code"
140
+ }
141
+ }
142
+ }
143
+ }
144
+ ```
145
+
146
+ Tanpa `env`, server membaca `~/.config/armada/agent.env` — file yang sama
147
+ yang dipakai [`armada` CLI](https://github.com/verrysimatupang99/armada),
148
+ jadi kredensial berbagi satu tempat. `ARMADA_BUS_URL` adalah *origin* bus
149
+ tanpa suffix `/bus`. Ingat: grant dieksekusi oleh policy di host target —
150
+ mode `user`/`root`/`sandbox` hanya jalan bila host mengizinkan agenmu.
151
+
152
+ 👉 See detailed client setup guides in [`docs/clients/`](docs/clients/).
153
+
154
+ ---
155
+
156
+ ### 🚀 Daily Solo Developer Workflow
157
+
158
+ - **Session Start**: Run `pack_overview` + `journal_resume` + `memory_recall "<topic>"` to get oriented in seconds.
159
+ - **Before Risky Changes**: Run `checkpoint_create` to create a safe recovery point.
160
+ - **While Coding**: Run `memory_save` to store architectural decisions, and `pack_audit` before committing.
161
+ - **Session End / Compaction**: Run `journal_handoff` so your next session picks up right where you left off.
162
+
163
+ ---
164
+
165
+ ### 📊 Utility CLIs Included
166
+
167
+ Install globally with `npm i -g @maximalabs/dev-mcp-suite` to access built-in maintenance tools:
168
+
169
+ - `stats` — View total notes, journal activity, and storage stats across all projects (`stats --json`).
170
+ - `prune` — Safely clean up temporary project scratch files (`prune --yes`).
171
+ - `provider-smoke` — Probe configured LLM providers (chat & embedding endpoints) for health and latency.
172
+
173
+ ---
174
+
175
+ ### 🔒 Privacy & Local-First Philosophy
176
+
177
+ - **Zero Cloud Backend**: Everything is saved locally as plain Markdown & JSON files on your hard drive (`~/.ai-shared-memory` or project directory).
178
+ - **Zero Telemetry**: No tracking, no user accounts, no phoning home.
179
+ - **Network Isolation Ready**: Set `MCP_DETERMINISTIC_FALLBACK=true` for 100% air-gapped, offline operations.
180
+ - See detailed [privacy and data flow documentation](docs/privacy.md).
181
+
182
+ ---
183
+
184
+ ### ☕ Support / Donasi
185
+
186
+ Jika `@maximalabs/dev-mcp-suite` membantu alur kerja pengkodean Anda dan menghemat waktu Anda, dukung pengembangan proyek open-source ini melalui Saweria (QRIS, GoPay, DANA, OVO, ShopeePay):
187
+
188
+ [![Saweria](https://img.shields.io/badge/Saweria-Dukung%20Proyek-FAAE2B?style=for-the-badge&logo=saweria&logoColor=black)](https://saweria.co/sijuling)
189
+
190
+ ---
191
+
192
+ ### 📄 License
193
+
194
+ MIT © Verry Simatupang — see [LICENSE](./LICENSE).
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "armada-mcp",
3
+ "version": "1.0.0",
4
+ "description": "Fleet ops MCP for Armada (MaximaLabs): health watch + policy-gated remote jobs on many hosts",
5
+ "type": "module",
6
+ "main": "server.js",
7
+ "scripts": {
8
+ "start": "node server.js",
9
+ "test": "node test.mjs"
10
+ },
11
+ "dependencies": {
12
+ "@modelcontextprotocol/sdk": "^1.0.0"
13
+ }
14
+ }
@@ -0,0 +1,329 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Armada MCP Server — fleet ops for AI agents.
5
+ *
6
+ * Talks to an Armada bus (https://github.com/verrysimatupang99/armada):
7
+ * an append-only mailbox + job queue that thin wr-node daemons poll from
8
+ * every host — outbound only, no inbound ports, no SSH fan-in.
9
+ *
10
+ * Agents use these tools to watch host health and enqueue policy-gated
11
+ * jobs. Whether a job actually runs is decided by the TARGET host's own
12
+ * policy (capability ladder: health < allow < user < root < sandbox);
13
+ * this server only delivers requests — the node has veto.
14
+ *
15
+ * Config (env): ARMADA_BUS_URL or BUS_URL (origin, no /bus suffix),
16
+ * ARMADA_BUS_TOKEN or BUS_TOKEN, ARMADA_AGENT (agent identity label).
17
+ * Fallback: ~/.config/armada/agent.env — the same file the `armada` CLI
18
+ * reads, so credentials are shared.
19
+ *
20
+ * Tools: fleet_health, fleet_jobs, job_post, job_status, job_watch,
21
+ * job_tail, job_cancel, bus_note, bus_read
22
+ */
23
+
24
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
25
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
26
+ import {
27
+ CallToolRequestSchema,
28
+ ListToolsRequestSchema,
29
+ } from "@modelcontextprotocol/sdk/types.js";
30
+ import fs from "fs";
31
+ import os from "os";
32
+ import path from "path";
33
+
34
+ // ---------- config ----------
35
+
36
+ function loadAgentEnv() {
37
+ try {
38
+ const p = path.join(os.homedir(), ".config", "armada", "agent.env");
39
+ for (const line of fs.readFileSync(p, "utf8").split("\n")) {
40
+ const i = line.indexOf("=");
41
+ if (i <= 0 || line.trim().startsWith("#")) continue;
42
+ const k = line.slice(0, i).trim();
43
+ const v = line.slice(i + 1).trim().replace(/^["']|["']$/g, "");
44
+ if (k && !(k in process.env)) process.env[k] = v;
45
+ }
46
+ } catch {}
47
+ }
48
+ loadAgentEnv();
49
+
50
+ const BUS_URL = (process.env.ARMADA_BUS_URL || process.env.BUS_URL || "")
51
+ .replace(/\/+$/, "");
52
+ const TOKEN = (process.env.ARMADA_BUS_TOKEN || process.env.BUS_TOKEN || "").trim();
53
+ const AGENT = (process.env.ARMADA_AGENT || os.hostname()).slice(0, 64);
54
+ const MODES = ["allow", "user", "root", "sandbox"];
55
+
56
+ // ---------- bus client ----------
57
+
58
+ async function bus(method, p, body) {
59
+ if (!BUS_URL) throw new Error("ARMADA_BUS_URL/BUS_URL kosong — set env atau ~/.config/armada/agent.env");
60
+ if (!TOKEN) throw new Error("ARMADA_BUS_TOKEN/BUS_TOKEN kosong — set env atau ~/.config/armada/agent.env");
61
+ const res = await fetch(BUS_URL + p, {
62
+ method,
63
+ headers: { "X-Bus-Token": TOKEN, "Content-Type": "application/json" },
64
+ body: body === undefined ? undefined : JSON.stringify(body),
65
+ });
66
+ const raw = await res.text();
67
+ let data;
68
+ try { data = JSON.parse(raw); } catch { data = raw; }
69
+ if (!res.ok) {
70
+ const msg = typeof data === "object" && data?.error ? data.error : `HTTP ${res.status}`;
71
+ const e = new Error(`bus ${method} ${p}: ${msg}`);
72
+ e.status = res.status;
73
+ throw e;
74
+ }
75
+ return data;
76
+ }
77
+
78
+ const ok = (text) => ({ content: [{ type: "text", text }] });
79
+ const terminal = (s) => ["done", "failed", "expired", "cancelled"].includes(s);
80
+
81
+ // ---------- server ----------
82
+
83
+ class ArmadaServer {
84
+ constructor() {
85
+ this.server = new Server({ name: "armada", version: "1.0.0" }, { capabilities: { tools: {} } });
86
+ this.setup();
87
+ }
88
+
89
+ setup() {
90
+ this.server.setRequestHandler(ListToolsRequestSchema, () => ({
91
+ tools: [
92
+ {
93
+ name: "fleet_health",
94
+ description: "Fleet status board: which hosts heartbeat recently (online vs stale) and which agents are active. Call first to see what hosts exist before posting jobs.",
95
+ inputSchema: { type: "object", properties: {} },
96
+ },
97
+ {
98
+ name: "fleet_jobs",
99
+ description: "List the most recent jobs across the fleet (id, host, agent, mode, state, exit code).",
100
+ inputSchema: {
101
+ type: "object",
102
+ properties: {
103
+ state: { type: "string", description: "Filter: queued|claimed|done|failed|expired|cancelled (default: all)" },
104
+ },
105
+ },
106
+ },
107
+ {
108
+ name: "job_post",
109
+ description: "Enqueue a job on a host. argv is exec'd directly (no shell — no pipes/;). mode: 'allow' = strict allowlist, 'user' = daemon's user, 'root' = sudo, 'sandbox' = docker container. The HOST's policy grants or denies — a 200 here means queued, not permitted. Set dedupe for idempotent retry.",
110
+ inputSchema: {
111
+ type: "object",
112
+ properties: {
113
+ host: { type: "string", description: "Target host name (see fleet_health)" },
114
+ argv: { type: "array", items: { type: "string" }, description: "Command argv, e.g. [\"df\",\"-h\"]" },
115
+ mode: { type: "string", enum: MODES, default: "allow" },
116
+ dedupe: { type: "string", description: "Idempotency key — reposts return the original job" },
117
+ after_id: { type: "string", description: "Run only after this job id finishes done" },
118
+ timeout_sec: { type: "number", description: "Kill after N seconds (default 300)" },
119
+ ttl_sec: { type: "number", description: "Expire if unclaimed for N seconds (default 86400)" },
120
+ priority: { type: "number", description: "Lower runs earlier (default 50)" },
121
+ env_profile: { type: "string", description: "Name of a LOCAL env profile on the target host — secrets never transit the bus" },
122
+ },
123
+ required: ["host", "argv"],
124
+ },
125
+ },
126
+ {
127
+ name: "job_status",
128
+ description: "Current state of one job: queued|claimed|done|failed|expired|cancelled, cancel flag, exit code.",
129
+ inputSchema: {
130
+ type: "object",
131
+ properties: { id: { type: "string", description: "Job id" } },
132
+ required: ["id"],
133
+ },
134
+ },
135
+ {
136
+ name: "job_watch",
137
+ description: "Poll a job until it reaches a terminal state or max_wait_sec elapses. Returns state + exit code.",
138
+ inputSchema: {
139
+ type: "object",
140
+ properties: {
141
+ id: { type: "string", description: "Job id" },
142
+ max_wait_sec: { type: "number", description: "Give up after N seconds (default 60, max 300)", default: 60 },
143
+ },
144
+ required: ["id"],
145
+ },
146
+ },
147
+ {
148
+ name: "job_tail",
149
+ description: "Read a job's audit trail: streamed stdout chunks + final result (exit code, stdout, stderr).",
150
+ inputSchema: {
151
+ type: "object",
152
+ properties: { id: { type: "string", description: "Job id" } },
153
+ required: ["id"],
154
+ },
155
+ },
156
+ {
157
+ name: "job_cancel",
158
+ description: "Cancel a job: queued jobs are cancelled outright; claimed jobs get a cancel flag the node honours by killing the process.",
159
+ inputSchema: {
160
+ type: "object",
161
+ properties: { id: { type: "string", description: "Job id" } },
162
+ required: ["id"],
163
+ },
164
+ },
165
+ {
166
+ name: "bus_note",
167
+ description: "Leave a note on a bus topic for other agents (append-only, never deleted — don't post secrets).",
168
+ inputSchema: {
169
+ type: "object",
170
+ properties: {
171
+ topic: { type: "string", description: "Topic name", default: "warroom" },
172
+ text: { type: "string", description: "Note body" },
173
+ kind: { type: "string", description: "Message kind (default: note)", default: "note" },
174
+ },
175
+ required: ["text"],
176
+ },
177
+ },
178
+ {
179
+ name: "bus_read",
180
+ description: "Read messages on a bus topic (e.g. 'warroom', 'health/<host>', 'job/<id>').",
181
+ inputSchema: {
182
+ type: "object",
183
+ properties: {
184
+ topic: { type: "string", description: "Topic name", default: "warroom" },
185
+ since: { type: "number", description: "Only seq > N", default: 0 },
186
+ limit: { type: "number", description: "Max messages (default 20)", default: 20 },
187
+ },
188
+ },
189
+ },
190
+ ],
191
+ }));
192
+
193
+ this.server.setRequestHandler(CallToolRequestSchema, async (req) => {
194
+ const { name, arguments: args } = req.params;
195
+ try {
196
+ switch (name) {
197
+ case "fleet_health": return await this.fleetHealth();
198
+ case "fleet_jobs": return await this.fleetJobs(args || {});
199
+ case "job_post": return await this.jobPost(args || {});
200
+ case "job_status": return await this.jobStatus(args || {});
201
+ case "job_watch": return await this.jobWatch(args || {});
202
+ case "job_tail": return await this.jobTail(args || {});
203
+ case "job_cancel": return await this.jobCancel(args || {});
204
+ case "bus_note": return await this.busNote(args || {});
205
+ case "bus_read": return await this.busRead(args || {});
206
+ default: throw new Error(`Unknown tool: ${name}`);
207
+ }
208
+ } catch (e) {
209
+ return { content: [{ type: "text", text: `Error: ${e.message}` }], isError: true };
210
+ }
211
+ });
212
+ }
213
+
214
+ async fleetHealth() {
215
+ const [topics, agents] = await Promise.all([
216
+ bus("GET", "/bus/topics"),
217
+ bus("GET", "/bus/agents"),
218
+ ]);
219
+ const now = Date.now() / 1000;
220
+ const lines = [`bus: ${BUS_URL}`, "", "hosts (heartbeat):"];
221
+ const healthTopics = (topics.topics || []).filter((t) => t.topic.startsWith("health/"));
222
+ if (!healthTopics.length) lines.push(" (none yet)");
223
+ for (const t of healthTopics.sort((a, b) => b.last_ts - a.last_ts)) {
224
+ const age = Math.round(now - t.last_ts);
225
+ const state = age > 300 ? "STALE" : "ok";
226
+ lines.push(` ${t.topic.replace("health/", "").padEnd(20)} ${state.padEnd(5)} ${age}s ago (${t.n} beats)`);
227
+ }
228
+ lines.push("", "agents seen:");
229
+ const seen = (agents.agents || [])
230
+ .sort((a, b) => b.last_ts - a.last_ts).slice(0, 15);
231
+ if (!seen.length) lines.push(" (none)");
232
+ for (const a of seen) {
233
+ lines.push(` ${a.agent}@${a.host || "-"} ${Math.round(now - a.last_ts)}s ago`);
234
+ }
235
+ return ok(lines.join("\n"));
236
+ }
237
+
238
+ async fleetJobs({ state }) {
239
+ const r = await bus("GET", "/bus/job/list" + (state ? `?state=${encodeURIComponent(state)}` : ""));
240
+ const jobs = r.jobs || [];
241
+ if (!jobs.length) return ok("no jobs");
242
+ const lines = jobs.slice(0, 30).map((j) =>
243
+ `${String(j.id).slice(0, 20).padEnd(22)} ${String(j.host).slice(0, 14).padEnd(15)} ` +
244
+ `${String(j.agent).slice(0, 18).padEnd(19)} ${String(j.mode).padEnd(8)} ${String(j.state).padEnd(9)} ` +
245
+ `exit=${j.exit_code ?? "-"}`
246
+ );
247
+ return ok(lines.join("\n"));
248
+ }
249
+
250
+ async jobPost(a) {
251
+ if (!Array.isArray(a.argv) || !a.argv.length || !a.argv.every((x) => typeof x === "string"))
252
+ throw new Error("argv wajib array string non-kosong");
253
+ const body = {
254
+ host: a.host, mode: a.mode || "allow", argv: a.argv,
255
+ dedupe: a.dedupe, after_id: a.after_id, ttl_sec: a.ttl_sec,
256
+ timeout_sec: a.timeout_sec, priority: a.priority, env_profile: a.env_profile,
257
+ };
258
+ for (const k of Object.keys(body)) if (body[k] === undefined) delete body[k];
259
+ const r = await bus("POST", "/bus/job/post", body);
260
+ return ok(`${r.id} state=${r.state}${r.deduped ? " (deduped)" : ""}\n` +
261
+ `queued on ${a.host} as ${AGENT} — run job_watch to follow, job_tail for output`);
262
+ }
263
+
264
+ async jobStatus({ id }) {
265
+ const r = await bus("GET", `/bus/job/status?id=${encodeURIComponent(id)}`);
266
+ return ok(JSON.stringify(r));
267
+ }
268
+
269
+ async jobWatch({ id, max_wait_sec = 60 }) {
270
+ const cap = Math.min(Number(max_wait_sec) || 60, 300);
271
+ const deadline = Date.now() + cap * 1000;
272
+ const seen = [];
273
+ while (Date.now() < deadline) {
274
+ const r = await bus("GET", `/bus/job/status?id=${encodeURIComponent(id)}`);
275
+ const line = `${r.state}${r.exit_code != null ? ` exit=${r.exit_code}` : ""}`;
276
+ if (seen[seen.length - 1] !== line) seen.push(line);
277
+ if (terminal(r.state)) {
278
+ return ok(`${id}: ${seen.join(" → ")}\n(final: ${line})`);
279
+ }
280
+ await new Promise((r2) => setTimeout(r2, 3000));
281
+ }
282
+ return ok(`${id}: ${seen.join(" → ")}\n(still running after ${cap}s — check job_tail)`);
283
+ }
284
+
285
+ async jobTail({ id }) {
286
+ const [msgs, list] = await Promise.all([
287
+ bus("GET", `/bus/messages?topic=${encodeURIComponent("job/" + id)}&limit=100`),
288
+ bus("GET", "/bus/job/list"),
289
+ ]);
290
+ const lines = [];
291
+ for (const m of msgs.messages || []) {
292
+ const body = m.kind === "result"
293
+ ? (() => { try { const j = JSON.parse(m.text); return `result exit=${j.exit_code}\nstdout:\n${j.stdout || ""}\nstderr:\n${j.stderr || ""}`; } catch { return m.text; } })()
294
+ : m.text;
295
+ lines.push(`[${m.agent} ${m.kind}] ${body}`);
296
+ }
297
+ const j = (list.jobs || []).find((x) => x.id === id);
298
+ if (j) lines.push(`-- state=${j.state} exit=${j.exit_code ?? "-"} claimed_by=${j.claim_agent || "-"}`);
299
+ return ok(lines.length ? lines.join("\n") : `no audit yet for ${id}`);
300
+ }
301
+
302
+ async jobCancel({ id }) {
303
+ const r = await bus("POST", "/bus/job/cancel", { id });
304
+ return ok(`cancel ${id}: ${JSON.stringify(r)}`);
305
+ }
306
+
307
+ async busNote({ topic = "warroom", text, kind = "note" }) {
308
+ if (!text || !String(text).trim()) throw new Error("text wajib");
309
+ const r = await bus("POST", "/bus/post", {
310
+ topic, text: String(text), kind, agent: AGENT,
311
+ });
312
+ return ok(`posted to ${r.topic} seq=${r.seq} as ${AGENT}`);
313
+ }
314
+
315
+ async busRead({ topic = "warroom", since = 0, limit = 20 }) {
316
+ const r = await bus("GET",
317
+ `/bus/messages?topic=${encodeURIComponent(topic)}&since=${since}&limit=${limit}`);
318
+ const msgs = r.messages || [];
319
+ if (!msgs.length) return ok(`(kosong di topic ${topic})`);
320
+ const lines = msgs.map((m) => {
321
+ const ts = new Date(m.ts * 1000).toISOString().slice(11, 19);
322
+ return `${ts} #${m.seq} [${m.agent}@${m.host || "-"}] ${m.text.slice(0, 500)}`;
323
+ });
324
+ return ok(lines.join("\n"));
325
+ }
326
+ }
327
+
328
+ const srv = new ArmadaServer();
329
+ await srv.server.connect(new StdioServerTransport());