cohorte 3.2.0 → 3.3.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.
- package/CHANGELOG.md +14 -0
- package/bin/cli.js +8 -3
- package/package.json +6 -2
- package/scripts/build-ui.mjs +28 -0
- package/ui/dist-server/server/docker.js +209 -0
- package/ui/dist-server/server/findings.js +64 -0
- package/ui/dist-server/server/gitinfo.js +171 -0
- package/ui/dist-server/server/history.js +96 -0
- package/ui/dist-server/server/jobs.js +162 -0
- package/ui/dist-server/server/legacy.js +29 -0
- package/ui/dist-server/server/ops.js +202 -0
- package/ui/dist-server/server/pipeline.js +89 -0
- package/ui/dist-server/server/runs.js +284 -0
- package/ui/dist-server/server/server.js +544 -0
- package/ui/dist-server/shared/api.js +4 -0
- package/ui/dist-web/assets/index-Clp1YW4S.js +152 -0
- package/ui/dist-web/assets/style-0oNNMjwU.css +1 -0
- package/ui/dist-web/index.html +15 -0
- package/ui/docker.js +0 -147
- package/ui/jobs.js +0 -127
- package/ui/ops.js +0 -164
- package/ui/public/app.js +0 -420
- package/ui/public/index.html +0 -13
- package/ui/public/style.css +0 -35
- package/ui/runs.js +0 -213
- package/ui/server.js +0 -299
package/ui/runs.js
DELETED
|
@@ -1,213 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
// cohorte ui — runs a pipeline command (`/cohorte-build f1`) through `claude -p`, headless, and turns the
|
|
3
|
-
// stream into a short feed plus the decisions only a human can make.
|
|
4
|
-
//
|
|
5
|
-
// This is NOT a chat: there is no free-form message box. A run is one command in one worktree, and the
|
|
6
|
-
// human's part is limited to the gates the CLI raises on its control channel — a permission ask (the
|
|
7
|
-
// project's gate answering `ask`, or Claude Code's own prompt) and AskUserQuestion (the interview
|
|
8
|
-
// commands). Protocol, verified against Claude Code 2.1.326:
|
|
9
|
-
//
|
|
10
|
-
// claude -p --output-format stream-json --input-format stream-json --permission-prompt-tool stdio --verbose
|
|
11
|
-
// stdin ← {"type":"user","message":{"role":"user","content":[{"type":"text","text":"/cohorte-build f1"}]}}
|
|
12
|
-
// stdout → system | assistant | user(tool_result) | control_request(can_use_tool) | result (NDJSON)
|
|
13
|
-
// stdin ← {"type":"control_response","response":{"subtype":"success","request_id":…,
|
|
14
|
-
// "response":{"behavior":"allow","updatedInput":…}}} or {"behavior":"deny","message":…}
|
|
15
|
-
//
|
|
16
|
-
// Our stdin is also the CLI's EOF signal. It is closed only once the turn's `result` is in, nothing is
|
|
17
|
-
// parked on a human, and the stream has been quiet for a moment (a background subagent's asks would
|
|
18
|
-
// otherwise be thrown away at the source with "Stream closed").
|
|
19
|
-
|
|
20
|
-
const crypto = require('crypto');
|
|
21
|
-
const readline = require('readline');
|
|
22
|
-
const { spawn } = require('child_process');
|
|
23
|
-
|
|
24
|
-
const MAX_EVENTS = 3000;
|
|
25
|
-
const QUIET_AFTER_RESULT_MS = 2000;
|
|
26
|
-
const MODES = ['default', 'acceptEdits', 'plan']; // never bypassPermissions: the gate's asks would turn into denials
|
|
27
|
-
const DENY_MESSAGE = 'cohorte ui: the user denied this tool call.';
|
|
28
|
-
|
|
29
|
-
const clip = (s, n) => { s = String(s == null ? '' : s); return s.length > n ? `${s.slice(0, n)}…` : s; };
|
|
30
|
-
|
|
31
|
-
function summarize(name, input) {
|
|
32
|
-
const i = input && typeof input === 'object' ? input : {};
|
|
33
|
-
if (name === 'Bash') return clip(i.command, 400);
|
|
34
|
-
if (name === 'Task' || name === 'Agent') return clip(`${i.subagent_type || 'agent'} — ${i.description || ''}`, 200);
|
|
35
|
-
if (i.file_path) return clip(i.file_path, 300);
|
|
36
|
-
if (i.path) return clip(i.path, 300);
|
|
37
|
-
if (i.pattern) return clip(i.pattern, 200);
|
|
38
|
-
try { return clip(JSON.stringify(i), 300); } catch { return ''; }
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
class Runs {
|
|
42
|
-
constructor({ bin } = {}) { this.runs = new Map(); this.bin = bin || process.env.COHORTE_CLAUDE_BIN || 'claude'; }
|
|
43
|
-
|
|
44
|
-
// opts: { projectId, cwd, command (e.g. "/cohorte-build f1"), permissionMode }
|
|
45
|
-
start(opts) {
|
|
46
|
-
const mode = MODES.includes(opts.permissionMode) ? opts.permissionMode : 'default';
|
|
47
|
-
const run = {
|
|
48
|
-
id: crypto.randomBytes(4).toString('hex'), projectId: opts.projectId, cwd: opts.cwd, command: opts.command,
|
|
49
|
-
permissionMode: mode, status: 'running', startedAt: new Date().toISOString(), endedAt: null,
|
|
50
|
-
events: [], dropped: 0, pending: new Map(), result: null, sessionId: null, child: null, closeTimer: null, stopping: false,
|
|
51
|
-
};
|
|
52
|
-
this.#spawn(run, null);
|
|
53
|
-
this.runs.set(run.id, run);
|
|
54
|
-
this.#write(run, { type: 'user', message: { role: 'user', content: [{ type: 'text', text: opts.command }] } });
|
|
55
|
-
return run;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
// One `claude -p` process for the run's next turn. A reply resumes the same session in a new process.
|
|
59
|
-
#spawn(run, resumeId) {
|
|
60
|
-
const args = ['-p', '--output-format', 'stream-json', '--input-format', 'stream-json', '--permission-prompt-tool', 'stdio', '--verbose'];
|
|
61
|
-
if (run.permissionMode !== 'default') args.push('--permission-mode', run.permissionMode);
|
|
62
|
-
if (resumeId) args.push('--resume', resumeId);
|
|
63
|
-
const child = spawn(this.bin, args, { cwd: run.cwd, detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe'], env: process.env });
|
|
64
|
-
run.child = child;
|
|
65
|
-
child.stdin.on('error', () => { /* the child went away first */ });
|
|
66
|
-
child.on('error', (e) => { this.#push(run, { kind: 'system', text: `could not start ${this.bin}: ${e.message}` }); if (run.child === child) this.#end(run, 'failed'); });
|
|
67
|
-
readline.createInterface({ input: child.stdout }).on('line', (line) => { if (run.child === child) this.#line(run, line); });
|
|
68
|
-
child.stderr.on('data', (d) => this.#push(run, { kind: 'stderr', text: clip(String(d).trim(), 1000) }));
|
|
69
|
-
child.on('close', (code) => {
|
|
70
|
-
if (run.child !== child) return;
|
|
71
|
-
clearTimeout(run.closeTimer);
|
|
72
|
-
if (run.status === 'running') this.#end(run, run.stopping ? 'stopped' : run.result && !run.result.ok ? 'failed' : code === 0 ? 'done' : 'failed');
|
|
73
|
-
run.exitCode = code;
|
|
74
|
-
});
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
// Answers the command's free-text question (or steers it) in the SAME session. Only a Cohorte run
|
|
78
|
-
// that has ended its turn: there is no free-standing conversation here.
|
|
79
|
-
reply(run, text) {
|
|
80
|
-
if (!/^\/cohorte-/.test(run.command)) return 'not a cohorte run';
|
|
81
|
-
if (run.status === 'running') return 'the command is still running — answer its gates first, or wait for it to finish';
|
|
82
|
-
if (!run.sessionId) return 'this run has no session to continue';
|
|
83
|
-
if (typeof text !== 'string' || !text.trim() || text.length > 4000) return 'a reply of 1 to 4000 characters is required';
|
|
84
|
-
run.status = 'running'; run.endedAt = null; run.result = null; run.stopping = false;
|
|
85
|
-
this.#push(run, { kind: 'reply', text: text.trim() });
|
|
86
|
-
this.#spawn(run, run.sessionId);
|
|
87
|
-
this.#write(run, { type: 'user', message: { role: 'user', content: [{ type: 'text', text: text.trim() }] } });
|
|
88
|
-
return null;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
#write(run, obj) { try { if (run.child.stdin.writable) run.child.stdin.write(`${JSON.stringify(obj)}\n`); } catch { /* closed */ } }
|
|
92
|
-
|
|
93
|
-
#push(run, ev) {
|
|
94
|
-
run.events.push({ t: Date.now(), ...ev });
|
|
95
|
-
if (run.events.length > MAX_EVENTS) { const cut = run.events.length - MAX_EVENTS; run.events.splice(0, cut); run.dropped += cut; }
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
#end(run, status) { run.status = status; run.endedAt = new Date().toISOString(); run.pending.clear(); }
|
|
99
|
-
|
|
100
|
-
#line(run, line) {
|
|
101
|
-
if (!line.trim()) return;
|
|
102
|
-
let v;
|
|
103
|
-
try { v = JSON.parse(line); } catch { this.#push(run, { kind: 'stderr', text: clip(line, 500) }); return; }
|
|
104
|
-
clearTimeout(run.closeTimer);
|
|
105
|
-
if (v.session_id && !run.sessionId) run.sessionId = v.session_id;
|
|
106
|
-
|
|
107
|
-
if (v.type === 'assistant' && v.message && Array.isArray(v.message.content)) {
|
|
108
|
-
for (const b of v.message.content) {
|
|
109
|
-
if (b.type === 'text' && b.text && b.text.trim()) this.#push(run, { kind: 'text', text: clip(b.text, 8000) });
|
|
110
|
-
else if (b.type === 'tool_use') this.#push(run, { kind: 'tool', id: b.id, name: b.name, summary: summarize(b.name, b.input) });
|
|
111
|
-
}
|
|
112
|
-
} else if (v.type === 'user' && v.message && Array.isArray(v.message.content)) {
|
|
113
|
-
for (const b of v.message.content) {
|
|
114
|
-
if (b.type !== 'tool_result') continue;
|
|
115
|
-
const text = Array.isArray(b.content) ? b.content.map((c) => c.text || '').join('\n') : b.content;
|
|
116
|
-
this.#push(run, { kind: 'tool_result', id: b.tool_use_id, error: b.is_error === true, text: clip(text, 1500) });
|
|
117
|
-
}
|
|
118
|
-
} else if (v.type === 'control_request') {
|
|
119
|
-
this.#control(run, v);
|
|
120
|
-
} else if (v.type === 'result') {
|
|
121
|
-
run.result = { ok: !v.is_error && v.subtype !== 'error_during_execution', text: clip(v.result, 4000), costUsd: v.total_cost_usd ?? null,
|
|
122
|
-
durationMs: v.duration_ms ?? null, turns: v.num_turns ?? null };
|
|
123
|
-
this.#push(run, { kind: 'result', ...run.result });
|
|
124
|
-
}
|
|
125
|
-
this.#maybeClose(run);
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
#control(run, v) {
|
|
129
|
-
const req = v.request || {};
|
|
130
|
-
if (req.subtype !== 'can_use_tool') {
|
|
131
|
-
this.#write(run, { type: 'control_response', response: { subtype: 'error', request_id: v.request_id, error: 'unsupported control request' } });
|
|
132
|
-
return;
|
|
133
|
-
}
|
|
134
|
-
const input = req.input && typeof req.input === 'object' ? req.input : {};
|
|
135
|
-
const base = { requestId: v.request_id, tool: req.tool_name };
|
|
136
|
-
if (req.tool_name === 'AskUserQuestion' && Array.isArray(input.questions) && input.questions.length) {
|
|
137
|
-
const questions = input.questions.map((q) => ({ question: String(q.question || ''), header: String(q.header || ''), multiSelect: q.multiSelect === true,
|
|
138
|
-
options: (Array.isArray(q.options) ? q.options : []).map((o) => ({ label: String(o.label || ''), description: String(o.description || '') })) }));
|
|
139
|
-
run.pending.set(v.request_id, { ...base, kind: 'question', input, questions });
|
|
140
|
-
this.#push(run, { kind: 'question', ...base, questions });
|
|
141
|
-
return;
|
|
142
|
-
}
|
|
143
|
-
if (req.tool_name === 'AskUserQuestion') {
|
|
144
|
-
this.#write(run, { type: 'control_response', response: { subtype: 'success', request_id: v.request_id, response: { behavior: 'deny', message: 'malformed AskUserQuestion input' } } });
|
|
145
|
-
return;
|
|
146
|
-
}
|
|
147
|
-
const reason = typeof req.decision_reason === 'string' ? req.decision_reason.trim() : '';
|
|
148
|
-
const via = typeof req.decision_reason_type === 'string' ? req.decision_reason_type : '';
|
|
149
|
-
const ask = { ...base, kind: 'permission', input, summary: summarize(req.tool_name, input), reason, via };
|
|
150
|
-
run.pending.set(v.request_id, ask);
|
|
151
|
-
this.#push(run, { kind: 'approval', requestId: v.request_id, tool: req.tool_name, summary: ask.summary, reason, via });
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
// behavior: 'allow' | 'deny'. For a question, `answers` maps each question text to the chosen label(s).
|
|
155
|
-
respond(run, requestId, behavior, answers) {
|
|
156
|
-
const p = run.pending.get(requestId);
|
|
157
|
-
if (!p) return false;
|
|
158
|
-
let response;
|
|
159
|
-
if (behavior === 'allow') {
|
|
160
|
-
const updated = { ...p.input };
|
|
161
|
-
if (p.kind === 'question') {
|
|
162
|
-
const out = {};
|
|
163
|
-
for (const q of p.questions) {
|
|
164
|
-
const a = answers && answers[q.question];
|
|
165
|
-
out[q.question] = Array.isArray(a) ? a.join(', ') : typeof a === 'string' ? a : '';
|
|
166
|
-
}
|
|
167
|
-
updated.answers = out;
|
|
168
|
-
}
|
|
169
|
-
response = { behavior: 'allow', updatedInput: updated };
|
|
170
|
-
} else {
|
|
171
|
-
response = { behavior: 'deny', message: p.kind === 'question' ? 'The user declined to answer.' : DENY_MESSAGE };
|
|
172
|
-
}
|
|
173
|
-
run.pending.delete(requestId);
|
|
174
|
-
this.#write(run, { type: 'control_response', response: { subtype: 'success', request_id: requestId, response } });
|
|
175
|
-
this.#push(run, { kind: 'resolved', requestId, decision: behavior });
|
|
176
|
-
return true;
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
#maybeClose(run) {
|
|
180
|
-
if (run.status !== 'running' || !run.result || run.pending.size) return;
|
|
181
|
-
run.closeTimer = setTimeout(() => {
|
|
182
|
-
if (run.status === 'running' && !run.pending.size) { try { run.child.stdin.end(); } catch { /* closed */ } }
|
|
183
|
-
}, QUIET_AFTER_RESULT_MS);
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
stop(run) {
|
|
187
|
-
if (run.status !== 'running') return false;
|
|
188
|
-
run.stopping = true;
|
|
189
|
-
try { run.child.stdin.end(); } catch { /* closed */ }
|
|
190
|
-
try { if (process.platform === 'win32') spawn('taskkill', ['/pid', String(run.child.pid), '/T', '/F'], { stdio: 'ignore' }); else process.kill(-run.child.pid, 'SIGTERM'); } catch { /* gone */ }
|
|
191
|
-
const t = setTimeout(() => { try { if (process.platform !== 'win32') process.kill(-run.child.pid, 'SIGKILL'); } catch { /* gone */ } }, 4000);
|
|
192
|
-
t.unref();
|
|
193
|
-
return true;
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
stopAll() { for (const r of this.runs.values()) this.stop(r); }
|
|
197
|
-
get(id) { return this.runs.get(id) || null; }
|
|
198
|
-
forProject(projectId) { return [...this.runs.values()].filter((r) => r.projectId === projectId); }
|
|
199
|
-
find(projectId, cwd) { return [...this.runs.values()].find((r) => r.projectId === projectId && r.cwd === cwd && r.status === 'running') || null; }
|
|
200
|
-
|
|
201
|
-
view(run, since) {
|
|
202
|
-
const out = { id: run.id, command: run.command, cwd: run.cwd, permissionMode: run.permissionMode, status: run.status, startedAt: run.startedAt,
|
|
203
|
-
endedAt: run.endedAt, result: run.result, sessionId: run.sessionId,
|
|
204
|
-
pending: [...run.pending.values()].map((p) => ({ requestId: p.requestId, kind: p.kind, tool: p.tool, summary: p.summary, reason: p.reason, via: p.via, questions: p.questions })) };
|
|
205
|
-
if (since !== undefined) {
|
|
206
|
-
out.events = run.events.slice(Math.max(0, since - run.dropped));
|
|
207
|
-
out.cursor = run.dropped + run.events.length;
|
|
208
|
-
}
|
|
209
|
-
return out;
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
module.exports = { Runs, MODES };
|
package/ui/server.js
DELETED
|
@@ -1,299 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
// cohorte ui — a local dashboard over every project registered in the registry.
|
|
3
|
-
//
|
|
4
|
-
// Security model (this origin will launch commands in a later release, so it is hardened now):
|
|
5
|
-
// - listens on 127.0.0.1 only;
|
|
6
|
-
// - every /api request needs the session token (Authorization: Bearer), a loopback Host (DNS
|
|
7
|
-
// rebinding) and, when the browser sends one, an Origin equal to this server's own;
|
|
8
|
-
// - state-changing requests must be application/json (a cross-site form cannot send that);
|
|
9
|
-
// - reads address a project by the id of a REGISTERED project, never by a path;
|
|
10
|
-
// - the page is served with a strict CSP and renders project content with textContent only.
|
|
11
|
-
|
|
12
|
-
const fs = require('fs');
|
|
13
|
-
const http = require('http');
|
|
14
|
-
const path = require('path');
|
|
15
|
-
const crypto = require('crypto');
|
|
16
|
-
const { spawn } = require('child_process');
|
|
17
|
-
const registry = require('../lib/registry.js');
|
|
18
|
-
const { state, scanSpecs } = require('../lib/doctor.js');
|
|
19
|
-
const report = require('../bin/report.js');
|
|
20
|
-
const { Jobs } = require('./jobs.js');
|
|
21
|
-
const { Runs } = require('./runs.js');
|
|
22
|
-
const ops = require('./ops.js');
|
|
23
|
-
const docker = require('./docker.js');
|
|
24
|
-
|
|
25
|
-
const pkgRoot = path.join(__dirname, '..');
|
|
26
|
-
const PUBLIC = path.join(__dirname, 'public');
|
|
27
|
-
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml' };
|
|
28
|
-
const CSP = "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
|
|
29
|
-
const REPORT_KINDS = ['readiness', 'build', 'verdict', 'verify'];
|
|
30
|
-
const SPEC_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,100}$/;
|
|
31
|
-
const MAX_BODY = 16 * 1024;
|
|
32
|
-
|
|
33
|
-
// A small TTL cache keyed by string; concurrent callers share one in-flight computation.
|
|
34
|
-
function memo(ttlMs) {
|
|
35
|
-
const m = new Map();
|
|
36
|
-
const run = (key, fn) => {
|
|
37
|
-
const hit = m.get(key);
|
|
38
|
-
if (hit && (hit.pending || Date.now() - hit.at < ttlMs)) return hit.value;
|
|
39
|
-
const value = Promise.resolve().then(fn);
|
|
40
|
-
const entry = { at: Date.now(), value, pending: true };
|
|
41
|
-
m.set(key, entry);
|
|
42
|
-
value.then(() => { entry.pending = false; entry.at = Date.now(); }, () => m.delete(key));
|
|
43
|
-
return value;
|
|
44
|
-
};
|
|
45
|
-
run.clear = (key) => m.delete(key);
|
|
46
|
-
return run;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
function runMetrics(root, args) {
|
|
50
|
-
return new Promise((resolve, reject) => {
|
|
51
|
-
const script = path.join(pkgRoot, 'scripts', 'metrics', 'collect.mjs');
|
|
52
|
-
const child = spawn(process.execPath, [script, root, '--json', ...args], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
53
|
-
let out = '';
|
|
54
|
-
child.stdout.on('data', (d) => { out += d; });
|
|
55
|
-
const timer = setTimeout(() => { child.kill(); reject(new Error('metrics timed out')); }, 60000);
|
|
56
|
-
child.on('error', (e) => { clearTimeout(timer); reject(e); });
|
|
57
|
-
child.on('close', (code) => {
|
|
58
|
-
clearTimeout(timer);
|
|
59
|
-
if (code !== 0) return reject(new Error(`metrics exited ${code}`));
|
|
60
|
-
try { resolve(JSON.parse(out)); } catch { reject(new Error('metrics returned no JSON')); }
|
|
61
|
-
});
|
|
62
|
-
});
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
function readJson(p) { try { return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { return null; } }
|
|
66
|
-
|
|
67
|
-
function create({ globalDir, version, token = crypto.randomBytes(24).toString('hex'), storePath }) {
|
|
68
|
-
const cacheDoctor = memo(8000);
|
|
69
|
-
const cacheMetrics = memo(60000);
|
|
70
|
-
const jobs = new Jobs();
|
|
71
|
-
const runs = new Runs();
|
|
72
|
-
let origin = null; // set once listening
|
|
73
|
-
|
|
74
|
-
const doctorOf = (root) => cacheDoctor(root, () => state({ projectRoot: root, globalDir, cliVersion: version, offline: true }));
|
|
75
|
-
|
|
76
|
-
async function summary(p) {
|
|
77
|
-
const base = { id: p.id, root: p.root, name: path.basename(p.root), addedAt: p.addedAt };
|
|
78
|
-
if (!fs.existsSync(p.root)) return { ...base, missing: true };
|
|
79
|
-
try {
|
|
80
|
-
const s = await doctorOf(p.root);
|
|
81
|
-
const counts = {};
|
|
82
|
-
for (const sp of s.specs) counts[sp.status || 'unknown'] = (counts[sp.status || 'unknown'] || 0) + 1;
|
|
83
|
-
return { ...base, missing: false, title: s.profile && s.profile.name || base.name,
|
|
84
|
-
oneLiner: s.profile && s.profile.one_liner || '', summary: s.summary, specCounts: counts,
|
|
85
|
-
specTotal: s.specs.length, core: s.versions && s.versions.core || null };
|
|
86
|
-
} catch (e) {
|
|
87
|
-
return { ...base, missing: false, error: String(e && e.message || e) };
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
async function detail(p) {
|
|
92
|
-
const s = await doctorOf(p.root);
|
|
93
|
-
const specs = report.specRecords(p.root, scanSpecs);
|
|
94
|
-
const wt = registry.worktrees(p.root);
|
|
95
|
-
const dev = ops.devInfo(p.root);
|
|
96
|
-
const scripts = ops.isolationScripts(p.root);
|
|
97
|
-
const withDev = wt.map((w, i) => ({ ...w, main: i === 0, dev: (jobs.find(p.id, 'dev', w.path) && jobs.view(jobs.find(p.id, 'dev', w.path))) || null }));
|
|
98
|
-
return { id: p.id, root: p.root, name: path.basename(p.root), doctor: s, specs, worktrees: withDev,
|
|
99
|
-
dev: { command: dev.command, ready: dev.ready }, isolation: scripts,
|
|
100
|
-
docker: (() => { const c = docker.composeFile(p.root); return c ? { file: c.rel } : null; })(),
|
|
101
|
-
runs: runs.forProject(p.id).map((r) => runs.view(r)) };
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
function specDetail(p, specId) {
|
|
105
|
-
if (!SPEC_ID.test(specId)) return null;
|
|
106
|
-
const spec = scanSpecs(p.root).find((s) => s.id === specId);
|
|
107
|
-
if (!spec) return null;
|
|
108
|
-
let body = '';
|
|
109
|
-
try { body = fs.readFileSync(path.join(p.root, 'specs', path.basename(spec.file)), 'utf8'); } catch { /* listed, then removed */ }
|
|
110
|
-
const reports = {};
|
|
111
|
-
for (const k of REPORT_KINDS) reports[k] = readJson(path.join(p.root, 'specs', 'reports', `${specId}.${k}.json`));
|
|
112
|
-
return { spec, body: body.slice(0, 200000), reports };
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
// --- http plumbing -------------------------------------------------------
|
|
116
|
-
const send = (res, code, obj) => {
|
|
117
|
-
const body = JSON.stringify(obj);
|
|
118
|
-
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
|
|
119
|
-
res.end(body);
|
|
120
|
-
};
|
|
121
|
-
const fail = (res, code, message) => send(res, code, { error: message });
|
|
122
|
-
|
|
123
|
-
function hostOk(req) {
|
|
124
|
-
const h = String(req.headers.host || '');
|
|
125
|
-
return /^(127\.0\.0\.1|localhost|\[::1\]):\d+$/.test(h);
|
|
126
|
-
}
|
|
127
|
-
function tokenOk(req) {
|
|
128
|
-
const m = /^Bearer (.+)$/.exec(String(req.headers.authorization || ''));
|
|
129
|
-
if (!m) return false;
|
|
130
|
-
const a = Buffer.from(m[1]);
|
|
131
|
-
const b = Buffer.from(token);
|
|
132
|
-
return a.length === b.length && crypto.timingSafeEqual(a, b);
|
|
133
|
-
}
|
|
134
|
-
function readBody(req) {
|
|
135
|
-
return new Promise((resolve, reject) => {
|
|
136
|
-
let n = 0;
|
|
137
|
-
const chunks = [];
|
|
138
|
-
req.on('data', (c) => { n += c.length; if (n > MAX_BODY) { reject(new Error('body too large')); req.destroy(); } else chunks.push(c); });
|
|
139
|
-
req.on('end', () => { try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')); } catch { reject(new Error('invalid JSON')); } });
|
|
140
|
-
req.on('error', reject);
|
|
141
|
-
});
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
async function api(req, res, url) {
|
|
145
|
-
const method = req.method;
|
|
146
|
-
const parts = url.pathname.split('/').filter(Boolean).slice(1); // drop "api"
|
|
147
|
-
if (method === 'POST' || method === 'DELETE') {
|
|
148
|
-
if (method === 'POST' && !/^application\/json\b/i.test(String(req.headers['content-type'] || ''))) return fail(res, 415, 'application/json required');
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
if (parts[0] === 'state' && method === 'GET') {
|
|
152
|
-
const list = registry.load(globalDir);
|
|
153
|
-
return send(res, 200, { version, projects: await Promise.all(list.map(summary)) });
|
|
154
|
-
}
|
|
155
|
-
if (parts[0] === 'commands' && method === 'GET') return send(res, 200, { commands: ops.listCommands(globalDir) });
|
|
156
|
-
if (parts[0] === 'discover' && method === 'GET') {
|
|
157
|
-
return send(res, 200, { suggestions: registry.discover(globalDir, storePath) });
|
|
158
|
-
}
|
|
159
|
-
if (parts[0] === 'projects' && parts.length === 1 && method === 'POST') {
|
|
160
|
-
let body;
|
|
161
|
-
try { body = await readBody(req); } catch (e) { return fail(res, 400, e.message); }
|
|
162
|
-
try {
|
|
163
|
-
const r = registry.add(globalDir, body.path);
|
|
164
|
-
return send(res, r.created ? 201 : 200, { project: await summary(r.project), created: r.created });
|
|
165
|
-
} catch (e) {
|
|
166
|
-
if (e instanceof registry.RegistryError) return fail(res, 400, e.message);
|
|
167
|
-
throw e;
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
if (parts[0] === 'projects' && parts[1]) {
|
|
171
|
-
const p = registry.get(globalDir, parts[1]);
|
|
172
|
-
if (!p) return fail(res, 404, 'unknown project');
|
|
173
|
-
if (parts.length === 2 && method === 'DELETE') { registry.remove(globalDir, p.id); return send(res, 200, { removed: true }); }
|
|
174
|
-
if (!fs.existsSync(p.root)) return fail(res, 410, `${p.root} no longer exists — remove it from the list`);
|
|
175
|
-
if (parts.length === 2 && method === 'GET') return send(res, 200, await detail(p));
|
|
176
|
-
if (parts[2] === 'jobs') {
|
|
177
|
-
if (parts.length === 3 && method === 'GET') return send(res, 200, { jobs: jobs.forProject(p.id).map((j) => jobs.view(j)) });
|
|
178
|
-
const job = parts[3] && jobs.get(parts[3]);
|
|
179
|
-
if (!job || job.projectId !== p.id) return fail(res, 404, 'unknown job');
|
|
180
|
-
if (parts[4] === 'logs' && method === 'GET') return send(res, 200, jobs.view(job, Math.max(0, parseInt(url.searchParams.get('since'), 10) || 0)));
|
|
181
|
-
if (parts[4] === 'stop' && method === 'POST') return send(res, 200, { stopped: ops.stopJob(jobs, p, job.id) });
|
|
182
|
-
}
|
|
183
|
-
if (parts[2] === 'runs') {
|
|
184
|
-
if (parts.length === 3 && method === 'GET') return send(res, 200, { runs: runs.forProject(p.id).map((r) => runs.view(r)) });
|
|
185
|
-
if (parts.length === 3 && method === 'POST') {
|
|
186
|
-
let body;
|
|
187
|
-
try { body = await readBody(req); } catch (e) { return fail(res, 400, e.message); }
|
|
188
|
-
try { return send(res, 202, { run: runs.view(ops.startRun(runs, p, globalDir, body), 0) }); } catch (e) {
|
|
189
|
-
if (e instanceof ops.OpError) return send(res, e.code, { error: e.message, untrusted: e.untrusted || false, fix: e.fix });
|
|
190
|
-
throw e;
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
const run = parts[3] && runs.get(parts[3]);
|
|
194
|
-
if (!run || run.projectId !== p.id) return fail(res, 404, 'unknown run');
|
|
195
|
-
if (parts.length === 4 && method === 'GET') return send(res, 200, runs.view(run, Math.max(0, parseInt(url.searchParams.get('since'), 10) || 0)));
|
|
196
|
-
if (parts[4] === 'stop' && method === 'POST') return send(res, 200, { stopped: runs.stop(run) });
|
|
197
|
-
if (parts[4] === 'reply' && method === 'POST') {
|
|
198
|
-
let body;
|
|
199
|
-
try { body = await readBody(req); } catch (e) { return fail(res, 400, e.message); }
|
|
200
|
-
const err = runs.reply(run, body.text);
|
|
201
|
-
return err ? fail(res, 409, err) : send(res, 202, { run: runs.view(run, 0) });
|
|
202
|
-
}
|
|
203
|
-
if (parts[4] === 'respond' && method === 'POST') {
|
|
204
|
-
let body;
|
|
205
|
-
try { body = await readBody(req); } catch (e) { return fail(res, 400, e.message); }
|
|
206
|
-
if (body.behavior !== 'allow' && body.behavior !== 'deny') return fail(res, 400, 'behavior must be allow or deny');
|
|
207
|
-
return runs.respond(run, String(body.requestId), body.behavior, body.answers) ? send(res, 200, { ok: true }) : fail(res, 404, 'no such pending request');
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
if (parts[2] === 'docker' && parts.length === 3) {
|
|
211
|
-
if (method === 'GET') return send(res, 200, await docker.status(p.root));
|
|
212
|
-
if (method === 'POST') {
|
|
213
|
-
let body;
|
|
214
|
-
try { body = await readBody(req); } catch (e) { return fail(res, 400, e.message); }
|
|
215
|
-
try { return send(res, 202, { job: jobs.view(await docker.act(jobs, p, { action: body.action, service: body.service, confirmed: body.confirmed === true })) }); } catch (e) {
|
|
216
|
-
if (e instanceof ops.OpError) return send(res, e.code, { error: e.message, needsConfirmation: e.needsConfirmation || false, command: e.command, reason: e.reason, dockerDown: e.dockerDown || false });
|
|
217
|
-
throw e;
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
if (method === 'POST' && (parts[2] === 'dev' || parts[2] === 'worktrees')) {
|
|
222
|
-
let body;
|
|
223
|
-
try { body = await readBody(req); } catch (e) { return fail(res, 400, e.message); }
|
|
224
|
-
const confirmed = body.confirmed === true;
|
|
225
|
-
try {
|
|
226
|
-
let job;
|
|
227
|
-
if (parts[2] === 'worktrees' && parts.length === 3 && body.skipDockerCheck !== true) {
|
|
228
|
-
const pre = await docker.preflight(p.root);
|
|
229
|
-
if (pre && !pre.ok) return send(res, 409, { error: pre.reason, dockerPreflight: pre });
|
|
230
|
-
}
|
|
231
|
-
if (parts[2] === 'dev' && parts.length === 3) job = ops.startDev(jobs, p, body.worktree, { confirmed });
|
|
232
|
-
else if (parts[2] === 'worktrees' && parts.length === 3) job = ops.createWorktree(jobs, p, body.feature, { confirmed });
|
|
233
|
-
else if (parts[2] === 'worktrees' && parts[3] === 'remove') job = ops.removeWorktree(jobs, p, body.path, { confirmed });
|
|
234
|
-
else return fail(res, 404, 'not found');
|
|
235
|
-
cacheDoctor.clear(p.root);
|
|
236
|
-
return send(res, 202, { job: jobs.view(job) });
|
|
237
|
-
} catch (e) {
|
|
238
|
-
if (e instanceof ops.OpError) return send(res, e.code, { error: e.message, needsConfirmation: e.needsConfirmation || false, command: e.command, reason: e.reason });
|
|
239
|
-
throw e;
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
if (parts[2] === 'metrics' && method === 'GET') {
|
|
243
|
-
const days = Math.min(365, Math.max(1, parseInt(url.searchParams.get('days'), 10) || 30));
|
|
244
|
-
try { return send(res, 200, await cacheMetrics(`${p.root}|${days}`, () => runMetrics(p.root, [`--days=${days}`, '--runs']))); }
|
|
245
|
-
catch (e) { return fail(res, 502, e.message); }
|
|
246
|
-
}
|
|
247
|
-
if (parts[2] === 'specs' && parts[3] && method === 'GET') {
|
|
248
|
-
const d = specDetail(p, parts[3]);
|
|
249
|
-
return d ? send(res, 200, d) : fail(res, 404, 'unknown spec');
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
return fail(res, 404, 'not found');
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
function serveStatic(req, res, url) {
|
|
256
|
-
if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405); return res.end(); }
|
|
257
|
-
const rel = url.pathname === '/' ? 'index.html' : url.pathname.slice(1);
|
|
258
|
-
const file = path.join(PUBLIC, rel);
|
|
259
|
-
const ext = path.extname(file);
|
|
260
|
-
if (!file.startsWith(PUBLIC + path.sep) || !TYPES[ext]) { res.writeHead(404); return res.end('not found'); }
|
|
261
|
-
fs.readFile(file, (err, buf) => {
|
|
262
|
-
if (err) { res.writeHead(404); return res.end('not found'); }
|
|
263
|
-
res.writeHead(200, { 'Content-Type': TYPES[ext], 'Content-Security-Policy': CSP, 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer', 'Cache-Control': 'no-store' });
|
|
264
|
-
res.end(buf);
|
|
265
|
-
});
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
const server = http.createServer(async (req, res) => {
|
|
269
|
-
try {
|
|
270
|
-
if (!hostOk(req)) { res.writeHead(403); return res.end('bad host'); }
|
|
271
|
-
const url = new URL(req.url, 'http://x');
|
|
272
|
-
if (url.pathname === '/api' || url.pathname.startsWith('/api/')) {
|
|
273
|
-
const o = req.headers.origin;
|
|
274
|
-
if (o && o !== origin) return fail(res, 403, 'bad origin');
|
|
275
|
-
if (!tokenOk(req)) return fail(res, 401, 'missing or invalid token');
|
|
276
|
-
return await api(req, res, url);
|
|
277
|
-
}
|
|
278
|
-
serveStatic(req, res, url);
|
|
279
|
-
} catch (e) {
|
|
280
|
-
if (!res.headersSent) fail(res, 500, String(e && e.message || e));
|
|
281
|
-
else res.end();
|
|
282
|
-
}
|
|
283
|
-
});
|
|
284
|
-
|
|
285
|
-
function listen(port = 0) {
|
|
286
|
-
return new Promise((resolve, reject) => {
|
|
287
|
-
server.once('error', reject);
|
|
288
|
-
server.listen(port, '127.0.0.1', () => {
|
|
289
|
-
const p = server.address().port;
|
|
290
|
-
origin = `http://127.0.0.1:${p}`;
|
|
291
|
-
resolve({ port: p, url: `${origin}/#token=${token}`, token, origin });
|
|
292
|
-
});
|
|
293
|
-
});
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
return { server, listen, token, jobs, runs, close: () => { jobs.stopAll(); runs.stopAll(); return new Promise((r) => server.close(r)); } };
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
module.exports = { create };
|