cohorte 3.2.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,20 @@ 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.3.0 — 2026-11-18
11
+
12
+ - **`cohorte ui` is now a full dashboard.** The Specs tab shows every spec as a pipeline
13
+ (Spec → Build → Review → Verify → Ship) with the **next command** to run, derived from the spec's
14
+ status and the reports the pipeline writes; opening one lists the review's findings by severity
15
+ with `file:line` and fix. Worktrees show git state (ahead/behind, dirty files, last commit), the
16
+ PR and its checks (with `gh`), the diff against the default branch, and an **Open** link for
17
+ each dev server. Updates are pushed live, a Home screen lists what is running across projects,
18
+ and the page can notify you when a run needs approval or finishes. Run history is kept across
19
+ restarts. Command palette (Ctrl/Cmd-K) and keyboard shortcuts.
20
+ - **Rebuilt in TypeScript.** The page is React + TypeScript (Vite), the server TypeScript compiled
21
+ to plain Node; both ship built, the package still has no runtime dependency. Looks like Francois
22
+ (same design tokens, dark by default, light theme).
23
+
10
24
  ## 3.2.0 — 2026-11-18
11
25
 
12
26
  - **`cohorte ui` — a local dashboard over all your Cohorte projects.** Run it in a terminal; it opens
package/bin/cli.js CHANGED
@@ -115,12 +115,17 @@ const project = target || process.cwd();
115
115
 
116
116
  // --- dashboard ---------------------------------------------------------------
117
117
  if (mode === 'ui') {
118
- const { create } = require('../ui/server.js');
118
+ const built = path.join(__dirname, '..', 'ui', 'dist-server', 'server', 'server.js');
119
+ if (!fs.existsSync(built) || !fs.existsSync(path.join(__dirname, '..', 'ui', 'dist-web', 'index.html'))) {
120
+ console.error('error: the dashboard is not built in this checkout.\n Run `npm run build:ui` here first (the published package ships it built).');
121
+ process.exit(1);
122
+ }
123
+ const { create } = require(built);
119
124
  const ui = create({ globalDir, version: VERSION });
120
- const bye = () => { ui.jobs.stopAll(); ui.runs.stopAll(); process.exit(0); };
125
+ const bye = () => { ui.jobs.stopAll(); ui.runs.stopAll(); ui.runs.flush(); process.exit(0); };
121
126
  process.on('SIGINT', bye);
122
127
  process.on('SIGTERM', bye);
123
- process.on('exit', () => { ui.jobs.stopAll(); ui.runs.stopAll(); });
128
+ process.on('exit', () => { ui.jobs.stopAll(); ui.runs.stopAll(); ui.runs.flush(); });
124
129
  ui.listen(uiPort).then((l) => {
125
130
  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
131
  if (uiOpen && process.stdout.isTTY) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cohorte",
3
- "version": "3.2.0",
3
+ "version": "3.3.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,7 +11,8 @@
11
11
  "core",
12
12
  "profile",
13
13
  "scripts",
14
- "ui",
14
+ "ui/dist-server",
15
+ "ui/dist-web",
15
16
  "!scripts/new-feature.sh",
16
17
  "!scripts/remove-feature.sh",
17
18
  "!scripts/demo",
@@ -27,6 +28,9 @@
27
28
  "CHANGELOG.md"
28
29
  ],
29
30
  "scripts": {
31
+ "build:ui": "node scripts/build-ui.mjs",
32
+ "prepack": "npm run build:ui",
33
+ "pretest": "npm run build:ui",
30
34
  "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"
31
35
  },
32
36
  "engines": {
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env node
2
+ // Builds the dashboard (ui/): installs its build tooling, then compiles the server (tsc) and the page (vite)
3
+ // into ui/dist-server and ui/dist-web — the only parts of ui/ that ship. Run by `npm run build:ui`, by
4
+ // `prepack`, and by CI before the dashboard's tests.
5
+ //
6
+ // node scripts/build-ui.mjs [--no-install]
7
+
8
+ import { spawnSync } from "node:child_process";
9
+ import { fileURLToPath } from "node:url";
10
+ import { existsSync } from "node:fs";
11
+ import { join } from "node:path";
12
+
13
+ const ui = fileURLToPath(new URL("../ui", import.meta.url));
14
+ const win = process.platform === "win32";
15
+ const install = !process.argv.includes("--no-install") || !existsSync(join(ui, "node_modules"));
16
+
17
+ // A user-level `allow-scripts` setting reaches child npm processes as npm_config_allow_scripts, which npm
18
+ // (11.x) rejects for project-scoped installs — and it is no business of this build.
19
+ const env = { ...process.env };
20
+ for (const k of Object.keys(env)) if (/^npm_config_allow[-_]scripts$/i.test(k)) delete env[k];
21
+
22
+ const step = (args) => {
23
+ const r = spawnSync(win ? "npm.cmd" : "npm", args, { cwd: ui, stdio: "inherit", env, shell: win });
24
+ if (r.status !== 0) { console.error(`\nbuild-ui: \`npm ${args.join(" ")}\` failed (${r.status ?? r.error?.message})`); process.exit(r.status || 1); }
25
+ };
26
+
27
+ if (install) step(["ci", "--no-audit", "--no-fund"]);
28
+ step(["run", "build"]);
@@ -0,0 +1,209 @@
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
+ 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.ACTIONS = void 0;
16
+ exports.composeFile = composeFile;
17
+ exports.parsePs = parsePs;
18
+ exports.status = status;
19
+ exports.act = act;
20
+ exports.preflight = preflight;
21
+ const fs_1 = __importDefault(require("fs"));
22
+ const path_1 = __importDefault(require("path"));
23
+ const child_process_1 = require("child_process");
24
+ const ops_1 = require("./ops");
25
+ const CANDIDATES = ['compose.yaml', 'compose.yml', 'docker-compose.yaml', 'docker-compose.yml'];
26
+ exports.ACTIONS = ['up', 'stop', 'restart', 'down', 'logs'];
27
+ const bin = () => process.env.COHORTE_DOCKER_BIN || 'docker';
28
+ const realOr = (p) => { try {
29
+ return fs_1.default.realpathSync(p);
30
+ }
31
+ catch {
32
+ return path_1.default.resolve(p);
33
+ } };
34
+ // { file, rel } or null. The declared file wins; it must stay inside the repo.
35
+ function composeFile(root) {
36
+ const declared = (0, ops_1.readProfile)(root).isolation?.compose_file;
37
+ const names = typeof declared === 'string' && declared.trim() ? [declared.trim(), ...CANDIDATES] : CANDIDATES;
38
+ const base = realOr(root);
39
+ for (const n of names) {
40
+ if (path_1.default.isAbsolute(n))
41
+ continue;
42
+ const file = realOr(path_1.default.join(root, n));
43
+ if (!file.startsWith(base + path_1.default.sep))
44
+ continue;
45
+ try {
46
+ if (fs_1.default.statSync(file).isFile())
47
+ return { file, rel: path_1.default.relative(base, file) };
48
+ }
49
+ catch { /* next */ }
50
+ }
51
+ return null;
52
+ }
53
+ function exec(args, { cwd, timeout = 8000 } = {}) {
54
+ return new Promise((resolve) => {
55
+ let out = '';
56
+ let err = '';
57
+ let done = false;
58
+ const finish = (r) => { if (!done) {
59
+ done = true;
60
+ clearTimeout(timer);
61
+ resolve({ code: null, out, err, ...r });
62
+ } };
63
+ let child;
64
+ try {
65
+ child = (0, child_process_1.spawn)(bin(), args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
66
+ }
67
+ catch (e) {
68
+ const x = e;
69
+ return resolve({ code: -1, out, err: x.message, missing: x.code === 'ENOENT' });
70
+ }
71
+ const timer = setTimeout(() => { try {
72
+ child.kill('SIGKILL');
73
+ }
74
+ catch { /* gone */ } finish({ code: -1, timedOut: true }); }, timeout);
75
+ child.stdout?.on('data', (d) => { out += d; if (out.length > 2e6)
76
+ out = out.slice(-2e6); });
77
+ child.stderr?.on('data', (d) => { err += d; if (err.length > 2e5)
78
+ err = err.slice(-2e5); });
79
+ child.on('error', (e) => finish({ code: -1, missing: e.code === 'ENOENT', err: e.message }));
80
+ child.on('close', (code) => finish({ code }));
81
+ });
82
+ }
83
+ const firstLine = (s) => String(s || '').trim().split(/\r?\n/).find((l) => l.trim()) || '';
84
+ // `docker compose ps --format json` prints one object per line on recent versions, a JSON array on older ones.
85
+ function parsePs(out) {
86
+ const text = String(out || '').trim();
87
+ if (!text)
88
+ return [];
89
+ let rows = [];
90
+ try {
91
+ const v = JSON.parse(text);
92
+ rows = Array.isArray(v) ? v : [v];
93
+ }
94
+ catch {
95
+ for (const l of text.split(/\r?\n/)) {
96
+ try {
97
+ rows.push(JSON.parse(l));
98
+ }
99
+ catch { /* not a row */ }
100
+ }
101
+ }
102
+ return rows.filter((r) => r && typeof r === 'object');
103
+ }
104
+ function portsOf(row) {
105
+ const pubs = Array.isArray(row.Publishers) ? row.Publishers : [];
106
+ const seen = new Set();
107
+ for (const p of pubs)
108
+ if (p && p.PublishedPort)
109
+ seen.add(`${p.PublishedPort}→${p.TargetPort}`);
110
+ return [...seen];
111
+ }
112
+ async function daemon() {
113
+ const r = await exec(['info', '--format', '{{.ServerVersion}}'], { timeout: 6000 });
114
+ if (r.missing)
115
+ return { installed: false, up: false, error: 'the docker CLI is not installed (or not on PATH)' };
116
+ if (r.timedOut)
117
+ return { installed: true, up: false, error: 'the Docker daemon did not answer in time' };
118
+ if (r.code !== 0)
119
+ return { installed: true, up: false, error: firstLine(r.err) || 'the Docker daemon is not running' };
120
+ return { installed: true, up: true, version: firstLine(r.out) };
121
+ }
122
+ // Everything the Docker tab shows. Each part degrades alone: no daemon still lists the declared services.
123
+ async function status(root) {
124
+ const cf = composeFile(root);
125
+ if (!cf)
126
+ return { configured: false };
127
+ const [d, cfg] = await Promise.all([daemon(), exec(['compose', '-f', cf.file, 'config', '--services'], { cwd: root })]);
128
+ const defined = cfg.code === 0 ? cfg.out.split(/\r?\n/).map((s) => s.trim()).filter(Boolean) : [];
129
+ 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' };
130
+ let rows = [];
131
+ if (d.up && defined.length) {
132
+ const ps = await exec(['compose', '-f', cf.file, 'ps', '-a', '--format', 'json'], { cwd: root });
133
+ if (ps.code === 0)
134
+ rows = parsePs(ps.out);
135
+ else
136
+ out.psError = firstLine(ps.err);
137
+ }
138
+ const by = new Map();
139
+ for (const r of rows)
140
+ by.set(r.Service || r.Name, r);
141
+ const names = defined.length ? defined : [...by.keys()];
142
+ out.services = names.map((name) => {
143
+ const r = by.get(name);
144
+ if (!r)
145
+ return { name, state: d.up ? 'not created' : 'unknown', health: '', status: '', ports: [], image: '' };
146
+ return { name, state: String(r.State || '').toLowerCase() || 'unknown', health: String(r.Health || '').toLowerCase(), status: String(r.Status || ''), ports: portsOf(r), image: String(r.Image || '') };
147
+ });
148
+ out.running = out.services.filter((s) => s.state === 'running').length;
149
+ return out;
150
+ }
151
+ // Starts up/stop/restart/down/logs as a job. Returns the job.
152
+ async function act(jobs, project, { action, service, confirmed = false }) {
153
+ if (typeof action !== 'string' || !exports.ACTIONS.includes(action))
154
+ throw new ops_1.OpError(`action must be one of ${exports.ACTIONS.join(', ')}`);
155
+ const cf = composeFile(project.root);
156
+ if (!cf)
157
+ throw new ops_1.OpError('this project declares no compose file (isolation.compose_file)', 400);
158
+ const d = await daemon();
159
+ if (!d.up)
160
+ throw new ops_1.OpError(d.error || 'the Docker daemon is not running', 409, { dockerDown: true });
161
+ let svc = null;
162
+ if (service !== undefined && service !== null && service !== '') {
163
+ if (action === 'down')
164
+ throw new ops_1.OpError('down applies to the whole stack');
165
+ const cfg = await exec(['compose', '-f', cf.file, 'config', '--services'], { cwd: project.root });
166
+ const defined = cfg.out.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
167
+ if (typeof service !== 'string' || !defined.includes(service))
168
+ throw new ops_1.OpError('not a service of this compose file', 404);
169
+ svc = service;
170
+ }
171
+ const verb = { up: ['up', '-d'], stop: ['stop'], restart: ['restart'], down: ['down'], logs: ['logs', '--no-color', '--tail', '200', '-f'] }[action];
172
+ const args = ['compose', '-f', cf.file, ...verb, ...(svc ? [svc] : [])];
173
+ const shown = `docker compose -f ${cf.rel} ${verb.join(' ')}${svc ? ` ${svc}` : ''}`;
174
+ const kind = action === 'logs' ? 'docker-logs' : 'docker';
175
+ const tag = action === 'logs' ? (svc || '*') : 'stack';
176
+ if (jobs.find(project.id, kind, tag))
177
+ throw new ops_1.OpError(action === 'logs' ? 'these logs are already being followed' : 'a docker command is already running for this project', 409);
178
+ (0, ops_1.confirm)((0, ops_1.gateVerdict)(project.root, shown, project.root), confirmed, shown);
179
+ return jobs.start({ projectId: project.id, kind, tag, label: `docker · ${verb[0]}${svc ? ` ${svc}` : ''}`, cwd: project.root, file: bin(), args, display: shown });
180
+ }
181
+ // Before `scripts/new-feature.sh`: the script creates the worktree's database INSIDE a compose service
182
+ // (`docker compose exec -T postgres …`), so it fails — late and obscurely — when Docker or that service is down.
183
+ // Returns null when the script needs nothing, else { ok, reason, services, missing }.
184
+ async function preflight(root) {
185
+ const cf = composeFile(root);
186
+ let script = '';
187
+ try {
188
+ script = fs_1.default.readFileSync(path_1.default.join(root, 'scripts', 'new-feature.sh'), 'utf8');
189
+ }
190
+ catch {
191
+ return null;
192
+ }
193
+ if (!cf || !/\bdocker\b/.test(script))
194
+ return null;
195
+ const needs = new Set();
196
+ const re = /docker\s+compose[^\n]*?\bexec\b\s+(?:-[A-Za-z-]+\s+)*([A-Za-z][\w.-]*)/g;
197
+ for (let m = re.exec(script); m; m = re.exec(script))
198
+ needs.add(m[1]);
199
+ const s = await status(root);
200
+ const dm = s.daemon;
201
+ if (!dm.installed)
202
+ return { ok: false, reason: dm.error || '', services: [...needs], missing: [...needs], daemonUp: false };
203
+ if (!dm.up)
204
+ return { ok: false, reason: `${dm.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 };
205
+ const down = [...needs].filter((n) => { const x = (s.services || []).find((v) => v.name === n); return !x || x.state !== 'running'; });
206
+ if (down.length)
207
+ 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 };
208
+ return { ok: true, reason: '', services: [...needs], missing: [], daemonUp: true };
209
+ }
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ // Reads a REVIEW REPORT (specs/reports/<id>.md, the shape in core/agents/cohorte-review.md) into rows.
3
+ // One line per finding: - **[SEVERITY]** `file:line` · category · problem → **Fix:** change [· out of scope: why]
4
+ // Anything that does not match stays out: the page also offers the raw report, so a drifting prompt costs rows, not truth.
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.parseFinding = parseFinding;
7
+ exports.parseReviewReport = parseReviewReport;
8
+ const SEVERITIES = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW'];
9
+ const LINE = /^\s*[-*]\s+\*\*\[(CRITICAL|HIGH|MEDIUM|LOW)\]\*\*\s*(.*)$/i;
10
+ function parseFinding(line) {
11
+ const m = LINE.exec(line);
12
+ if (!m)
13
+ return null;
14
+ let rest = m[2].trim();
15
+ const severity = m[1].toUpperCase();
16
+ let file = '';
17
+ let ln = null;
18
+ const loc = /^`([^`]+)`\s*(?:·|—|-)?\s*(.*)$/.exec(rest);
19
+ if (loc) {
20
+ rest = loc[2];
21
+ const pos = /^(.*?):(\d+)(?:[-–]\d+)?$/.exec(loc[1]);
22
+ file = pos ? pos[1] : loc[1];
23
+ ln = pos ? Number(pos[2]) : null;
24
+ }
25
+ const parts = rest.split(/\s+·\s+/);
26
+ let category = '';
27
+ if (parts.length > 1 && /^(spec-violation|quality|security|complexity)$/i.test(parts[0].trim()))
28
+ category = parts.shift().trim().toLowerCase();
29
+ let body = parts.join(' · ');
30
+ let scope = '';
31
+ const oos = /\s*·\s*out of scope:\s*(.*)$/i.exec(body);
32
+ if (oos) {
33
+ scope = oos[1].trim();
34
+ body = body.slice(0, oos.index);
35
+ }
36
+ const fix = /^(.*?)\s*(?:→|->)\s*\*\*Fix:\*\*\s*(.*)$/s.exec(body);
37
+ return { severity, file, line: ln, category, problem: (fix ? fix[1] : body).trim(), fix: fix ? fix[2].trim() : '', outOfScope: scope };
38
+ }
39
+ function parseReviewReport(md) {
40
+ const out = { findings: [], deferred: [], verdict: null };
41
+ let section = null;
42
+ for (const raw of md.split(/\r?\n/)) {
43
+ const h = /^##\s+(.*)$/.exec(raw);
44
+ if (h) {
45
+ const t = h[1].trim().toLowerCase();
46
+ section = t.startsWith('findings') ? 'findings' : t.startsWith('deferred') ? 'deferred' : null;
47
+ continue;
48
+ }
49
+ const v = /^Verdict:\s*(SHIP|REVISE|BLOCK)\b/i.exec(raw);
50
+ if (v) {
51
+ out.verdict = v[1].toUpperCase();
52
+ continue;
53
+ }
54
+ if (!section)
55
+ continue;
56
+ const f = parseFinding(raw);
57
+ if (f)
58
+ out[section].push(f);
59
+ }
60
+ const rank = (s) => SEVERITIES.indexOf(s);
61
+ out.findings.sort((a, b) => rank(a.severity) - rank(b.severity));
62
+ out.deferred.sort((a, b) => rank(a.severity) - rank(b.severity));
63
+ return out;
64
+ }
@@ -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;