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,89 @@
1
+ "use strict";
2
+ // Where a spec stands in the pipeline, derived ONLY from what the pipeline itself writes: the spec's `status`
3
+ // (profile/schema/spec-status.md) and the machine reports under specs/reports/ — readiness.json and build.json
4
+ // (/cohorte-build), verdict.json (/cohorte-review), verify.json (/cohorte-verify), loop.json (the loop workflow).
5
+ // Nothing here guesses; an unreadable report counts as absent.
6
+ var __importDefault = (this && this.__importDefault) || function (mod) {
7
+ return (mod && mod.__esModule) ? mod : { "default": mod };
8
+ };
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.reportsOf = reportsOf;
11
+ exports.pipelineOf = pipelineOf;
12
+ const fs_1 = __importDefault(require("fs"));
13
+ const path_1 = __importDefault(require("path"));
14
+ const STAGES = [
15
+ { key: 'spec', label: 'Spec' }, { key: 'build', label: 'Build' }, { key: 'review', label: 'Review' },
16
+ { key: 'verify', label: 'Verify' }, { key: 'ship', label: 'Ship' },
17
+ ];
18
+ function readJson(file) {
19
+ try {
20
+ const v = JSON.parse(fs_1.default.readFileSync(file, 'utf8'));
21
+ return v && typeof v === 'object' ? v : null;
22
+ }
23
+ catch {
24
+ return null;
25
+ }
26
+ }
27
+ function reportsOf(root, id) {
28
+ const r = (k) => readJson(path_1.default.join(root, 'specs', 'reports', `${id}.${k}.json`));
29
+ return { readiness: r('readiness'), build: r('build'), verdict: r('verdict'), verify: r('verify'), loop: r('loop') };
30
+ }
31
+ function pipelineOf(root, spec) {
32
+ const status = String(spec.status || 'draft');
33
+ const rep = reportsOf(root, spec.id);
34
+ const closed = status === 'shipped' || status === 'merged';
35
+ const abandoned = status === 'abandoned';
36
+ const built = !!rep.build;
37
+ const buildFailed = built && (Object.values(rep.build?.surfaces || {}).some((v) => v !== 'ok') || (rep.build?.dead || []).length > 0);
38
+ const notReady = rep.readiness && rep.readiness.verdict && rep.readiness.verdict !== 'READY';
39
+ const verdict = rep.verdict?.verdict;
40
+ const reviewed = !!rep.verdict && !rep.verdict.aborted;
41
+ const shipOk = verdict === 'SHIP' && !(rep.verdict?.unreviewed || []).length;
42
+ const verifyVerdict = rep.verify?.verdict;
43
+ const state = {};
44
+ state.spec = status === 'draft' ? 'current' : 'done';
45
+ state.build = closed || built ? (buildFailed ? 'blocked' : 'done') : notReady ? 'blocked' : state.spec === 'done' ? 'current' : 'todo';
46
+ state.review = closed ? 'done' : reviewed ? (shipOk ? 'done' : 'blocked') : state.build === 'done' ? 'current' : 'todo';
47
+ state.verify = closed ? 'done' : verifyVerdict === 'PASS' ? 'done' : verifyVerdict === 'FAIL' ? 'blocked' : verifyVerdict === 'SKIPPED' ? 'skipped' : shipOk ? 'current' : 'todo';
48
+ state.ship = closed ? 'done' : shipOk && (verifyVerdict === 'PASS' || verifyVerdict === 'SKIPPED') ? 'current' : 'todo';
49
+ if (abandoned)
50
+ for (const k of Object.keys(state))
51
+ if (state[k] !== 'done')
52
+ state[k] = 'todo';
53
+ // The next command a human would type — the same routing the commands themselves document.
54
+ let next = null;
55
+ const id = spec.id;
56
+ if (abandoned || status === 'merged')
57
+ next = null;
58
+ else if (status === 'shipped')
59
+ next = { command: 'cohorte-ship', args: id, why: 'reconcile the PR with the host (merged / closed)' };
60
+ else if (status === 'draft')
61
+ next = { command: 'cohorte-spec', args: id, why: 'the interview is open — freeze the contract' };
62
+ else if (status === 'blocked')
63
+ next = { command: 'cohorte-fix', args: id, why: `a round gave up${rep.loop?.reason ? `: ${rep.loop.reason}` : ''}` };
64
+ else if (state.build === 'blocked')
65
+ next = { command: 'cohorte-build', args: id, why: notReady ? 'the spec is not ready to build' : 'a surface failed to build' };
66
+ else if (state.build === 'current')
67
+ next = { command: 'cohorte-build', args: id, why: 'the contract is frozen' };
68
+ else if (state.review === 'current')
69
+ next = { command: 'cohorte-review', args: id, why: 'built — audit it against the spec' };
70
+ else if (state.review === 'blocked')
71
+ next = { command: 'cohorte-fix', args: id, why: verdict ? `review verdict ${verdict}` : 'review has no usable verdict' };
72
+ else if (state.verify === 'blocked')
73
+ next = { command: 'cohorte-verify', args: id, why: 'the last verification failed' };
74
+ else if (state.verify === 'current')
75
+ next = { command: 'cohorte-verify', args: id, why: 'review passed — run it for real' };
76
+ else if (state.ship === 'current')
77
+ next = { command: 'cohorte-ship', args: id, why: 'review and verification are clean' };
78
+ const stages = STAGES.map((s) => ({ ...s, state: state[s.key] }));
79
+ return {
80
+ stages, next,
81
+ verdict: reviewed ? {
82
+ verdict: String(verdict || ''), blocking: num(rep.verdict?.blocking), findings: num(rep.verdict?.findings), security: num(rep.verdict?.security),
83
+ deferred: num(rep.verdict?.deferred), ts: str(rep.verdict?.ts),
84
+ } : null,
85
+ loop: rep.loop ? { outcome: str(rep.loop.outcome), reason: str(rep.loop.reason) } : null,
86
+ };
87
+ }
88
+ const num = (v) => (typeof v === 'number' ? v : null);
89
+ const str = (v) => (typeof v === 'string' ? v : null);
@@ -0,0 +1,284 @@
1
+ "use strict";
2
+ // cohorte ui — runs a pipeline command (`/cohorte-build f1`) through `claude -p`, headless, and turns the
3
+ // stream into a short feed plus the decisions only a human can make.
4
+ //
5
+ // This is NOT a chat: there is no free-form message box. A run is one command in one worktree, and the
6
+ // human's part is limited to the gates the CLI raises on its control channel — a permission ask (the
7
+ // project's gate answering `ask`, or Claude Code's own prompt) and AskUserQuestion (the interview
8
+ // commands). Protocol, verified against Claude Code 2.1.326:
9
+ //
10
+ // claude -p --output-format stream-json --input-format stream-json --permission-prompt-tool stdio --verbose
11
+ // stdin ← {"type":"user","message":{"role":"user","content":[{"type":"text","text":"/cohorte-build f1"}]}}
12
+ // stdout → system | assistant | user(tool_result) | control_request(can_use_tool) | result (NDJSON)
13
+ // stdin ← {"type":"control_response","response":{"subtype":"success","request_id":…,
14
+ // "response":{"behavior":"allow","updatedInput":…}}} or {"behavior":"deny","message":…}
15
+ //
16
+ // Our stdin is also the CLI's EOF signal. It is closed only once the turn's `result` is in, nothing is
17
+ // parked on a human, and the stream has been quiet for a moment (a background subagent's asks would
18
+ // otherwise be thrown away at the source with "Stream closed").
19
+ var __importDefault = (this && this.__importDefault) || function (mod) {
20
+ return (mod && mod.__esModule) ? mod : { "default": mod };
21
+ };
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.Runs = exports.MODES = void 0;
24
+ const crypto_1 = __importDefault(require("crypto"));
25
+ const readline_1 = __importDefault(require("readline"));
26
+ const child_process_1 = require("child_process");
27
+ const MAX_EVENTS = 3000;
28
+ const QUIET_AFTER_RESULT_MS = 2000;
29
+ exports.MODES = ['default', 'acceptEdits', 'plan']; // never bypassPermissions: the gate's asks would turn into denials
30
+ const DENY_MESSAGE = 'cohorte ui: the user denied this tool call.';
31
+ const clip = (v, n) => { const s = String(v == null ? '' : v); return s.length > n ? `${s.slice(0, n)}…` : s; };
32
+ function summarize(name, input) {
33
+ const i = (input && typeof input === 'object' ? input : {});
34
+ if (name === 'Bash')
35
+ return clip(i.command, 400);
36
+ if (name === 'Task' || name === 'Agent')
37
+ return clip(`${i.subagent_type || 'agent'} — ${i.description || ''}`, 200);
38
+ if (i.file_path)
39
+ return clip(i.file_path, 300);
40
+ if (i.path)
41
+ return clip(i.path, 300);
42
+ if (i.pattern)
43
+ return clip(i.pattern, 200);
44
+ try {
45
+ return clip(JSON.stringify(i), 300);
46
+ }
47
+ catch {
48
+ return '';
49
+ }
50
+ }
51
+ class Runs {
52
+ runs = new Map();
53
+ bin;
54
+ onChange = () => { };
55
+ store;
56
+ constructor({ bin, store } = {}) {
57
+ this.bin = bin || process.env.COHORTE_CLAUDE_BIN || 'claude';
58
+ this.store = store || null;
59
+ for (const r of this.store?.loadAll() || [])
60
+ this.runs.set(r.id, r);
61
+ }
62
+ // opts: { projectId, cwd, command (e.g. "/cohorte-build f1"), permissionMode }
63
+ start(opts) {
64
+ const mode = typeof opts.permissionMode === 'string' && exports.MODES.includes(opts.permissionMode) ? opts.permissionMode : 'default';
65
+ const run = {
66
+ id: crypto_1.default.randomBytes(4).toString('hex'), projectId: opts.projectId, cwd: opts.cwd, command: opts.command,
67
+ permissionMode: mode, status: 'running', startedAt: new Date().toISOString(), endedAt: null,
68
+ events: [], dropped: 0, pending: new Map(), result: null, sessionId: null, child: null, closeTimer: null, stopping: false,
69
+ };
70
+ this.#spawn(run, null);
71
+ this.runs.set(run.id, run);
72
+ this.#write(run, { type: 'user', message: { role: 'user', content: [{ type: 'text', text: opts.command }] } });
73
+ return run;
74
+ }
75
+ // One `claude -p` process for the run's next turn. A reply resumes the same session in a new process.
76
+ #spawn(run, resumeId) {
77
+ const args = ['-p', '--output-format', 'stream-json', '--input-format', 'stream-json', '--permission-prompt-tool', 'stdio', '--verbose'];
78
+ if (run.permissionMode !== 'default')
79
+ args.push('--permission-mode', run.permissionMode);
80
+ if (resumeId)
81
+ args.push('--resume', resumeId);
82
+ const child = (0, child_process_1.spawn)(this.bin, args, { cwd: run.cwd, detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe'], env: process.env });
83
+ run.child = child;
84
+ child.stdin?.on('error', () => { });
85
+ child.on('error', (e) => { this.#push(run, { kind: 'system', text: `could not start ${this.bin}: ${e.message}` }); if (run.child === child)
86
+ this.#end(run, 'failed'); });
87
+ readline_1.default.createInterface({ input: child.stdout }).on('line', (line) => { if (run.child === child)
88
+ this.#line(run, line); });
89
+ child.stderr?.on('data', (d) => this.#push(run, { kind: 'stderr', text: clip(String(d).trim(), 1000) }));
90
+ child.on('close', (code) => {
91
+ if (run.child !== child)
92
+ return;
93
+ if (run.closeTimer)
94
+ clearTimeout(run.closeTimer);
95
+ if (run.status === 'running')
96
+ this.#end(run, run.stopping ? 'stopped' : run.result && !run.result.ok ? 'failed' : code === 0 ? 'done' : 'failed');
97
+ run.exitCode = code;
98
+ });
99
+ }
100
+ // Answers the command's free-text question (or steers it) in the SAME session. Only a Cohorte run
101
+ // that has ended its turn: there is no free-standing conversation here.
102
+ reply(run, text) {
103
+ if (!/^\/cohorte-/.test(run.command))
104
+ return 'not a cohorte run';
105
+ if (run.status === 'running')
106
+ return 'the command is still running — answer its gates first, or wait for it to finish';
107
+ if (!run.sessionId)
108
+ return 'this run has no session to continue';
109
+ if (typeof text !== 'string' || !text.trim() || text.length > 4000)
110
+ return 'a reply of 1 to 4000 characters is required';
111
+ run.status = 'running';
112
+ run.endedAt = null;
113
+ run.result = null;
114
+ run.stopping = false;
115
+ this.#push(run, { kind: 'reply', text: text.trim() });
116
+ this.#spawn(run, run.sessionId);
117
+ this.#write(run, { type: 'user', message: { role: 'user', content: [{ type: 'text', text: text.trim() }] } });
118
+ return null;
119
+ }
120
+ #write(run, obj) { try {
121
+ if (run.child?.stdin?.writable)
122
+ run.child.stdin.write(`${JSON.stringify(obj)}\n`);
123
+ }
124
+ catch { /* closed */ } }
125
+ #push(run, ev) {
126
+ run.events.push({ t: Date.now(), ...ev });
127
+ this.onChange(run);
128
+ this.store?.schedule(run);
129
+ if (run.events.length > MAX_EVENTS) {
130
+ const cut = run.events.length - MAX_EVENTS;
131
+ run.events.splice(0, cut);
132
+ run.dropped += cut;
133
+ }
134
+ }
135
+ #end(run, status) { run.status = status; run.endedAt = new Date().toISOString(); run.pending.clear(); this.onChange(run); this.store?.schedule(run, true); }
136
+ #line(run, line) {
137
+ if (!line.trim())
138
+ return;
139
+ let v;
140
+ try {
141
+ v = JSON.parse(line);
142
+ }
143
+ catch {
144
+ this.#push(run, { kind: 'stderr', text: clip(line, 500) });
145
+ return;
146
+ }
147
+ if (run.closeTimer)
148
+ clearTimeout(run.closeTimer);
149
+ if (v.session_id && !run.sessionId)
150
+ run.sessionId = v.session_id;
151
+ if (v.type === 'assistant' && v.message && Array.isArray(v.message.content)) {
152
+ for (const b of v.message.content) {
153
+ if (b.type === 'text' && b.text && b.text.trim())
154
+ this.#push(run, { kind: 'text', text: clip(b.text, 8000) });
155
+ else if (b.type === 'tool_use')
156
+ this.#push(run, { kind: 'tool', id: b.id, name: b.name, summary: summarize(b.name, b.input) });
157
+ }
158
+ }
159
+ else if (v.type === 'user' && v.message && Array.isArray(v.message.content)) {
160
+ for (const b of v.message.content) {
161
+ if (b.type !== 'tool_result')
162
+ continue;
163
+ const text = Array.isArray(b.content) ? b.content.map((c) => c.text || '').join('\n') : b.content;
164
+ this.#push(run, { kind: 'tool_result', id: b.tool_use_id, error: b.is_error === true, text: clip(text, 1500) });
165
+ }
166
+ }
167
+ else if (v.type === 'control_request') {
168
+ this.#control(run, v);
169
+ }
170
+ else if (v.type === 'result') {
171
+ run.result = { ok: !v.is_error && v.subtype !== 'error_during_execution', text: clip(v.result, 4000), costUsd: v.total_cost_usd ?? null,
172
+ durationMs: v.duration_ms ?? null, turns: v.num_turns ?? null };
173
+ this.#push(run, { kind: 'result', ...run.result });
174
+ this.store?.schedule(run, true);
175
+ }
176
+ this.#maybeClose(run);
177
+ }
178
+ #control(run, v) {
179
+ const req = v.request || {};
180
+ if (req.subtype !== 'can_use_tool') {
181
+ this.#write(run, { type: 'control_response', response: { subtype: 'error', request_id: v.request_id, error: 'unsupported control request' } });
182
+ return;
183
+ }
184
+ const input = req.input && typeof req.input === 'object' ? req.input : {};
185
+ const base = { requestId: v.request_id, tool: req.tool_name };
186
+ if (req.tool_name === 'AskUserQuestion' && Array.isArray(input.questions) && input.questions.length) {
187
+ const questions = input.questions.map((q) => ({ question: String(q.question || ''), header: String(q.header || ''), multiSelect: q.multiSelect === true,
188
+ options: (Array.isArray(q.options) ? q.options : []).map((o) => ({ label: String(o.label || ''), description: String(o.description || '') })) }));
189
+ run.pending.set(v.request_id, { ...base, kind: 'question', input, questions });
190
+ this.#push(run, { kind: 'question', ...base, questions });
191
+ return;
192
+ }
193
+ if (req.tool_name === 'AskUserQuestion') {
194
+ this.#write(run, { type: 'control_response', response: { subtype: 'success', request_id: v.request_id, response: { behavior: 'deny', message: 'malformed AskUserQuestion input' } } });
195
+ return;
196
+ }
197
+ const reason = typeof req.decision_reason === 'string' ? req.decision_reason.trim() : '';
198
+ const via = typeof req.decision_reason_type === 'string' ? req.decision_reason_type : '';
199
+ const ask = { ...base, kind: 'permission', input, summary: summarize(req.tool_name, input), reason, via };
200
+ run.pending.set(v.request_id, ask);
201
+ this.#push(run, { kind: 'approval', requestId: v.request_id, tool: req.tool_name, summary: ask.summary || '', reason, via });
202
+ }
203
+ // behavior: 'allow' | 'deny'. For a question, `answers` maps each question text to the chosen label(s).
204
+ respond(run, requestId, behavior, answers) {
205
+ const p = run.pending.get(requestId);
206
+ if (!p)
207
+ return false;
208
+ let response;
209
+ if (behavior === 'allow') {
210
+ const updated = { ...p.input };
211
+ if (p.kind === 'question') {
212
+ const out = {};
213
+ for (const q of p.questions || []) {
214
+ const a = answers && answers[q.question];
215
+ out[q.question] = Array.isArray(a) ? a.join(', ') : typeof a === 'string' ? a : '';
216
+ }
217
+ updated.answers = out;
218
+ }
219
+ response = { behavior: 'allow', updatedInput: updated };
220
+ }
221
+ else {
222
+ response = { behavior: 'deny', message: p.kind === 'question' ? 'The user declined to answer.' : DENY_MESSAGE };
223
+ }
224
+ run.pending.delete(requestId);
225
+ this.#write(run, { type: 'control_response', response: { subtype: 'success', request_id: requestId, response } });
226
+ this.#push(run, { kind: 'resolved', requestId, decision: behavior });
227
+ return true;
228
+ }
229
+ #maybeClose(run) {
230
+ if (run.status !== 'running' || !run.result || run.pending.size)
231
+ return;
232
+ run.closeTimer = setTimeout(() => {
233
+ if (run.status === 'running' && !run.pending.size) {
234
+ try {
235
+ run.child?.stdin?.end();
236
+ }
237
+ catch { /* closed */ }
238
+ }
239
+ }, QUIET_AFTER_RESULT_MS);
240
+ }
241
+ stop(run) {
242
+ if (run.status !== 'running')
243
+ return false;
244
+ run.stopping = true;
245
+ try {
246
+ run.child?.stdin?.end();
247
+ }
248
+ catch { /* closed */ }
249
+ const pid = run.child?.pid;
250
+ if (!pid)
251
+ return true;
252
+ try {
253
+ if (process.platform === 'win32')
254
+ (0, child_process_1.spawn)('taskkill', ['/pid', String(pid), '/T', '/F'], { stdio: 'ignore' });
255
+ else
256
+ process.kill(-pid, 'SIGTERM');
257
+ }
258
+ catch { /* gone */ }
259
+ const t = setTimeout(() => { try {
260
+ if (process.platform !== 'win32')
261
+ process.kill(-pid, 'SIGKILL');
262
+ }
263
+ catch { /* gone */ } }, 4000);
264
+ t.unref();
265
+ return true;
266
+ }
267
+ flush() { this.store?.flush(this.runs.values()); }
268
+ stopAll() { for (const r of this.runs.values())
269
+ this.stop(r); }
270
+ get(id) { return this.runs.get(id) || null; }
271
+ forProject(projectId) { return [...this.runs.values()].filter((r) => r.projectId === projectId); }
272
+ find(projectId, cwd) { return [...this.runs.values()].find((r) => r.projectId === projectId && r.cwd === cwd && r.status === 'running') || null; }
273
+ view(run, since) {
274
+ const out = { id: run.id, command: run.command, cwd: run.cwd, permissionMode: run.permissionMode, status: run.status, startedAt: run.startedAt,
275
+ endedAt: run.endedAt, result: run.result, sessionId: run.sessionId,
276
+ pending: [...run.pending.values()].map((p) => ({ requestId: p.requestId, kind: p.kind, tool: p.tool, summary: p.summary, reason: p.reason, via: p.via, questions: p.questions })) };
277
+ if (since !== undefined) {
278
+ out.events = run.events.slice(Math.max(0, since - run.dropped));
279
+ out.cursor = run.dropped + run.events.length;
280
+ }
281
+ return out;
282
+ }
283
+ }
284
+ exports.Runs = Runs;