cohorte 3.1.3 → 3.2.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 +15 -0
- package/bin/cli.js +33 -1
- package/lib/doctor.js +1 -1
- package/lib/registry.js +118 -0
- package/package.json +3 -2
- package/ui/docker.js +147 -0
- package/ui/jobs.js +127 -0
- package/ui/ops.js +164 -0
- package/ui/public/app.js +420 -0
- package/ui/public/index.html +13 -0
- package/ui/public/style.css +35 -0
- package/ui/runs.js +213 -0
- package/ui/server.js +299 -0
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,21 @@ short, user-facing, most recent first. One `## <version> — <YYYY-MM-DD>` secti
|
|
|
7
7
|
> They are history and are deliberately not rewritten — every command gained a `cohorte-` prefix
|
|
8
8
|
> in 2.0.0.
|
|
9
9
|
|
|
10
|
+
## 3.2.0 — 2026-11-18
|
|
11
|
+
|
|
12
|
+
- **`cohorte ui` — a local dashboard over all your Cohorte projects.** Run it in a terminal; it opens
|
|
13
|
+
a page on `127.0.0.1` (session token, loopback Host/Origin checks, strict CSP) listing every
|
|
14
|
+
registered project (add one by path, or pick from the repos Claude Code already knows). Per project:
|
|
15
|
+
an overview, doctor checks, specs with their reports, cost by command, worktrees (create/remove,
|
|
16
|
+
dev servers with live logs) and the **Docker** stack — services, health and ports, start / stop /
|
|
17
|
+
restart / down (never `-v`) and logs. Zero dependencies, nothing leaves the machine.
|
|
18
|
+
- **Run `/cohorte-*` commands from the page.** Headless `claude -p` runs with the project's gate
|
|
19
|
+
asked first; permission asks and interview questions are answered in the page, and a reply resumes
|
|
20
|
+
the same session. It talks to Claude only through Cohorte commands — it is not a chat.
|
|
21
|
+
- **Worktree creation checks Docker first.** `scripts/new-feature.sh` creates the worktree's database
|
|
22
|
+
inside a compose service, and failed late and obscurely when Docker or that service was down; the
|
|
23
|
+
dashboard now says so up front and offers to start the stack.
|
|
24
|
+
|
|
10
25
|
## 3.1.3 — 2026-11-16
|
|
11
26
|
|
|
12
27
|
- **Kanban moves on macOS use a kernel lock.** macOS has no `flock(1)`, so parallel moves on one
|
package/bin/cli.js
CHANGED
|
@@ -35,6 +35,7 @@ Usage:
|
|
|
35
35
|
cohorte doctor [project] [--porcelain | --json | --panel]
|
|
36
36
|
cohorte specs [project] [--porcelain | --json | --panel]
|
|
37
37
|
cohorte metrics [project] [--days=N] [--since=ISO] [--runs] [--json]
|
|
38
|
+
cohorte ui [--port=N] [--no-open] Local dashboard over every registered project
|
|
38
39
|
cohorte version
|
|
39
40
|
|
|
40
41
|
Where things go:
|
|
@@ -69,7 +70,9 @@ let projectScope = false;
|
|
|
69
70
|
const metricsFlags = [];
|
|
70
71
|
const isMetricsFlag = (a) =>
|
|
71
72
|
a === '--json' || a === '--runs' || a.startsWith('--days=') || a.startsWith('--since=');
|
|
72
|
-
const VERBS = ['install', 'update', 'sync', 'uninstall', 'metrics', 'specs', 'doctor'];
|
|
73
|
+
const VERBS = ['install', 'update', 'sync', 'uninstall', 'metrics', 'specs', 'doctor', 'ui'];
|
|
74
|
+
let uiPort = 0;
|
|
75
|
+
let uiOpen = true;
|
|
73
76
|
|
|
74
77
|
for (const a of args) {
|
|
75
78
|
if (!mode && VERBS.includes(a)) mode = a;
|
|
@@ -77,6 +80,11 @@ for (const a of args) {
|
|
|
77
80
|
else if (isMetricsFlag(a)) { if (a === '--json') format = 'json'; metricsFlags.push(a); }
|
|
78
81
|
else if (a === 'version' || a === '--version' || a === '-v') { console.log(VERSION); process.exit(0); }
|
|
79
82
|
else if (a === 'help' || a === '--help' || a === '-h') usage(0);
|
|
83
|
+
else if (a.startsWith('--port=') && mode === 'ui') {
|
|
84
|
+
uiPort = Number(a.slice(7));
|
|
85
|
+
if (!Number.isInteger(uiPort) || uiPort < 0 || uiPort > 65535) { console.error('error: --port must be 0-65535'); process.exit(2); }
|
|
86
|
+
}
|
|
87
|
+
else if (a === '--no-open' && mode === 'ui') uiOpen = false;
|
|
80
88
|
else if (a === '--purge') purge = true;
|
|
81
89
|
else if (a === '--project') projectScope = true;
|
|
82
90
|
// 2.x flags. --global is what 3.x always does; --runtime=claude is the only runtime left.
|
|
@@ -98,8 +106,32 @@ if ((mode === 'install' || mode === 'update') && target) {
|
|
|
98
106
|
+ ' 2.x "bundled" installs (a core copied into the repo) no longer exist.');
|
|
99
107
|
process.exit(2);
|
|
100
108
|
}
|
|
109
|
+
if (mode === 'ui' && target) {
|
|
110
|
+
console.error('error: `cohorte ui` is a dashboard over all your projects and takes no path.\n'
|
|
111
|
+
+ ' Add a project from the page, or open one with its own `cohorte doctor <path>`.');
|
|
112
|
+
process.exit(2);
|
|
113
|
+
}
|
|
101
114
|
const project = target || process.cwd();
|
|
102
115
|
|
|
116
|
+
// --- dashboard ---------------------------------------------------------------
|
|
117
|
+
if (mode === 'ui') {
|
|
118
|
+
const { create } = require('../ui/server.js');
|
|
119
|
+
const ui = create({ globalDir, version: VERSION });
|
|
120
|
+
const bye = () => { ui.jobs.stopAll(); ui.runs.stopAll(); process.exit(0); };
|
|
121
|
+
process.on('SIGINT', bye);
|
|
122
|
+
process.on('SIGTERM', bye);
|
|
123
|
+
process.on('exit', () => { ui.jobs.stopAll(); ui.runs.stopAll(); });
|
|
124
|
+
ui.listen(uiPort).then((l) => {
|
|
125
|
+
console.log(`cohorte ui — ${l.url}\n Local only (127.0.0.1); the link carries this session's token. Ctrl-C stops it and the dev servers it started.`);
|
|
126
|
+
if (uiOpen && process.stdout.isTTY) {
|
|
127
|
+
const [cmd, ...a] = process.platform === 'darwin' ? ['open'] : process.platform === 'win32' ? ['cmd', '/c', 'start', ''] : ['xdg-open'];
|
|
128
|
+
const c = spawnSync(cmd, [...a, l.url], { stdio: 'ignore' });
|
|
129
|
+
if (c.error) console.log(' (could not open a browser — open the link above)');
|
|
130
|
+
}
|
|
131
|
+
}).catch((e) => { console.error(`error: ${e && e.message ? e.message : e}`); process.exit(1); });
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
|
|
103
135
|
// --- read-only reports -------------------------------------------------------
|
|
104
136
|
if (mode === 'specs' || mode === 'doctor') {
|
|
105
137
|
const report = require('./report.js');
|
package/lib/doctor.js
CHANGED
package/lib/registry.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// cohorte — the list of projects the dashboard (`cohorte ui`) manages.
|
|
3
|
+
//
|
|
4
|
+
// <globalDir>/cohorte.projects.json { "version": 1, "projects": [{ "root": "/abs/path", "addedAt": "ISO" }] }
|
|
5
|
+
//
|
|
6
|
+
// A separate file on purpose: cohorte.config.yaml is the user's own, hand-edited file. The registry
|
|
7
|
+
// stores real paths only — the id a client sees is a hash of the path, so the HTTP layer never
|
|
8
|
+
// accepts a filesystem path for a read, only the id of a project that was registered.
|
|
9
|
+
|
|
10
|
+
const fs = require('fs');
|
|
11
|
+
const os = require('os');
|
|
12
|
+
const path = require('path');
|
|
13
|
+
const crypto = require('crypto');
|
|
14
|
+
const { spawnSync } = require('child_process');
|
|
15
|
+
|
|
16
|
+
const FILE = 'cohorte.projects.json';
|
|
17
|
+
|
|
18
|
+
const realOr = (p) => { try { return fs.realpathSync(p); } catch { return path.resolve(p); } };
|
|
19
|
+
const idOf = (root) => crypto.createHash('sha1').update(root).digest('hex').slice(0, 10);
|
|
20
|
+
const isDir = (p) => { try { return fs.statSync(p).isDirectory(); } catch { return false; } };
|
|
21
|
+
const isCohorteProject = (root) =>
|
|
22
|
+
fs.existsSync(path.join(root, 'PIPELINE.md')) || fs.existsSync(path.join(root, '.claude', 'pipeline.json'));
|
|
23
|
+
|
|
24
|
+
function gitTop(dir) {
|
|
25
|
+
const r = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd: dir, encoding: 'utf8' });
|
|
26
|
+
return r.status === 0 && r.stdout.trim() ? realOr(r.stdout.trim()) : null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
class RegistryError extends Error {}
|
|
30
|
+
|
|
31
|
+
function file(globalDir) { return path.join(globalDir, FILE); }
|
|
32
|
+
|
|
33
|
+
function load(globalDir) {
|
|
34
|
+
let data;
|
|
35
|
+
try { data = JSON.parse(fs.readFileSync(file(globalDir), 'utf8')); } catch { return []; }
|
|
36
|
+
const list = Array.isArray(data && data.projects) ? data.projects : [];
|
|
37
|
+
const seen = new Set();
|
|
38
|
+
const out = [];
|
|
39
|
+
for (const p of list) {
|
|
40
|
+
if (!p || typeof p.root !== 'string' || !path.isAbsolute(p.root) || seen.has(p.root)) continue;
|
|
41
|
+
seen.add(p.root);
|
|
42
|
+
out.push({ id: idOf(p.root), root: p.root, addedAt: typeof p.addedAt === 'string' ? p.addedAt : null });
|
|
43
|
+
}
|
|
44
|
+
return out;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function save(globalDir, projects) {
|
|
48
|
+
fs.mkdirSync(globalDir, { recursive: true });
|
|
49
|
+
const body = { version: 1, projects: projects.map((p) => ({ root: p.root, addedAt: p.addedAt })) };
|
|
50
|
+
const tmp = `${file(globalDir)}.${process.pid}.tmp`;
|
|
51
|
+
fs.writeFileSync(tmp, JSON.stringify(body, null, 2) + '\n');
|
|
52
|
+
fs.renameSync(tmp, file(globalDir));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Registers a project by path. The path may be any folder inside the repo: the git root is stored,
|
|
56
|
+
// so two entries for one repo cannot exist. A missing folder or a repo without cohorte is refused.
|
|
57
|
+
function add(globalDir, input) {
|
|
58
|
+
if (typeof input !== 'string' || !input.trim()) throw new RegistryError('a project path is required');
|
|
59
|
+
const expanded = input.trim().replace(/^~(?=$|[\\/])/, os.homedir());
|
|
60
|
+
if (!path.isAbsolute(expanded)) throw new RegistryError('the path must be absolute');
|
|
61
|
+
if (!isDir(expanded)) throw new RegistryError(`${expanded} is not a folder`);
|
|
62
|
+
const root = gitTop(expanded) || realOr(expanded);
|
|
63
|
+
if (!isCohorteProject(root)) {
|
|
64
|
+
throw new RegistryError(`${root} has no PIPELINE.md or .claude/pipeline.json — run /cohorte-init-pipeline in it first`);
|
|
65
|
+
}
|
|
66
|
+
const list = load(globalDir);
|
|
67
|
+
const existing = list.find((p) => p.root === root);
|
|
68
|
+
if (existing) return { project: existing, created: false };
|
|
69
|
+
const project = { id: idOf(root), root, addedAt: new Date().toISOString() };
|
|
70
|
+
save(globalDir, list.concat([project]));
|
|
71
|
+
return { project, created: true };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function remove(globalDir, id) {
|
|
75
|
+
const list = load(globalDir);
|
|
76
|
+
const next = list.filter((p) => p.id !== id);
|
|
77
|
+
if (next.length === list.length) return false;
|
|
78
|
+
save(globalDir, next);
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function get(globalDir, id) { return load(globalDir).find((p) => p.id === id) || null; }
|
|
83
|
+
|
|
84
|
+
// Folders Claude Code has been used in (the `projects` keys of its user store) that look like a cohorte
|
|
85
|
+
// project and are not registered yet. Suggestions only: nothing is added without a click.
|
|
86
|
+
function discover(globalDir, storePath) {
|
|
87
|
+
const store = storePath
|
|
88
|
+
|| (process.env.CLAUDE_CONFIG_DIR ? path.join(process.env.CLAUDE_CONFIG_DIR, '.claude.json') : path.join(os.homedir(), '.claude.json'));
|
|
89
|
+
let projects = {};
|
|
90
|
+
try { projects = JSON.parse(fs.readFileSync(store, 'utf8')).projects || {}; } catch { return []; }
|
|
91
|
+
const known = new Set(load(globalDir).map((p) => p.root));
|
|
92
|
+
const out = [];
|
|
93
|
+
for (const key of Object.keys(projects)) {
|
|
94
|
+
if (!path.isAbsolute(key) || !isDir(key)) continue;
|
|
95
|
+
const root = realOr(key);
|
|
96
|
+
if (known.has(root) || out.some((o) => o.root === root)) continue;
|
|
97
|
+
if (isCohorteProject(root)) out.push({ root, name: path.basename(root) });
|
|
98
|
+
}
|
|
99
|
+
return out.sort((a, b) => a.name.localeCompare(b.name));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Worktrees of one repo, from git itself. The main checkout comes first.
|
|
103
|
+
function worktrees(root) {
|
|
104
|
+
const r = spawnSync('git', ['worktree', 'list', '--porcelain'], { cwd: root, encoding: 'utf8' });
|
|
105
|
+
if (r.status !== 0) return [];
|
|
106
|
+
const out = [];
|
|
107
|
+
let cur = null;
|
|
108
|
+
for (const line of r.stdout.split('\n')) {
|
|
109
|
+
if (line.startsWith('worktree ')) { cur = { path: line.slice(9), branch: null, head: null, bare: false }; out.push(cur); }
|
|
110
|
+
else if (!cur) continue;
|
|
111
|
+
else if (line.startsWith('HEAD ')) cur.head = line.slice(5, 12);
|
|
112
|
+
else if (line.startsWith('branch ')) cur.branch = line.slice(7).replace(/^refs\/heads\//, '');
|
|
113
|
+
else if (line === 'bare') cur.bare = true;
|
|
114
|
+
}
|
|
115
|
+
return out;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
module.exports = { load, add, remove, get, discover, worktrees, idOf, isCohorteProject, RegistryError, FILE };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cohorte",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.2.0",
|
|
4
4
|
"description": "Multi-agent development pipeline for Claude Code — install it once, run /cohorte-init-pipeline in a repo, and it adapts to that project's stack.",
|
|
5
5
|
"bin": {
|
|
6
6
|
"cohorte": "bin/cli.js"
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
"core",
|
|
12
12
|
"profile",
|
|
13
13
|
"scripts",
|
|
14
|
+
"ui",
|
|
14
15
|
"!scripts/new-feature.sh",
|
|
15
16
|
"!scripts/remove-feature.sh",
|
|
16
17
|
"!scripts/demo",
|
|
@@ -26,7 +27,7 @@
|
|
|
26
27
|
"CHANGELOG.md"
|
|
27
28
|
],
|
|
28
29
|
"scripts": {
|
|
29
|
-
"test": "node scripts/validate-core.mjs && node scripts/test-install.mjs && node scripts/test-gate.mjs && node scripts/test-lib.mjs && node scripts/test-workflows.mjs && node scripts/test-kanban.mjs && node scripts/test-metrics.mjs && node scripts/test-e2e.mjs && node scripts/test-verify.mjs"
|
|
30
|
+
"test": "node scripts/validate-core.mjs && node scripts/test-install.mjs && node scripts/test-gate.mjs && node scripts/test-lib.mjs && node scripts/test-workflows.mjs && node scripts/test-kanban.mjs && node scripts/test-metrics.mjs && node scripts/test-e2e.mjs && node scripts/test-verify.mjs && node scripts/test-ui.mjs"
|
|
30
31
|
},
|
|
31
32
|
"engines": {
|
|
32
33
|
"node": ">=20"
|
package/ui/docker.js
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// cohorte ui — the project's Docker Compose stack: what is up, and the few things the dashboard may do to it.
|
|
3
|
+
//
|
|
4
|
+
// Same rules as ops.js:
|
|
5
|
+
// - the compose file is the one the profile declares (isolation.compose_file) or a conventional name at the
|
|
6
|
+
// repo root, resolved INSIDE the repo — never a path from the client;
|
|
7
|
+
// - the verbs are fixed (up -d, stop, restart, down, logs); `down` never takes -v, so volumes (the data) stay;
|
|
8
|
+
// - a service name from the client is only accepted when `docker compose config --services` lists it;
|
|
9
|
+
// - the project's gate is asked first, like every other command this dashboard launches.
|
|
10
|
+
// Reads (daemon, ps) never go through a shell and are bounded by a timeout so a hung daemon cannot hang the page.
|
|
11
|
+
|
|
12
|
+
const fs = require('fs');
|
|
13
|
+
const path = require('path');
|
|
14
|
+
const { spawn } = require('child_process');
|
|
15
|
+
const { OpError, gateVerdict, confirm, readProfile } = require('./ops.js');
|
|
16
|
+
|
|
17
|
+
const CANDIDATES = ['compose.yaml', 'compose.yml', 'docker-compose.yaml', 'docker-compose.yml'];
|
|
18
|
+
const ACTIONS = ['up', 'stop', 'restart', 'down', 'logs'];
|
|
19
|
+
const bin = () => process.env.COHORTE_DOCKER_BIN || 'docker';
|
|
20
|
+
const realOr = (p) => { try { return fs.realpathSync(p); } catch { return path.resolve(p); } };
|
|
21
|
+
|
|
22
|
+
// { file, rel } or null. The declared file wins; it must stay inside the repo.
|
|
23
|
+
function composeFile(root) {
|
|
24
|
+
const declared = ((readProfile(root).isolation || {}).compose_file);
|
|
25
|
+
const names = typeof declared === 'string' && declared.trim() ? [declared.trim(), ...CANDIDATES] : CANDIDATES;
|
|
26
|
+
const base = realOr(root);
|
|
27
|
+
for (const n of names) {
|
|
28
|
+
if (path.isAbsolute(n)) continue;
|
|
29
|
+
const file = realOr(path.join(root, n));
|
|
30
|
+
if (!file.startsWith(base + path.sep)) continue;
|
|
31
|
+
try { if (fs.statSync(file).isFile()) return { file, rel: path.relative(base, file) }; } catch { /* next */ }
|
|
32
|
+
}
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Async, bounded, no shell. Resolves { code, out, err, missing } — never rejects.
|
|
37
|
+
function exec(args, { cwd, timeout = 8000 } = {}) {
|
|
38
|
+
return new Promise((resolve) => {
|
|
39
|
+
let out = ''; let err = ''; let done = false;
|
|
40
|
+
const finish = (r) => { if (!done) { done = true; clearTimeout(timer); resolve({ out, err, ...r }); } };
|
|
41
|
+
let child;
|
|
42
|
+
try { child = spawn(bin(), args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] }); } catch (e) { return resolve({ code: -1, out, err: e.message, missing: e.code === 'ENOENT' }); }
|
|
43
|
+
const timer = setTimeout(() => { try { child.kill('SIGKILL'); } catch { /* gone */ } finish({ code: -1, timedOut: true }); }, timeout);
|
|
44
|
+
child.stdout.on('data', (d) => { out += d; if (out.length > 2e6) out = out.slice(-2e6); });
|
|
45
|
+
child.stderr.on('data', (d) => { err += d; if (err.length > 2e5) err = err.slice(-2e5); });
|
|
46
|
+
child.on('error', (e) => finish({ code: -1, missing: e.code === 'ENOENT', err: e.message }));
|
|
47
|
+
child.on('close', (code) => finish({ code }));
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const firstLine = (s) => String(s || '').trim().split(/\r?\n/).find((l) => l.trim()) || '';
|
|
52
|
+
|
|
53
|
+
// `docker compose ps --format json` prints one object per line on recent versions, a JSON array on older ones.
|
|
54
|
+
function parsePs(out) {
|
|
55
|
+
const text = String(out || '').trim();
|
|
56
|
+
if (!text) return [];
|
|
57
|
+
let rows = [];
|
|
58
|
+
try { const v = JSON.parse(text); rows = Array.isArray(v) ? v : [v]; } catch {
|
|
59
|
+
for (const l of text.split(/\r?\n/)) { try { rows.push(JSON.parse(l)); } catch { /* not a row */ } }
|
|
60
|
+
}
|
|
61
|
+
return rows.filter((r) => r && typeof r === 'object');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function portsOf(row) {
|
|
65
|
+
const pubs = Array.isArray(row.Publishers) ? row.Publishers : [];
|
|
66
|
+
const seen = new Set();
|
|
67
|
+
for (const p of pubs) if (p && p.PublishedPort) seen.add(`${p.PublishedPort}→${p.TargetPort}`);
|
|
68
|
+
return [...seen];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function daemon() {
|
|
72
|
+
const r = await exec(['info', '--format', '{{.ServerVersion}}'], { timeout: 6000 });
|
|
73
|
+
if (r.missing) return { installed: false, up: false, error: 'the docker CLI is not installed (or not on PATH)' };
|
|
74
|
+
if (r.timedOut) return { installed: true, up: false, error: 'the Docker daemon did not answer in time' };
|
|
75
|
+
if (r.code !== 0) return { installed: true, up: false, error: firstLine(r.err) || 'the Docker daemon is not running' };
|
|
76
|
+
return { installed: true, up: true, version: firstLine(r.out) };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Everything the Docker tab shows. Each part degrades alone: no daemon still lists the declared services.
|
|
80
|
+
async function status(root) {
|
|
81
|
+
const cf = composeFile(root);
|
|
82
|
+
if (!cf) return { configured: false };
|
|
83
|
+
const [d, cfg] = await Promise.all([daemon(), exec(['compose', '-f', cf.file, 'config', '--services'], { cwd: root })]);
|
|
84
|
+
const defined = cfg.code === 0 ? cfg.out.split(/\r?\n/).map((s) => s.trim()).filter(Boolean) : [];
|
|
85
|
+
const out = { configured: true, file: cf.rel, daemon: d, services: [], configError: cfg.code === 0 ? null : firstLine(cfg.err) || 'docker compose could not read the file' };
|
|
86
|
+
let rows = [];
|
|
87
|
+
if (d.up && defined.length) {
|
|
88
|
+
const ps = await exec(['compose', '-f', cf.file, 'ps', '-a', '--format', 'json'], { cwd: root });
|
|
89
|
+
if (ps.code === 0) rows = parsePs(ps.out); else out.psError = firstLine(ps.err);
|
|
90
|
+
}
|
|
91
|
+
const by = new Map();
|
|
92
|
+
for (const r of rows) by.set(r.Service || r.Name, r);
|
|
93
|
+
const names = defined.length ? defined : [...by.keys()];
|
|
94
|
+
out.services = names.map((name) => {
|
|
95
|
+
const r = by.get(name);
|
|
96
|
+
if (!r) return { name, state: d.up ? 'not created' : 'unknown', health: '', status: '', ports: [], image: '' };
|
|
97
|
+
return { name, state: String(r.State || '').toLowerCase() || 'unknown', health: String(r.Health || '').toLowerCase(), status: String(r.Status || ''), ports: portsOf(r), image: String(r.Image || '') };
|
|
98
|
+
});
|
|
99
|
+
out.running = out.services.filter((s) => s.state === 'running').length;
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Starts up/stop/restart/down/logs as a job. Returns the job.
|
|
104
|
+
async function act(jobs, project, { action, service, confirmed = false }) {
|
|
105
|
+
if (!ACTIONS.includes(action)) throw new OpError(`action must be one of ${ACTIONS.join(', ')}`);
|
|
106
|
+
const cf = composeFile(project.root);
|
|
107
|
+
if (!cf) throw new OpError('this project declares no compose file (isolation.compose_file)', 400);
|
|
108
|
+
const d = await daemon();
|
|
109
|
+
if (!d.up) throw new OpError(d.error || 'the Docker daemon is not running', 409, { dockerDown: true });
|
|
110
|
+
let svc = null;
|
|
111
|
+
if (service !== undefined && service !== null && service !== '') {
|
|
112
|
+
if (action === 'down') throw new OpError('down applies to the whole stack');
|
|
113
|
+
const cfg = await exec(['compose', '-f', cf.file, 'config', '--services'], { cwd: project.root });
|
|
114
|
+
const defined = cfg.out.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
|
|
115
|
+
if (typeof service !== 'string' || !defined.includes(service)) throw new OpError('not a service of this compose file', 404);
|
|
116
|
+
svc = service;
|
|
117
|
+
}
|
|
118
|
+
const verb = { up: ['up', '-d'], stop: ['stop'], restart: ['restart'], down: ['down'], logs: ['logs', '--no-color', '--tail', '200', '-f'] }[action];
|
|
119
|
+
const args = ['compose', '-f', cf.file, ...verb, ...(svc ? [svc] : [])];
|
|
120
|
+
const shown = `docker compose -f ${cf.rel} ${verb.join(' ')}${svc ? ` ${svc}` : ''}`;
|
|
121
|
+
const kind = action === 'logs' ? 'docker-logs' : 'docker';
|
|
122
|
+
const tag = action === 'logs' ? (svc || '*') : 'stack';
|
|
123
|
+
if (jobs.find(project.id, kind, tag)) throw new OpError(action === 'logs' ? 'these logs are already being followed' : 'a docker command is already running for this project', 409);
|
|
124
|
+
confirm(gateVerdict(project.root, shown, project.root), confirmed, shown);
|
|
125
|
+
return jobs.start({ projectId: project.id, kind, tag, label: `docker · ${verb[0]}${svc ? ` ${svc}` : ''}`, cwd: project.root, file: bin(), args, command: undefined, display: shown });
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Before `scripts/new-feature.sh`: the script creates the worktree's database INSIDE a compose service
|
|
129
|
+
// (`docker compose exec -T postgres …`), so it fails — late and obscurely — when Docker or that service is down.
|
|
130
|
+
// Returns null when the script needs nothing, else { ok, reason, services, missing }.
|
|
131
|
+
async function preflight(root) {
|
|
132
|
+
const cf = composeFile(root);
|
|
133
|
+
let script = '';
|
|
134
|
+
try { script = fs.readFileSync(path.join(root, 'scripts', 'new-feature.sh'), 'utf8'); } catch { return null; }
|
|
135
|
+
if (!cf || !/\bdocker\b/.test(script)) return null;
|
|
136
|
+
const needs = new Set();
|
|
137
|
+
const re = /docker\s+compose[^\n]*?\bexec\b\s+(?:-[A-Za-z-]+\s+)*([A-Za-z][\w.-]*)/g;
|
|
138
|
+
for (let m = re.exec(script); m; m = re.exec(script)) needs.add(m[1]);
|
|
139
|
+
const s = await status(root);
|
|
140
|
+
if (!s.daemon.installed) return { ok: false, reason: s.daemon.error, services: [...needs], missing: [...needs], daemonUp: false };
|
|
141
|
+
if (!s.daemon.up) return { ok: false, reason: `${s.daemon.error || 'the Docker daemon is not running'} — scripts/new-feature.sh needs it to create the worktree's database`, services: [...needs], missing: [...needs], daemonUp: false };
|
|
142
|
+
const down = [...needs].filter((n) => { const x = s.services.find((v) => v.name === n); return !x || x.state !== 'running'; });
|
|
143
|
+
if (down.length) return { ok: false, reason: `scripts/new-feature.sh runs commands inside ${down.join(', ')}, which ${down.length > 1 ? 'are' : 'is'} not running`, services: [...needs], missing: down, daemonUp: true };
|
|
144
|
+
return { ok: true, services: [...needs], missing: [], daemonUp: true };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
module.exports = { composeFile, status, act, preflight, ACTIONS, parsePs };
|
package/ui/jobs.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// cohorte ui — child processes the dashboard starts (dev servers, worktree scripts).
|
|
3
|
+
//
|
|
4
|
+
// A job is one command in one folder, in its own process group so that stopping it stops the whole
|
|
5
|
+
// tree (a dev server spawns children). Output is kept in a bounded ring buffer that clients poll with a
|
|
6
|
+
// cursor. Nothing here accepts a command from a client: callers pass commands that came from the
|
|
7
|
+
// project's own profile or from fixed git invocations, after the project's gate had its say.
|
|
8
|
+
|
|
9
|
+
const http = require('http');
|
|
10
|
+
const https = require('https');
|
|
11
|
+
const crypto = require('crypto');
|
|
12
|
+
const { spawn } = require('child_process');
|
|
13
|
+
|
|
14
|
+
const MAX_LINES = 2000;
|
|
15
|
+
const MAX_LINE = 4000;
|
|
16
|
+
const KILL_GRACE_MS = 4000;
|
|
17
|
+
|
|
18
|
+
function killTree(child, signal) {
|
|
19
|
+
if (!child || child.exitCode !== null || child.signalCode) return;
|
|
20
|
+
try {
|
|
21
|
+
if (process.platform === 'win32') spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
|
|
22
|
+
else process.kill(-child.pid, signal);
|
|
23
|
+
} catch { /* already gone */ }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function probeOnce(target, cwd) {
|
|
27
|
+
return new Promise((resolve) => {
|
|
28
|
+
if (/^https?:\/\//i.test(target)) {
|
|
29
|
+
const lib = target.startsWith('https') ? https : http;
|
|
30
|
+
const req = lib.get(target, { timeout: 1500 }, (res) => { res.resume(); resolve(res.statusCode >= 200 && res.statusCode < 400); });
|
|
31
|
+
req.on('timeout', () => { req.destroy(); resolve(false); });
|
|
32
|
+
req.on('error', () => resolve(false));
|
|
33
|
+
} else {
|
|
34
|
+
const c = spawn(target, { shell: true, cwd, stdio: 'ignore' });
|
|
35
|
+
const t = setTimeout(() => c.kill(), 5000);
|
|
36
|
+
c.on('close', (code) => { clearTimeout(t); resolve(code === 0); });
|
|
37
|
+
c.on('error', () => { clearTimeout(t); resolve(false); });
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
class Jobs {
|
|
43
|
+
constructor() { this.jobs = new Map(); }
|
|
44
|
+
|
|
45
|
+
// opts: { projectId, kind, label, cwd, command (shell string) | file+args (+ display: what to show), ready, readyTimeoutMs, tag, env }
|
|
46
|
+
start(opts) {
|
|
47
|
+
const id = crypto.randomBytes(4).toString('hex');
|
|
48
|
+
const job = {
|
|
49
|
+
id, projectId: opts.projectId, kind: opts.kind, label: opts.label, cwd: opts.cwd, tag: opts.tag || null,
|
|
50
|
+
command: opts.display || opts.command || [opts.file, ...(opts.args || [])].join(' '),
|
|
51
|
+
status: 'starting', pid: null, startedAt: new Date().toISOString(), endedAt: null, exitCode: null,
|
|
52
|
+
lines: [], dropped: 0, stopping: false, child: null,
|
|
53
|
+
};
|
|
54
|
+
const push = (chunk) => {
|
|
55
|
+
for (const raw of String(chunk).split(/\r?\n/)) {
|
|
56
|
+
if (raw === '') continue;
|
|
57
|
+
job.lines.push(raw.length > MAX_LINE ? `${raw.slice(0, MAX_LINE)}…` : raw);
|
|
58
|
+
}
|
|
59
|
+
if (job.lines.length > MAX_LINES) { const cut = job.lines.length - MAX_LINES; job.lines.splice(0, cut); job.dropped += cut; }
|
|
60
|
+
};
|
|
61
|
+
const child = opts.command
|
|
62
|
+
? spawn(opts.command, { shell: true, cwd: opts.cwd, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...(opts.env || {}) } })
|
|
63
|
+
: spawn(opts.file, opts.args || [], { cwd: opts.cwd, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...(opts.env || {}) } });
|
|
64
|
+
job.child = child;
|
|
65
|
+
job.pid = child.pid || null;
|
|
66
|
+
job.status = 'running';
|
|
67
|
+
child.stdout.on('data', push);
|
|
68
|
+
child.stderr.on('data', push);
|
|
69
|
+
child.on('error', (e) => { push(`[cohorte ui] could not start: ${e.message}`); job.status = 'failed'; job.endedAt = new Date().toISOString(); });
|
|
70
|
+
child.on('close', (code, signal) => {
|
|
71
|
+
job.exitCode = code;
|
|
72
|
+
job.endedAt = new Date().toISOString();
|
|
73
|
+
job.status = job.stopping ? 'stopped' : code === 0 ? 'done' : 'failed';
|
|
74
|
+
if (signal && !job.stopping) push(`[cohorte ui] killed by ${signal}`);
|
|
75
|
+
clearTimeout(job.readyTimer);
|
|
76
|
+
});
|
|
77
|
+
if (opts.ready) this.#waitReady(job, opts.ready, opts.readyTimeoutMs || 90000);
|
|
78
|
+
this.jobs.set(id, job);
|
|
79
|
+
return job;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async #waitReady(job, target, timeoutMs) {
|
|
83
|
+
const until = Date.now() + timeoutMs;
|
|
84
|
+
while (job.status === 'running' && Date.now() < until) {
|
|
85
|
+
if (await probeOnce(target, job.cwd)) { if (job.status === 'running') job.status = 'ready'; return; }
|
|
86
|
+
await new Promise((r) => { job.readyTimer = setTimeout(r, 1000); });
|
|
87
|
+
}
|
|
88
|
+
if (job.status === 'running') job.lines.push(`[cohorte ui] not ready after ${Math.round(timeoutMs / 1000)}s (still running) — probe: ${target}`);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
isLive(job) { return job.status === 'running' || job.status === 'ready' || job.status === 'starting'; }
|
|
92
|
+
|
|
93
|
+
find(projectId, kind, tag) {
|
|
94
|
+
return [...this.jobs.values()].reverse().find((j) => j.projectId === projectId && j.kind === kind && j.tag === tag && this.isLive(j)) || null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
get(id) { return this.jobs.get(id) || null; }
|
|
98
|
+
|
|
99
|
+
forProject(projectId) { return [...this.jobs.values()].filter((j) => j.projectId === projectId); }
|
|
100
|
+
|
|
101
|
+
stop(job) {
|
|
102
|
+
if (!this.isLive(job)) return false;
|
|
103
|
+
job.stopping = true;
|
|
104
|
+
killTree(job.child, 'SIGTERM');
|
|
105
|
+
const t = setTimeout(() => killTree(job.child, 'SIGKILL'), KILL_GRACE_MS);
|
|
106
|
+
t.unref();
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
stopAll() {
|
|
111
|
+
for (const j of this.jobs.values()) if (this.isLive(j)) { j.stopping = true; killTree(j.child, 'SIGTERM'); }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
view(job, since) {
|
|
115
|
+
const out = { id: job.id, kind: job.kind, label: job.label, cwd: job.cwd, tag: job.tag, command: job.command, status: job.status,
|
|
116
|
+
pid: job.pid, startedAt: job.startedAt, endedAt: job.endedAt, exitCode: job.exitCode };
|
|
117
|
+
if (since !== undefined) {
|
|
118
|
+
const total = job.dropped + job.lines.length;
|
|
119
|
+
const from = Math.max(0, since - job.dropped);
|
|
120
|
+
out.lines = job.lines.slice(from);
|
|
121
|
+
out.cursor = total;
|
|
122
|
+
}
|
|
123
|
+
return out;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
module.exports = { Jobs };
|