cohorte 3.1.2 → 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 +31 -0
- package/bin/cli.js +33 -1
- package/core/hooks/gate.py +561 -550
- package/lib/doctor.js +48 -1
- package/lib/registry.js +118 -0
- package/package.json +3 -2
- package/scripts/kanban-move.sh +51 -11
- 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/lib/doctor.js
CHANGED
|
@@ -367,6 +367,51 @@ function checkHooks(projectRoot, globalDir) {
|
|
|
367
367
|
return mk('hooks', 'Gate hook', 'ok', `registered once (${shell[0].matcher} + Write|Edit|MultiEdit|NotebookEdit), committed`);
|
|
368
368
|
}
|
|
369
369
|
|
|
370
|
+
// Claude Code ignores a project's permissions.allow until its folder is trusted (the dialog an
|
|
371
|
+
// interactive `claude` shows once). Under `claude -p` — CI, and tools such as francois that drive
|
|
372
|
+
// Claude Code headless — nothing ever shows that dialog, so every pipeline script and test command
|
|
373
|
+
// prompts (or is refused) instead of running. Hooks still run: the gate is unaffected. The answer
|
|
374
|
+
// lives on the user store (`<config>/.claude.json`, or `~/.claude.json` without CLAUDE_CONFIG_DIR),
|
|
375
|
+
// keyed by the git root and honoured from any ancestor folder.
|
|
376
|
+
function claudeUserStore(globalDir) {
|
|
377
|
+
if (process.env.CLAUDE_CONFIG_DIR) return path.join(process.env.CLAUDE_CONFIG_DIR, '.claude.json');
|
|
378
|
+
return path.join(require('os').homedir(), '.claude.json');
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
const realOr = (p) => { try { return fs.realpathSync(p); } catch { return path.resolve(p); } };
|
|
382
|
+
|
|
383
|
+
// Trusted folders, as written and resolved (macOS: /var ⇄ /private/var, /tmp ⇄ /private/tmp).
|
|
384
|
+
function trustedBy(projects, dirs) {
|
|
385
|
+
const trusted = new Map();
|
|
386
|
+
for (const [k, node] of Object.entries(projects || {})) {
|
|
387
|
+
if (node && node.hasTrustDialogAccepted === true) { trusted.set(path.resolve(k), k); trusted.set(realOr(k), k); }
|
|
388
|
+
}
|
|
389
|
+
for (const start of dirs) {
|
|
390
|
+
for (let d = path.resolve(start); ; d = path.dirname(d)) {
|
|
391
|
+
if (trusted.has(d)) return trusted.get(d);
|
|
392
|
+
if (path.dirname(d) === d) break;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
return null;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
function checkTrust(projectRoot, globalDir) {
|
|
399
|
+
const store = readJson(claudeUserStore(globalDir));
|
|
400
|
+
if (!store) return mk('trust', 'Folder trust', 'skip', 'no Claude Code user store found (never run on this machine?)');
|
|
401
|
+
const top = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd: projectRoot, encoding: 'utf8' });
|
|
402
|
+
const root = top.status === 0 && top.stdout.trim() ? path.resolve(top.stdout.trim()) : path.resolve(projectRoot);
|
|
403
|
+
const by = trustedBy(store.projects, [root, realOr(root), projectRoot]);
|
|
404
|
+
if (by) {
|
|
405
|
+
const self = [root, realOr(root), path.resolve(projectRoot)].some((d) => realOr(by) === realOr(d));
|
|
406
|
+
return mk('trust', 'Folder trust', 'ok', self ? 'trusted' : `trusted through ${by}`);
|
|
407
|
+
}
|
|
408
|
+
const settings = readJson(path.join(projectRoot, '.claude', 'settings.json'));
|
|
409
|
+
const n = (settings && settings.permissions && Array.isArray(settings.permissions.allow)) ? settings.permissions.allow.length : 0;
|
|
410
|
+
return mk('trust', 'Folder trust', 'warn',
|
|
411
|
+
`not trusted — under \`claude -p\` (CI, francois, scripts) Claude Code ignores the ${n} permissions.allow rule(s), so every pipeline script prompts or is refused (the gate itself still runs)`,
|
|
412
|
+
`run \`claude\` once in ${root} (or a parent folder) and accept the trust dialog`);
|
|
413
|
+
}
|
|
414
|
+
|
|
370
415
|
function checkRetrieval(profile, projectRoot) {
|
|
371
416
|
const provider = profile && profile.retrieval && profile.retrieval.provider;
|
|
372
417
|
if (!provider || provider === 'none' || String(provider).startsWith('<')) {
|
|
@@ -496,6 +541,8 @@ async function state({ projectRoot, globalDir, cliVersion, offline }) {
|
|
|
496
541
|
checkLocalArtifacts(projectRoot, ['.claude']),
|
|
497
542
|
isProject ? checkHooks(projectRoot, globalDir)
|
|
498
543
|
: mk('hooks', 'Gate hook', 'skip', 'not a cohorte project yet (no PIPELINE.md / .claude/pipeline.json)'),
|
|
544
|
+
isProject ? checkTrust(projectRoot, globalDir)
|
|
545
|
+
: mk('trust', 'Folder trust', 'skip', 'not a cohorte project yet'),
|
|
499
546
|
checkRetrieval(profile, projectRoot),
|
|
500
547
|
checkDesign(profile, projectRoot),
|
|
501
548
|
checkIsolation(profile, projectRoot),
|
|
@@ -525,4 +572,4 @@ async function state({ projectRoot, globalDir, cliVersion, offline }) {
|
|
|
525
572
|
};
|
|
526
573
|
}
|
|
527
574
|
|
|
528
|
-
module.exports = { state, scanSpecs };
|
|
575
|
+
module.exports = { state, scanSpecs, checkTrust };
|
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/scripts/kanban-move.sh
CHANGED
|
@@ -230,14 +230,43 @@ fi
|
|
|
230
230
|
|
|
231
231
|
# Serialize the read-modify-write: parallel worktrees (/cohorte-fleet, the loop workflow) move
|
|
232
232
|
# cards on ONE board, and two concurrent rewrites used to lose one of the moves.
|
|
233
|
-
#
|
|
234
|
-
#
|
|
235
|
-
#
|
|
236
|
-
#
|
|
237
|
-
# the
|
|
233
|
+
# A kernel lock whenever possible: flock(2) on fd 9, held by this shell until it exits — the
|
|
234
|
+
# kernel drops it if we die, so there is no stale lock to break. flock(1) where it exists (Linux);
|
|
235
|
+
# otherwise python3 takes it on the INHERITED fd 9 (a flock belongs to the open file, which this
|
|
236
|
+
# shell keeps open after python exits) — python3 is there wherever cohorte runs, the gate needs it.
|
|
237
|
+
# The lock file lives in $TMPDIR keyed by the board's physical path (`./Tasks.md`, an absolute
|
|
238
|
+
# path and a symlinked vault serialize together), never next to the board in the human's vault.
|
|
239
|
+
# Last resort, neither available: an atomic `mkdir` with the holder's PID (stale only when that
|
|
240
|
+
# process is gone; breaking it is serialized under `<lock>.break`).
|
|
241
|
+
# COHORTE_KANBAN_LOCK=flock|python|mkdir forces one (tests); COHORTE_KANBAN_NO_FLOCK=1 skips flock(1).
|
|
242
|
+
board_key="$(cd "$(dirname "$board")" && pwd -P)/$(basename "$board")"
|
|
238
243
|
lock="${board}.lock"
|
|
239
|
-
|
|
240
|
-
|
|
244
|
+
flockfile="${TMPDIR:-/tmp}/cohorte-kanban-$(printf '%s' "$board_key" | cksum | cut -d' ' -f1).lock"
|
|
245
|
+
lock_kind=${COHORTE_KANBAN_LOCK:-}
|
|
246
|
+
if [ -z "$lock_kind" ]; then
|
|
247
|
+
if [ -z "${COHORTE_KANBAN_NO_FLOCK:-}" ] && command -v flock >/dev/null 2>&1; then lock_kind=flock
|
|
248
|
+
elif python3 -c 'import fcntl' >/dev/null 2>&1; then lock_kind=python
|
|
249
|
+
else lock_kind=mkdir
|
|
250
|
+
fi
|
|
251
|
+
fi
|
|
252
|
+
if [ "$lock_kind" = python ]; then
|
|
253
|
+
exec 9>"$flockfile"
|
|
254
|
+
if ! python3 -c 'import errno, fcntl, sys, time
|
|
255
|
+
end = time.time() + 30
|
|
256
|
+
while True:
|
|
257
|
+
try:
|
|
258
|
+
fcntl.flock(9, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
259
|
+
sys.exit(0)
|
|
260
|
+
except OSError as e:
|
|
261
|
+
if e.errno not in (errno.EAGAIN, errno.EACCES, errno.EWOULDBLOCK):
|
|
262
|
+
raise
|
|
263
|
+
if time.time() > end:
|
|
264
|
+
sys.exit(1)
|
|
265
|
+
time.sleep(0.02)'; then
|
|
266
|
+
echo "error: board is locked by another move ($flockfile) — retry" >&2
|
|
267
|
+
exit 4
|
|
268
|
+
fi
|
|
269
|
+
elif [ "$lock_kind" = flock ]; then
|
|
241
270
|
exec 9>"$flockfile"
|
|
242
271
|
if ! flock -w 30 9; then
|
|
243
272
|
echo "error: board is locked by another move ($flockfile) — retry" >&2
|
|
@@ -248,11 +277,22 @@ else
|
|
|
248
277
|
until mkdir "$lock" 2>/dev/null; do
|
|
249
278
|
holder=$(cat "$lock/pid" 2>/dev/null || true)
|
|
250
279
|
if [ -n "$holder" ] && ! kill -0 "$holder" 2>/dev/null; then
|
|
251
|
-
# Dead holder.
|
|
252
|
-
|
|
253
|
-
|
|
280
|
+
# Dead holder. One breaker at a time; under that, remove the lock only if it still names
|
|
281
|
+
# the same dead holder — then nobody else can have replaced it (only a breaker or its
|
|
282
|
+
# owner removes a lock, and the owner is dead).
|
|
283
|
+
if mkdir "$lock.break" 2>/dev/null; then
|
|
284
|
+
echo $$ > "$lock.break/pid"
|
|
285
|
+
if [ "$(cat "$lock/pid" 2>/dev/null || true)" = "$holder" ]; then
|
|
286
|
+
rm -f "$lock/pid"; rmdir "$lock" 2>/dev/null || true
|
|
287
|
+
fi
|
|
288
|
+
rm -f "$lock.break/pid"; rmdir "$lock.break" 2>/dev/null || true
|
|
289
|
+
continue
|
|
290
|
+
fi
|
|
291
|
+
# Another waiter is breaking it — unless that breaker died mid-way too.
|
|
292
|
+
breaker=$(cat "$lock.break/pid" 2>/dev/null || true)
|
|
293
|
+
if [ -n "$breaker" ] && ! kill -0 "$breaker" 2>/dev/null; then
|
|
294
|
+
rm -f "$lock.break/pid"; rmdir "$lock.break" 2>/dev/null || true
|
|
254
295
|
fi
|
|
255
|
-
continue
|
|
256
296
|
fi
|
|
257
297
|
waited=$((waited + 1))
|
|
258
298
|
if [ "$waited" -gt 300 ]; then
|
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 };
|