cohorte 3.1.3 → 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.
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ // What git (and, when it is installed, `gh`) says about a worktree: ahead/behind, dirty files, the last commit,
3
+ // the PR for its branch and that PR's checks, and the diff against the default branch.
4
+ // Read-only and bounded: every call is async, has a timeout and never goes through a shell. A file to diff must be
5
+ // one that `git` itself lists for the worktree — the client never names a path git did not report.
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.baseRef = baseRef;
8
+ exports.parseStatus = parseStatus;
9
+ exports.parseShortstat = parseShortstat;
10
+ exports.worktreeGit = worktreeGit;
11
+ exports.pullFor = pullFor;
12
+ exports.ghAvailable = ghAvailable;
13
+ exports.changedFiles = changedFiles;
14
+ exports.fileDiff = fileDiff;
15
+ const child_process_1 = require("child_process");
16
+ function run(file, args, cwd, timeout = 8000, max = 400_000) {
17
+ return new Promise((resolve) => {
18
+ let out = '';
19
+ let err = '';
20
+ let done = false;
21
+ let child;
22
+ const finish = (code) => { if (!done) {
23
+ done = true;
24
+ clearTimeout(timer);
25
+ resolve({ code, out, err });
26
+ } };
27
+ try {
28
+ child = (0, child_process_1.spawn)(file, args, { cwd, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, GIT_TERMINAL_PROMPT: '0', LC_ALL: 'C' } });
29
+ }
30
+ catch {
31
+ return resolve({ code: -1, out, err: 'spawn failed' });
32
+ }
33
+ const timer = setTimeout(() => { try {
34
+ child.kill('SIGKILL');
35
+ }
36
+ catch { /* gone */ } finish(-1); }, timeout);
37
+ child.stdout?.on('data', (d) => { if (out.length < max)
38
+ out += d; });
39
+ child.stderr?.on('data', (d) => { if (err.length < 20_000)
40
+ err += d; });
41
+ child.on('error', () => finish(-1));
42
+ child.on('close', (c) => finish(c));
43
+ });
44
+ }
45
+ const git = (cwd, ...a) => run('git', a, cwd);
46
+ async function baseRef(cwd, defaultBranch) {
47
+ for (const ref of [`origin/${defaultBranch}`, defaultBranch]) {
48
+ if ((await git(cwd, 'rev-parse', '--verify', '-q', ref)).code === 0)
49
+ return ref;
50
+ }
51
+ return null;
52
+ }
53
+ function parseStatus(out) {
54
+ const r = { branch: null, ahead: 0, behind: 0, upstream: null, modified: 0, staged: 0, untracked: 0, conflicted: 0 };
55
+ for (const l of out.split('\n')) {
56
+ if (l.startsWith('# branch.head ')) {
57
+ const b = l.slice(14).trim();
58
+ r.branch = b === '(detached)' ? null : b;
59
+ }
60
+ else if (l.startsWith('# branch.upstream '))
61
+ r.upstream = l.slice(18).trim();
62
+ else if (l.startsWith('# branch.ab ')) {
63
+ const m = /\+(\d+) -(\d+)/.exec(l);
64
+ if (m) {
65
+ r.ahead = Number(m[1]);
66
+ r.behind = Number(m[2]);
67
+ }
68
+ }
69
+ else if (l.startsWith('1 ') || l.startsWith('2 ')) {
70
+ const xy = l.split(' ')[1] || '..';
71
+ if (xy[0] !== '.')
72
+ r.staged++;
73
+ if (xy[1] !== '.')
74
+ r.modified++;
75
+ }
76
+ else if (l.startsWith('u '))
77
+ r.conflicted++;
78
+ else if (l.startsWith('? '))
79
+ r.untracked++;
80
+ }
81
+ return r;
82
+ }
83
+ function parseShortstat(out) {
84
+ const n = (re) => { const m = re.exec(out); return m ? Number(m[1]) : 0; };
85
+ return { files: n(/(\d+) files? changed/), insertions: n(/(\d+) insertions?\(\+\)/), deletions: n(/(\d+) deletions?\(-\)/) };
86
+ }
87
+ async function worktreeGit(wtPath, defaultBranch) {
88
+ const [st, last, base] = await Promise.all([
89
+ git(wtPath, 'status', '--porcelain=v2', '--branch'),
90
+ git(wtPath, 'log', '-1', '--format=%h%x09%s%x09%cr'),
91
+ baseRef(wtPath, defaultBranch),
92
+ ]);
93
+ if (st.code !== 0)
94
+ return { error: (st.err || 'git status failed').trim().split('\n')[0] };
95
+ const s = parseStatus(st.out);
96
+ const [sha, subject, when] = last.out.trim().split('\t');
97
+ let diff = { files: 0, insertions: 0, deletions: 0 };
98
+ if (base) {
99
+ const mb = await git(wtPath, 'merge-base', base, 'HEAD');
100
+ if (mb.code === 0 && mb.out.trim())
101
+ diff = parseShortstat((await git(wtPath, 'diff', '--shortstat', mb.out.trim())).out);
102
+ }
103
+ return { ...s, base, lastCommit: sha ? { sha, subject: subject || '', when: when || '' } : null, diff, clean: !s.modified && !s.staged && !s.untracked && !s.conflicted };
104
+ }
105
+ // ---- pull request for a branch, via gh (optional, cached by the caller) ----
106
+ async function pullFor(root, branch) {
107
+ const r = await run('gh', ['pr', 'list', '--head', branch, '--state', 'all', '--limit', '1', '--json', 'number,state,url,title,isDraft,reviewDecision,statusCheckRollup'], root, 12000);
108
+ if (r.code !== 0)
109
+ return null;
110
+ let rows;
111
+ try {
112
+ rows = JSON.parse(r.out);
113
+ }
114
+ catch {
115
+ return null;
116
+ }
117
+ const p = rows[0];
118
+ if (!p)
119
+ return null;
120
+ const roll = Array.isArray(p.statusCheckRollup) ? p.statusCheckRollup : [];
121
+ const bad = roll.some((c) => ['FAILURE', 'TIMED_OUT', 'CANCELLED', 'ACTION_REQUIRED', 'STARTUP_FAILURE'].includes(String(c.conclusion || c.state || '').toUpperCase()));
122
+ const pending = roll.some((c) => !c.conclusion && !['SUCCESS', 'FAILURE', 'ERROR'].includes(String(c.state || '').toUpperCase()) && String(c.status || c.state || '').toUpperCase() !== 'COMPLETED');
123
+ return { number: p.number, state: String(p.state), url: String(p.url), title: String(p.title), draft: p.isDraft === true, review: p.reviewDecision ? String(p.reviewDecision) : null,
124
+ checks: !roll.length ? null : bad ? 'failure' : pending ? 'pending' : 'success' };
125
+ }
126
+ async function ghAvailable() { return (await run('gh', ['--version'], process.cwd(), 4000)).code === 0; }
127
+ // ---- diff ----
128
+ const STATUS = { A: 'added', M: 'modified', D: 'deleted', R: 'renamed', C: 'copied', T: 'changed' };
129
+ async function changedFiles(wtPath, base) {
130
+ const files = new Map();
131
+ if (base) {
132
+ const mb = await git(wtPath, 'merge-base', base, 'HEAD');
133
+ if (mb.code === 0 && mb.out.trim()) {
134
+ const d = await git(wtPath, 'diff', '--name-status', '-z', mb.out.trim());
135
+ const t = d.out.split('\0').filter(Boolean);
136
+ for (let i = 0; i < t.length;) {
137
+ const code = t[i][0];
138
+ if (code === 'R' || code === 'C') {
139
+ files.set(t[i + 2], { path: t[i + 2], status: STATUS[code] });
140
+ i += 3;
141
+ }
142
+ else {
143
+ files.set(t[i + 1], { path: t[i + 1], status: STATUS[code] || 'modified' });
144
+ i += 2;
145
+ }
146
+ }
147
+ }
148
+ }
149
+ const un = await git(wtPath, 'ls-files', '--others', '--exclude-standard', '-z');
150
+ for (const f of un.out.split('\0').filter(Boolean))
151
+ files.set(f, { path: f, status: 'untracked' });
152
+ return [...files.values()].sort((a, b) => a.path.localeCompare(b.path)).slice(0, 500);
153
+ }
154
+ async function fileDiff(wtPath, base, file) {
155
+ const list = await changedFiles(wtPath, base);
156
+ const entry = list.find((f) => f.path === file);
157
+ if (!entry)
158
+ return null;
159
+ if (entry.status === 'untracked') {
160
+ const r = await run('git', ['diff', '--no-index', '--no-color', '--', '/dev/null', file], wtPath);
161
+ return { file, status: entry.status, diff: r.out.slice(0, 200_000), truncated: r.out.length > 200_000 };
162
+ }
163
+ let range = 'HEAD';
164
+ if (base) {
165
+ const mb = await git(wtPath, 'merge-base', base, 'HEAD');
166
+ if (mb.code === 0 && mb.out.trim())
167
+ range = mb.out.trim();
168
+ }
169
+ const r = await git(wtPath, 'diff', '--no-color', '--no-ext-diff', range, '--', file);
170
+ return { file, status: entry.status, diff: r.out.slice(0, 200_000), truncated: r.out.length > 200_000 };
171
+ }
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ // Run history on disk: <globalDir>/cohorte-ui/runs/<projectId>/<runId>.json — so a finished (or interrupted) command
3
+ // survives a restart of `cohorte ui` and can still be replied to (its sessionId is kept). Bounded per project and
4
+ // pruned oldest first; events are trimmed. Writes are atomic (tmp + rename) and debounced.
5
+ var __importDefault = (this && this.__importDefault) || function (mod) {
6
+ return (mod && mod.__esModule) ? mod : { "default": mod };
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.RunStore = void 0;
10
+ const fs_1 = __importDefault(require("fs"));
11
+ const path_1 = __importDefault(require("path"));
12
+ const KEEP_PER_PROJECT = 40;
13
+ const KEEP_EVENTS = 400;
14
+ const SAFE = /^[A-Za-z0-9._-]+$/;
15
+ class RunStore {
16
+ dir;
17
+ timers = new Map();
18
+ constructor(dir) {
19
+ this.dir = dir;
20
+ }
21
+ fileOf(run) {
22
+ return SAFE.test(run.projectId) && SAFE.test(run.id) ? path_1.default.join(this.dir, run.projectId, `${run.id}.json`) : null;
23
+ }
24
+ /** Coalesces bursts of events into one write per run. `now` writes immediately (end of a turn, shutdown). */
25
+ schedule(run, now = false) {
26
+ const f = this.fileOf(run);
27
+ if (!f)
28
+ return;
29
+ clearTimeout(this.timers.get(f));
30
+ if (now) {
31
+ this.timers.delete(f);
32
+ this.write(run, f);
33
+ return;
34
+ }
35
+ const t = setTimeout(() => { this.timers.delete(f); this.write(run, f); }, 400);
36
+ t.unref();
37
+ this.timers.set(f, t);
38
+ }
39
+ flush(runs) { for (const r of runs)
40
+ this.schedule(r, true); }
41
+ write(run, f) {
42
+ try {
43
+ fs_1.default.mkdirSync(path_1.default.dirname(f), { recursive: true });
44
+ const cut = Math.max(0, run.events.length - KEEP_EVENTS);
45
+ const body = { v: 1, id: run.id, projectId: run.projectId, cwd: run.cwd, command: run.command, permissionMode: run.permissionMode, status: run.status,
46
+ startedAt: run.startedAt, endedAt: run.endedAt, result: run.result, sessionId: run.sessionId, dropped: run.dropped + cut, events: run.events.slice(cut) };
47
+ const tmp = `${f}.${process.pid}.tmp`;
48
+ fs_1.default.writeFileSync(tmp, JSON.stringify(body));
49
+ fs_1.default.renameSync(tmp, f);
50
+ this.prune(path_1.default.dirname(f));
51
+ }
52
+ catch { /* history is a convenience: never take a run down with it */ }
53
+ }
54
+ prune(projectDir) {
55
+ try {
56
+ const rows = fs_1.default.readdirSync(projectDir).filter((n) => n.endsWith('.json')).map((n) => ({ n, t: fs_1.default.statSync(path_1.default.join(projectDir, n)).mtimeMs })).sort((a, b) => b.t - a.t);
57
+ for (const old of rows.slice(KEEP_PER_PROJECT))
58
+ fs_1.default.rmSync(path_1.default.join(projectDir, old.n), { force: true });
59
+ }
60
+ catch { /* ignore */ }
61
+ }
62
+ /** Every stored run as a finished Run. A run that was still `running` when the process died is `stopped`. */
63
+ loadAll() {
64
+ const out = [];
65
+ let projects = [];
66
+ try {
67
+ projects = fs_1.default.readdirSync(this.dir);
68
+ }
69
+ catch {
70
+ return out;
71
+ }
72
+ for (const p of projects) {
73
+ let names = [];
74
+ try {
75
+ names = fs_1.default.readdirSync(path_1.default.join(this.dir, p)).filter((n) => n.endsWith('.json'));
76
+ }
77
+ catch {
78
+ continue;
79
+ }
80
+ for (const n of names) {
81
+ try {
82
+ const v = JSON.parse(fs_1.default.readFileSync(path_1.default.join(this.dir, p, n), 'utf8'));
83
+ if (v.v !== 1 || !SAFE.test(v.id) || v.projectId !== p)
84
+ continue;
85
+ const interrupted = v.status === 'running';
86
+ out.push({ id: v.id, projectId: v.projectId, cwd: v.cwd, command: v.command, permissionMode: v.permissionMode, status: interrupted ? 'stopped' : v.status,
87
+ startedAt: v.startedAt, endedAt: v.endedAt || (interrupted ? new Date().toISOString() : null), events: Array.isArray(v.events) ? v.events : [], dropped: v.dropped || 0,
88
+ pending: new Map(), result: v.result || null, sessionId: v.sessionId || null, child: null, closeTimer: null, stopping: false });
89
+ }
90
+ catch { /* a corrupt file is skipped */ }
91
+ }
92
+ }
93
+ return out;
94
+ }
95
+ }
96
+ exports.RunStore = RunStore;
@@ -0,0 +1,162 @@
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
+ var __importDefault = (this && this.__importDefault) || function (mod) {
9
+ return (mod && mod.__esModule) ? mod : { "default": mod };
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.Jobs = void 0;
13
+ exports.urlsIn = urlsIn;
14
+ const http_1 = __importDefault(require("http"));
15
+ const https_1 = __importDefault(require("https"));
16
+ const crypto_1 = __importDefault(require("crypto"));
17
+ const child_process_1 = require("child_process");
18
+ const MAX_LINES = 2000;
19
+ const MAX_LINE = 4000;
20
+ const KILL_GRACE_MS = 4000;
21
+ function killTree(child, signal) {
22
+ if (!child || child.exitCode !== null || child.signalCode)
23
+ return;
24
+ if (!child.pid)
25
+ return;
26
+ try {
27
+ if (process.platform === 'win32')
28
+ (0, child_process_1.spawn)('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
29
+ else
30
+ process.kill(-child.pid, signal);
31
+ }
32
+ catch { /* already gone */ }
33
+ }
34
+ function probeOnce(target, cwd) {
35
+ return new Promise((resolve) => {
36
+ if (/^https?:\/\//i.test(target)) {
37
+ const lib = target.startsWith('https') ? https_1.default : http_1.default;
38
+ const req = lib.get(target, { timeout: 1500 }, (res) => { res.resume(); resolve((res.statusCode ?? 0) >= 200 && (res.statusCode ?? 0) < 400); });
39
+ req.on('timeout', () => { req.destroy(); resolve(false); });
40
+ req.on('error', () => resolve(false));
41
+ }
42
+ else {
43
+ const c = (0, child_process_1.spawn)(target, { shell: true, cwd, stdio: 'ignore' });
44
+ const t = setTimeout(() => c.kill(), 5000);
45
+ c.on('close', (code) => { clearTimeout(t); resolve(code === 0); });
46
+ c.on('error', () => { clearTimeout(t); resolve(false); });
47
+ }
48
+ });
49
+ }
50
+ // A dev server announces where it listens ("Local: http://localhost:5173/"); the page offers an Open link for it.
51
+ const URL_RE = /https?:\/\/(?:localhost|127\.0\.0\.1|\[::1\]|0\.0\.0\.0):\d+[^\s'")\]]*/g;
52
+ // eslint-disable-next-line no-control-regex
53
+ const ANSI = /\u001b\[[0-9;]*[A-Za-z]/g;
54
+ function urlsIn(lines) {
55
+ const seen = new Set();
56
+ for (const l of lines.slice(-300)) {
57
+ for (const m of l.replace(ANSI, '').match(URL_RE) || [])
58
+ seen.add(m.replace('0.0.0.0', 'localhost').replace(/[.,;]+$/, ''));
59
+ if (seen.size >= 4)
60
+ break;
61
+ }
62
+ return [...seen];
63
+ }
64
+ class Jobs {
65
+ jobs = new Map();
66
+ onChange = () => { };
67
+ // opts: { projectId, kind, label, cwd, command (shell string) | file+args (+ display: what to show), ready, readyTimeoutMs, tag, env }
68
+ start(opts) {
69
+ const id = crypto_1.default.randomBytes(4).toString('hex');
70
+ const job = {
71
+ id, projectId: opts.projectId, kind: opts.kind, label: opts.label, cwd: opts.cwd, tag: opts.tag || null,
72
+ command: opts.display || opts.command || [opts.file, ...(opts.args || [])].join(' '),
73
+ status: 'starting', pid: null, startedAt: new Date().toISOString(), endedAt: null, exitCode: null,
74
+ lines: [], dropped: 0, stopping: false, child: null,
75
+ };
76
+ const changed = () => this.onChange(job);
77
+ const push = (chunk) => {
78
+ for (const raw of String(chunk).split(/\r?\n/)) {
79
+ if (raw === '')
80
+ continue;
81
+ job.lines.push(raw.length > MAX_LINE ? `${raw.slice(0, MAX_LINE)}…` : raw);
82
+ }
83
+ if (job.lines.length > MAX_LINES) {
84
+ const cut = job.lines.length - MAX_LINES;
85
+ job.lines.splice(0, cut);
86
+ job.dropped += cut;
87
+ }
88
+ changed();
89
+ };
90
+ const child = opts.command
91
+ ? (0, child_process_1.spawn)(opts.command, { shell: true, cwd: opts.cwd, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...(opts.env || {}) } })
92
+ : (0, child_process_1.spawn)(opts.file, opts.args || [], { cwd: opts.cwd, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...(opts.env || {}) } });
93
+ job.child = child;
94
+ job.pid = child.pid || null;
95
+ job.status = 'running';
96
+ child.stdout?.on('data', push);
97
+ child.stderr?.on('data', push);
98
+ child.on('error', (e) => { push(`[cohorte ui] could not start: ${e.message}`); job.status = 'failed'; job.endedAt = new Date().toISOString(); changed(); });
99
+ child.on('close', (code, signal) => {
100
+ job.exitCode = code;
101
+ job.endedAt = new Date().toISOString();
102
+ job.status = job.stopping ? 'stopped' : code === 0 ? 'done' : 'failed';
103
+ if (signal && !job.stopping)
104
+ push(`[cohorte ui] killed by ${signal}`);
105
+ clearTimeout(job.readyTimer);
106
+ changed();
107
+ });
108
+ if (opts.ready)
109
+ this.#waitReady(job, opts.ready, opts.readyTimeoutMs || 90000);
110
+ this.jobs.set(id, job);
111
+ return job;
112
+ }
113
+ async #waitReady(job, target, timeoutMs) {
114
+ const until = Date.now() + timeoutMs;
115
+ while (job.status === 'running' && Date.now() < until) {
116
+ if (await probeOnce(target, job.cwd)) {
117
+ if (job.status === 'running') {
118
+ job.status = 'ready';
119
+ this.onChange(job);
120
+ }
121
+ return;
122
+ }
123
+ await new Promise((r) => { job.readyTimer = setTimeout(r, 1000); });
124
+ }
125
+ if (job.status === 'running')
126
+ job.lines.push(`[cohorte ui] not ready after ${Math.round(timeoutMs / 1000)}s (still running) — probe: ${target}`);
127
+ }
128
+ isLive(job) { return job.status === 'running' || job.status === 'ready' || job.status === 'starting'; }
129
+ find(projectId, kind, tag) {
130
+ return [...this.jobs.values()].reverse().find((j) => j.projectId === projectId && j.kind === kind && j.tag === tag && this.isLive(j)) || null;
131
+ }
132
+ get(id) { return this.jobs.get(id) || null; }
133
+ forProject(projectId) { return [...this.jobs.values()].filter((j) => j.projectId === projectId); }
134
+ stop(job) {
135
+ if (!this.isLive(job))
136
+ return false;
137
+ job.stopping = true;
138
+ killTree(job.child, 'SIGTERM');
139
+ const t = setTimeout(() => killTree(job.child, 'SIGKILL'), KILL_GRACE_MS);
140
+ t.unref();
141
+ return true;
142
+ }
143
+ stopAll() {
144
+ for (const j of this.jobs.values())
145
+ if (this.isLive(j)) {
146
+ j.stopping = true;
147
+ killTree(j.child, 'SIGTERM');
148
+ }
149
+ }
150
+ view(job, since) {
151
+ const out = { id: job.id, kind: job.kind, label: job.label, cwd: job.cwd, tag: job.tag, command: job.command, status: job.status,
152
+ pid: job.pid, startedAt: job.startedAt, endedAt: job.endedAt, exitCode: job.exitCode, urls: job.kind === 'dev' ? urlsIn(job.lines) : [] };
153
+ if (since !== undefined) {
154
+ const total = job.dropped + job.lines.length;
155
+ const from = Math.max(0, since - job.dropped);
156
+ out.lines = job.lines.slice(from);
157
+ out.cursor = total;
158
+ }
159
+ return out;
160
+ }
161
+ }
162
+ exports.Jobs = Jobs;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.parseProfileBlock = exports.report = exports.doctor = exports.registry = exports.RegistryErrorBase = exports.uiDir = exports.repo = void 0;
7
+ // Typed views of the plain-JS modules shared with the CLI (lib/*.js, bin/report.js). They stay JavaScript —
8
+ // the CLI, the installer and the tests use them directly — so the dashboard describes only what it uses.
9
+ const fs_1 = __importDefault(require("fs"));
10
+ const path_1 = __importDefault(require("path"));
11
+ // The package root, found by walking up: this file runs from ui/server/ (ts) and ui/dist-server/server/ (built).
12
+ function findRoot(from) {
13
+ for (let d = from;; d = path_1.default.dirname(d)) {
14
+ if (fs_1.default.existsSync(path_1.default.join(d, 'bin', 'cli.js')) && fs_1.default.existsSync(path_1.default.join(d, 'lib', 'registry.js')))
15
+ return d;
16
+ if (path_1.default.dirname(d) === d)
17
+ throw new Error('cohorte ui: cannot locate the cohorte package root');
18
+ }
19
+ }
20
+ exports.repo = findRoot(__dirname);
21
+ exports.uiDir = path_1.default.join(exports.repo, 'ui');
22
+ const load = (rel) => require(path_1.default.join(exports.repo, rel)); // eslint-disable-line @typescript-eslint/no-require-imports
23
+ class RegistryErrorBase extends Error {
24
+ }
25
+ exports.RegistryErrorBase = RegistryErrorBase;
26
+ exports.registry = load('lib/registry.js');
27
+ exports.doctor = load('lib/doctor.js');
28
+ exports.report = load('bin/report.js');
29
+ exports.parseProfileBlock = load('lib/yaml.js').parseProfileBlock;
@@ -0,0 +1,202 @@
1
+ "use strict";
2
+ // cohorte ui — what the dashboard can DO to a project: provision / remove a worktree, start a dev server.
3
+ //
4
+ // Rules, each one a thing the HTTP layer must not be trusted with:
5
+ // - the command that runs is never client-supplied: it is the project's own `commands.dev` or its own
6
+ // isolation scripts, or a fixed git invocation;
7
+ // - the project's gate (.claude/hooks/cohorte-gate.py --check) is asked first, like verify-run.sh does:
8
+ // `deny` refuses, `ask` needs an explicit confirmation from the human;
9
+ // - a worktree is addressed by a path that `git worktree list` reports for that repo;
10
+ // - the main checkout is never removed, and removal never forces (a dirty tree is refused by git).
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.OpError = exports.FEATURE_ID = void 0;
16
+ exports.readProfile = readProfile;
17
+ exports.gateVerdict = gateVerdict;
18
+ exports.isolationScripts = isolationScripts;
19
+ exports.devInfo = devInfo;
20
+ exports.resolveWorktree = resolveWorktree;
21
+ exports.confirm = confirm;
22
+ exports.startDev = startDev;
23
+ exports.stopJob = stopJob;
24
+ exports.createWorktree = createWorktree;
25
+ exports.removeWorktree = removeWorktree;
26
+ exports.listCommands = listCommands;
27
+ exports.startRun = startRun;
28
+ const fs_1 = __importDefault(require("fs"));
29
+ const path_1 = __importDefault(require("path"));
30
+ const child_process_1 = require("child_process");
31
+ const legacy_1 = require("./legacy");
32
+ const { checkTrust } = legacy_1.doctor;
33
+ exports.FEATURE_ID = /^[a-z0-9][a-z0-9-]{0,62}$/;
34
+ class OpError extends Error {
35
+ code;
36
+ needsConfirmation;
37
+ command;
38
+ reason;
39
+ untrusted;
40
+ fix;
41
+ dockerDown;
42
+ constructor(message, code = 400, extra = {}) { super(message); this.code = code; Object.assign(this, extra); }
43
+ }
44
+ exports.OpError = OpError;
45
+ // git reports `C:/x/y` where Node says `C:\x\y` (and 8.3 short names, and drive-letter case) on Windows:
46
+ // compare paths through the native realpath, normalized, case-insensitively there.
47
+ const realOr = (p) => {
48
+ let r;
49
+ try {
50
+ r = fs_1.default.realpathSync.native(p);
51
+ }
52
+ catch {
53
+ r = path_1.default.resolve(p);
54
+ }
55
+ r = path_1.default.normalize(r);
56
+ return process.platform === 'win32' ? r.toLowerCase() : r;
57
+ };
58
+ const git = (cwd, ...a) => (0, child_process_1.spawnSync)('git', ['-C', cwd, ...a], { encoding: 'utf8' });
59
+ function readProfile(root) {
60
+ try {
61
+ return JSON.parse(fs_1.default.readFileSync(path_1.default.join(root, '.claude', 'profile.json'), 'utf8'));
62
+ }
63
+ catch { /* fall through */ }
64
+ try {
65
+ return (0, legacy_1.parseProfileBlock)(fs_1.default.readFileSync(path_1.default.join(root, 'PIPELINE.md'), 'utf8')) || {};
66
+ }
67
+ catch {
68
+ return {};
69
+ }
70
+ }
71
+ function gateVerdict(root, command, cwd) {
72
+ const gate = path_1.default.join(root, '.claude', 'hooks', 'cohorte-gate.py');
73
+ if (!fs_1.default.existsSync(gate))
74
+ return { verdict: 'allow', reason: '' };
75
+ const r = (0, child_process_1.spawnSync)('python3', [gate, '--check', '--cwd', cwd || root, '--', command], { encoding: 'utf8', timeout: 15000 });
76
+ if (r.error)
77
+ return { verdict: 'ask', reason: `the gate could not run (${r.error.message})` };
78
+ const reason = (r.stdout || '').trim();
79
+ return { verdict: r.status === 0 ? 'allow' : r.status === 2 ? 'deny' : 'ask', reason };
80
+ }
81
+ function isolationScripts(root) {
82
+ const has = (n) => fs_1.default.existsSync(path_1.default.join(root, 'scripts', n));
83
+ return { create: has('new-feature.sh'), remove: has('remove-feature.sh') };
84
+ }
85
+ function devInfo(root) {
86
+ const c = (readProfile(root).commands || {});
87
+ return { command: typeof c.dev === 'string' && c.dev.trim() ? c.dev.trim() : null,
88
+ ready: typeof c.dev_ready === 'string' && c.dev_ready.trim() ? c.dev_ready.trim() : null };
89
+ }
90
+ function resolveWorktree(root, wtPath) {
91
+ if (typeof wtPath !== 'string')
92
+ throw new OpError('a worktree path is required');
93
+ const want = realOr(wtPath);
94
+ const wt = legacy_1.registry.worktrees(root).find((w) => realOr(w.path) === want);
95
+ if (!wt)
96
+ throw new OpError('not a worktree of this project', 404);
97
+ return wt;
98
+ }
99
+ function confirm(verdict, confirmed, command) {
100
+ if (verdict.verdict === 'deny')
101
+ throw new OpError(`the project's gate refuses this command: ${verdict.reason}`, 403);
102
+ if (verdict.verdict === 'ask' && !confirmed) {
103
+ throw new OpError('the project gate asks for confirmation', 409, { needsConfirmation: true, command, reason: verdict.reason });
104
+ }
105
+ }
106
+ function startDev(jobs, project, wtPath, { confirmed = false } = {}) {
107
+ const wt = resolveWorktree(project.root, wtPath);
108
+ const dev = devInfo(project.root);
109
+ if (!dev.command)
110
+ throw new OpError('this project declares no commands.dev in its profile', 400);
111
+ if (jobs.find(project.id, 'dev', wt.path))
112
+ throw new OpError('a dev server is already running in this worktree', 409);
113
+ confirm(gateVerdict(project.root, dev.command, wt.path), confirmed, dev.command);
114
+ return jobs.start({ projectId: project.id, kind: 'dev', tag: wt.path, label: `dev · ${path_1.default.basename(wt.path)}`, cwd: wt.path,
115
+ command: dev.command, ready: dev.ready });
116
+ }
117
+ function stopJob(jobs, project, jobId) {
118
+ const job = jobs.get(jobId);
119
+ if (!job || job.projectId !== project.id)
120
+ throw new OpError('unknown job', 404);
121
+ return jobs.stop(job);
122
+ }
123
+ function createWorktree(jobs, project, feature, { confirmed = false } = {}) {
124
+ if (typeof feature !== 'string' || !exports.FEATURE_ID.test(feature))
125
+ throw new OpError('the feature id must be kebab-case (a-z, 0-9, -; at most 63 chars)');
126
+ const root = project.root;
127
+ const scripts = isolationScripts(root);
128
+ const label = `worktree · ${feature}`;
129
+ if (scripts.create) {
130
+ const command = `scripts/new-feature.sh ${feature}`;
131
+ confirm(gateVerdict(root, command, root), confirmed, command);
132
+ return jobs.start({ projectId: project.id, kind: 'worktree-create', tag: feature, label, cwd: root, file: 'bash', args: ['scripts/new-feature.sh', feature] });
133
+ }
134
+ // No isolation script: a plain sibling worktree on a new branch, off the remote default branch when there is one.
135
+ const profile = readProfile(root);
136
+ const vcs = profile.vcs || {};
137
+ const prefix = typeof vcs.feature_branch_prefix === 'string' ? vcs.feature_branch_prefix : 'feature/';
138
+ const def = typeof vcs.default_branch === 'string' && vcs.default_branch ? vcs.default_branch : 'main';
139
+ const base = git(root, 'rev-parse', '--verify', '-q', `origin/${def}`).status === 0 ? `origin/${def}` : 'HEAD';
140
+ const dir = path_1.default.join(path_1.default.dirname(root), `${path_1.default.basename(root)}-${feature}`);
141
+ if (fs_1.default.existsSync(dir))
142
+ throw new OpError(`${dir} already exists`, 409);
143
+ return jobs.start({ projectId: project.id, kind: 'worktree-create', tag: feature, label, cwd: root,
144
+ file: 'git', args: ['worktree', 'add', '-b', `${prefix}${feature}`, dir, base] });
145
+ }
146
+ function removeWorktree(jobs, project, wtPath, { confirmed = false } = {}) {
147
+ const root = project.root;
148
+ const all = legacy_1.registry.worktrees(root);
149
+ const wt = resolveWorktree(root, wtPath);
150
+ if (all[0] && realOr(all[0].path) === realOr(wt.path))
151
+ throw new OpError('the main checkout cannot be removed', 400);
152
+ if (jobs.find(project.id, 'dev', wt.path))
153
+ throw new OpError('stop the dev server in this worktree first', 409);
154
+ const label = `remove · ${path_1.default.basename(wt.path)}`;
155
+ const scripts = isolationScripts(root);
156
+ const prefix = readProfile(root).vcs?.feature_branch_prefix || 'feature/';
157
+ const id = wt.branch && wt.branch.startsWith(prefix) ? wt.branch.slice(prefix.length) : null;
158
+ if (scripts.remove && id && exports.FEATURE_ID.test(id)) {
159
+ const command = `scripts/remove-feature.sh ${id}`;
160
+ confirm(gateVerdict(root, command, root), confirmed, command);
161
+ return jobs.start({ projectId: project.id, kind: 'worktree-remove', tag: wt.path, label, cwd: root, file: 'bash', args: ['scripts/remove-feature.sh', id] });
162
+ }
163
+ // Never --force: git itself refuses a worktree with changes in it. The branch is left alone.
164
+ return jobs.start({ projectId: project.id, kind: 'worktree-remove', tag: wt.path, label, cwd: root, file: 'git', args: ['worktree', 'remove', wt.path] });
165
+ }
166
+ function listCommands(globalDir) {
167
+ const dir = path_1.default.join(globalDir, 'commands');
168
+ let files = [];
169
+ try {
170
+ files = fs_1.default.readdirSync(dir).filter((f) => /^cohorte-[a-z0-9-]+\.md$/.test(f)).sort();
171
+ }
172
+ catch {
173
+ return [];
174
+ }
175
+ return files.map((f) => {
176
+ const txt = fs_1.default.readFileSync(path_1.default.join(dir, f), 'utf8');
177
+ const fm = txt.match(/^---\r?\n([\s\S]*?)\r?\n---/);
178
+ const d = fm && fm[1].match(/^description:\s*(.*)$/m);
179
+ const h = fm && fm[1].match(/^argument-hint:\s*(.*)$/m);
180
+ return { name: f.slice(0, -3), description: d ? d[1].replace(/^["']|["']$/g, '').trim() : '', argumentHint: h ? h[1].replace(/^["']|["']$/g, '').trim() : '' };
181
+ });
182
+ }
183
+ function startRun(runs, project, globalDir, body) {
184
+ const wt = resolveWorktree(project.root, body.worktree);
185
+ const name = typeof body.command === 'string' ? body.command.replace(/^\//, '') : '';
186
+ if (!listCommands(globalDir).some((c) => c.name === name))
187
+ throw new OpError('unknown cohorte command — run `cohorte install`', 400);
188
+ const args = typeof body.args === 'string' ? body.args.trim() : '';
189
+ if (args.length > 500 || /[\r\n]/.test(args))
190
+ throw new OpError('arguments must be one line of at most 500 characters');
191
+ if (runs.find(project.id, wt.path))
192
+ throw new OpError('a run is already in progress in this worktree', 409);
193
+ // Under `claude -p`, an untrusted folder's permissions.allow are ignored: every pipeline script would prompt.
194
+ const trust = checkTrust(wt.path, globalDir);
195
+ if (trust.status === 'warn' && body.acknowledgeUntrusted !== true) {
196
+ throw new OpError(trust.detail, 409, { untrusted: true, fix: trust.fix });
197
+ }
198
+ if (fs_1.default.existsSync(path_1.default.join(project.root, '.claude', 'hooks', 'cohorte-gate.py')) && (0, child_process_1.spawnSync)('python3', ['--version'], { stdio: 'ignore' }).status !== 0) {
199
+ throw new OpError('python3 is not on PATH: the project gate is fail-closed, so every tool call would be refused', 400);
200
+ }
201
+ return runs.start({ projectId: project.id, cwd: wt.path, command: `/${name}${args ? ` ${args}` : ''}`, permissionMode: body.permissionMode });
202
+ }