@d86e/hive-panel 0.0.0-stage → 0.3.5

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.
package/src/actions.js ADDED
@@ -0,0 +1,59 @@
1
+ import { execFile } from "node:child_process";
2
+
3
+ const exec = (file, args, cwd) => new Promise((resolve) => {
4
+ execFile(file, args, { cwd, maxBuffer: 16 * 1024 * 1024, timeout: 30 * 60 * 1000 }, (error, stdout, stderr) => {
5
+ resolve({ ok: !error, code: error ? (error.code || 1) : 0, stdout: stdout || "", stderr: stderr || "" });
6
+ });
7
+ });
8
+
9
+ const list = (value) => (Array.isArray(value) ? value : value ? [value] : []);
10
+
11
+ /** One action name -> argv builder. Every write goes through here; nothing else is callable. */
12
+ const ACTIONS = {
13
+ init: (p) => ["init", ...(p.force ? ["--force"] : [])],
14
+ add: (p) => {
15
+ const args = ["add", "--title", String(p.title || "")];
16
+ if (p.role) args.push("--role", p.role);
17
+ for (const scope of list(p.scope)) args.push("--scope", scope);
18
+ for (const after of list(p.after)) args.push("--after", after);
19
+ if (p.acceptance) args.push("--acceptance", p.acceptance);
20
+ if (p.priority) args.push("--priority", String(p.priority));
21
+ return args;
22
+ },
23
+ plan: (p) => ["plan", "--goal", String(p.goal || ""), "--max-cards", String(p.maxCards || 8), ...(p.apply ? ["--apply"] : [])],
24
+ claim: (p) => ["claim", String(p.id), "--agent", String(p.agent || "panel"), "--ttl", String(p.ttl || "5m")],
25
+ done: (p) => ["done", String(p.id), ...(p.sha ? ["--sha", String(p.sha)] : []), ...(p.verdict ? ["--verdict", String(p.verdict)] : [])],
26
+ fail: (p) => ["fail", String(p.id), "--reason", String(p.reason || "failed from panel")],
27
+ retry: (p) => ["retry", String(p.id)],
28
+ block: (p) => ["block", String(p.id), "--reason", String(p.reason || "blocked from panel")],
29
+ renew: (p) => ["renew", String(p.id), "--ttl", String(p.ttl || "5m"), ...(p.agent ? ["--agent", String(p.agent)] : [])],
30
+ mode: (p) => ["mode", p.mode === "freeze" ? "freeze" : "free", "--reason", String(p.reason || "panel")],
31
+ learn: (p) => ["lesson", "add", "--scope", String(p.scope || ""), String(p.text || "")],
32
+ recall: (p) => ["recall", String(p.scope || ""), ...(p.limit ? ["--limit", String(p.limit)] : [])],
33
+ verdict: (p) => ["verdict", String(p.sha || "HEAD"), "--result", String(p.result || "pass"), ...(p.note ? ["--note", String(p.note)] : [])],
34
+ run: (p) => ["run", "--once", "--agent", String(p.agent || "panel"), "--concurrency", String(p.concurrency || 3), ...(p.budget ? ["--budget", String(p.budget)] : []), ...(p.timeout ? ["--timeout", String(p.timeout)] : [])],
35
+ commit: (p) => ["commit", "-m", String(p.message || "panel commit"), ...list(p.set).flatMap((entry) => ["--set", String(entry)])],
36
+ doctor: () => ["doctor"],
37
+ };
38
+
39
+ const BIN = {
40
+ init: "HIVE_BIN", add: "HIVE_TASKS_BIN", plan: "HIVE_RUN_BIN", claim: "HIVE_TASKS_BIN",
41
+ done: "HIVE_TASKS_BIN", fail: "HIVE_TASKS_BIN", retry: "HIVE_TASKS_BIN", block: "HIVE_TASKS_BIN",
42
+ renew: "HIVE_TASKS_BIN", mode: "HIVE_BIN", learn: "HIVE_BIN", recall: "HIVE_BIN",
43
+ verdict: "HIVE_BIN", run: "HIVE_RUN_BIN", commit: "MOC_BIN", doctor: "HIVE_BIN",
44
+ };
45
+
46
+ const FALLBACK = {
47
+ HIVE_BIN: "hive", HIVE_TASKS_BIN: "hive-tasks", HIVE_RUN_BIN: "hive-run", MOC_BIN: "moc",
48
+ };
49
+
50
+ export function listActions() {
51
+ return Object.keys(ACTIONS);
52
+ }
53
+
54
+ export async function runAction(name, payload, { cwd, env = process.env }) {
55
+ const build = ACTIONS[name];
56
+ if (!build) return { ok: false, code: 2, stdout: "", stderr: "unknown action: " + name };
57
+ const file = env[BIN[name]] || FALLBACK[BIN[name]];
58
+ return exec(file, build(payload || {}), cwd);
59
+ }
package/src/data.js ADDED
@@ -0,0 +1,58 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { spawnSync } from "node:child_process";
4
+
5
+ function run(file, args, cwd) {
6
+ const result = spawnSync(file, args, { cwd, encoding: "utf8", maxBuffer: 16 * 1024 * 1024 });
7
+ return { code: result.status, stdout: result.stdout || "", stderr: result.stderr || "" };
8
+ }
9
+
10
+ function json(file, args, cwd, fallback) {
11
+ const result = run(file, args, cwd);
12
+ if (result.code !== 0) return fallback;
13
+ try { return JSON.parse(result.stdout); } catch { return fallback; }
14
+ }
15
+
16
+ export function readMode(repo) {
17
+ const result = run("git", ["cat-file", "-p", "refs/hive/v1/mode"], repo);
18
+ if (result.code !== 0) return { mode: "free" };
19
+ try { return JSON.parse(result.stdout); } catch { return { mode: "free" }; }
20
+ }
21
+
22
+ export function readEvents(repo, limit = 80) {
23
+ const file = path.join(repo, ".hive", "events.jsonl");
24
+ if (!fs.existsSync(file)) return [];
25
+ const lines = fs.readFileSync(file, "utf8").split("\n").filter(Boolean).slice(-limit);
26
+ return lines.map((line) => {
27
+ try { return JSON.parse(line); } catch { return null; }
28
+ }).filter(Boolean).reverse();
29
+ }
30
+
31
+ /** True once Hive has written anything under refs/hive/v1 (the ref itself or a sub-ref). */
32
+ export function isInitialised(repo) {
33
+ const result = run("git", ["for-each-ref", "--format=%(refname)", "refs/hive/v1"], repo);
34
+ return result.code === 0 && result.stdout.trim() !== "";
35
+ }
36
+
37
+ export function snapshot(repo, env = process.env) {
38
+ const initialised = isInitialised(repo);
39
+ const data = {
40
+ at: new Date().toISOString(),
41
+ repo,
42
+ initialised,
43
+ mode: readMode(repo),
44
+ board: [],
45
+ tasks: [],
46
+ stats: null,
47
+ events: readEvents(repo),
48
+ };
49
+ if (!initialised) return data;
50
+ const hive = env.HIVE_BIN || "hive";
51
+ const tasks = env.HIVE_TASKS_BIN || "hive-tasks";
52
+ return {
53
+ ...data,
54
+ board: json(hive, ["board", "--json"], repo, []),
55
+ tasks: json(tasks, ["list", "--json"], repo, []),
56
+ stats: json(tasks, ["stats", "--json"], repo, null),
57
+ };
58
+ }
package/src/server.js ADDED
@@ -0,0 +1,81 @@
1
+ import fs from "node:fs";
2
+ import http from "node:http";
3
+ import path from "node:path";
4
+ import { execFile } from "node:child_process";
5
+ import { snapshot } from "./data.js";
6
+ import { listActions, runAction } from "./actions.js";
7
+
8
+ const MIME = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".svg": "image/svg+xml" };
9
+
10
+ function run(file, args, cwd) {
11
+ return new Promise((resolve) => {
12
+ execFile(file, args, { cwd, maxBuffer: 8 * 1024 * 1024 }, (error, stdout, stderr) => {
13
+ resolve({ ok: !error, code: error && error.code, stdout: stdout || "", stderr: stderr || "" });
14
+ });
15
+ });
16
+ }
17
+
18
+ function body(request) {
19
+ return new Promise((resolve) => {
20
+ let raw = "";
21
+ request.on("data", (chunk) => { raw += chunk; if (raw.length > 1e6) request.destroy(); });
22
+ request.on("end", () => {
23
+ try { resolve(JSON.parse(raw || "{}")); } catch { resolve({}); }
24
+ });
25
+ });
26
+ }
27
+
28
+ export function createServer({ repo, publicDir, env = process.env, writable = false }) {
29
+ const hive = env.HIVE_BIN || "hive";
30
+ const tasks = env.HIVE_TASKS_BIN || "hive-tasks";
31
+ const server = http.createServer(async (request, response) => {
32
+ const url = new URL(request.url, "http://localhost");
33
+
34
+ if (url.pathname === "/api/health") {
35
+ const address = server.address();
36
+ const data = { ok: true, repo, port: address && typeof address === "object" ? address.port : null, pid: process.pid };
37
+ response.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
38
+ return response.end(JSON.stringify(data));
39
+ }
40
+
41
+ if (url.pathname === "/api/snapshot") {
42
+ const data = { ...snapshot(repo, env), writable };
43
+ response.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
44
+ return response.end(JSON.stringify(data));
45
+ }
46
+
47
+ if (url.pathname === "/api/actions") {
48
+ response.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
49
+ return response.end(JSON.stringify({ writable, actions: listActions() }));
50
+ }
51
+
52
+ if (request.method === "POST" && url.pathname.startsWith("/api/")) {
53
+ if (!writable) {
54
+ response.writeHead(403, { "content-type": "application/json" });
55
+ return response.end(JSON.stringify({ error: "read-only: start with --write" }));
56
+ }
57
+ const payload = await body(request);
58
+ let result = { ok: false, code: 2, stdout: "", stderr: "unknown action" };
59
+ const match = url.pathname.match(/^\/api\/actions\/([a-z]+)$/);
60
+ if (match) result = await runAction(match[1], payload, { cwd: repo, env });
61
+ else if (url.pathname === "/api/mode") {
62
+ result = await runAction("mode", { mode: payload.mode }, { cwd: repo, env });
63
+ } else if (url.pathname === "/api/retry") {
64
+ result = payload.id ? await runAction("retry", { id: payload.id }, { cwd: repo, env }) : { error: "id required" };
65
+ }
66
+ response.writeHead(result.ok ? 200 : 400, { "content-type": "application/json" });
67
+ return response.end(JSON.stringify(result));
68
+ }
69
+
70
+ const relative = url.pathname === "/" ? "/index.html" : url.pathname;
71
+ const file = path.join(publicDir, path.normalize(relative).replace(/^(\.\.[/\\])+/, ""));
72
+ if (!file.startsWith(publicDir) || !fs.existsSync(file)) {
73
+ response.writeHead(404, { "content-type": "text/plain" });
74
+ return response.end("not found");
75
+ }
76
+ response.writeHead(200, { "content-type": MIME[path.extname(file)] || "application/octet-stream", "cache-control": "no-store" });
77
+ fs.createReadStream(file).pipe(response);
78
+ });
79
+
80
+ return server;
81
+ }