cohorte 3.3.0 → 4.1.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/README.md +23 -3
  3. package/core/agents/cohorte-review.md +11 -3
  4. package/core/agents/implementer.template.md +19 -1
  5. package/core/commands/cohorte-acceptance.md +35 -0
  6. package/core/commands/cohorte-build.md +17 -0
  7. package/core/commands/cohorte-fix.md +6 -0
  8. package/core/commands/cohorte-foundation.md +90 -0
  9. package/core/commands/cohorte-lead.md +90 -0
  10. package/core/commands/cohorte-learn.md +67 -0
  11. package/core/commands/cohorte-po.md +76 -0
  12. package/core/commands/cohorte-product-map.md +53 -0
  13. package/core/commands/cohorte-retro.md +44 -13
  14. package/core/commands/cohorte-scaffold.md +59 -0
  15. package/core/commands/cohorte-vision.md +80 -0
  16. package/lib/install.js +2 -0
  17. package/lib/project.js +1 -1
  18. package/lib/registry.js +4 -3
  19. package/package.json +2 -2
  20. package/profile/PIPELINE.template.md +3 -1
  21. package/profile/schema/kanban.md +23 -0
  22. package/scripts/kanban-move.sh +45 -11
  23. package/ui/dist-server/server/agents.js +100 -0
  24. package/ui/dist-server/server/decider.js +241 -0
  25. package/ui/dist-server/server/features.js +128 -0
  26. package/ui/dist-server/server/flow.js +934 -0
  27. package/ui/dist-server/server/founding.js +706 -0
  28. package/ui/dist-server/server/gitinfo.js +22 -0
  29. package/ui/dist-server/server/history.js +10 -3
  30. package/ui/dist-server/server/legacy.js +3 -1
  31. package/ui/dist-server/server/next.js +91 -0
  32. package/ui/dist-server/server/runs.js +73 -11
  33. package/ui/dist-server/server/server.js +222 -6
  34. package/ui/dist-server/server/settings.js +81 -0
  35. package/ui/dist-server/server/tracker.js +438 -0
  36. package/ui/dist-server/shared/blocks.js +165 -0
  37. package/ui/dist-web/assets/index-BfN944Jm.js +165 -0
  38. package/ui/dist-web/assets/{style-0oNNMjwU.css → style-BMfadlCl.css} +1 -1
  39. package/ui/dist-web/index.html +2 -2
  40. package/ui/dist-web/assets/index-Clp1YW4S.js +0 -152
@@ -4,6 +4,7 @@
4
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
5
  // one that `git` itself lists for the worktree — the client never names a path git did not report.
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.probe = void 0;
7
8
  exports.baseRef = baseRef;
8
9
  exports.parseStatus = parseStatus;
9
10
  exports.parseShortstat = parseShortstat;
@@ -12,6 +13,7 @@ exports.pullFor = pullFor;
12
13
  exports.ghAvailable = ghAvailable;
13
14
  exports.changedFiles = changedFiles;
14
15
  exports.fileDiff = fileDiff;
16
+ exports.remoteInfo = remoteInfo;
15
17
  const child_process_1 = require("child_process");
16
18
  function run(file, args, cwd, timeout = 8000, max = 400_000) {
17
19
  return new Promise((resolve) => {
@@ -169,3 +171,23 @@ async function fileDiff(wtPath, base, file) {
169
171
  const r = await git(wtPath, 'diff', '--no-color', '--no-ext-diff', range, '--', file);
170
172
  return { file, status: entry.status, diff: r.out.slice(0, 200_000), truncated: r.out.length > 200_000 };
171
173
  }
174
+ const ghBin = () => process.env.COHORTE_GH_BIN || 'gh';
175
+ /** Where the code is hosted, and whether `gh` could create a GitHub repository from here. Read-only. */
176
+ async function remoteInfo(root) {
177
+ const [origin, branch, ahead, ghv] = await Promise.all([
178
+ git(root, 'remote', 'get-url', 'origin'), git(root, 'rev-parse', '--abbrev-ref', 'HEAD'),
179
+ git(root, 'rev-list', '--count', '@{u}..HEAD'), run(ghBin(), ['--version'], root, 4000),
180
+ ]);
181
+ let authed = false;
182
+ let user = null;
183
+ if (ghv.code === 0) {
184
+ const who = await run(ghBin(), ['api', 'user', '--jq', '.login'], root, 10000);
185
+ authed = who.code === 0 && !!who.out.trim();
186
+ user = authed ? who.out.trim().split('\n')[0].slice(0, 100) : null;
187
+ }
188
+ return { origin: origin.code === 0 ? origin.out.trim() || null : null, branch: branch.code === 0 ? branch.out.trim() || null : null,
189
+ ahead: ahead.code === 0 ? Number(ahead.out.trim()) || 0 : null, gh: { installed: ghv.code === 0, authed, user } };
190
+ }
191
+ /** A bounded, shell-less process run (tool probes for the foundations context). */
192
+ const probe = (file, args, cwd, timeout = 4000) => run(file, args, cwd, timeout, 20_000);
193
+ exports.probe = probe;
@@ -9,7 +9,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.RunStore = void 0;
10
10
  const fs_1 = __importDefault(require("fs"));
11
11
  const path_1 = __importDefault(require("path"));
12
- const KEEP_PER_PROJECT = 40;
12
+ const KEEP_PER_PROJECT = 120; // the company flow keeps its conversations here too
13
13
  const KEEP_EVENTS = 400;
14
14
  const SAFE = /^[A-Za-z0-9._-]+$/;
15
15
  class RunStore {
@@ -43,7 +43,8 @@ class RunStore {
43
43
  fs_1.default.mkdirSync(path_1.default.dirname(f), { recursive: true });
44
44
  const cut = Math.max(0, run.events.length - KEEP_EVENTS);
45
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) };
46
+ startedAt: run.startedAt, endedAt: run.endedAt, result: run.result, sessionId: run.sessionId, dropped: run.dropped + cut, events: run.events.slice(cut),
47
+ meta: run.meta, model: run.model, disallowedTools: run.disallowedTools, allowedTools: run.allowedTools, addDirs: run.addDirs, seen: run.seen, tickets: run.tickets, strictMcp: run.strictMcp, mcpConfig: run.mcpConfig };
47
48
  const tmp = `${f}.${process.pid}.tmp`;
48
49
  fs_1.default.writeFileSync(tmp, JSON.stringify(body));
49
50
  fs_1.default.renameSync(tmp, f);
@@ -85,7 +86,13 @@ class RunStore {
85
86
  const interrupted = v.status === 'running';
86
87
  out.push({ id: v.id, projectId: v.projectId, cwd: v.cwd, command: v.command, permissionMode: v.permissionMode, status: interrupted ? 'stopped' : v.status,
87
88
  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
+ pending: new Map(), result: v.result || null, sessionId: v.sessionId || null, child: null, closeTimer: null, stopping: false,
90
+ meta: v.meta && typeof v.meta === 'object' && typeof v.meta.role === 'string' ? v.meta : { role: 'command' }, model: typeof v.model === 'string' ? v.model : null,
91
+ disallowedTools: Array.isArray(v.disallowedTools) ? v.disallowedTools.filter((t) => typeof t === 'string') : [],
92
+ allowedTools: Array.isArray(v.allowedTools) ? v.allowedTools.filter((t) => typeof t === 'string') : [],
93
+ addDirs: Array.isArray(v.addDirs) ? v.addDirs.filter((t) => typeof t === 'string') : [],
94
+ seen: typeof v.seen === 'number' ? v.seen : 0, tickets: v.tickets && typeof v.tickets === 'object' ? v.tickets : {},
95
+ strictMcp: v.strictMcp === true, mcpConfig: typeof v.mcpConfig === 'string' ? v.mcpConfig : null });
89
96
  }
90
97
  catch { /* a corrupt file is skipped */ }
91
98
  }
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.parseProfileBlock = exports.report = exports.doctor = exports.registry = exports.RegistryErrorBase = exports.uiDir = exports.repo = void 0;
6
+ exports.project = exports.parseProfileBlock = exports.report = exports.doctor = exports.registry = exports.RegistryErrorBase = exports.uiDir = exports.repo = void 0;
7
7
  // Typed views of the plain-JS modules shared with the CLI (lib/*.js, bin/report.js). They stay JavaScript —
8
8
  // the CLI, the installer and the tests use them directly — so the dashboard describes only what it uses.
9
9
  const fs_1 = __importDefault(require("fs"));
@@ -27,3 +27,5 @@ exports.registry = load('lib/registry.js');
27
27
  exports.doctor = load('lib/doctor.js');
28
28
  exports.report = load('bin/report.js');
29
29
  exports.parseProfileBlock = load('lib/yaml.js').parseProfileBlock;
30
+ /** `cohorte sync` — re-wires a repo from its PIPELINE.md (profile.json, gate, pointer). */
31
+ exports.project = load('lib/project.js');
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ // The autopilot's routing between two checkpoints, as a pure function: where a feature stands (the pipeline's own
3
+ // reports, through pipelineOf) plus what the autopilot remembers (rounds, the last blocking count, failures) in;
4
+ // the next stage to run — or the checkpoint to open, and why — out.
5
+ //
6
+ // CP2 ("course check") opens only on a signal that a human should look before more money is spent:
7
+ // - a stage failed twice (or a human stopped it);
8
+ // - the spec is NOT-READY (the lead has to fix it), or a surface came back dead/failed from a build;
9
+ // - the review found a security issue (BLOCK) — never auto-fixed;
10
+ // - the spec had RESERVATIONS: after the first build, check the direction once before reviewing;
11
+ // - the fix loop is out of rounds, or treading water (blocking findings not going down).
12
+ // CP3 opens when review and verification are clean: what ships is the human's call.
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.nextStep = nextStep;
15
+ const settings_1 = require("./settings");
16
+ const modelFor = (stage, s) => s.models[stage];
17
+ function nextStep(id, sig, mem, s) {
18
+ const cp2 = (reason) => ({ kind: 'checkpoint', cp: 'cp2', reason });
19
+ const last = mem.stages[mem.stages.length - 1];
20
+ // 1. the stage that just ended did not finish
21
+ if (last && last.status !== 'done' && last.stage !== 'ship') {
22
+ if (last.status === 'stopped')
23
+ return cp2(`you stopped the ${last.stage} run`);
24
+ const n = mem.failures[last.stage] || 0;
25
+ if (n >= 2)
26
+ return cp2(`the ${last.stage} run failed twice${last.note ? `: ${last.note}` : ''}`);
27
+ if (['build', 'review', 'fix', 'verify'].includes(last.stage)) {
28
+ const st = last.stage;
29
+ return { kind: 'run', stage: st, model: (0, settings_1.escalate)(last.model || modelFor(st, s)), args: last.stage === 'fix' ? `${id} the previous fix run died before finishing — redo its open Remediation items` : id, note: 'retry after a failed run, one model up' };
30
+ }
31
+ }
32
+ // 2. signals that stop the line
33
+ if (sig.readiness === 'NOT-READY')
34
+ return cp2('the spec is not ready to build — the lead has to complete it');
35
+ // The pipeline's reports cannot tell a fixed tree from a reviewed one (verdict.json is only rewritten by a review),
36
+ // so the autopilot's own memory routes the loop: after a fix, always a review — before the last verdict is read.
37
+ const lastDone = [...mem.stages].reverse().find((x) => x.status === 'done');
38
+ if (lastDone?.stage === 'fix')
39
+ return { kind: 'run', stage: 'review', model: modelFor('review', s), args: id, note: 'after a fix round' };
40
+ // a review that aborted certifies nothing: a red preflight is a fix round, anything else a human's call
41
+ if (sig.verdict?.aborted && lastDone?.stage === 'review') {
42
+ if (sig.verdict.aborted !== 'preflight')
43
+ return cp2(`the review aborted (${sig.verdict.aborted})`);
44
+ if (mem.rounds >= s.maxRounds)
45
+ return cp2(`${mem.rounds} fix rounds and the preflight is still red`);
46
+ return { kind: 'run', stage: 'fix', model: modelFor('fix', s), args: `${id} the review's preflight is red — read specs/reports/${id}.preflight.txt and make typecheck, lint and tests pass`, note: 'preflight red' };
47
+ }
48
+ if (sig.verdict?.verdict === 'BLOCK' && !sig.verdict.aborted)
49
+ return cp2('the review found a security issue (BLOCK) — not fixed without you');
50
+ let next = sig.pipeline.next?.command || null;
51
+ // a verify.json FAIL from before the last fix/review is stale: verify again instead of fixing again
52
+ if (next === 'cohorte-verify' && sig.verify === 'FAIL' && lastDone?.stage !== 'verify')
53
+ next = 'cohorte-verify-again';
54
+ const built = mem.stages.some((x) => x.stage === 'build' && x.status === 'done');
55
+ // a SHIP that still carries HIGH/MEDIUM findings is not a clean bill: /cohorte-ship would refuse it
56
+ const dirtyShip = sig.verdict?.verdict === 'SHIP' && (sig.verdict.high > 0 || sig.verdict.medium > 0);
57
+ if (next === 'cohorte-build') {
58
+ if (built && (sig.buildDead || sig.pipeline.stages.find((x) => x.key === 'build')?.state === 'blocked'))
59
+ return cp2('a surface failed or died during the build');
60
+ return { kind: 'run', stage: 'build', model: modelFor('build', s), args: id, note: '' };
61
+ }
62
+ if (next === 'cohorte-review') {
63
+ if (sig.readiness === 'RESERVATIONS' && !mem.reservationsAck && built)
64
+ return cp2('the spec had reservations — check the direction of the first build before the review');
65
+ return { kind: 'run', stage: 'review', model: modelFor('review', s), args: id, note: '' };
66
+ }
67
+ const wantsFix = next === 'cohorte-fix' || dirtyShip || (next === 'cohorte-verify' && sig.verify === 'FAIL');
68
+ if (wantsFix) {
69
+ if (mem.rounds >= s.maxRounds)
70
+ return cp2(`${mem.rounds} fix round${mem.rounds === 1 ? '' : 's'} and the review still says ${sig.verdict?.verdict || 'no'}`);
71
+ const blocking = sig.verdict?.blocking ?? null;
72
+ const stuck = mem.rounds >= 2 && blocking !== null && mem.lastBlocking !== null && blocking >= mem.lastBlocking;
73
+ if (stuck)
74
+ return cp2(`the fix loop is treading water (${blocking} blocking finding${blocking === 1 ? '' : 's'}, not going down)`);
75
+ const noProgress = mem.rounds >= 1 && blocking !== null && mem.lastBlocking !== null && blocking >= mem.lastBlocking;
76
+ const model = noProgress ? (0, settings_1.escalate)(modelFor('fix', s)) : modelFor('fix', s);
77
+ let args = id;
78
+ if (next === 'cohorte-verify' && sig.verify === 'FAIL')
79
+ args = `${id} the runtime verification failed — read specs/reports/${id}.verify.json for the failing checks`;
80
+ else if (next !== 'cohorte-fix' && dirtyShip)
81
+ args = `${id} the review passed with HIGH/MEDIUM findings left — fix them (specs/reports/${id}.md)`;
82
+ return { kind: 'run', stage: 'fix', model, args, note: noProgress ? 'no progress last round — one model up' : '' };
83
+ }
84
+ if (next === 'cohorte-verify' || next === 'cohorte-verify-again')
85
+ return { kind: 'run', stage: 'verify', model: modelFor('verify', s), args: id, note: '' };
86
+ if (next === 'cohorte-ship')
87
+ return { kind: 'checkpoint', cp: 'cp3', reason: 'review and verification are clean — ready to ship' };
88
+ if (next === 'cohorte-spec')
89
+ return cp2('the spec is not frozen');
90
+ return cp2(sig.pipeline.next ? `unexpected next step: ${sig.pipeline.next.command}` : 'nothing left to run, but nothing shipped either');
91
+ }
@@ -2,10 +2,12 @@
2
2
  // cohorte ui — runs a pipeline command (`/cohorte-build f1`) through `claude -p`, headless, and turns the
3
3
  // stream into a short feed plus the decisions only a human can make.
4
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:
5
+ // A run is one Cohorte command in one worktree. The human's part is the gates the CLI raises on its control
6
+ // channel — a permission ask (the project's gate answering `ask`, or Claude Code's own prompt) and
7
+ // AskUserQuestion (the interview commands) — plus, once a turn has ended, a reply in the same session.
8
+ // The company flow (flow.ts) starts runs of its own — the PO and lead conversations, the autopilot's stages —
9
+ // with a role in `meta`, a model, and for the business-facing ones a read-only tool set. Protocol, verified
10
+ // against Claude Code 2.1.326:
9
11
  //
10
12
  // claude -p --output-format stream-json --input-format stream-json --permission-prompt-tool stdio --verbose
11
13
  // stdin ← {"type":"user","message":{"role":"user","content":[{"type":"text","text":"/cohorte-build f1"}]}}
@@ -20,7 +22,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
20
22
  return (mod && mod.__esModule) ? mod : { "default": mod };
21
23
  };
22
24
  Object.defineProperty(exports, "__esModule", { value: true });
23
- exports.Runs = exports.MODES = void 0;
25
+ exports.Runs = exports.MODEL = exports.ALLOWED_RULE = exports.MODES = void 0;
26
+ const path_1 = __importDefault(require("path"));
24
27
  const crypto_1 = __importDefault(require("crypto"));
25
28
  const readline_1 = __importDefault(require("readline"));
26
29
  const child_process_1 = require("child_process");
@@ -48,11 +51,15 @@ function summarize(name, input) {
48
51
  return '';
49
52
  }
50
53
  }
54
+ /** A permission rule: a tool name, optionally with a specifier — `Bash(npm:*)`, `Bash(docker compose:*)`. No comma (the list separator). */
55
+ exports.ALLOWED_RULE = /^[A-Za-z][\w]{0,40}(\([^(),\r\n]{1,400}\))?$/;
56
+ exports.MODEL = /^[A-Za-z0-9][A-Za-z0-9._:\[\]-]{0,80}$/;
51
57
  class Runs {
52
58
  runs = new Map();
53
59
  bin;
54
60
  onChange = () => { };
55
61
  store;
62
+ hooks = {};
56
63
  constructor({ bin, store } = {}) {
57
64
  this.bin = bin || process.env.COHORTE_CLAUDE_BIN || 'claude';
58
65
  this.store = store || null;
@@ -62,14 +69,21 @@ class Runs {
62
69
  // opts: { projectId, cwd, command (e.g. "/cohorte-build f1"), permissionMode }
63
70
  start(opts) {
64
71
  const mode = typeof opts.permissionMode === 'string' && exports.MODES.includes(opts.permissionMode) ? opts.permissionMode : 'default';
72
+ const model = typeof opts.model === 'string' && exports.MODEL.test(opts.model) ? opts.model : null;
65
73
  const run = {
66
74
  id: crypto_1.default.randomBytes(4).toString('hex'), projectId: opts.projectId, cwd: opts.cwd, command: opts.command,
67
75
  permissionMode: mode, status: 'running', startedAt: new Date().toISOString(), endedAt: null,
68
76
  events: [], dropped: 0, pending: new Map(), result: null, sessionId: null, child: null, closeTimer: null, stopping: false,
77
+ meta: opts.meta || { role: 'command' }, model, disallowedTools: (opts.disallowedTools || []).filter((t) => /^[A-Za-z][\w:-]{0,60}$/.test(t)),
78
+ allowedTools: (opts.allowedTools || []).filter((t) => exports.ALLOWED_RULE.test(t)),
79
+ addDirs: (opts.addDirs || []).filter((d) => typeof d === 'string' && path_1.default.isAbsolute(d)),
80
+ seen: 0, tickets: {}, strictMcp: opts.strictMcp === true, mcpConfig: typeof opts.mcpConfig === 'string' ? opts.mcpConfig : null,
69
81
  };
70
82
  this.#spawn(run, null);
71
83
  this.runs.set(run.id, run);
72
- this.#write(run, { type: 'user', message: { role: 'user', content: [{ type: 'text', text: opts.command }] } });
84
+ if (opts.echo)
85
+ this.#push(run, { kind: 'reply', text: clip(opts.echo, 8000) });
86
+ this.#write(run, { type: 'user', message: { role: 'user', content: [{ type: 'text', text: opts.prompt || opts.command }] } });
73
87
  return run;
74
88
  }
75
89
  // One `claude -p` process for the run's next turn. A reply resumes the same session in a new process.
@@ -77,6 +91,18 @@ class Runs {
77
91
  const args = ['-p', '--output-format', 'stream-json', '--input-format', 'stream-json', '--permission-prompt-tool', 'stdio', '--verbose'];
78
92
  if (run.permissionMode !== 'default')
79
93
  args.push('--permission-mode', run.permissionMode);
94
+ if (run.model)
95
+ args.push('--model', run.model);
96
+ if (run.disallowedTools.length)
97
+ args.push('--disallowedTools', run.disallowedTools.join(','));
98
+ if (run.allowedTools.length)
99
+ args.push('--allowedTools', run.allowedTools.join(','));
100
+ for (const d of run.addDirs)
101
+ args.push('--add-dir', d);
102
+ if (run.strictMcp)
103
+ args.push('--strict-mcp-config');
104
+ if (run.mcpConfig)
105
+ args.push('--mcp-config', run.mcpConfig);
80
106
  if (resumeId)
81
107
  args.push('--resume', resumeId);
82
108
  const child = (0, child_process_1.spawn)(this.bin, args, { cwd: run.cwd, detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe'], env: process.env });
@@ -132,7 +158,25 @@ class Runs {
132
158
  run.dropped += cut;
133
159
  }
134
160
  }
135
- #end(run, status) { run.status = status; run.endedAt = new Date().toISOString(); run.pending.clear(); this.onChange(run); this.store?.schedule(run, true); }
161
+ #end(run, status) {
162
+ run.status = status;
163
+ run.endedAt = new Date().toISOString();
164
+ run.pending.clear();
165
+ this.onChange(run);
166
+ this.store?.schedule(run, true);
167
+ try {
168
+ this.hooks.onEnd?.(run);
169
+ }
170
+ catch { /* the flow never takes a run down */ }
171
+ }
172
+ /** The flow updates a parked item (deciding → advice) without answering it. */
173
+ annotate(run, requestId, patch) {
174
+ const p = run.pending.get(requestId);
175
+ if (!p)
176
+ return;
177
+ Object.assign(p, patch);
178
+ this.onChange(run);
179
+ }
136
180
  #line(run, line) {
137
181
  if (!line.trim())
138
182
  return;
@@ -186,7 +230,17 @@ class Runs {
186
230
  if (req.tool_name === 'AskUserQuestion' && Array.isArray(input.questions) && input.questions.length) {
187
231
  const questions = input.questions.map((q) => ({ question: String(q.question || ''), header: String(q.header || ''), multiSelect: q.multiSelect === true,
188
232
  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 });
233
+ const p = { ...base, kind: 'question', input, questions };
234
+ run.pending.set(v.request_id, p);
235
+ let held = false;
236
+ try {
237
+ held = this.hooks.onQuestion?.(run, p) === true;
238
+ }
239
+ catch {
240
+ held = false;
241
+ }
242
+ if (held)
243
+ p.deciding = true;
190
244
  this.#push(run, { kind: 'question', ...base, questions });
191
245
  return;
192
246
  }
@@ -201,11 +255,12 @@ class Runs {
201
255
  this.#push(run, { kind: 'approval', requestId: v.request_id, tool: req.tool_name, summary: ask.summary || '', reason, via });
202
256
  }
203
257
  // behavior: 'allow' | 'deny'. For a question, `answers` maps each question text to the chosen label(s).
204
- respond(run, requestId, behavior, answers) {
258
+ respond(run, requestId, behavior, answers, by = 'human') {
205
259
  const p = run.pending.get(requestId);
206
260
  if (!p)
207
261
  return false;
208
262
  let response;
263
+ let given = {};
209
264
  if (behavior === 'allow') {
210
265
  const updated = { ...p.input };
211
266
  if (p.kind === 'question') {
@@ -215,6 +270,7 @@ class Runs {
215
270
  out[q.question] = Array.isArray(a) ? a.join(', ') : typeof a === 'string' ? a : '';
216
271
  }
217
272
  updated.answers = out;
273
+ given = out;
218
274
  }
219
275
  response = { behavior: 'allow', updatedInput: updated };
220
276
  }
@@ -224,6 +280,11 @@ class Runs {
224
280
  run.pending.delete(requestId);
225
281
  this.#write(run, { type: 'control_response', response: { subtype: 'success', request_id: requestId, response } });
226
282
  this.#push(run, { kind: 'resolved', requestId, decision: behavior });
283
+ try {
284
+ this.hooks.onAnswered?.(run, p, behavior, given, by);
285
+ }
286
+ catch { /* never fails an answer */ }
287
+ this.#maybeClose(run);
227
288
  return true;
228
289
  }
229
290
  #maybeClose(run) {
@@ -272,8 +333,9 @@ class Runs {
272
333
  find(projectId, cwd) { return [...this.runs.values()].find((r) => r.projectId === projectId && r.cwd === cwd && r.status === 'running') || null; }
273
334
  view(run, since) {
274
335
  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 })) };
336
+ endedAt: run.endedAt, result: run.result, sessionId: run.sessionId, meta: run.meta, model: run.model,
337
+ 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,
338
+ deciding: p.deciding || undefined, advice: p.advice })) };
277
339
  if (since !== undefined) {
278
340
  out.events = run.events.slice(Math.max(0, since - run.dropped));
279
341
  out.cursor = run.dropped + run.events.length;
@@ -60,6 +60,10 @@ const ops = __importStar(require("./ops"));
60
60
  const docker = __importStar(require("./docker"));
61
61
  const pipeline_1 = require("./pipeline");
62
62
  const findings_1 = require("./findings");
63
+ const flow_1 = require("./flow");
64
+ const founding_1 = require("./founding");
65
+ const settings_1 = require("./settings");
66
+ const tracker_1 = require("./tracker");
63
67
  const { state, scanSpecs } = legacy_1.doctor;
64
68
  const pkgRoot = legacy_1.repo;
65
69
  const PUBLIC = path_1.default.join(legacy_1.uiDir, 'dist-web');
@@ -143,8 +147,21 @@ function create({ globalDir, version, token = crypto_1.default.randomBytes(24).t
143
147
  }
144
148
  }, 120);
145
149
  };
146
- jobs.onChange = (j) => notify({ type: 'job', projectId: j.projectId, id: j.id, status: j.status });
147
- runs.onChange = (r) => notify({ type: 'run', projectId: r.projectId, id: r.id, status: r.status, pending: r.pending.size });
150
+ const flow = new flow_1.Flow({ globalDir, runs, jobs, dataDir: path_1.default.join(globalDir, 'cohorte-ui'), changed: (projectId) => {
151
+ const pr = legacy_1.registry.get(globalDir, projectId);
152
+ if (pr)
153
+ cacheDoctor.clear(pr.root); // a founding step may have just written PIPELINE.md
154
+ notify({ type: 'flow', projectId, id: projectId, status: 'changed' });
155
+ } });
156
+ jobs.onChange = (j) => {
157
+ notify({ type: 'job', projectId: j.projectId, id: j.id, status: j.status });
158
+ try {
159
+ flow.onJob(j);
160
+ flow.onMergeJob(j);
161
+ }
162
+ catch { /* the flow never takes a job down */ }
163
+ };
164
+ runs.onChange = (r) => notify({ type: 'run', projectId: r.projectId, id: r.id, status: r.status, pending: [...r.pending.values()].filter((x) => !x.deciding).length });
148
165
  let origin = null; // set once listening
149
166
  const doctorOf = (root) => cacheDoctor(root, () => state({ projectRoot: root, globalDir, cliVersion: version, offline: true }));
150
167
  async function summary(p) {
@@ -156,12 +173,12 @@ function create({ globalDir, version, token = crypto_1.default.randomBytes(24).t
156
173
  const counts = {};
157
174
  for (const sp of s.specs)
158
175
  counts[sp.status || 'unknown'] = (counts[sp.status || 'unknown'] || 0) + 1;
159
- return { ...base, missing: false, title: s.profile && s.profile.name || base.name,
176
+ return { ...base, missing: false, founding: flow.founding.phaseOf(p.id), title: s.profile && s.profile.name || base.name,
160
177
  oneLiner: s.profile && s.profile.one_liner || '', summary: s.summary, specCounts: counts,
161
178
  specTotal: s.specs.length, core: s.versions && s.versions.core || null };
162
179
  }
163
180
  catch (e) {
164
- return { ...base, missing: false, error: String(e?.message || e) };
181
+ return { ...base, missing: false, founding: flow.founding.phaseOf(p.id), error: String(e?.message || e) };
165
182
  }
166
183
  }
167
184
  async function detail(p) {
@@ -270,11 +287,33 @@ function create({ globalDir, version, token = crypto_1.default.randomBytes(24).t
270
287
  items.push({ projectId: r.projectId, projectName: names.get(r.projectId), kind: 'run', id: r.id, label: r.command, status: r.status, pending: r.pending.size, startedAt: r.startedAt });
271
288
  return send(res, 200, { items });
272
289
  }
290
+ if (parts[0] === 'inbox' && method === 'GET')
291
+ return send(res, 200, { items: flow.inbox() });
273
292
  if (parts[0] === 'commands' && method === 'GET')
274
293
  return send(res, 200, { commands: ops.listCommands(globalDir) });
275
294
  if (parts[0] === 'discover' && method === 'GET') {
276
295
  return send(res, 200, { suggestions: legacy_1.registry.discover(globalDir, storePath) });
277
296
  }
297
+ if (parts[0] === 'founding' && parts.length === 1 && method === 'POST') {
298
+ let body;
299
+ try {
300
+ body = await readBody(req);
301
+ }
302
+ catch (e) {
303
+ return fail(res, 400, e.message);
304
+ }
305
+ try {
306
+ const r = await flow.founding.create(body);
307
+ return send(res, 201, { project: await summary(r.project), founding: r.founding });
308
+ }
309
+ catch (e) {
310
+ if (e instanceof ops.OpError)
311
+ return send(res, e.code, { error: e.message });
312
+ if (e instanceof legacy_1.registry.RegistryError)
313
+ return fail(res, 400, e.message);
314
+ throw e;
315
+ }
316
+ }
278
317
  if (parts[0] === 'projects' && parts.length === 1 && method === 'POST') {
279
318
  let body;
280
319
  try {
@@ -289,7 +328,7 @@ function create({ globalDir, version, token = crypto_1.default.randomBytes(24).t
289
328
  }
290
329
  catch (e) {
291
330
  if (e instanceof legacy_1.registry.RegistryError)
292
- return fail(res, 400, e.message);
331
+ return send(res, 400, { error: e.message, notCohorte: /has no PIPELINE\.md/.test(e.message) });
293
332
  throw e;
294
333
  }
295
334
  }
@@ -351,6 +390,28 @@ function create({ globalDir, version, token = crypto_1.default.randomBytes(24).t
351
390
  catch (e) {
352
391
  return fail(res, 400, e.message);
353
392
  }
393
+ if (founding_1.FOUNDING_ROLES.includes(run.meta.role)) {
394
+ try {
395
+ flow.founding.reply(p.id, body.text);
396
+ return send(res, 202, { run: runs.view(run, 0) });
397
+ }
398
+ catch (e) {
399
+ if (e instanceof ops.OpError)
400
+ return fail(res, e.code, e.message);
401
+ throw e;
402
+ }
403
+ }
404
+ if (run.meta.role === 'lead' && run.meta.featureId) {
405
+ try {
406
+ flow.replyLead(p.id, run.meta.featureId, body.text);
407
+ return send(res, 202, { run: runs.view(run, 0) });
408
+ }
409
+ catch (e) {
410
+ if (e instanceof ops.OpError)
411
+ return fail(res, e.code, e.message);
412
+ throw e;
413
+ }
414
+ }
354
415
  const err = runs.reply(run, body.text);
355
416
  return err ? fail(res, 409, err) : send(res, 202, { run: runs.view(run, 0) });
356
417
  }
@@ -367,6 +428,159 @@ function create({ globalDir, version, token = crypto_1.default.randomBytes(24).t
367
428
  return runs.respond(run, String(body.requestId), body.behavior, body.answers) ? send(res, 200, { ok: true }) : fail(res, 404, 'no such pending request');
368
429
  }
369
430
  }
431
+ // ---- company flow ----
432
+ const flowCall = async (fn, code = 200) => {
433
+ try {
434
+ return send(res, code, await fn());
435
+ }
436
+ catch (e) {
437
+ if (e instanceof ops.OpError)
438
+ return send(res, e.code, { error: e.message, needsConfirmation: e.needsConfirmation || false, command: e.command, reason: e.reason, untrusted: e.untrusted || false, fix: e.fix });
439
+ if (e instanceof tracker_1.TrackerError)
440
+ return fail(res, 400, e.message);
441
+ throw e;
442
+ }
443
+ };
444
+ const bodyOf = async () => { try {
445
+ return await readBody(req);
446
+ }
447
+ catch (e) {
448
+ fail(res, 400, e.message);
449
+ return null;
450
+ } };
451
+ if (parts[2] === 'tickets') {
452
+ if (parts.length === 3 && method === 'GET')
453
+ return flowCall(() => { const tr = flow.tracker(p); return { tracker: tr.info, tickets: tr.list(), conversations: flow.conversations(p.id) }; });
454
+ if (parts.length === 3 && method === 'POST') {
455
+ const b = await bodyOf();
456
+ if (!b)
457
+ return;
458
+ return flowCall(() => ({ ticket: flow.createTicket(p.id, b) }), 201);
459
+ }
460
+ const tid = parts[3];
461
+ if (!(0, tracker_1.isTicketId)(tid))
462
+ return fail(res, 404, 'unknown ticket');
463
+ if (parts.length === 4 && method === 'GET') {
464
+ const t = flow.tracker(p).get(tid);
465
+ return t ? send(res, 200, { ticket: t }) : fail(res, 404, 'unknown ticket');
466
+ }
467
+ if (method === 'POST' && parts[4] === 'decide') {
468
+ const b = await bodyOf();
469
+ if (!b)
470
+ return;
471
+ return flowCall(() => ({ ticket: flow.decideTicket(p.id, tid, b.action) }));
472
+ }
473
+ if (method === 'POST' && parts[4] === 'acceptance') {
474
+ const b = await bodyOf();
475
+ if (!b)
476
+ return;
477
+ return flowCall(() => { const r = flow.acceptance(p.id, tid, b); return { ticket: r.ticket, run: r.run ? runs.view(r.run, 0) : null }; });
478
+ }
479
+ if (method === 'POST' && parts[4] === 'take') {
480
+ const b = await bodyOf();
481
+ if (!b)
482
+ return;
483
+ if (b.skipDockerCheck !== true && !flow.features.get(p.id, tid)) {
484
+ const pre = await docker.preflight(p.root);
485
+ if (pre && !pre.ok)
486
+ return send(res, 409, { error: pre.reason, dockerPreflight: pre });
487
+ }
488
+ return flowCall(() => { cacheDoctor.clear(p.root); return { feature: flow.take(p.id, tid, { confirmed: b.confirmed === true }) }; }, 202);
489
+ }
490
+ }
491
+ if (parts[2] === 'founding') {
492
+ if (parts.length === 3 && method === 'GET')
493
+ return flowCall(() => flow.founding.view(p.id));
494
+ if (parts[3] === 'reply' && method === 'POST') {
495
+ const b = await bodyOf();
496
+ if (!b)
497
+ return;
498
+ return flowCall(() => flow.founding.reply(p.id, b.text), 202);
499
+ }
500
+ if (parts[3] === 'checkpoint' && method === 'POST') {
501
+ const b = await bodyOf();
502
+ if (!b)
503
+ return;
504
+ return flowCall(async () => { const v = await flow.founding.checkpoint(p.id, b); cacheDoctor.clear(p.root); return v; });
505
+ }
506
+ }
507
+ if (parts[2] === 'remote' && parts.length === 3) {
508
+ if (method === 'GET')
509
+ return flowCall(() => flow.founding.remote(p.id));
510
+ if (method === 'POST') {
511
+ const b = await bodyOf();
512
+ if (!b)
513
+ return;
514
+ return flowCall(async () => ({ job: jobs.view(await flow.founding.connectRemote(p.id, b)) }), 202);
515
+ }
516
+ }
517
+ if (parts[2] === 'po' && parts.length === 3 && method === 'POST') {
518
+ const b = await bodyOf();
519
+ if (!b)
520
+ return;
521
+ return flowCall(() => ({ run: runs.view(flow.startPO(p.id, b), 0) }), 202);
522
+ }
523
+ if (parts[2] === 'features') {
524
+ if (parts.length === 3 && method === 'GET')
525
+ return send(res, 200, { features: flow.features.list(p.id) });
526
+ const fid = parts[3];
527
+ if (!(0, tracker_1.isTicketId)(fid))
528
+ return fail(res, 404, 'unknown feature');
529
+ if (parts.length === 4 && method === 'GET')
530
+ return flowCall(() => flow.detail(p.id, fid));
531
+ if (method === 'POST' && parts[4] === 'checkpoint') {
532
+ const b = await bodyOf();
533
+ if (!b)
534
+ return;
535
+ return flowCall(() => ({ feature: flow.checkpoint(p.id, fid, b) }));
536
+ }
537
+ if (method === 'POST' && parts[4] === 'lead') {
538
+ const b = await bodyOf();
539
+ if (!b)
540
+ return;
541
+ return flowCall(() => { flow.replyLead(p.id, fid, b.text); return { ok: true }; }, 202);
542
+ }
543
+ if (method === 'POST' && parts[4] === 'merge')
544
+ return flowCall(() => ({ job: jobs.view(flow.merge(p.id, fid)) }), 202);
545
+ if (method === 'POST' && parts[4] === 'decisions' && parts[5] && parts[6] === 'contest') {
546
+ const b = await bodyOf();
547
+ if (!b)
548
+ return;
549
+ return flowCall(() => ({ feature: flow.contest(p.id, fid, parts[5], b.note) }));
550
+ }
551
+ }
552
+ if (parts[2] === 'settings' && parts.length === 3) {
553
+ const view = () => {
554
+ const pm = path_1.default.join(p.root, 'PRODUCT.md');
555
+ let updated = null;
556
+ try {
557
+ updated = fs_1.default.statSync(pm).mtime.toISOString();
558
+ }
559
+ catch {
560
+ updated = null;
561
+ }
562
+ return { settings: flow.settings.get(p.id), defaults: settings_1.DEFAULTS, tracker: flow.tracker(p).info, productMap: { exists: updated !== null, updated } };
563
+ };
564
+ if (method === 'GET')
565
+ return send(res, 200, view());
566
+ if (method === 'POST') {
567
+ const b = await bodyOf();
568
+ if (!b)
569
+ return;
570
+ flow.settings.set(p.id, b);
571
+ return send(res, 200, view());
572
+ }
573
+ }
574
+ if (parts[2] === 'tracker' && parts.length === 3 && method === 'POST') {
575
+ const b = await bodyOf();
576
+ if (!b)
577
+ return;
578
+ return flowCall(() => ({ ...(0, tracker_1.connectObsidian)(globalDir, p.root, b), tracker: flow.tracker(p).info }));
579
+ }
580
+ if (parts[2] === 'product-map' && parts.length === 3 && method === 'POST')
581
+ return flowCall(() => ({ run: runs.view(flow.startProductMap(p.id), 0) }), 202);
582
+ if (parts[2] === 'learning' && parts.length === 3 && method === 'GET')
583
+ return send(res, 200, flow.learning(p.id));
370
584
  if (parts[2] === 'docker' && parts.length === 3) {
371
585
  if (method === 'GET')
372
586
  return send(res, 200, await docker.status(p.root));
@@ -528,7 +742,9 @@ function create({ globalDir, version, token = crypto_1.default.randomBytes(24).t
528
742
  });
529
743
  });
530
744
  }
531
- return { server, listen, token, jobs, runs, close: () => {
745
+ flow.start();
746
+ return { server, listen, token, jobs, runs, flow, close: () => {
747
+ flow.stop();
532
748
  jobs.stopAll();
533
749
  runs.stopAll();
534
750
  runs.flush();