cohorte 4.0.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.
- package/CHANGELOG.md +20 -0
- package/README.md +5 -2
- package/core/commands/cohorte-foundation.md +90 -0
- package/core/commands/cohorte-scaffold.md +59 -0
- package/core/commands/cohorte-vision.md +80 -0
- package/lib/install.js +2 -0
- package/lib/registry.js +4 -3
- package/package.json +1 -1
- package/ui/dist-server/server/agents.js +100 -0
- package/ui/dist-server/server/flow.js +90 -123
- package/ui/dist-server/server/founding.js +706 -0
- package/ui/dist-server/server/gitinfo.js +22 -0
- package/ui/dist-server/server/history.js +3 -1
- package/ui/dist-server/server/legacy.js +3 -1
- package/ui/dist-server/server/runs.js +10 -1
- package/ui/dist-server/server/server.js +67 -4
- package/ui/dist-server/server/settings.js +1 -1
- package/ui/dist-server/shared/blocks.js +53 -1
- package/ui/dist-web/assets/index-BfN944Jm.js +165 -0
- package/ui/dist-web/assets/{style-C8LIQAF3.css → style-BMfadlCl.css} +1 -1
- package/ui/dist-web/index.html +2 -2
- package/ui/dist-web/assets/index-C7bFrB-X.js +0 -163
|
@@ -0,0 +1,706 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Founding a project from cohorte ui (New project) — the company flow's first ticket, before there is a repo.
|
|
3
|
+
//
|
|
4
|
+
// an idea ──► PO conversation (/cohorte-vision) ──► vision + first-version tickets ──[Vision: the requester validates]
|
|
5
|
+
// (or a developer who knows what to build starts here)
|
|
6
|
+
// ──► lead conversation (/cohorte-foundation) ──► stack plan ──[Foundations: the developer validates]
|
|
7
|
+
// ──► /cohorte-scaffold: official generators, a walking skeleton, its checks green, committed
|
|
8
|
+
// ──► /cohorte-init-pipeline (answers from the approved plan) ──► PIPELINE.md, gate, agents — committed
|
|
9
|
+
// ──► done: the project is an ordinary cohorte project, its first-version tickets in the backlog.
|
|
10
|
+
//
|
|
11
|
+
// An existing folder without cohorte goes straight to the pipeline set-up step.
|
|
12
|
+
// The code host is never required: `remote()` / `connectRemote()` add one when the developer wants it.
|
|
13
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
14
|
+
if (k2 === undefined) k2 = k;
|
|
15
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
16
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
17
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
18
|
+
}
|
|
19
|
+
Object.defineProperty(o, k2, desc);
|
|
20
|
+
}) : (function(o, m, k, k2) {
|
|
21
|
+
if (k2 === undefined) k2 = k;
|
|
22
|
+
o[k2] = m[k];
|
|
23
|
+
}));
|
|
24
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
25
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
26
|
+
}) : function(o, v) {
|
|
27
|
+
o["default"] = v;
|
|
28
|
+
});
|
|
29
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
30
|
+
var ownKeys = function(o) {
|
|
31
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
32
|
+
var ar = [];
|
|
33
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
34
|
+
return ar;
|
|
35
|
+
};
|
|
36
|
+
return ownKeys(o);
|
|
37
|
+
};
|
|
38
|
+
return function (mod) {
|
|
39
|
+
if (mod && mod.__esModule) return mod;
|
|
40
|
+
var result = {};
|
|
41
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
42
|
+
__setModuleDefault(result, mod);
|
|
43
|
+
return result;
|
|
44
|
+
};
|
|
45
|
+
})();
|
|
46
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
47
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
48
|
+
};
|
|
49
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
50
|
+
exports.FoundingFlow = exports.FOUNDING_ROLES = void 0;
|
|
51
|
+
exports.visionMarkdown = visionMarkdown;
|
|
52
|
+
exports.scaffoldTools = scaffoldTools;
|
|
53
|
+
exports.withVcs = withVcs;
|
|
54
|
+
exports.parseRemote = parseRemote;
|
|
55
|
+
const fs_1 = __importDefault(require("fs"));
|
|
56
|
+
const os_1 = __importDefault(require("os"));
|
|
57
|
+
const path_1 = __importDefault(require("path"));
|
|
58
|
+
const child_process_1 = require("child_process");
|
|
59
|
+
const legacy_1 = require("./legacy");
|
|
60
|
+
const settings_1 = require("./settings");
|
|
61
|
+
const decider_1 = require("./decider");
|
|
62
|
+
const tracker_1 = require("./tracker");
|
|
63
|
+
const agents_1 = require("./agents");
|
|
64
|
+
const blocks_1 = require("../shared/blocks");
|
|
65
|
+
const gitinfo = __importStar(require("./gitinfo"));
|
|
66
|
+
const ops = __importStar(require("./ops"));
|
|
67
|
+
exports.FOUNDING_ROLES = ['vision', 'foundation', 'scaffold', 'setup'];
|
|
68
|
+
const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
69
|
+
const git = (cwd, ...a) => (0, child_process_1.spawnSync)('git', ['-C', cwd, ...a], { encoding: 'utf8', timeout: 30000 });
|
|
70
|
+
const expand = (p) => p.trim().replace(/^~(?=$|[\\/])/, os_1.default.homedir());
|
|
71
|
+
const isCohorte = (root) => fs_1.default.existsSync(path_1.default.join(root, 'PIPELINE.md')) && fs_1.default.existsSync(path_1.default.join(root, '.claude', 'pipeline.json'));
|
|
72
|
+
const IGNORED = new Set(['.git', 'node_modules', 'dist', 'build', 'out', 'coverage', '.next', '.nuxt', '.turbo', '.venv', 'venv', '__pycache__', 'target', '.idea', '.vscode', '.DS_Store', 'vendor', '.dart_tool']);
|
|
73
|
+
class FoundingStore {
|
|
74
|
+
dir;
|
|
75
|
+
constructor(dir) {
|
|
76
|
+
this.dir = dir;
|
|
77
|
+
}
|
|
78
|
+
file(id) { return path_1.default.join(this.dir, `${id.replace(/[^A-Za-z0-9._-]/g, '')}.json`); }
|
|
79
|
+
get(id) { try {
|
|
80
|
+
return JSON.parse(fs_1.default.readFileSync(this.file(id), 'utf8'));
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
return null;
|
|
84
|
+
} }
|
|
85
|
+
save(f) {
|
|
86
|
+
f.updatedAt = (0, agents_1.now)();
|
|
87
|
+
fs_1.default.mkdirSync(this.dir, { recursive: true });
|
|
88
|
+
const tmp = `${this.file(f.projectId)}.${process.pid}.tmp`;
|
|
89
|
+
fs_1.default.writeFileSync(tmp, JSON.stringify(f, null, 2) + '\n');
|
|
90
|
+
fs_1.default.renameSync(tmp, this.file(f.projectId));
|
|
91
|
+
}
|
|
92
|
+
list() {
|
|
93
|
+
let names = [];
|
|
94
|
+
try {
|
|
95
|
+
names = fs_1.default.readdirSync(this.dir).filter((n) => n.endsWith('.json'));
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
return [];
|
|
99
|
+
}
|
|
100
|
+
return names.map((n) => this.get(n.slice(0, -5))).filter((f) => !!f);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/** The vision as the product map's first version: what the product is FOR, before there is any code to describe. */
|
|
104
|
+
function visionMarkdown(v, name) {
|
|
105
|
+
const ul = (xs) => xs.map((x) => `- ${x}`).join('\n');
|
|
106
|
+
return [
|
|
107
|
+
`# ${v.name || name}`, '', `> ${v.pitch}`, '',
|
|
108
|
+
'_Written from the vision validated when the project was founded. `/cohorte-product-map` rewrites this file from the code once the product exists._', '',
|
|
109
|
+
'## Who it is for', '', ul(v.users), '', '## The problem', '', v.problem, '',
|
|
110
|
+
...(v.today ? ['## What they do today', '', v.today, ''] : []),
|
|
111
|
+
'## The first version', '', ul(v.firstVersion), '',
|
|
112
|
+
...(v.later.length ? ['## Later — deliberately not in the first version', '', ul(v.later), ''] : []),
|
|
113
|
+
...(v.success ? ['## How we will know it works', '', v.success, ''] : []),
|
|
114
|
+
...(v.constraints.length ? ['## Constraints', '', ul(v.constraints), ''] : []),
|
|
115
|
+
...(v.language ? [`Users' language: ${v.language}`, ''] : []),
|
|
116
|
+
].join('\n');
|
|
117
|
+
}
|
|
118
|
+
/** The tools the approved plan names, as permission rules the scaffold may use without asking. Never a shell, a fetcher or a remover. */
|
|
119
|
+
const NEVER = new Set(['rm', 'sudo', 'su', 'curl', 'wget', 'sh', 'bash', 'zsh', 'fish', 'chmod', 'chown', 'dd', 'mv', 'eval', 'exec', 'ssh', 'scp', 'git', 'docker', 'kill', 'pkill', 'open', 'xargs', 'env', 'cd', 'source', 'export', 'set']);
|
|
120
|
+
function scaffoldTools(plan) {
|
|
121
|
+
const out = new Set(['Bash(git init:*)', 'Bash(git status:*)', 'Bash(git add:*)', 'Bash(git commit:*)', 'Bash(git log:*)', 'Bash(git diff:*)',
|
|
122
|
+
'Bash(git rev-parse:*)', 'Bash(git branch:*)', 'Bash(cd:*)', 'Bash(mkdir:*)', 'Bash(ls:*)', 'Bash(pwd)', 'Bash(which:*)', 'Bash(cat:*)', 'Bash(echo:*)', 'Bash(test:*)', 'Bash(node --version)']);
|
|
123
|
+
const cmds = [plan.devCommand, ...plan.surfaces.flatMap((s) => [s.generate || '', s.test, s.lint, s.build, s.packageManager])];
|
|
124
|
+
for (const c of cmds) {
|
|
125
|
+
for (const seg of c.split(/&&|\|\||;|\|/)) {
|
|
126
|
+
const words = seg.trim().split(/\s+/).filter((w) => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(w));
|
|
127
|
+
const w = words[0];
|
|
128
|
+
if (!w || !/^[a-z][a-z0-9._-]{0,30}$/.test(w))
|
|
129
|
+
continue;
|
|
130
|
+
if (w === 'docker' && words[1] === 'compose') {
|
|
131
|
+
out.add('Bash(docker compose:*)');
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (NEVER.has(w))
|
|
135
|
+
continue;
|
|
136
|
+
out.add(`Bash(${w}:*)`);
|
|
137
|
+
if (['npm', 'pnpm', 'yarn', 'bun'].includes(w)) {
|
|
138
|
+
out.add('Bash(npx:*)');
|
|
139
|
+
out.add('Bash(node:*)');
|
|
140
|
+
}
|
|
141
|
+
if (w === 'uv')
|
|
142
|
+
out.add('Bash(uvx:*)');
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
if (/docker|compose/i.test(`${plan.data} ${plan.devCommand}`))
|
|
146
|
+
out.add('Bash(docker compose:*)');
|
|
147
|
+
return [...out];
|
|
148
|
+
}
|
|
149
|
+
/** A shallow listing of a project, for "start from one of my projects": the SHAPE, never the code. */
|
|
150
|
+
function tree(root, depth = 2, prefix = '') {
|
|
151
|
+
let names = [];
|
|
152
|
+
try {
|
|
153
|
+
names = fs_1.default.readdirSync(path_1.default.join(root, prefix), { withFileTypes: true });
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
return [];
|
|
157
|
+
}
|
|
158
|
+
const out = [];
|
|
159
|
+
for (const d of names.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
160
|
+
if (IGNORED.has(d.name) || (d.name.startsWith('.') && !['.github', '.claude', '.env.example', '.editorconfig'].includes(d.name)))
|
|
161
|
+
continue;
|
|
162
|
+
const rel = prefix ? `${prefix}/${d.name}` : d.name;
|
|
163
|
+
out.push(d.isDirectory() ? `${rel}/` : rel);
|
|
164
|
+
if (d.isDirectory() && depth > 1 && out.length < 150)
|
|
165
|
+
out.push(...tree(root, depth - 1, rel));
|
|
166
|
+
if (out.length >= 150)
|
|
167
|
+
break;
|
|
168
|
+
}
|
|
169
|
+
return out;
|
|
170
|
+
}
|
|
171
|
+
function manifests(root, dirs) {
|
|
172
|
+
const out = [];
|
|
173
|
+
for (const d of ['', ...dirs]) {
|
|
174
|
+
const pkg = path_1.default.join(root, d, 'package.json');
|
|
175
|
+
if (fs_1.default.existsSync(pkg)) {
|
|
176
|
+
try {
|
|
177
|
+
const j = JSON.parse((0, agents_1.readText)(pkg));
|
|
178
|
+
out.push(`${d || '.'}/package.json — scripts: ${Object.keys(j.scripts || {}).join(', ') || '(none)'}; dependencies: ${Object.keys(j.dependencies || {}).join(', ') || '(none)'}; devDependencies: ${Object.keys(j.devDependencies || {}).join(', ') || '(none)'}${j.packageManager ? `; packageManager: ${j.packageManager}` : ''}`);
|
|
179
|
+
}
|
|
180
|
+
catch { /* unreadable manifest: skipped */ }
|
|
181
|
+
}
|
|
182
|
+
for (const f of ['pyproject.toml', 'go.mod', 'Cargo.toml', 'pubspec.yaml', 'composer.json', 'Gemfile']) {
|
|
183
|
+
const t = (0, agents_1.readText)(path_1.default.join(root, d, f));
|
|
184
|
+
if (t)
|
|
185
|
+
out.push(`${d || '.'}/${f}:\n${t.split('\n').slice(0, 40).join('\n')}`);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
const compose = ['docker-compose.yml', 'docker-compose.yaml', 'compose.yml', 'compose.yaml'].map((f) => (0, agents_1.readText)(path_1.default.join(root, f))).find(Boolean);
|
|
189
|
+
if (compose)
|
|
190
|
+
out.push(`docker compose:\n${compose.split('\n').slice(0, 60).join('\n')}`);
|
|
191
|
+
return out;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* The profile's `vcs.host` / `vcs.remote`, rewritten in place in PIPELINE.md's machine block — so /cohorte-ship opens
|
|
195
|
+
* PRs on the host the developer just connected. Only those two lines change; null when the block has no `vcs:` key.
|
|
196
|
+
*/
|
|
197
|
+
function withVcs(md, host, remote) {
|
|
198
|
+
const lines = md.split('\n');
|
|
199
|
+
const at = lines.findIndex((l) => /^vcs:\s*(#.*)?$/.test(l));
|
|
200
|
+
if (at < 0)
|
|
201
|
+
return null;
|
|
202
|
+
let end = at + 1;
|
|
203
|
+
while (end < lines.length && (/^\s+\S/.test(lines[end]) || lines[end].trim() === ''))
|
|
204
|
+
end++;
|
|
205
|
+
const indent = (lines.slice(at + 1, end).find((l) => l.trim()) || ' x').match(/^(\s+)/)?.[1] || ' ';
|
|
206
|
+
const set = (key, value) => {
|
|
207
|
+
const i = lines.slice(at + 1, end).findIndex((l) => new RegExp(`^\\s+${key}:`).test(l));
|
|
208
|
+
if (i >= 0)
|
|
209
|
+
lines[at + 1 + i] = `${indent}${key}: ${value}`;
|
|
210
|
+
else {
|
|
211
|
+
lines.splice(at + 1, 0, `${indent}${key}: ${value}`);
|
|
212
|
+
end++;
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
set('remote', remote);
|
|
216
|
+
set('host', host);
|
|
217
|
+
return lines.join('\n');
|
|
218
|
+
}
|
|
219
|
+
/** `owner/repo` and the host kind of a remote URL (https, ssh or scp-like). */
|
|
220
|
+
function parseRemote(url) {
|
|
221
|
+
const m = url.match(/^(?:https:\/\/|ssh:\/\/(?:[^@/]+@)?|[^@\s]+@)([^/:]+)[/:](.+?)(?:\.git)?\/?$/);
|
|
222
|
+
const server = m ? m[1].toLowerCase() : '';
|
|
223
|
+
return { host: /(^|\.)github\.com$/.test(server) ? 'github' : /gitlab/.test(server) ? 'gitlab' : 'none', remote: m ? m[2] : '' };
|
|
224
|
+
}
|
|
225
|
+
class FoundingFlow {
|
|
226
|
+
d;
|
|
227
|
+
store;
|
|
228
|
+
constructor(d, dir) {
|
|
229
|
+
this.d = d;
|
|
230
|
+
this.store = new FoundingStore(dir);
|
|
231
|
+
}
|
|
232
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
233
|
+
// reads
|
|
234
|
+
phaseOf(projectId) {
|
|
235
|
+
const f = this.store.get(projectId);
|
|
236
|
+
return f && f.phase !== 'done' && f.phase !== 'abandoned' ? f.phase : null;
|
|
237
|
+
}
|
|
238
|
+
view(projectId) {
|
|
239
|
+
const f = this.store.get(projectId);
|
|
240
|
+
if (!f)
|
|
241
|
+
throw new agents_1.FlowError('this project is not being founded', 404);
|
|
242
|
+
return this.toView(f);
|
|
243
|
+
}
|
|
244
|
+
toView(f) {
|
|
245
|
+
const { visionRunId: _v, foundationRunId: _f, setupRunId: _s, scaffoldRuns: _n, ticketIds: _t, ...v } = f;
|
|
246
|
+
return { ...v, costUsd: Math.round(f.stages.reduce((a, s) => a + (s.costUsd || 0), 0) * 10000) / 10000 };
|
|
247
|
+
}
|
|
248
|
+
project(projectId) {
|
|
249
|
+
const p = legacy_1.registry.get(this.d.globalDir, projectId);
|
|
250
|
+
if (!p)
|
|
251
|
+
throw new agents_1.FlowError('unknown project', 404);
|
|
252
|
+
return p;
|
|
253
|
+
}
|
|
254
|
+
must(projectId) {
|
|
255
|
+
const f = this.store.get(projectId);
|
|
256
|
+
if (!f)
|
|
257
|
+
throw new agents_1.FlowError('this project is not being founded', 404);
|
|
258
|
+
return f;
|
|
259
|
+
}
|
|
260
|
+
phase(f, phase, error = null) {
|
|
261
|
+
f.phase = phase;
|
|
262
|
+
f.error = error;
|
|
263
|
+
this.store.save(f);
|
|
264
|
+
}
|
|
265
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
266
|
+
// start
|
|
267
|
+
/** New project: a folder (created, `git init`), registered as founding, and its first conversation started. */
|
|
268
|
+
async create(body) {
|
|
269
|
+
const mode = body.mode === 'idea' || body.mode === 'stack' || body.mode === 'existing' ? body.mode : (() => { throw new agents_1.FlowError('mode must be idea, stack or existing'); })();
|
|
270
|
+
const brief = typeof body.brief === 'string' ? body.brief.trim() : '';
|
|
271
|
+
if (brief.length > 8000)
|
|
272
|
+
throw new agents_1.FlowError('the brief is at most 8000 characters');
|
|
273
|
+
if (mode === 'idea' && !brief)
|
|
274
|
+
throw new agents_1.FlowError('say what the idea is — the product owner starts from it');
|
|
275
|
+
const requester = typeof body.requester === 'string' ? body.requester.trim().slice(0, 80) : '';
|
|
276
|
+
const basedOn = typeof body.basedOn === 'string' && body.basedOn ? body.basedOn : null;
|
|
277
|
+
if (basedOn && !legacy_1.registry.get(this.d.globalDir, basedOn))
|
|
278
|
+
throw new agents_1.FlowError('the project to start from is not registered', 400);
|
|
279
|
+
// Every command this path needs must be installed before anything is created.
|
|
280
|
+
for (const c of mode === 'existing' ? ['cohorte-init-pipeline'] : mode === 'stack' ? ['cohorte-foundation', 'cohorte-scaffold', 'cohorte-init-pipeline'] : ['cohorte-vision', 'cohorte-foundation', 'cohorte-scaffold', 'cohorte-init-pipeline']) {
|
|
281
|
+
(0, agents_1.expandCommand)(this.d.globalDir, c, '');
|
|
282
|
+
}
|
|
283
|
+
let root;
|
|
284
|
+
if (mode === 'existing') {
|
|
285
|
+
const want = typeof body.path === 'string' ? expand(body.path) : '';
|
|
286
|
+
if (!want || !path_1.default.isAbsolute(want))
|
|
287
|
+
throw new agents_1.FlowError('an absolute folder path is required');
|
|
288
|
+
if (!fs_1.default.existsSync(want) || !fs_1.default.statSync(want).isDirectory())
|
|
289
|
+
throw new agents_1.FlowError(`${want} is not a folder`);
|
|
290
|
+
root = want;
|
|
291
|
+
if (isCohorte(root))
|
|
292
|
+
throw new agents_1.FlowError('this folder already uses cohorte — add it instead', 409);
|
|
293
|
+
if (!git(root, 'rev-parse', '--show-toplevel').stdout?.trim())
|
|
294
|
+
throw new agents_1.FlowError('this folder is not a git repository — cohorte works on git repositories (run `git init` in it first)');
|
|
295
|
+
}
|
|
296
|
+
else {
|
|
297
|
+
const name = typeof body.name === 'string' ? body.name.trim() : '';
|
|
298
|
+
if (!NAME.test(name))
|
|
299
|
+
throw new agents_1.FlowError('the folder name is letters, digits, dot, dash or underscore (at most 64)');
|
|
300
|
+
const parent = typeof body.parent === 'string' ? expand(body.parent) : '';
|
|
301
|
+
if (!parent || !path_1.default.isAbsolute(parent))
|
|
302
|
+
throw new agents_1.FlowError('the parent folder must be an absolute path');
|
|
303
|
+
if (!fs_1.default.existsSync(parent) || !fs_1.default.statSync(parent).isDirectory())
|
|
304
|
+
throw new agents_1.FlowError(`${parent} is not a folder`);
|
|
305
|
+
root = path_1.default.join(parent, name);
|
|
306
|
+
if (fs_1.default.existsSync(root) && fs_1.default.readdirSync(root).length)
|
|
307
|
+
throw new agents_1.FlowError(`${root} already exists and is not empty`, 409);
|
|
308
|
+
fs_1.default.mkdirSync(root, { recursive: true });
|
|
309
|
+
if (git(root, 'init', '-q', '-b', 'main').status !== 0) {
|
|
310
|
+
if (git(root, 'init', '-q').status !== 0)
|
|
311
|
+
throw new agents_1.FlowError('git init failed — is git installed?', 500);
|
|
312
|
+
git(root, 'symbolic-ref', 'HEAD', 'refs/heads/main');
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
const { project } = legacy_1.registry.add(this.d.globalDir, root, { founding: true });
|
|
316
|
+
const s = this.d.settings.get(project.id);
|
|
317
|
+
if (requester && !s.requester)
|
|
318
|
+
this.d.settings.set(project.id, { requester });
|
|
319
|
+
const f = {
|
|
320
|
+
projectId: project.id, root: project.root, name: path_1.default.basename(project.root), mode, phase: mode === 'idea' ? 'vision' : mode === 'stack' ? 'foundation' : 'setup',
|
|
321
|
+
brief, basedOn, requester, vision: null, tickets: [], foundation: null, scaffold: null, currentRunId: null, stages: [], error: null, warning: null,
|
|
322
|
+
createdAt: (0, agents_1.now)(), updatedAt: (0, agents_1.now)(), costUsd: 0, visionRunId: null, foundationRunId: null, setupRunId: null, scaffoldRuns: 0, ticketIds: [],
|
|
323
|
+
};
|
|
324
|
+
this.store.save(f);
|
|
325
|
+
if (mode === 'idea')
|
|
326
|
+
this.startVision(f);
|
|
327
|
+
else if (mode === 'stack')
|
|
328
|
+
await this.startFoundation(f);
|
|
329
|
+
else
|
|
330
|
+
this.startSetup(f);
|
|
331
|
+
this.d.changed(project.id);
|
|
332
|
+
return { project, founding: this.toView(f) };
|
|
333
|
+
}
|
|
334
|
+
track(f, stage, run) {
|
|
335
|
+
f.stages.push({ stage, runId: run.id, model: run.model || '', status: 'running', costUsd: null, startedAt: run.startedAt, endedAt: null });
|
|
336
|
+
f.currentRunId = run.id;
|
|
337
|
+
this.store.save(f);
|
|
338
|
+
}
|
|
339
|
+
startVision(f) {
|
|
340
|
+
const s = this.d.settings.get(f.projectId);
|
|
341
|
+
const prompt = (0, agents_1.expandCommand)(this.d.globalDir, 'cohorte-vision', f.brief) + (0, agents_1.contextBlock)([
|
|
342
|
+
`Project: ${f.name} (a new product — there is no code yet)`, 'Talk in: the language the person writes in',
|
|
343
|
+
`The person: ${f.requester || s.requester || 'the person with the idea'}`,
|
|
344
|
+
]);
|
|
345
|
+
const run = this.d.runs.start({ ...(0, agents_1.mcp)(f.root), projectId: f.projectId, cwd: f.root, command: '/cohorte-vision', prompt, model: s.models.po, disallowedTools: agents_1.READ_ONLY, echo: f.brief,
|
|
346
|
+
meta: { role: 'vision', title: `Vision · ${f.name}` } });
|
|
347
|
+
f.visionRunId = run.id;
|
|
348
|
+
this.track(f, 'vision', run);
|
|
349
|
+
this.phase(f, 'vision');
|
|
350
|
+
}
|
|
351
|
+
async machine() {
|
|
352
|
+
const tools = [['node', ['--version']], ['npm', ['--version']], ['pnpm', ['--version']], ['yarn', ['--version']], ['bun', ['--version']],
|
|
353
|
+
['python3', ['--version']], ['uv', ['--version']], ['docker', ['--version']], ['go', ['version']], ['cargo', ['--version']], ['java', ['-version']], ['flutter', ['--version']],
|
|
354
|
+
[process.env.COHORTE_GH_BIN || 'gh', ['--version']]];
|
|
355
|
+
const rs = await Promise.all(tools.map(([t, a]) => gitinfo.probe(t, a, os_1.default.homedir(), 5000)));
|
|
356
|
+
return tools.map(([t], i) => {
|
|
357
|
+
const r = rs[i];
|
|
358
|
+
const v = `${r.out}\n${r.err}`.split('\n').map((x) => x.trim()).find(Boolean) || '';
|
|
359
|
+
return `- ${path_1.default.basename(t)}: ${r.code === 0 ? v.slice(0, 80) : 'not installed'}`;
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
others(f) {
|
|
363
|
+
const out = [];
|
|
364
|
+
for (const p of legacy_1.registry.load(this.d.globalDir)) {
|
|
365
|
+
if (p.id === f.projectId || !fs_1.default.existsSync(p.root) || this.phaseOf(p.id))
|
|
366
|
+
continue;
|
|
367
|
+
const prof = ops.readProfile(p.root);
|
|
368
|
+
const surf = Array.isArray(prof.surfaces) ? prof.surfaces.map((x) => `${x.key}${x.label ? ` (${x.label})` : ''} at ${x.path}${x.test_cmd ? `, tests: ${x.test_cmd}` : ''}`).join('; ') : '';
|
|
369
|
+
out.push(`- ${prof.name || path_1.default.basename(p.root)} [id ${p.id}]${prof.project?.kind ? ` · ${prof.project.kind}` : ''}${prof.package_manager ? ` · ${prof.package_manager}` : ''}${surf ? ` — ${surf}` : ''}`);
|
|
370
|
+
if (out.length >= 15)
|
|
371
|
+
break;
|
|
372
|
+
}
|
|
373
|
+
return out;
|
|
374
|
+
}
|
|
375
|
+
basedOnBlock(f) {
|
|
376
|
+
if (!f.basedOn)
|
|
377
|
+
return [];
|
|
378
|
+
const p = legacy_1.registry.get(this.d.globalDir, f.basedOn);
|
|
379
|
+
if (!p || !fs_1.default.existsSync(p.root))
|
|
380
|
+
return [];
|
|
381
|
+
const prof = ops.readProfile(p.root);
|
|
382
|
+
const dirs = Array.isArray(prof.surfaces) ? prof.surfaces.map((x) => String(x.path || '')).filter((x) => x && !x.includes('..')) : [];
|
|
383
|
+
const surfaces = Array.isArray(prof.surfaces) ? prof.surfaces.map((x) => {
|
|
384
|
+
const cmds = Object.entries(x).filter(([k]) => k.endsWith('_cmd')).map(([k, v]) => `${k}=${v}`).join(', ');
|
|
385
|
+
return `- ${x.key} at ${x.path}${x.label ? ` — ${x.label}` : ''}${cmds ? ` (${cmds})` : ''}`;
|
|
386
|
+
}) : [];
|
|
387
|
+
const conventions = (0, decider_1.conventionsOf)((0, agents_1.readText)(path_1.default.join(p.root, 'PIPELINE.md')));
|
|
388
|
+
return [
|
|
389
|
+
'', `START FROM THIS PROJECT — the developer asked for the same shape: "${prof.name || path_1.default.basename(p.root)}". Follow its structure, tooling and conventions; copy none of its business code.`,
|
|
390
|
+
`Kind: ${prof.project?.kind || '?'} · package manager: ${prof.package_manager || '?'} · layout: ${prof.repo?.layout || '?'}`,
|
|
391
|
+
'Its surfaces:', ...(surfaces.length ? surfaces : ['(none declared)']),
|
|
392
|
+
'Its files (two levels):', ...tree(p.root).map((x) => ` ${x}`),
|
|
393
|
+
'Its manifests:', ...manifests(p.root, dirs).map((x) => x.slice(0, 3000)),
|
|
394
|
+
'Its conventions (PIPELINE.md §Conventions):', conventions ? conventions.slice(0, 8000) : '(none)',
|
|
395
|
+
];
|
|
396
|
+
}
|
|
397
|
+
async startFoundation(f) {
|
|
398
|
+
const s = this.d.settings.get(f.projectId);
|
|
399
|
+
const vision = f.vision ? JSON.stringify(f.vision, null, 2) : null;
|
|
400
|
+
const prompt = (0, agents_1.expandCommand)(this.d.globalDir, 'cohorte-foundation', f.brief || (f.vision ? '(see the vision below)' : '(no brief — ask the developer what they want to build)')) + (0, agents_1.contextBlock)([
|
|
401
|
+
`Project: ${f.name} — folder ${f.root} (empty but for PRODUCT.md when there is a vision)`,
|
|
402
|
+
'Talk in: the language the developer writes in',
|
|
403
|
+
'', vision ? 'THE VISION (validated by the business):' : 'No vision: the developer starts from the brief above.', ...(vision ? [vision] : []),
|
|
404
|
+
...(f.tickets.length ? ['', 'The first version\'s tickets (built later, one at a time — NOT by the skeleton):', ...f.tickets.map((t) => `- ${t.title}`)] : []),
|
|
405
|
+
'', 'Installed on this machine:', ...(await this.machine()),
|
|
406
|
+
'', "The developer's other projects (default to what they already use):", ...(this.others(f).length ? this.others(f) : ['(none registered)']),
|
|
407
|
+
...this.basedOnBlock(f),
|
|
408
|
+
]);
|
|
409
|
+
const run = this.d.runs.start({ ...(0, agents_1.mcp)(f.root), projectId: f.projectId, cwd: f.root, command: '/cohorte-foundation', prompt, model: s.models.lead, disallowedTools: agents_1.READ_ONLY,
|
|
410
|
+
echo: f.brief && !f.vision ? f.brief : undefined, meta: { role: 'foundation', title: `Foundations · ${f.name}` } });
|
|
411
|
+
f.foundationRunId = run.id;
|
|
412
|
+
this.track(f, 'foundation', run);
|
|
413
|
+
this.phase(f, 'foundation');
|
|
414
|
+
}
|
|
415
|
+
startScaffold(f, note = '') {
|
|
416
|
+
if (!f.foundation)
|
|
417
|
+
throw new agents_1.FlowError('there is no approved foundations plan');
|
|
418
|
+
const s = this.d.settings.get(f.projectId);
|
|
419
|
+
let model = s.models.scaffold;
|
|
420
|
+
for (let i = 0; i < f.scaffoldRuns; i++)
|
|
421
|
+
model = (0, settings_1.escalate)(model); // a retry climbs one model per attempt
|
|
422
|
+
const prompt = (0, agents_1.expandCommand)(this.d.globalDir, 'cohorte-scaffold', '') + (0, agents_1.contextBlock)([
|
|
423
|
+
`Project root: ${f.root} (git initialised, branch main)${fs_1.default.existsSync(path_1.default.join(f.root, 'PRODUCT.md')) ? ' — PRODUCT.md holds the validated vision' : ''}`,
|
|
424
|
+
'', 'THE APPROVED FOUNDATIONS PLAN:', JSON.stringify(f.foundation, null, 2),
|
|
425
|
+
...this.basedOnBlock(f),
|
|
426
|
+
...(note ? ['', `The developer adds: ${note}`] : []),
|
|
427
|
+
...(f.scaffoldRuns > 0 ? ['', 'A previous scaffold attempt stopped in this folder: read what is already there, keep what works, finish the job.'] : []),
|
|
428
|
+
]) + (0, agents_1.AUTOPILOT_NOTE)(null);
|
|
429
|
+
const run = this.d.runs.start({ ...(0, agents_1.mcp)(f.root), projectId: f.projectId, cwd: f.root, command: '/cohorte-scaffold', prompt, model, permissionMode: 'acceptEdits',
|
|
430
|
+
allowedTools: scaffoldTools(f.foundation), meta: { role: 'scaffold', title: `Skeleton · ${f.name}` } });
|
|
431
|
+
f.scaffoldRuns += 1;
|
|
432
|
+
this.track(f, 'scaffold', run);
|
|
433
|
+
this.phase(f, 'scaffold');
|
|
434
|
+
}
|
|
435
|
+
startSetup(f) {
|
|
436
|
+
const s = this.d.settings.get(f.projectId);
|
|
437
|
+
const founded = f.mode !== 'existing';
|
|
438
|
+
const lines = founded ? [
|
|
439
|
+
`This project was founded in cohorte ui a moment ago: ${f.root}. The developer APPROVED its foundations (the plan below) and the skeleton is committed.`,
|
|
440
|
+
'- Detect as usual, but treat everything the plan settles as already confirmed: do not re-ask the project kind, the surfaces, their paths or their commands.',
|
|
441
|
+
'- Ask (AskUserQuestion, recommended option first) only what neither the plan nor the code settles.',
|
|
442
|
+
'- The Phase 3 go-ahead: the developer gave it by approving the plan. Show the draft in your reply and go on to Phase 4 in the same turn.',
|
|
443
|
+
"- Carry the plan's `conventions` into PIPELINE.md §Conventions.",
|
|
444
|
+
fs_1.default.existsSync(path_1.default.join(f.root, 'PRODUCT.md')) ? '- PRODUCT.md exists (the validated vision): use it for the one-liner; leave it as it is.' : '',
|
|
445
|
+
'', 'THE APPROVED FOUNDATIONS PLAN:', JSON.stringify(f.foundation, null, 2),
|
|
446
|
+
...(f.scaffold ? ['', 'THE SKELETON REPORT:', JSON.stringify(f.scaffold, null, 2)] : []),
|
|
447
|
+
] : [
|
|
448
|
+
`Running inside cohorte ui for an existing repository that does not use cohorte yet: ${f.root}.`,
|
|
449
|
+
'- Ask through AskUserQuestion (recommended option first). A free-text question ends your turn: the developer answers in the dashboard.',
|
|
450
|
+
];
|
|
451
|
+
const prompt = (0, agents_1.expandCommand)(this.d.globalDir, 'cohorte-init-pipeline', '') + (0, agents_1.contextBlock)([
|
|
452
|
+
...lines.filter((x) => x !== ''),
|
|
453
|
+
'- Read the pipeline core\'s files (templates, schema, steps) with the Read tool — the folder is readable — never with cat/ls through Bash: every Bash call outside the allowed ones stops for the developer\'s permission. Run <sync> exactly as written, alone, from the repo root. Never write inside the core folder.',
|
|
454
|
+
'- Never recommend `/clear`, and never tell anyone to run a command next: cohorte ui takes over when you end.',
|
|
455
|
+
]);
|
|
456
|
+
const run = this.d.runs.start({ ...(0, agents_1.mcp)(f.root), projectId: f.projectId, cwd: f.root, command: '/cohorte-init-pipeline', prompt, model: s.models.setup, permissionMode: 'acceptEdits',
|
|
457
|
+
allowedTools: [...this.syncRule(), 'Bash(git status:*)', 'Bash(git ls-files:*)', 'Bash(git log:*)', 'Bash(git remote:*)', 'Bash(ls:*)', 'Bash(cat:*)'],
|
|
458
|
+
addDirs: [path_1.default.join(this.d.globalDir, 'cohorte')], meta: { role: 'setup', title: `Pipeline set-up · ${f.name}` } });
|
|
459
|
+
f.setupRunId = run.id;
|
|
460
|
+
this.track(f, 'setup', run);
|
|
461
|
+
this.phase(f, 'setup');
|
|
462
|
+
}
|
|
463
|
+
/** `<sync>` exactly as the installed /cohorte-init-pipeline spells it (it depends on where cohorte is installed). */
|
|
464
|
+
syncRule() {
|
|
465
|
+
const m = (0, agents_1.readText)(path_1.default.join(this.d.globalDir, 'commands', 'cohorte-init-pipeline.md')).match(/`<sync>` = `([^`]+)`/);
|
|
466
|
+
const cmd = m ? m[1].trim().replace(/\s+\.$/, '') : '';
|
|
467
|
+
return cmd && !/[(),\r\n]/.test(cmd) ? [`Bash(${cmd}:*)`] : [];
|
|
468
|
+
}
|
|
469
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
470
|
+
// the person's moves
|
|
471
|
+
/** A message to whichever agent the founding is talking with. */
|
|
472
|
+
reply(projectId, text) {
|
|
473
|
+
const f = this.must(projectId);
|
|
474
|
+
const t = typeof text === 'string' ? text.trim() : '';
|
|
475
|
+
if (!t)
|
|
476
|
+
throw new agents_1.FlowError('a message is required');
|
|
477
|
+
const target = {
|
|
478
|
+
vision: [f.visionRunId, 'vision'], 'cp-vision': [f.visionRunId, 'vision'], foundation: [f.foundationRunId, 'foundation'], 'cp-foundation': [f.foundationRunId, 'foundation'],
|
|
479
|
+
setup: [f.setupRunId, 'setup'], scaffold: [f.currentRunId, 'scaffold'], 'cp-scaffold': [f.currentRunId, 'scaffold'],
|
|
480
|
+
};
|
|
481
|
+
const [runId, next] = target[f.phase] || [null, f.phase];
|
|
482
|
+
const run = runId ? this.d.runs.get(runId) : null;
|
|
483
|
+
if (!run)
|
|
484
|
+
throw new agents_1.FlowError(`nothing to answer in this step (${f.phase})`, 409);
|
|
485
|
+
const err = this.d.runs.reply(run, t);
|
|
486
|
+
if (err)
|
|
487
|
+
throw new agents_1.FlowError(err, 409);
|
|
488
|
+
const st = f.stages.find((x) => x.runId === run.id);
|
|
489
|
+
if (st) {
|
|
490
|
+
st.status = 'running';
|
|
491
|
+
st.endedAt = null;
|
|
492
|
+
}
|
|
493
|
+
f.currentRunId = run.id;
|
|
494
|
+
this.phase(f, next);
|
|
495
|
+
this.d.changed(projectId);
|
|
496
|
+
return this.toView(f);
|
|
497
|
+
}
|
|
498
|
+
async checkpoint(projectId, body) {
|
|
499
|
+
const f = this.must(projectId);
|
|
500
|
+
const text = typeof body.text === 'string' ? body.text.trim().slice(0, 4000) : '';
|
|
501
|
+
const action = body.action;
|
|
502
|
+
if (action === 'abandon') {
|
|
503
|
+
const run = f.currentRunId ? this.d.runs.get(f.currentRunId) : null;
|
|
504
|
+
if (run && run.status === 'running')
|
|
505
|
+
this.d.runs.stop(run);
|
|
506
|
+
this.phase(f, 'abandoned');
|
|
507
|
+
this.d.changed(projectId);
|
|
508
|
+
return this.toView(f);
|
|
509
|
+
}
|
|
510
|
+
if (action === 'reply')
|
|
511
|
+
return this.reply(projectId, text);
|
|
512
|
+
if (f.phase === 'cp-vision' && action === 'approve') {
|
|
513
|
+
if (!f.vision)
|
|
514
|
+
throw new agents_1.FlowError('there is no vision to approve', 409);
|
|
515
|
+
fs_1.default.writeFileSync(path_1.default.join(f.root, 'PRODUCT.md'), visionMarkdown(f.vision, f.name));
|
|
516
|
+
await this.startFoundation(f);
|
|
517
|
+
}
|
|
518
|
+
else if (f.phase === 'cp-foundation' && action === 'approve') {
|
|
519
|
+
if (!f.foundation)
|
|
520
|
+
throw new agents_1.FlowError('there is no plan to approve', 409);
|
|
521
|
+
this.startScaffold(f, text);
|
|
522
|
+
}
|
|
523
|
+
else if (f.phase === 'cp-scaffold' && action === 'retry') {
|
|
524
|
+
this.startScaffold(f, text);
|
|
525
|
+
}
|
|
526
|
+
else if (f.phase === 'cp-scaffold' && action === 'continue') {
|
|
527
|
+
if (git(f.root, 'rev-parse', '--verify', '-q', 'HEAD').status !== 0)
|
|
528
|
+
throw new agents_1.FlowError('nothing is committed yet — retry the skeleton, or commit it yourself first', 409);
|
|
529
|
+
this.startSetup(f);
|
|
530
|
+
}
|
|
531
|
+
else if (f.phase === 'setup' && action === 'retry') {
|
|
532
|
+
this.startSetup(f);
|
|
533
|
+
}
|
|
534
|
+
else {
|
|
535
|
+
throw new agents_1.FlowError(`"${String(action)}" is not possible while the project is in ${f.phase}`, 409);
|
|
536
|
+
}
|
|
537
|
+
this.d.changed(projectId);
|
|
538
|
+
return this.toView(f);
|
|
539
|
+
}
|
|
540
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
541
|
+
// run ends
|
|
542
|
+
async onEnd(r) {
|
|
543
|
+
const f = this.store.get(r.projectId);
|
|
544
|
+
if (!f || f.phase === 'abandoned' || f.phase === 'done')
|
|
545
|
+
return;
|
|
546
|
+
const st = f.stages.find((x) => x.runId === r.id);
|
|
547
|
+
if (st) {
|
|
548
|
+
st.status = r.status;
|
|
549
|
+
st.costUsd = (st.costUsd || 0) + (r.result?.costUsd ?? 0);
|
|
550
|
+
st.endedAt = r.endedAt;
|
|
551
|
+
}
|
|
552
|
+
if (f.currentRunId === r.id)
|
|
553
|
+
f.currentRunId = null;
|
|
554
|
+
const failed = r.status !== 'done' ? `the ${r.meta.role} run ${r.status}${r.result?.text ? `: ${r.result.text.slice(0, 300)}` : ''}` : null;
|
|
555
|
+
const texts = (0, agents_1.textsOf)(r.events);
|
|
556
|
+
if (r.meta.role === 'vision') {
|
|
557
|
+
const v = (0, blocks_1.lastOf)(texts, 'cohorte-vision', blocks_1.toVision);
|
|
558
|
+
if (v) {
|
|
559
|
+
f.vision = v;
|
|
560
|
+
f.tickets = (0, blocks_1.proposalsOf)(texts);
|
|
561
|
+
}
|
|
562
|
+
this.phase(f, v && !failed ? 'cp-vision' : 'vision', failed);
|
|
563
|
+
}
|
|
564
|
+
else if (r.meta.role === 'foundation') {
|
|
565
|
+
const plan = (0, blocks_1.lastOf)(texts, 'cohorte-foundation', blocks_1.toFoundation);
|
|
566
|
+
if (plan)
|
|
567
|
+
f.foundation = plan;
|
|
568
|
+
this.phase(f, plan && !plan.questions.length && !failed ? 'cp-foundation' : 'foundation', failed);
|
|
569
|
+
}
|
|
570
|
+
else if (r.meta.role === 'scaffold') {
|
|
571
|
+
const rep = (0, blocks_1.lastOf)(texts, 'cohorte-scaffold', blocks_1.toScaffold);
|
|
572
|
+
if (rep)
|
|
573
|
+
f.scaffold = rep;
|
|
574
|
+
const committed = git(f.root, 'rev-parse', '--verify', '-q', 'HEAD').status === 0;
|
|
575
|
+
if (!failed && rep?.status === 'ok' && committed) {
|
|
576
|
+
this.store.save(f);
|
|
577
|
+
try {
|
|
578
|
+
this.startSetup(f);
|
|
579
|
+
}
|
|
580
|
+
catch (e) {
|
|
581
|
+
this.phase(f, 'cp-scaffold', `the pipeline set-up could not start: ${String(e.message || e)}`);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
else {
|
|
585
|
+
const why = failed || (!rep ? 'the skeleton run ended without its report — answer it, or retry' : rep.status !== 'ok' ? `the skeleton's checks failed${rep.notes ? `: ${rep.notes.slice(0, 300)}` : ''}` : 'the skeleton was not committed');
|
|
586
|
+
this.phase(f, 'cp-scaffold', why);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
else if (r.meta.role === 'setup') {
|
|
590
|
+
if (!failed && isCohorte(f.root))
|
|
591
|
+
await this.finish(f);
|
|
592
|
+
else
|
|
593
|
+
this.phase(f, 'setup', failed);
|
|
594
|
+
}
|
|
595
|
+
this.d.changed(r.projectId);
|
|
596
|
+
}
|
|
597
|
+
/** The pipeline is set up: commit it (a new project only), file the first version's tickets, and hand over to the company flow. */
|
|
598
|
+
async finish(f) {
|
|
599
|
+
if (f.mode !== 'existing' && (git(f.root, 'status', '--porcelain').stdout || '').trim()) {
|
|
600
|
+
git(f.root, 'add', '-A');
|
|
601
|
+
const c = git(f.root, 'commit', '-q', '-m', 'chore: set up the cohorte pipeline');
|
|
602
|
+
if (c.status !== 0)
|
|
603
|
+
f.warning = `the pipeline files could not be committed: ${(c.stderr || '').trim().slice(0, 300)}`;
|
|
604
|
+
}
|
|
605
|
+
else if (f.mode === 'existing') {
|
|
606
|
+
f.warning = 'The pipeline files are written but not committed — review them and commit them with your own message.';
|
|
607
|
+
}
|
|
608
|
+
if (f.tickets.length && !f.ticketIds.length) {
|
|
609
|
+
try {
|
|
610
|
+
const p = this.project(f.projectId);
|
|
611
|
+
const tr = (0, tracker_1.trackerFor)(this.d.globalDir, p.root, p.id);
|
|
612
|
+
const requester = f.requester || this.d.settings.get(p.id).requester;
|
|
613
|
+
for (const prop of f.tickets) {
|
|
614
|
+
const t = tr.create(prop, { status: 'backlog', requester, conversation: f.visionRunId, parent: null });
|
|
615
|
+
f.ticketIds.push(t.id);
|
|
616
|
+
await tr.move(t);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
catch (e) {
|
|
620
|
+
f.warning = `${f.warning ? `${f.warning}\n` : ''}the first version's tickets could not be filed: ${String(e.message || e)}`;
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
this.phase(f, 'done');
|
|
624
|
+
}
|
|
625
|
+
/** After a restart nothing is running: a founding mid-run waits for the developer instead of guessing. */
|
|
626
|
+
recover() {
|
|
627
|
+
for (const f of this.store.list()) {
|
|
628
|
+
if (!['vision', 'foundation', 'scaffold', 'setup'].includes(f.phase))
|
|
629
|
+
continue;
|
|
630
|
+
const r = f.currentRunId ? this.d.runs.get(f.currentRunId) : null;
|
|
631
|
+
if (r && r.status === 'running')
|
|
632
|
+
continue;
|
|
633
|
+
for (const s of f.stages)
|
|
634
|
+
if (s.status === 'running')
|
|
635
|
+
s.status = 'stopped';
|
|
636
|
+
f.currentRunId = null;
|
|
637
|
+
if (f.phase === 'scaffold')
|
|
638
|
+
this.phase(f, 'cp-scaffold', 'cohorte ui restarted while the skeleton was being generated — retry to resume');
|
|
639
|
+
else {
|
|
640
|
+
f.error = 'cohorte ui restarted during this step — send a message to resume the conversation';
|
|
641
|
+
this.store.save(f);
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
// -------------------------------------------------------------------------------------------------------------
|
|
646
|
+
// the code host — never required, one click when wanted
|
|
647
|
+
async remote(projectId) { return gitinfo.remoteInfo(this.project(projectId).root); }
|
|
648
|
+
/**
|
|
649
|
+
* `github`: `gh repo create <name> --private|--public --source . --remote origin --push`.
|
|
650
|
+
* `url`: an existing empty repository anywhere (GitLab, Gitea…): `git remote add origin <url>`, then push.
|
|
651
|
+
*/
|
|
652
|
+
async connectRemote(projectId, body) {
|
|
653
|
+
const p = this.project(projectId);
|
|
654
|
+
const info = await gitinfo.remoteInfo(p.root);
|
|
655
|
+
if (info.origin)
|
|
656
|
+
throw new agents_1.FlowError(`this project already has a remote: ${info.origin}`, 409);
|
|
657
|
+
if (git(p.root, 'rev-parse', '--verify', '-q', 'HEAD').status !== 0)
|
|
658
|
+
throw new agents_1.FlowError('there is no commit to push yet', 409);
|
|
659
|
+
if (body.kind === 'github') {
|
|
660
|
+
if (!info.gh.installed)
|
|
661
|
+
throw new agents_1.FlowError('the GitHub CLI (gh) is not installed — install it from https://cli.github.com, or paste the URL of a repository you created yourself', 400);
|
|
662
|
+
if (!info.gh.authed)
|
|
663
|
+
throw new agents_1.FlowError('gh is not signed in — run `gh auth login` in a terminal once, then try again', 400);
|
|
664
|
+
const name = typeof body.name === 'string' ? body.name.trim() : '';
|
|
665
|
+
if (!/^([A-Za-z0-9_.-]{1,100}\/)?[A-Za-z0-9_.-]{1,100}$/.test(name))
|
|
666
|
+
throw new agents_1.FlowError('the repository name is [owner/]name (letters, digits, . _ -)');
|
|
667
|
+
const vis = body.visibility === 'public' ? '--public' : body.visibility === 'internal' ? '--internal' : '--private';
|
|
668
|
+
this.pointProfile(p, 'github', name.includes('/') ? name : `${info.gh.user}/${name}`);
|
|
669
|
+
return this.d.jobs.start({ projectId: p.id, kind: 'remote', tag: 'github', label: `GitHub · ${name}`, cwd: p.root, file: process.env.COHORTE_GH_BIN || 'gh',
|
|
670
|
+
args: ['repo', 'create', name, vis, '--source', '.', '--remote', 'origin', '--push'] });
|
|
671
|
+
}
|
|
672
|
+
if (body.kind === 'url') {
|
|
673
|
+
const url = typeof body.url === 'string' ? body.url.trim() : '';
|
|
674
|
+
if (!/^(https:\/\/[^\s'"`]+|ssh:\/\/[^\s'"`]+|[A-Za-z0-9._-]+@[A-Za-z0-9.-]+:[^\s'"`]+)$/.test(url) || url.length > 300)
|
|
675
|
+
throw new agents_1.FlowError('paste the repository URL (https://…, ssh://… or git@host:owner/repo.git)');
|
|
676
|
+
const add = git(p.root, 'remote', 'add', 'origin', url);
|
|
677
|
+
if (add.status !== 0)
|
|
678
|
+
throw new agents_1.FlowError(`git remote add failed: ${(add.stderr || '').trim()}`, 400);
|
|
679
|
+
const r = parseRemote(url);
|
|
680
|
+
if (r.remote)
|
|
681
|
+
this.pointProfile(p, r.host, r.remote);
|
|
682
|
+
const branch = info.branch && info.branch !== 'HEAD' ? info.branch : 'main';
|
|
683
|
+
return this.d.jobs.start({ projectId: p.id, kind: 'remote', tag: 'url', label: `push · ${url}`, cwd: p.root, file: 'git', args: ['push', '-u', 'origin', branch] });
|
|
684
|
+
}
|
|
685
|
+
throw new agents_1.FlowError('kind must be github or url');
|
|
686
|
+
}
|
|
687
|
+
/** Before the first push: the profile names the new host, `cohorte sync` refreshes profile.json, and both are committed. */
|
|
688
|
+
pointProfile(p, host, remote) {
|
|
689
|
+
const file = path_1.default.join(p.root, 'PIPELINE.md');
|
|
690
|
+
const md = (0, agents_1.readText)(file);
|
|
691
|
+
const next = md ? withVcs(md, host, remote) : null;
|
|
692
|
+
if (!next || next === md)
|
|
693
|
+
return;
|
|
694
|
+
fs_1.default.writeFileSync(file, next);
|
|
695
|
+
try {
|
|
696
|
+
legacy_1.project.sync(p.root);
|
|
697
|
+
}
|
|
698
|
+
catch { /* the doctor reports a stale profile.json */ }
|
|
699
|
+
const dirty = (git(p.root, 'status', '--porcelain').stdout || '').trim();
|
|
700
|
+
if (dirty && git(p.root, 'diff', '--cached', '--quiet').status === 0) {
|
|
701
|
+
git(p.root, 'add', 'PIPELINE.md', '.claude/profile.json');
|
|
702
|
+
git(p.root, 'commit', '-q', '-m', `chore: point the pipeline at ${remote}`);
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
exports.FoundingFlow = FoundingFlow;
|