create-ombutocode 0.2.16 → 1.0.1

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 (2) hide show
  1. package/bin/create-ombutocode.js +1206 -1171
  2. package/package.json +31 -31
@@ -1,1171 +1,1206 @@
1
- #!/usr/bin/env node
2
-
3
- const fs = require('fs');
4
- const os = require('os');
5
- const path = require('path');
6
- const zlib = require('zlib');
7
- const { execSync } = require('child_process');
8
-
9
- const REPO_URL = 'https://github.com/FrancoisBotha/ombutocode.git';
10
- // Installer version is kept in lockstep with the workbench version
11
- // (.ombutocode/src/package.json) — every workbench release bumps both
12
- // to the same number. See DeployInstructions.md §3 and §3.0.
13
- const VERSION = '0.2.16';
14
-
15
- // Pinned Ombuto Code workbench release to clone.
16
- //
17
- // This installer version ships paired with a specific, tested release of
18
- // the workbench — not the tip of main — so that every `npx create-ombutocode`
19
- // run is reproducible. To ship a new workbench release to users:
20
- //
21
- // 1. Tag and release the workbench on GitHub (see DeployInstructions.md §2)
22
- // 2. Bump CLONE_REF below to the new tag
23
- // 3. Bump this installer's VERSION (above) and the package.json version
24
- // 4. `npm publish` the installer (see DeployInstructions.md §3)
25
- const CLONE_REF = 'v0.2.16';
26
-
27
- // Files and directories at the repo root that belong to the Ombuto Code
28
- // upstream project and should be removed from a scaffolded user project.
29
- //
30
- // Two categories:
31
- //
32
- // 1. Maintainer docs — describe how to contribute to / release Ombuto Code
33
- // itself, not anything the user's new project should inherit.
34
- //
35
- // 2. Sample / demo app files — the upstream repo contains an example
36
- // Electron + Vue app at the repo root (DropSync) that is used as a
37
- // test bed for the workbench. It is NOT meant to be a starter template
38
- // for user projects, so it is stripped too.
39
- const UPSTREAM_FILES_TO_STRIP = [
40
- // Maintainer docs
41
- 'README.md',
42
- 'CLA.md',
43
- 'CONTRIBUTING.md',
44
- 'DeployInstructions.md',
45
- 'UPGRADING.md',
46
- 'CLAUDE.md',
47
- 'LICENSE', // upstream Apache 2.0 lives under .ombutocode/LICENSE
48
-
49
- // Sample / demo app at the repo root (not a user-facing starter)
50
- 'src',
51
- 'scripts',
52
- 'package.json',
53
- 'package-lock.json',
54
- 'vite.config.js',
55
- 'eslint.config.js',
56
- 'tsconfig.json',
57
-
58
- // Maintainer-only tooling & content — not part of what a user's new project needs
59
- 'migration-tool',
60
- 'marketing',
61
- ];
62
-
63
- // Files in create-ombutocode/template/ that are copied into the scaffolded
64
- // project after stripping. Any occurrence of {{PROJECT_NAME}} in these
65
- // files is substituted with the user's project name at copy time.
66
- const TEMPLATE_FILES = [
67
- 'README.md',
68
- 'CLAUDE.md',
69
- 'GettingStarted.md',
70
- ];
71
-
72
- // Root .gitignore entries an adopted project needs so the workbench's
73
- // dependencies and build output never get committed. Runtime state under
74
- // .ombutocode/ (databases, logs, run output) is covered by the
75
- // .ombutocode/.gitignore that ships with the clone.
76
- const OMBUTO_GITIGNORE_LINES = [
77
- '.ombutocode/src/node_modules/',
78
- '.ombutocode/src/release/',
79
- '.ombutocode/src/dist/',
80
- ];
81
-
82
- // ── Upgrade contract ──
83
- //
84
- // `--upgrade` replaces the workbench code inside an existing project's
85
- // .ombutocode/ with the pinned release and leaves everything else alone.
86
- // These lists are the "Overwrite with the new release" / "Preserve" tables
87
- // in UPGRADING.md. The upgrade only ever deletes or writes the paths named
88
- // in UPGRADE_REPLACE_*; nothing under .ombutocode/ is wiped wholesale, so a
89
- // file that is in neither list is simply left as it was.
90
-
91
- // Directories replaced wholesale: the old one is deleted (src/ including
92
- // its node_modules) and the release's copy moved in.
93
- const UPGRADE_REPLACE_DIRS = ['src', 'tools', 'templates', 'scripts', 'bench'];
94
-
95
- // Plain files replaced with the release's copy.
96
- const UPGRADE_REPLACE_FILES = [
97
- 'OMBUTOCODE_ENGINEERING_GUIDE.md',
98
- 'README.md',
99
- 'LICENSE',
100
- 'codingagent-templates.json',
101
- ];
102
-
103
- // Launcher scripts: every plain file directly under .ombutocode/ whose name
104
- // starts with one of these (buildandrun, buildandrun.bat, buildandrun.sh,
105
- // initombuto, initombuto.bat, …) is replaced.
106
- const UPGRADE_REPLACE_PREFIXES = ['buildandrun', 'initombuto'];
107
-
108
- // Project state captured in the backup zip before anything is replaced,
109
- // relative to .ombutocode/. Entries that do not exist are skipped. The
110
- // workbench version marker (src/package.json) rides along so the archive
111
- // records what it was taken from.
112
- const UPGRADE_BACKUP_PATHS = [
113
- 'data',
114
- 'codingagents',
115
- 'codingagent-state.json',
116
- 'planning',
117
- 'features',
118
- 'profiles',
119
- 'src/package.json',
120
- ];
121
-
122
- // ── Helpers ──
123
-
124
- function log(msg) { console.log(` ${msg}`); }
125
- function heading(msg) { console.log(`\n── ${msg} ──`); }
126
-
127
- function fatal(msg) {
128
- console.error(`\n✖ ${msg}`);
129
- process.exit(1);
130
- }
131
-
132
- function run(cmd, opts = {}) {
133
- try {
134
- execSync(cmd, { stdio: 'inherit', ...opts });
135
- } catch {
136
- fatal(`Command failed: ${cmd}`);
137
- }
138
- }
139
-
140
- function copyDirSync(src, dest) {
141
- fs.mkdirSync(dest, { recursive: true });
142
- for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
143
- const srcPath = path.join(src, entry.name);
144
- const destPath = path.join(dest, entry.name);
145
- if (entry.isDirectory()) {
146
- copyDirSync(srcPath, destPath);
147
- } else {
148
- fs.copyFileSync(srcPath, destPath);
149
- }
150
- }
151
- }
152
-
153
- // Move a directory, falling back to copy + delete when the source and
154
- // destination sit on different volumes (rename fails with EXDEV there —
155
- // common when the OS temp directory is on another drive).
156
- function moveDirSync(src, dest) {
157
- try {
158
- fs.renameSync(src, dest);
159
- } catch (err) {
160
- if (err && err.code !== 'EXDEV') throw err;
161
- copyDirSync(src, dest);
162
- fs.rmSync(src, { recursive: true, force: true });
163
- }
164
- }
165
-
166
- // Copy every file under srcDir into destDir that does not already exist
167
- // there, recursing into sub-directories. Existing files are never touched.
168
- // Returns the relative paths that were added.
169
- function copyMissingFiles(srcDir, destDir) {
170
- const added = [];
171
- const walk = (src, rel) => {
172
- for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
173
- const srcPath = path.join(src, entry.name);
174
- const relPath = rel ? `${rel}/${entry.name}` : entry.name;
175
- const destPath = path.join(destDir, relPath);
176
- if (entry.isDirectory()) {
177
- walk(srcPath, relPath);
178
- } else if (entry.isFile() && !fs.existsSync(destPath)) {
179
- fs.mkdirSync(path.dirname(destPath), { recursive: true });
180
- fs.copyFileSync(srcPath, destPath);
181
- added.push(relPath);
182
- }
183
- }
184
- };
185
- if (fs.existsSync(srcDir)) walk(srcDir, '');
186
- return added;
187
- }
188
-
189
- function stripUpstreamFiles(projectDir) {
190
- for (const name of UPSTREAM_FILES_TO_STRIP) {
191
- const target = path.join(projectDir, name);
192
- if (fs.existsSync(target)) {
193
- // Use recursive + force so this handles both files and directories.
194
- fs.rmSync(target, { recursive: true, force: true });
195
- log(`Removed upstream ${name}`);
196
- }
197
- }
198
- }
199
-
200
- // Clone the pinned release into a fresh temp directory and reduce it to the
201
- // workbench: drop the clone's git history, the installer package, the
202
- // upstream maintainer files and the upstream docs/ (which hold the Ombuto
203
- // Code project's own specs and must not leak into someone else's repo).
204
- // Returns the path of the clone's .ombutocode/ and a cleanup function; the
205
- // temp directory is also removed on process exit.
206
- function cloneWorkbench() {
207
- heading(`Cloning Ombuto Code ${CLONE_REF}`);
208
- const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'create-ombutocode-'));
209
- const cloneDir = path.join(tempRoot, 'clone');
210
- const cleanupTemp = () => { try { fs.rmSync(tempRoot, { recursive: true, force: true }); } catch {} };
211
- process.on('exit', cleanupTemp);
212
- run(`git clone --depth 1 --branch ${CLONE_REF} ${REPO_URL} "${cloneDir}"`);
213
-
214
- heading('Preparing workbench files');
215
- fs.rmSync(path.join(cloneDir, '.git'), { recursive: true, force: true });
216
- fs.rmSync(path.join(cloneDir, 'create-ombutocode'), { recursive: true, force: true });
217
- stripUpstreamFiles(cloneDir);
218
- fs.rmSync(path.join(cloneDir, 'docs'), { recursive: true, force: true });
219
- log('Discarded upstream docs/');
220
-
221
- const clonedOmbutocode = path.join(cloneDir, '.ombutocode');
222
- if (!fs.existsSync(path.join(clonedOmbutocode, 'src', 'package.json'))) {
223
- fatal('.ombutocode/src/package.json not found in the clone — repository may be corrupted.');
224
- }
225
- return { clonedOmbutocode, cleanupTemp };
226
- }
227
-
228
- // Copy the template files into projectDir. With `skipExisting`, a file that
229
- // is already there (the adopted project's own README, CLAUDE.md, …) is left
230
- // untouched.
231
- function writeTemplateFiles(projectDir, projectName, { skipExisting = false } = {}) {
232
- // Template files ship inside the installer package at ../template
233
- // relative to this script (bin/create-ombutocode.js).
234
- const templateDir = path.resolve(__dirname, '..', 'template');
235
- if (!fs.existsSync(templateDir)) {
236
- log('Template directory not found — skipping template overlay.');
237
- return;
238
- }
239
-
240
- for (const name of TEMPLATE_FILES) {
241
- const src = path.join(templateDir, name);
242
- if (!fs.existsSync(src)) {
243
- log(`Template file missing: ${name} (skipping)`);
244
- continue;
245
- }
246
- const dest = path.join(projectDir, name);
247
- if (skipExisting && fs.existsSync(dest)) {
248
- log(`Kept existing ${name}`);
249
- continue;
250
- }
251
- const content = fs.readFileSync(src, 'utf-8')
252
- .replace(/\{\{PROJECT_NAME\}\}/g, projectName);
253
- fs.writeFileSync(dest, content);
254
- log(`Wrote ${name}`);
255
- }
256
- }
257
-
258
- // Ensure the Ombuto ignore lines are present in <projectDir>/.gitignore.
259
- // Creates the file if absent; otherwise appends only the missing lines.
260
- function ensureGitignore(projectDir) {
261
- const gitignorePath = path.join(projectDir, '.gitignore');
262
- if (!fs.existsSync(gitignorePath)) {
263
- fs.writeFileSync(gitignorePath, `# OmbutoCode\n${OMBUTO_GITIGNORE_LINES.join('\n')}\n`);
264
- log('Wrote .gitignore');
265
- return;
266
- }
267
- const existing = fs.readFileSync(gitignorePath, 'utf-8');
268
- const present = new Set(existing.split(/\r?\n/).map((l) => l.trim()));
269
- const missing = OMBUTO_GITIGNORE_LINES.filter((l) => !present.has(l));
270
- if (missing.length === 0) {
271
- log('Kept existing .gitignore (Ombuto entries already present)');
272
- return;
273
- }
274
- const separator = existing.length === 0 || existing.endsWith('\n') ? '' : '\n';
275
- fs.appendFileSync(gitignorePath, `${separator}\n# OmbutoCode\n${missing.join('\n')}\n`);
276
- log(`Appended ${missing.length} Ombuto entr${missing.length === 1 ? 'y' : 'ies'} to .gitignore`);
277
- }
278
-
279
- // Run initombuto against projectDir. `initArgs` is the argument list passed
280
- // to the script; `env` lets the caller propagate npm config (see --omit-dev).
281
- function runInitombuto(projectDir, initArgs, env) {
282
- const isWindows = process.platform === 'win32';
283
- const initScript = path.join(projectDir, '.ombutocode', isWindows ? 'initombuto.bat' : 'initombuto');
284
-
285
- if (fs.existsSync(initScript)) {
286
- const argString = initArgs.map((a) => (a.startsWith('--') ? a : `"${a}"`)).join(' ');
287
- if (isWindows) {
288
- run(`"${initScript}" ${argString}`, { cwd: projectDir, env });
289
- } else {
290
- // Ensure executable
291
- try { fs.chmodSync(initScript, 0o755); } catch {}
292
- run(`bash "${initScript}" ${argString}`, { cwd: projectDir, env });
293
- }
294
- return;
295
- }
296
-
297
- log('initombuto script not found — creating docs/ structure manually...');
298
- const dirs = [
299
- 'Structure', 'Product Requirements Document', 'Architecture',
300
- 'Functional Requirements', 'Non-Functional Requirements', 'Epics',
301
- 'BDD Use Cases', 'Use Cases', 'Use Case Diagrams', 'Class Diagrams',
302
- 'Data Model', 'Style Guide', 'Mockups', 'References', 'Skills',
303
- 'Test Strategy', 'ScratchPad'
304
- ];
305
- for (const dir of dirs) {
306
- fs.mkdirSync(path.join(projectDir, 'docs', dir), { recursive: true });
307
- }
308
- }
309
-
310
- // ── Minimal ZIP writer / reader ──
311
- //
312
- // The installer has no runtime dependencies and must stay that way, so the
313
- // upgrade backup is written with Node's built-in zlib and a hand-rolled ZIP
314
- // container: local file headers, a central directory and an end-of-central-
315
- // directory record, which is everything `unzip`, Expand-Archive and Finder
316
- // need. No zip64 — fewer than 65,535 entries and under 4 GB — which is far
317
- // beyond what a workbench backup holds.
318
-
319
- const CRC32_TABLE = (() => {
320
- const table = new Int32Array(256);
321
- for (let n = 0; n < 256; n++) {
322
- let c = n;
323
- for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
324
- table[n] = c;
325
- }
326
- return table;
327
- })();
328
-
329
- function crc32(buf) {
330
- let c = -1;
331
- for (let i = 0; i < buf.length; i++) c = CRC32_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
332
- return (c ^ -1) >>> 0;
333
- }
334
-
335
- // MS-DOS date/time fields as stored in ZIP headers (2-second resolution,
336
- // nothing before 1980).
337
- function dosDateTime(date) {
338
- const d = date.getFullYear() < 1980 ? new Date(1980, 0, 1) : date;
339
- return {
340
- time: (d.getHours() << 11) | (d.getMinutes() << 5) | (d.getSeconds() >> 1),
341
- date: ((d.getFullYear() - 1980) << 9) | ((d.getMonth() + 1) << 5) | d.getDate(),
342
- };
343
- }
344
-
345
- const ZIP_MAX_ENTRIES = 0xffff;
346
- const ZIP_MAX_BYTES = 0xffffffff;
347
-
348
- // Write a ZIP archive. `entries` is an array of { name, data } or
349
- // { name, file } (read from disk at write time, so a backup does not have
350
- // to sit in memory all at once), with an optional `mtime`. Names use
351
- // forward slashes. Each entry is deflated unless that would not save
352
- // anything, in which case it is stored. Returns { entries, bytes }.
353
- function writeZip(zipPath, entries) {
354
- if (entries.length > ZIP_MAX_ENTRIES) {
355
- throw new Error(`too many files for a plain ZIP archive (${entries.length})`);
356
- }
357
- const fd = fs.openSync(zipPath, 'w');
358
- const central = [];
359
- let offset = 0;
360
- const write = (buf) => { fs.writeSync(fd, buf); offset += buf.length; };
361
- try {
362
- for (const entry of entries) {
363
- const data = entry.data !== undefined ? entry.data : fs.readFileSync(entry.file);
364
- const mtime = entry.mtime || (entry.file ? fs.statSync(entry.file).mtime : new Date());
365
- if (data.length > ZIP_MAX_BYTES) throw new Error(`${entry.name} is too large for a plain ZIP archive`);
366
- const name = Buffer.from(entry.name, 'utf8');
367
- const crc = crc32(data);
368
- let method = 8;
369
- let payload = zlib.deflateRawSync(data);
370
- if (payload.length >= data.length) { method = 0; payload = data; }
371
- const { time, date } = dosDateTime(mtime);
372
-
373
- const local = Buffer.alloc(30);
374
- local.writeUInt32LE(0x04034b50, 0); // local file header signature
375
- local.writeUInt16LE(20, 4); // version needed to extract (2.0)
376
- local.writeUInt16LE(0x0800, 6); // flags: UTF-8 file names
377
- local.writeUInt16LE(method, 8);
378
- local.writeUInt16LE(time, 10);
379
- local.writeUInt16LE(date, 12);
380
- local.writeUInt32LE(crc, 14);
381
- local.writeUInt32LE(payload.length, 18);
382
- local.writeUInt32LE(data.length, 22);
383
- local.writeUInt16LE(name.length, 26);
384
- local.writeUInt16LE(0, 28); // extra field length
385
- central.push({ name, method, time, date, crc, compressedSize: payload.length, size: data.length, offset });
386
- write(local);
387
- write(name);
388
- write(payload);
389
- if (offset > ZIP_MAX_BYTES) throw new Error('archive is too large for a plain ZIP archive');
390
- }
391
-
392
- const cdStart = offset;
393
- for (const e of central) {
394
- const header = Buffer.alloc(46);
395
- header.writeUInt32LE(0x02014b50, 0); // central directory header signature
396
- header.writeUInt16LE(20, 4); // version made by
397
- header.writeUInt16LE(20, 6); // version needed to extract
398
- header.writeUInt16LE(0x0800, 8); // flags: UTF-8 file names
399
- header.writeUInt16LE(e.method, 10);
400
- header.writeUInt16LE(e.time, 12);
401
- header.writeUInt16LE(e.date, 14);
402
- header.writeUInt32LE(e.crc, 16);
403
- header.writeUInt32LE(e.compressedSize, 20);
404
- header.writeUInt32LE(e.size, 24);
405
- header.writeUInt16LE(e.name.length, 28);
406
- header.writeUInt16LE(0, 30); // extra field length
407
- header.writeUInt16LE(0, 32); // file comment length
408
- header.writeUInt16LE(0, 34); // disk number start
409
- header.writeUInt16LE(0, 36); // internal attributes
410
- header.writeUInt32LE(0, 38); // external attributes
411
- header.writeUInt32LE(e.offset, 42); // local header offset
412
- write(header);
413
- write(e.name);
414
- }
415
-
416
- const eocd = Buffer.alloc(22);
417
- eocd.writeUInt32LE(0x06054b50, 0); // end of central directory signature
418
- eocd.writeUInt16LE(0, 4); // this disk
419
- eocd.writeUInt16LE(0, 6); // disk with the central directory
420
- eocd.writeUInt16LE(central.length, 8); // entries on this disk
421
- eocd.writeUInt16LE(central.length, 10); // entries total
422
- eocd.writeUInt32LE(offset - cdStart, 12);
423
- eocd.writeUInt32LE(cdStart, 16);
424
- eocd.writeUInt16LE(0, 20); // comment length
425
- write(eocd);
426
- } finally {
427
- fs.closeSync(fd);
428
- }
429
- return { entries: central.length, bytes: offset };
430
- }
431
-
432
- // Read a ZIP archive's central directory: [{ name, method, crc32, size,
433
- // compressedSize, offset }]. With `verify`, every entry's data is also
434
- // inflated and checked against its CRC, which is what makes the backup
435
- // trustworthy before anything is deleted. Throws on a malformed archive.
436
- function readZipEntries(zipPath, { verify = false } = {}) {
437
- const buf = fs.readFileSync(zipPath);
438
- let eocd = -1;
439
- for (let i = buf.length - 22; i >= Math.max(0, buf.length - 22 - 0xffff); i--) {
440
- if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break; }
441
- }
442
- if (eocd < 0) throw new Error(`${zipPath}: not a ZIP archive (no end-of-central-directory record)`);
443
- const count = buf.readUInt16LE(eocd + 10);
444
- const cdSize = buf.readUInt32LE(eocd + 12);
445
- const cdOffset = buf.readUInt32LE(eocd + 16);
446
-
447
- const entries = [];
448
- let p = cdOffset;
449
- for (let i = 0; i < count; i++) {
450
- if (p + 46 > buf.length || buf.readUInt32LE(p) !== 0x02014b50) {
451
- throw new Error(`${zipPath}: corrupt central directory at entry ${i}`);
452
- }
453
- const nameLen = buf.readUInt16LE(p + 28);
454
- const extraLen = buf.readUInt16LE(p + 30);
455
- const commentLen = buf.readUInt16LE(p + 32);
456
- entries.push({
457
- name: buf.toString('utf8', p + 46, p + 46 + nameLen),
458
- method: buf.readUInt16LE(p + 10),
459
- crc32: buf.readUInt32LE(p + 16),
460
- compressedSize: buf.readUInt32LE(p + 20),
461
- size: buf.readUInt32LE(p + 24),
462
- offset: buf.readUInt32LE(p + 42),
463
- });
464
- p += 46 + nameLen + extraLen + commentLen;
465
- }
466
- if (p !== cdOffset + cdSize) throw new Error(`${zipPath}: central directory size mismatch`);
467
-
468
- if (verify) {
469
- for (const e of entries) {
470
- const h = e.offset;
471
- if (buf.readUInt32LE(h) !== 0x04034b50) throw new Error(`${zipPath}: bad local header for ${e.name}`);
472
- const dataStart = h + 30 + buf.readUInt16LE(h + 26) + buf.readUInt16LE(h + 28);
473
- const payload = buf.subarray(dataStart, dataStart + e.compressedSize);
474
- let data;
475
- try {
476
- data = e.method === 8 ? zlib.inflateRawSync(payload) : payload;
477
- } catch (err) {
478
- throw new Error(`${zipPath}: ${e.name} does not verify (${err.message})`);
479
- }
480
- if (data.length !== e.size || crc32(data) !== e.crc32) {
481
- throw new Error(`${zipPath}: ${e.name} does not verify (size or CRC mismatch)`);
482
- }
483
- }
484
- }
485
- return entries;
486
- }
487
-
488
- // ── Upgrade helpers ──
489
-
490
- function isPidAlive(pid) {
491
- try { process.kill(pid, 0); return true; } catch (err) { return err.code === 'EPERM'; }
492
- }
493
-
494
- // Executable name of a running process, or null if it cannot be determined.
495
- function processImageName(pid) {
496
- const opts = { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] };
497
- try {
498
- if (process.platform === 'win32') {
499
- const out = execSync(`tasklist /FI "PID eq ${pid}" /FO CSV /NH`, opts);
500
- const m = out.match(/^"([^"]+)","(\d+)"/m);
501
- return m && Number(m[2]) === pid ? m[1] : null;
502
- }
503
- return execSync(`ps -p ${pid} -o comm=`, opts).trim() || null;
504
- } catch {
505
- return null;
506
- }
507
- }
508
-
509
- // The workbench writes its PID to .ombutocode/.instance.lock on startup and
510
- // removes the file on a clean exit (see acquireProjectLock in main.js). A
511
- // crashed app, or a project scaffolded from a clone, leaves a stale PID
512
- // behind, so a lock only counts when that PID is alive and — where the OS
513
- // tells us — actually belongs to Electron / Ombuto Code rather than to some
514
- // unrelated process that inherited the number. Returns { pid, image } for
515
- // a running workbench, else null.
516
- function findRunningWorkbench(ombutoDir) {
517
- const lockPath = path.join(ombutoDir, '.instance.lock');
518
- if (!fs.existsSync(lockPath)) return null;
519
- const pid = parseInt(fs.readFileSync(lockPath, 'utf8').trim(), 10);
520
- if (!Number.isFinite(pid) || pid <= 0 || pid === process.pid) return null;
521
- if (!isPidAlive(pid)) return null;
522
- const image = processImageName(pid);
523
- if (image && !/electron|ombuto/i.test(image)) return null;
524
- return { pid, image };
525
- }
526
-
527
- function readWorkbenchVersion(ombutoDir) {
528
- const pkgPath = path.join(ombutoDir, 'src', 'package.json');
529
- try {
530
- const version = JSON.parse(fs.readFileSync(pkgPath, 'utf8')).version;
531
- return typeof version === 'string' && version ? version : null;
532
- } catch {
533
- return null;
534
- }
535
- }
536
-
537
- // Numeric dotted-version comparison: negative if a < b, positive if a > b.
538
- function compareVersions(a, b) {
539
- const pa = String(a).split('.').map((n) => parseInt(n, 10) || 0);
540
- const pb = String(b).split('.').map((n) => parseInt(n, 10) || 0);
541
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
542
- const diff = (pa[i] || 0) - (pb[i] || 0);
543
- if (diff !== 0) return diff;
544
- }
545
- return 0;
546
- }
547
-
548
- // Every file under the preserved paths (UPGRADE_BACKUP_PATHS), as ZIP
549
- // entries named `.ombutocode/<relative path>` so the archive extracts back
550
- // into place from the project root.
551
- function collectBackupEntries(ombutoDir) {
552
- const entries = [];
553
- const walk = (abs, rel) => {
554
- for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
555
- const absPath = path.join(abs, entry.name);
556
- const relPath = `${rel}/${entry.name}`;
557
- if (entry.isDirectory()) walk(absPath, relPath);
558
- else if (entry.isFile()) entries.push({ name: relPath, file: absPath });
559
- }
560
- };
561
- for (const p of UPGRADE_BACKUP_PATHS) {
562
- const abs = path.join(ombutoDir, p);
563
- if (!fs.existsSync(abs)) continue;
564
- const rel = `.ombutocode/${p}`;
565
- if (fs.statSync(abs).isDirectory()) walk(abs, rel);
566
- else entries.push({ name: rel, file: abs });
567
- }
568
- return entries;
569
- }
570
-
571
- // Write `.ombutocode-backup-<version>-<YYYYMMDD-HHMMSS>.zip` into projectDir
572
- // and verify it by re-reading the central directory (entry count, CRCs, and
573
- // that ombutocode.db made it in whenever it existed). Returns
574
- // { zipPath, entries, bytes }.
575
- function backupWorkbenchState(projectDir, currentVersion, now = new Date()) {
576
- const ombutoDir = path.join(projectDir, '.ombutocode');
577
- const pad = (n) => String(n).padStart(2, '0');
578
- const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
579
- const zipPath = path.join(projectDir, `.ombutocode-backup-${currentVersion}-${stamp}.zip`);
580
-
581
- const entries = collectBackupEntries(ombutoDir);
582
- const written = writeZip(zipPath, entries);
583
- const listed = readZipEntries(zipPath, { verify: true });
584
- if (listed.length !== entries.length) {
585
- throw new Error(`backup verification failed: wrote ${entries.length} entries, archive lists ${listed.length}`);
586
- }
587
- const dbName = '.ombutocode/data/ombutocode.db';
588
- if (fs.existsSync(path.join(ombutoDir, 'data', 'ombutocode.db')) && !listed.some((e) => e.name === dbName)) {
589
- throw new Error(`backup verification failed: ${dbName} is missing from the archive`);
590
- }
591
- return { zipPath, entries: listed.length, bytes: written.bytes };
592
- }
593
-
594
- // Replace the workbench code in targetOmbutoDir with the release in
595
- // newOmbutoDir, following the upgrade contract above. newOmbutoDir is
596
- // consumed (its directories are moved, not copied). Returns a summary:
597
- // { replaced, removed, profilesAdded, codingagentsAdded, codingagentsNew }.
598
- function replaceWorkbench(targetOmbutoDir, newOmbutoDir, logFn = log) {
599
- const result = { replaced: [], removed: [], profilesAdded: [], codingagentsAdded: [], codingagentsNew: null };
600
- const rm = (p) => fs.rmSync(p, { recursive: true, force: true, maxRetries: 3 });
601
-
602
- // Directories: delete the old one entirely, then move the release's in.
603
- for (const name of UPGRADE_REPLACE_DIRS) {
604
- const target = path.join(targetOmbutoDir, name);
605
- const source = path.join(newOmbutoDir, name);
606
- const hadOld = fs.existsSync(target);
607
- if (hadOld) rm(target);
608
- if (fs.existsSync(source)) {
609
- moveDirSync(source, target);
610
- result.replaced.push(`${name}/`);
611
- logFn(`Replaced ${name}/`);
612
- } else if (hadOld) {
613
- result.removed.push(`${name}/`);
614
- logFn(`Removed ${name}/ (not shipped by this release)`);
615
- }
616
- }
617
-
618
- // Plain files, including every launcher script (buildandrun*, initombuto*)
619
- // present on either side, so a launcher the release dropped goes too.
620
- const fileNames = new Set(UPGRADE_REPLACE_FILES);
621
- for (const dir of [targetOmbutoDir, newOmbutoDir]) {
622
- if (!fs.existsSync(dir)) continue;
623
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
624
- if (entry.isFile() && UPGRADE_REPLACE_PREFIXES.some((p) => entry.name.startsWith(p))) {
625
- fileNames.add(entry.name);
626
- }
627
- }
628
- }
629
- for (const name of fileNames) {
630
- const target = path.join(targetOmbutoDir, name);
631
- const source = path.join(newOmbutoDir, name);
632
- const hadOld = fs.existsSync(target);
633
- if (hadOld) rm(target);
634
- if (fs.existsSync(source)) {
635
- fs.copyFileSync(source, target);
636
- try { fs.chmodSync(target, fs.statSync(source).mode); } catch {}
637
- result.replaced.push(name);
638
- logFn(`Replaced ${name}`);
639
- } else if (hadOld) {
640
- result.removed.push(name);
641
- logFn(`Removed ${name} (not shipped by this release)`);
642
- }
643
- }
644
-
645
- // profiles/: additive only — the same rule initombuto applies to skills.
646
- result.profilesAdded = copyMissingFiles(path.join(newOmbutoDir, 'profiles'), path.join(targetOmbutoDir, 'profiles'));
647
- for (const rel of result.profilesAdded) logFn(`Added profiles/${rel}`);
648
-
649
- // codingagents/: codingagents.yml is the user's agent configuration and is
650
- // never overwritten. When the release's copy differs it is written
651
- // alongside as codingagents.yml.new for the user to merge. Any other file
652
- // the release ships in that directory is added only if missing.
653
- const ymlSource = path.join(newOmbutoDir, 'codingagents', 'codingagents.yml');
654
- const ymlTarget = path.join(targetOmbutoDir, 'codingagents', 'codingagents.yml');
655
- const ymlNew = `${ymlTarget}.new`;
656
- if (fs.existsSync(ymlSource) && fs.existsSync(ymlTarget)) {
657
- if (fs.readFileSync(ymlSource).equals(fs.readFileSync(ymlTarget))) {
658
- if (fs.existsSync(ymlNew)) rm(ymlNew);
659
- } else {
660
- fs.copyFileSync(ymlSource, ymlNew);
661
- result.codingagentsNew = ymlNew;
662
- logFn('Kept codingagents/codingagents.yml; the release\'s version differs and was written as codingagents.yml.new');
663
- }
664
- }
665
- result.codingagentsAdded = copyMissingFiles(path.join(newOmbutoDir, 'codingagents'), path.join(targetOmbutoDir, 'codingagents'));
666
- for (const rel of result.codingagentsAdded) logFn(`Added codingagents/${rel}`);
667
-
668
- return result;
669
- }
670
-
671
- // Seed docs/Skills/ with any skill template the release ships that the
672
- // project does not have yet — the same file-by-file rule initombuto uses.
673
- // initombuto itself is deliberately not run here: even with --keep-docs it
674
- // deletes the database, ticket files, features and agent state first.
675
- // Returns the relative paths added.
676
- function seedMissingSkills(projectDir, ombutoDir, logFn = log) {
677
- const docsDir = path.join(projectDir, 'docs');
678
- if (!fs.existsSync(docsDir)) {
679
- logFn('No docs/ directory — skipped skill seeding');
680
- return [];
681
- }
682
- const added = copyMissingFiles(path.join(ombutoDir, 'templates', 'skills'), path.join(docsDir, 'Skills'));
683
- for (const rel of added) logFn(`Added docs/Skills/${rel}`);
684
- return added;
685
- }
686
-
687
- // ── CLI ──
688
-
689
- const HELP = `
690
- create-ombutocode v${VERSION}
691
-
692
- Create a new Ombuto Code project — Agentic Software Engineering Workbench
693
-
694
- Usage:
695
- npx create-ombutocode <project-name> [--omit-dev]
696
- npx create-ombutocode --into-existing <dir> [--omit-dev]
697
- npx create-ombutocode --upgrade [<dir>] [--no-backup] [--force] [--omit-dev]
698
-
699
- Options:
700
- --into-existing <dir> Adopt Ombuto Code into an existing directory
701
- instead of creating a new project. Adds
702
- .ombutocode/ and seeds docs/ without touching
703
- any file that is already there, and never runs
704
- git init/add/commit. <dir> must exist and must
705
- not already contain .ombutocode/.
706
- --upgrade [<dir>] Upgrade the workbench (.ombutocode/) of an
707
- existing project to this installer's release,
708
- ${CLONE_REF}. <dir> defaults to the current directory.
709
- Replaces only workbench code (src/, tools/,
710
- templates/, scripts/, bench/, the launcher
711
- scripts, the engineering guide, README, LICENSE
712
- and codingagent-templates.json); the database,
713
- tickets, codingagents.yml, profiles and docs/
714
- are left alone. Zips the preserved state into
715
- .ombutocode-backup-<version>-<timestamp>.zip
716
- first, and refuses to run while the workbench
717
- is open.
718
- --no-backup Skip the backup zip (--upgrade only).
719
- --force Upgrade even when the project is already at
720
- ${CLONE_REF} or newer (--upgrade only).
721
- --omit-dev Install with \`npm install --omit=dev
722
- --legacy-peer-deps\`: no Electron, Vite or
723
- electron-builder. For headless and CLI use only —
724
- the workbench UI cannot be built from such an
725
- install.
726
- -h, --help Show this help.
727
-
728
- Example:
729
- npx create-ombutocode my-app
730
- cd my-app
731
- .ombutocode/buildandrun.bat # Windows
732
- bash .ombutocode/buildandrun # macOS / Linux
733
-
734
- Example (existing repository, headless):
735
- npx create-ombutocode --into-existing /app --omit-dev
736
- cd /app
737
- node .ombutocode/src/headless.js status
738
-
739
- Example (upgrade the workbench in the current project):
740
- cd my-app
741
- npx create-ombutocode@latest --upgrade
742
- `;
743
-
744
- function main() {
745
- const args = process.argv.slice(2);
746
- if (args.includes('--help') || args.includes('-h')) {
747
- console.log(HELP);
748
- process.exit(0);
749
- }
750
-
751
- let projectName = null;
752
- let intoExisting = null;
753
- let upgrade = null; // false: not requested; string: directory to upgrade
754
- let omitDev = false;
755
- let noBackup = false;
756
- let force = false;
757
-
758
- for (let i = 0; i < args.length; i++) {
759
- const arg = args[i];
760
- if (arg === '--omit-dev') {
761
- omitDev = true;
762
- } else if (arg === '--no-backup') {
763
- noBackup = true;
764
- } else if (arg === '--force') {
765
- force = true;
766
- } else if (arg === '--into-existing') {
767
- intoExisting = args[i + 1];
768
- i++;
769
- if (!intoExisting || intoExisting.startsWith('-')) {
770
- fatal('--into-existing requires a directory:\n\n npx create-ombutocode --into-existing /path/to/repo\n');
771
- }
772
- } else if (arg.startsWith('--into-existing=')) {
773
- intoExisting = arg.slice('--into-existing='.length);
774
- if (!intoExisting) {
775
- fatal('--into-existing requires a directory:\n\n npx create-ombutocode --into-existing /path/to/repo\n');
776
- }
777
- } else if (arg === '--upgrade') {
778
- // Optional directory; defaults to the current directory.
779
- if (args[i + 1] !== undefined && !args[i + 1].startsWith('-')) {
780
- upgrade = args[i + 1];
781
- i++;
782
- } else {
783
- upgrade = '.';
784
- }
785
- } else if (arg.startsWith('--upgrade=')) {
786
- upgrade = arg.slice('--upgrade='.length) || '.';
787
- } else if (arg.startsWith('-')) {
788
- fatal(`Unknown option "${arg}". Run with --help for usage.`);
789
- } else if (projectName === null) {
790
- projectName = arg;
791
- } else {
792
- fatal(`Unexpected argument "${arg}". Run with --help for usage.`);
793
- }
794
- }
795
-
796
- if ((noBackup || force) && upgrade === null) {
797
- fatal('--no-backup and --force only apply to --upgrade. Run with --help for usage.');
798
- }
799
-
800
- // --omit=dev alone still downloads Electron: @electron/remote (a runtime
801
- // dependency) declares electron as a peer dependency and npm 7+ installs
802
- // peers automatically. --legacy-peer-deps turns that off; --omit=peer does
803
- // not (verified against npm 10). Nothing headless.js loads needs a peer.
804
- const npmInstallCmd = omitDev
805
- ? 'npm install --no-audit --no-fund --omit=dev --legacy-peer-deps'
806
- : 'npm install --no-audit --no-fund';
807
- // initombuto runs its own plain `npm install`; npm reads npm_config_* from
808
- // the environment, so this keeps that second install from adding the dev
809
- // dependencies and Electron back.
810
- const initEnv = omitDev
811
- ? { ...process.env, npm_config_omit: 'dev', npm_config_legacy_peer_deps: 'true' }
812
- : process.env;
813
-
814
- function noteOmitDev() {
815
- if (!omitDev) return;
816
- log('--omit-dev: Electron, Vite and electron-builder were not installed.');
817
- log('The workbench UI cannot be built from this install; use the headless CLI');
818
- log('(node .ombutocode/src/headless.js) or re-run `npm install` in .ombutocode/src.');
819
- }
820
-
821
- const banner = () => console.log(`
822
- ╔═══════════════════════════════════════════╗
823
- ║ create-ombutocode v${VERSION} ║
824
- ║ Agentic Software Engineering Workbench ║
825
- ╚═══════════════════════════════════════════╝
826
- `);
827
-
828
- // ═════════════════════════════════════════════════════════════════════
829
- // Upgrade the workbench in an existing project
830
- // ═════════════════════════════════════════════════════════════════════
831
-
832
- if (upgrade !== null) {
833
- if (intoExisting !== null) {
834
- fatal('--upgrade cannot be combined with --into-existing.');
835
- }
836
- // `create-ombutocode my-app --upgrade` reads as naturally as
837
- // `--upgrade my-app`; treat the positional as the directory.
838
- if (projectName !== null) {
839
- if (upgrade !== '.') fatal(`Unexpected argument "${projectName}". Run with --help for usage.`);
840
- upgrade = projectName;
841
- }
842
-
843
- const projectDir = path.resolve(upgrade);
844
- const ombutoDir = path.join(projectDir, '.ombutocode');
845
- if (!fs.existsSync(path.join(ombutoDir, 'src', 'package.json'))) {
846
- fatal(`"${projectDir}" does not contain .ombutocode/src/package.json — nothing to upgrade.\n To add Ombuto Code to a directory that does not have it yet, use:\n\n npx create-ombutocode --into-existing "${projectDir}"\n`);
847
- }
848
-
849
- banner();
850
- console.log(`Upgrading Ombuto Code in: ${projectDir}`);
851
-
852
- // ── Step 1: Preflight ──
853
-
854
- heading('Checking the project');
855
- const running = findRunningWorkbench(ombutoDir);
856
- if (running) {
857
- fatal(`The workbench appears to be running for this project (PID ${running.pid}${running.image ? `, ${running.image}` : ''}).\n Close Ombuto Code and run the upgrade again. If the app is not running,\n delete the stale lock file .ombutocode/.instance.lock and retry.`);
858
- }
859
- const currentVersion = readWorkbenchVersion(ombutoDir) || 'unknown';
860
- const targetVersion = CLONE_REF.replace(/^v/, '');
861
- const cmp = currentVersion === 'unknown' ? -1 : compareVersions(currentVersion, targetVersion);
862
- if (cmp === 0 && !force) {
863
- log(`.ombutocode is already at ${targetVersion} — nothing to do. (Use --force to reinstall it anyway.)`);
864
- process.exit(0);
865
- }
866
- if (cmp > 0 && !force) {
867
- fatal(`.ombutocode is at ${currentVersion}, which is newer than this installer's release (${targetVersion}).\n Run \`npx create-ombutocode@latest --upgrade\` to use the newest installer, or pass --force to downgrade.`);
868
- }
869
- log(`Upgrading .ombutocode from ${currentVersion} to ${targetVersion}${cmp > 0 ? ' (downgrade, --force)' : cmp === 0 ? ' (reinstall, --force)' : ''}`);
870
-
871
- // ── Step 2: Backup ──
872
-
873
- let backup = null;
874
- if (noBackup) {
875
- heading('Backup');
876
- log('--no-backup: skipping the backup zip.');
877
- } else {
878
- heading('Backing up project state');
879
- try {
880
- backup = backupWorkbenchState(projectDir, currentVersion);
881
- } catch (err) {
882
- fatal(`Could not write the backup: ${err.message}\n Nothing has been changed. Fix the problem and retry, or pass --no-backup.`);
883
- }
884
- log(`Wrote ${path.basename(backup.zipPath)} (${backup.entries} files, ${(backup.bytes / 1024).toFixed(0)} KB)`);
885
- }
886
-
887
- // ── Step 3: Fetch the release ──
888
-
889
- const { clonedOmbutocode, cleanupTemp } = cloneWorkbench();
890
-
891
- // ── Step 4: Replace the workbench code ──
892
- //
893
- // From here on the project is being modified. Any failure — including
894
- // one inside `run()`, which exits the process — has to leave the user
895
- // with clear recovery instructions, hence the exit hook.
896
-
897
- heading('Replacing workbench code');
898
- let replacing = true;
899
- process.on('exit', (code) => {
900
- if (code === 0 || !replacing) return;
901
- console.error(`
902
- ✖ The upgrade did not complete; .ombutocode/ may be half-replaced.
903
- To restore the previous workbench:
904
- git checkout -- .ombutocode # if it was committed, and
905
- ${backup ? ` unzip -o "${path.basename(backup.zipPath)}" # or Expand-Archive on Windows\n` : ''} then re-run the upgrade once the cause is fixed.`);
906
- });
907
-
908
- let summary;
909
- try {
910
- summary = replaceWorkbench(ombutoDir, clonedOmbutocode);
911
- seedMissingSkills(projectDir, ombutoDir);
912
- } catch (err) {
913
- fatal(`Replacing the workbench failed: ${err.message}`);
914
- }
915
- cleanupTemp();
916
-
917
- // ── Step 5: Install dependencies ──
918
-
919
- heading('Installing dependencies');
920
- run(npmInstallCmd, { cwd: path.join(ombutoDir, 'src') });
921
- noteOmitDev();
922
- replacing = false;
923
-
924
- // ── Done ──
925
-
926
- const newVersion = readWorkbenchVersion(ombutoDir) || targetVersion;
927
- console.log(`
928
- ╔═══════════════════════════════════════════╗
929
- ║ Workbench upgraded! ║
930
- ╚═══════════════════════════════════════════╝
931
-
932
- .ombutocode: ${currentVersion} → ${newVersion}
933
- `);
934
- if (backup) {
935
- console.log(` Backup of your database, tickets, agent config and profiles:
936
- ${backup.zipPath}
937
- Delete it once you are happy with the upgrade (or ignore .ombutocode-backup-*.zip).
938
- `);
939
- }
940
- if (summary.codingagentsNew) {
941
- console.log(` codingagents/codingagents.yml was kept as-is. This release ships a
942
- different default, written next to it as codingagents.yml.new — compare
943
- and merge anything you want, then delete the .new file.
944
- `);
945
- }
946
- console.log(` Next:
947
- git status # review what changed under .ombutocode/ and docs/Skills/
948
- git add -A .ombutocode docs && git commit -m "Upgrade Ombuto Code to ${newVersion}"
949
-
950
- Check the release notes for version-specific steps:
951
- https://github.com/FrancoisBotha/ombutocode/releases
952
- ${omitDev ? `
953
- # Headless CLI:
954
- node .ombutocode/src/headless.js status
955
- ` : `
956
- # Launch the workbench:
957
- .ombutocode/buildandrun.bat # Windows
958
- bash .ombutocode/buildandrun # macOS / Linux
959
- `}`);
960
- process.exit(0);
961
- }
962
-
963
- // ═════════════════════════════════════════════════════════════════════
964
- // Adopt into an existing directory
965
- // ═════════════════════════════════════════════════════════════════════
966
-
967
- if (intoExisting !== null) {
968
- if (projectName !== null) {
969
- fatal('Give either a <project-name> or --into-existing <dir>, not both.');
970
- }
971
-
972
- const targetDir = path.resolve(intoExisting);
973
- if (!fs.existsSync(targetDir) || !fs.statSync(targetDir).isDirectory()) {
974
- fatal(`Directory "${targetDir}" does not exist. --into-existing adopts an existing directory; use \`npx create-ombutocode <project-name>\` to create a new one.`);
975
- }
976
- if (fs.existsSync(path.join(targetDir, '.ombutocode'))) {
977
- fatal(`"${targetDir}" already contains .ombutocode/ — refusing to overwrite an existing Ombuto Code installation. To move it to this installer's release, use \`npx create-ombutocode --upgrade "${targetDir}"\`.`);
978
- }
979
- const targetName = path.basename(targetDir);
980
- const targetIsGitRepo = fs.existsSync(path.join(targetDir, '.git'));
981
-
982
- banner();
983
- console.log(`Adopting Ombuto Code into: ${targetDir}`);
984
-
985
- // ── Step 1: Clone the pinned release and reduce it to the workbench ──
986
- //
987
- // Only .ombutocode/ travels into the adopted directory. The clone's
988
- // docs/ holds the upstream project's own specs and epics, which must not
989
- // leak into someone else's repository — the docs/ skeleton is seeded by
990
- // initombuto below instead, file by file, only where nothing exists yet.
991
-
992
- const { clonedOmbutocode, cleanupTemp } = cloneWorkbench();
993
- moveDirSync(clonedOmbutocode, path.join(targetDir, '.ombutocode'));
994
- log('Added .ombutocode/');
995
- cleanupTemp();
996
-
997
- writeTemplateFiles(targetDir, targetName, { skipExisting: true });
998
- ensureGitignore(targetDir);
999
-
1000
- // ── Step 2: Install dependencies ──
1001
-
1002
- heading('Installing dependencies');
1003
- run(npmInstallCmd, { cwd: path.join(targetDir, '.ombutocode', 'src') });
1004
- noteOmitDev();
1005
-
1006
- // ── Step 3: Initialise project data ──
1007
- //
1008
- // --keep-docs: never wipe docs/. initombuto still creates every missing
1009
- // docs/ folder, starter document and skill file, and skips any file that
1010
- // already exists, which is the non-destructive merge an adopted repo needs.
1011
-
1012
- heading('Initialising project');
1013
- runInitombuto(targetDir, ['--keep-docs', targetDir], initEnv);
1014
-
1015
- // ── No Step 4: the directory's git history is the owner's business ──
1016
-
1017
- console.log(`
1018
- ╔═══════════════════════════════════════════╗
1019
- ║ Workbench added! ║
1020
- ╚═══════════════════════════════════════════╝
1021
-
1022
- cd ${targetName}
1023
- `);
1024
- if (targetIsGitRepo) {
1025
- console.log(` This directory is already a git repository. Nothing was committed;
1026
- when you are ready, commit the workbench and its docs skeleton:
1027
-
1028
- git add .ombutocode docs .gitignore
1029
- git commit -m "Add Ombuto Code workbench"
1030
- `);
1031
- } else {
1032
- console.log(` This directory is not a git repository. The workbench needs one
1033
- (agents build in git worktrees), so initialise it before running agents:
1034
-
1035
- git init && git add -A && git commit -m "Initial commit"
1036
- `);
1037
- }
1038
- console.log(` # Read this first:
1039
- GettingStarted.md — what's in the project and what to do next
1040
- ${omitDev ? `
1041
- # Headless CLI:
1042
- node .ombutocode/src/headless.js status
1043
- ` : `
1044
- # Launch the workbench:
1045
- .ombutocode/buildandrun.bat # Windows
1046
- bash .ombutocode/buildandrun # macOS / Linux
1047
- `}
1048
- Happy building!
1049
- `);
1050
- process.exit(0);
1051
- }
1052
-
1053
- // ═════════════════════════════════════════════════════════════════════
1054
- // Create a new project
1055
- // ═════════════════════════════════════════════════════════════════════
1056
-
1057
- if (!projectName) {
1058
- fatal('Please specify a project name:\n\n npx create-ombutocode my-app\n');
1059
- }
1060
-
1061
- if (fs.existsSync(projectName)) {
1062
- fatal(`Directory "${projectName}" already exists.`);
1063
- }
1064
-
1065
- // ── Banner ──
1066
-
1067
- banner();
1068
-
1069
- console.log(`Creating project: ${projectName}`);
1070
-
1071
- // ── Step 1: Clone the repository at the pinned release tag ──
1072
-
1073
- heading(`Cloning Ombuto Code ${CLONE_REF}`);
1074
- run(`git clone --depth 1 --branch ${CLONE_REF} ${REPO_URL} "${projectName}"`);
1075
-
1076
- const projectDir = path.resolve(projectName);
1077
-
1078
- // Remove the .git directory so the user starts fresh
1079
- const gitDir = path.join(projectDir, '.git');
1080
- if (fs.existsSync(gitDir)) {
1081
- log('Removing upstream .git history...');
1082
- fs.rmSync(gitDir, { recursive: true, force: true });
1083
- }
1084
-
1085
- // Remove create-ombutocode directory (the installer itself)
1086
- const installerDir = path.join(projectDir, 'create-ombutocode');
1087
- if (fs.existsSync(installerDir)) {
1088
- log('Removing installer package...');
1089
- fs.rmSync(installerDir, { recursive: true, force: true });
1090
- }
1091
-
1092
- // ── Step 1b: Strip upstream maintainer files & write project templates ──
1093
- //
1094
- // The Ombuto Code repo we just cloned contains files that belong to the
1095
- // upstream project (README, CLA, CONTRIBUTING, DeployInstructions, CLAUDE,
1096
- // root LICENSE) — they should not travel into the user's new project.
1097
- // Replace them with minimal project-specific templates.
1098
-
1099
- heading('Preparing project files');
1100
- stripUpstreamFiles(projectDir);
1101
- writeTemplateFiles(projectDir, projectName);
1102
-
1103
- // ── Step 2: Install dependencies ──
1104
-
1105
- heading('Installing dependencies');
1106
- const srcDir = path.join(projectDir, '.ombutocode', 'src');
1107
- if (fs.existsSync(path.join(srcDir, 'package.json'))) {
1108
- run(npmInstallCmd, { cwd: srcDir });
1109
- noteOmitDev();
1110
- } else {
1111
- fatal('.ombutocode/src/package.json not found — repository may be corrupted.');
1112
- }
1113
-
1114
- // ── Step 3: Initialise project data ──
1115
-
1116
- heading('Initialising project');
1117
-
1118
- // Run initombuto with --clear to create fresh docs/
1119
- runInitombuto(projectDir, ['--clear', projectDir], initEnv);
1120
-
1121
- // ── Step 4: Initialise git ──
1122
-
1123
- heading('Initialising Git repository');
1124
- run('git init', { cwd: projectDir });
1125
- run('git add -A', { cwd: projectDir });
1126
- run('git commit -m "Initial commit — Ombuto Code project"', { cwd: projectDir });
1127
-
1128
- // ── Done ──
1129
-
1130
- console.log(`
1131
- ╔═══════════════════════════════════════════╗
1132
- ║ Project ready! ║
1133
- ╚═══════════════════════════════════════════╝
1134
-
1135
- cd ${projectName}
1136
-
1137
- # Read this first:
1138
- GettingStarted.md — what's in the project and what to do next
1139
-
1140
- # Launch the workbench:
1141
- .ombutocode/buildandrun.bat # Windows
1142
- bash .ombutocode/buildandrun # macOS / Linux
1143
-
1144
- Happy building!
1145
- `);
1146
- }
1147
-
1148
- // Exported for the tests in ../test; the CLI only runs when this file is
1149
- // executed directly.
1150
- module.exports = {
1151
- VERSION,
1152
- CLONE_REF,
1153
- UPGRADE_REPLACE_DIRS,
1154
- UPGRADE_REPLACE_FILES,
1155
- UPGRADE_REPLACE_PREFIXES,
1156
- UPGRADE_BACKUP_PATHS,
1157
- crc32,
1158
- writeZip,
1159
- readZipEntries,
1160
- collectBackupEntries,
1161
- backupWorkbenchState,
1162
- replaceWorkbench,
1163
- seedMissingSkills,
1164
- findRunningWorkbench,
1165
- compareVersions,
1166
- copyMissingFiles,
1167
- };
1168
-
1169
- if (require.main === module) {
1170
- main();
1171
- }
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+ const zlib = require('zlib');
7
+ const { execSync } = require('child_process');
8
+
9
+ const REPO_URL = 'https://github.com/FrancoisBotha/ombutocode.git';
10
+ // Installer version is kept in lockstep with the workbench version
11
+ // (.ombutocode/src/package.json) — every workbench release bumps both
12
+ // to the same number. See DeployInstructions.md §3 and §3.0.
13
+ const VERSION = '1.0.1';
14
+
15
+ // Pinned Ombuto Code workbench release to clone.
16
+ //
17
+ // This installer version ships paired with a specific, tested release of
18
+ // the workbench — not the tip of main — so that every `npx create-ombutocode`
19
+ // run is reproducible. To ship a new workbench release to users:
20
+ //
21
+ // 1. Tag and release the workbench on GitHub (see DeployInstructions.md §2)
22
+ // 2. Bump CLONE_REF below to the new tag
23
+ // 3. Bump this installer's VERSION (above) and the package.json version
24
+ // 4. `npm publish` the installer (see DeployInstructions.md §3)
25
+ const CLONE_REF = 'v1.0.1';
26
+
27
+ // Files and directories at the repo root that belong to the Ombuto Code
28
+ // upstream project and should be removed from a scaffolded user project.
29
+ //
30
+ // Two categories:
31
+ //
32
+ // 1. Maintainer docs — describe how to contribute to / release Ombuto Code
33
+ // itself, not anything the user's new project should inherit.
34
+ //
35
+ // 2. Sample / demo app files — the upstream repo contains an example
36
+ // Electron + Vue app at the repo root (DropSync) that is used as a
37
+ // test bed for the workbench. It is NOT meant to be a starter template
38
+ // for user projects, so it is stripped too.
39
+ const UPSTREAM_FILES_TO_STRIP = [
40
+ // Maintainer docs
41
+ 'README.md',
42
+ 'CLA.md',
43
+ 'CONTRIBUTING.md',
44
+ 'DeployInstructions.md',
45
+ 'UPGRADING.md',
46
+ 'CLAUDE.md',
47
+ 'LICENSE', // upstream Apache 2.0 lives under .ombutocode/LICENSE
48
+
49
+ // Sample / demo app at the repo root (not a user-facing starter)
50
+ 'src',
51
+ 'scripts',
52
+ 'package.json',
53
+ 'package-lock.json',
54
+ 'vite.config.js',
55
+ 'eslint.config.js',
56
+ 'tsconfig.json',
57
+
58
+ // Maintainer-only tooling & content — not part of what a user's new project needs
59
+ 'migration-tool',
60
+ 'marketing',
61
+ ];
62
+
63
+ // Files in create-ombutocode/template/ that are copied into the scaffolded
64
+ // project after stripping. Any occurrence of {{PROJECT_NAME}} in these
65
+ // files is substituted with the user's project name at copy time.
66
+ const TEMPLATE_FILES = [
67
+ 'README.md',
68
+ 'CLAUDE.md',
69
+ 'GettingStarted.md',
70
+ ];
71
+
72
+ // Root .gitignore entries an adopted project needs so the workbench's
73
+ // dependencies and build output never get committed. Runtime state under
74
+ // .ombutocode/ (databases, logs, run output) is covered by the
75
+ // .ombutocode/.gitignore that ships with the clone.
76
+ const OMBUTO_GITIGNORE_LINES = [
77
+ '.ombutocode/src/node_modules/',
78
+ '.ombutocode/src/release/',
79
+ '.ombutocode/src/dist/',
80
+ ];
81
+
82
+ // ── Upgrade contract ──
83
+ //
84
+ // `--upgrade` replaces the workbench code inside an existing project's
85
+ // .ombutocode/ with the pinned release and leaves everything else alone.
86
+ // These lists are the "Overwrite with the new release" / "Preserve" tables
87
+ // in UPGRADING.md. The upgrade only ever deletes or writes the paths named
88
+ // in UPGRADE_REPLACE_*; nothing under .ombutocode/ is wiped wholesale, so a
89
+ // file that is in neither list is simply left as it was.
90
+
91
+ // Directories replaced wholesale: the old one is deleted (src/ including
92
+ // its node_modules) and the release's copy moved in.
93
+ const UPGRADE_REPLACE_DIRS = ['src', 'tools', 'templates', 'scripts', 'bench'];
94
+
95
+ // Plain files replaced with the release's copy.
96
+ const UPGRADE_REPLACE_FILES = [
97
+ 'OMBUTOCODE_ENGINEERING_GUIDE.md',
98
+ 'README.md',
99
+ 'LICENSE',
100
+ 'codingagent-templates.json',
101
+ ];
102
+
103
+ // Launcher scripts: every plain file directly under .ombutocode/ whose name
104
+ // starts with one of these (buildandrun, buildandrun.bat, buildandrun.sh,
105
+ // initombuto, initombuto.bat, …) is replaced.
106
+ const UPGRADE_REPLACE_PREFIXES = ['buildandrun', 'initombuto'];
107
+
108
+ // Project state captured in the backup zip before anything is replaced,
109
+ // relative to .ombutocode/. Entries that do not exist are skipped. The
110
+ // workbench version marker (src/package.json) rides along so the archive
111
+ // records what it was taken from.
112
+ const UPGRADE_BACKUP_PATHS = [
113
+ 'data',
114
+ 'codingagents',
115
+ 'codingagent-state.json',
116
+ 'planning',
117
+ 'features',
118
+ 'profiles',
119
+ 'src/package.json',
120
+ ];
121
+
122
+ // ── Helpers ──
123
+
124
+ function log(msg) { console.log(` ${msg}`); }
125
+ function heading(msg) { console.log(`\n── ${msg} ──`); }
126
+
127
+ function fatal(msg) {
128
+ console.error(`\n✖ ${msg}`);
129
+ process.exit(1);
130
+ }
131
+
132
+ function run(cmd, opts = {}) {
133
+ try {
134
+ execSync(cmd, { stdio: 'inherit', ...opts });
135
+ } catch {
136
+ fatal(`Command failed: ${cmd}`);
137
+ }
138
+ }
139
+
140
+ function copyDirSync(src, dest) {
141
+ fs.mkdirSync(dest, { recursive: true });
142
+ for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
143
+ const srcPath = path.join(src, entry.name);
144
+ const destPath = path.join(dest, entry.name);
145
+ if (entry.isDirectory()) {
146
+ copyDirSync(srcPath, destPath);
147
+ } else {
148
+ fs.copyFileSync(srcPath, destPath);
149
+ }
150
+ }
151
+ }
152
+
153
+ // Move a directory, falling back to copy + delete when the source and
154
+ // destination sit on different volumes (rename fails with EXDEV there —
155
+ // common when the OS temp directory is on another drive).
156
+ function moveDirSync(src, dest) {
157
+ try {
158
+ fs.renameSync(src, dest);
159
+ } catch (err) {
160
+ if (err && err.code !== 'EXDEV') throw err;
161
+ copyDirSync(src, dest);
162
+ fs.rmSync(src, { recursive: true, force: true });
163
+ }
164
+ }
165
+
166
+ // Git checkouts of older releases may leave these launchers without the
167
+ // executable bit. Set it on the installed copy so ./buildandrun works on macOS
168
+ // and Linux, including after an upgrade.
169
+ function makeLaunchersExecutable(ombutoDir) {
170
+ if (process.platform === 'win32') return;
171
+ for (const name of ['buildandrun', 'buildandrun.sh']) {
172
+ const launcher = path.join(ombutoDir, name);
173
+ if (fs.existsSync(launcher)) {
174
+ fs.chmodSync(launcher, fs.statSync(launcher).mode | 0o111);
175
+ }
176
+ }
177
+ }
178
+
179
+ // node-pty executes spawn-helper when opening an interactive CLI agent PTY.
180
+ // Some macOS installs leave that binary without its executable bit. Its
181
+ // location depends on whether node-pty used a prebuild or compiled locally.
182
+ function makePtySpawnHelperExecutable(srcDir) {
183
+ if (process.platform === 'win32') return;
184
+ const ptyDir = path.join(srcDir, 'node_modules', 'node-pty');
185
+ for (const dir of ['build/Release', 'build/Debug', `prebuilds/${process.platform}-${process.arch}`]) {
186
+ const helper = path.join(ptyDir, dir, 'spawn-helper');
187
+ if (fs.existsSync(helper)) {
188
+ fs.chmodSync(helper, fs.statSync(helper).mode | 0o111);
189
+ }
190
+ }
191
+ }
192
+
193
+ // Copy every file under srcDir into destDir that does not already exist
194
+ // there, recursing into sub-directories. Existing files are never touched.
195
+ // Returns the relative paths that were added.
196
+ function copyMissingFiles(srcDir, destDir) {
197
+ const added = [];
198
+ const walk = (src, rel) => {
199
+ for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
200
+ const srcPath = path.join(src, entry.name);
201
+ const relPath = rel ? `${rel}/${entry.name}` : entry.name;
202
+ const destPath = path.join(destDir, relPath);
203
+ if (entry.isDirectory()) {
204
+ walk(srcPath, relPath);
205
+ } else if (entry.isFile() && !fs.existsSync(destPath)) {
206
+ fs.mkdirSync(path.dirname(destPath), { recursive: true });
207
+ fs.copyFileSync(srcPath, destPath);
208
+ added.push(relPath);
209
+ }
210
+ }
211
+ };
212
+ if (fs.existsSync(srcDir)) walk(srcDir, '');
213
+ return added;
214
+ }
215
+
216
+ function stripUpstreamFiles(projectDir) {
217
+ for (const name of UPSTREAM_FILES_TO_STRIP) {
218
+ const target = path.join(projectDir, name);
219
+ if (fs.existsSync(target)) {
220
+ // Use recursive + force so this handles both files and directories.
221
+ fs.rmSync(target, { recursive: true, force: true });
222
+ log(`Removed upstream ${name}`);
223
+ }
224
+ }
225
+ }
226
+
227
+ // Clone the pinned release into a fresh temp directory and reduce it to the
228
+ // workbench: drop the clone's git history, the installer package, the
229
+ // upstream maintainer files and the upstream docs/ (which hold the Ombuto
230
+ // Code project's own specs and must not leak into someone else's repo).
231
+ // Returns the path of the clone's .ombutocode/ and a cleanup function; the
232
+ // temp directory is also removed on process exit.
233
+ function cloneWorkbench() {
234
+ heading(`Cloning Ombuto Code ${CLONE_REF}`);
235
+ const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'create-ombutocode-'));
236
+ const cloneDir = path.join(tempRoot, 'clone');
237
+ const cleanupTemp = () => { try { fs.rmSync(tempRoot, { recursive: true, force: true }); } catch {} };
238
+ process.on('exit', cleanupTemp);
239
+ run(`git clone --depth 1 --branch ${CLONE_REF} ${REPO_URL} "${cloneDir}"`);
240
+
241
+ heading('Preparing workbench files');
242
+ fs.rmSync(path.join(cloneDir, '.git'), { recursive: true, force: true });
243
+ fs.rmSync(path.join(cloneDir, 'create-ombutocode'), { recursive: true, force: true });
244
+ stripUpstreamFiles(cloneDir);
245
+ fs.rmSync(path.join(cloneDir, 'docs'), { recursive: true, force: true });
246
+ log('Discarded upstream docs/');
247
+
248
+ const clonedOmbutocode = path.join(cloneDir, '.ombutocode');
249
+ if (!fs.existsSync(path.join(clonedOmbutocode, 'src', 'package.json'))) {
250
+ fatal('.ombutocode/src/package.json not found in the clone — repository may be corrupted.');
251
+ }
252
+ return { clonedOmbutocode, cleanupTemp };
253
+ }
254
+
255
+ // Copy the template files into projectDir. With `skipExisting`, a file that
256
+ // is already there (the adopted project's own README, CLAUDE.md, …) is left
257
+ // untouched.
258
+ function writeTemplateFiles(projectDir, projectName, { skipExisting = false } = {}) {
259
+ // Template files ship inside the installer package at ../template
260
+ // relative to this script (bin/create-ombutocode.js).
261
+ const templateDir = path.resolve(__dirname, '..', 'template');
262
+ if (!fs.existsSync(templateDir)) {
263
+ log('Template directory not found — skipping template overlay.');
264
+ return;
265
+ }
266
+
267
+ for (const name of TEMPLATE_FILES) {
268
+ const src = path.join(templateDir, name);
269
+ if (!fs.existsSync(src)) {
270
+ log(`Template file missing: ${name} (skipping)`);
271
+ continue;
272
+ }
273
+ const dest = path.join(projectDir, name);
274
+ if (skipExisting && fs.existsSync(dest)) {
275
+ log(`Kept existing ${name}`);
276
+ continue;
277
+ }
278
+ const content = fs.readFileSync(src, 'utf-8')
279
+ .replace(/\{\{PROJECT_NAME\}\}/g, projectName);
280
+ fs.writeFileSync(dest, content);
281
+ log(`Wrote ${name}`);
282
+ }
283
+ }
284
+
285
+ // Ensure the Ombuto ignore lines are present in <projectDir>/.gitignore.
286
+ // Creates the file if absent; otherwise appends only the missing lines.
287
+ function ensureGitignore(projectDir) {
288
+ const gitignorePath = path.join(projectDir, '.gitignore');
289
+ if (!fs.existsSync(gitignorePath)) {
290
+ fs.writeFileSync(gitignorePath, `# OmbutoCode\n${OMBUTO_GITIGNORE_LINES.join('\n')}\n`);
291
+ log('Wrote .gitignore');
292
+ return;
293
+ }
294
+ const existing = fs.readFileSync(gitignorePath, 'utf-8');
295
+ const present = new Set(existing.split(/\r?\n/).map((l) => l.trim()));
296
+ const missing = OMBUTO_GITIGNORE_LINES.filter((l) => !present.has(l));
297
+ if (missing.length === 0) {
298
+ log('Kept existing .gitignore (Ombuto entries already present)');
299
+ return;
300
+ }
301
+ const separator = existing.length === 0 || existing.endsWith('\n') ? '' : '\n';
302
+ fs.appendFileSync(gitignorePath, `${separator}\n# OmbutoCode\n${missing.join('\n')}\n`);
303
+ log(`Appended ${missing.length} Ombuto entr${missing.length === 1 ? 'y' : 'ies'} to .gitignore`);
304
+ }
305
+
306
+ // Run initombuto against projectDir. `initArgs` is the argument list passed
307
+ // to the script; `env` lets the caller propagate npm config (see --omit-dev).
308
+ function runInitombuto(projectDir, initArgs, env) {
309
+ const isWindows = process.platform === 'win32';
310
+ const initScript = path.join(projectDir, '.ombutocode', isWindows ? 'initombuto.bat' : 'initombuto');
311
+
312
+ if (fs.existsSync(initScript)) {
313
+ const argString = initArgs.map((a) => (a.startsWith('--') ? a : `"${a}"`)).join(' ');
314
+ if (isWindows) {
315
+ run(`"${initScript}" ${argString}`, { cwd: projectDir, env });
316
+ } else {
317
+ // Ensure executable
318
+ try { fs.chmodSync(initScript, 0o755); } catch {}
319
+ run(`bash "${initScript}" ${argString}`, { cwd: projectDir, env });
320
+ }
321
+ return;
322
+ }
323
+
324
+ log('initombuto script not found — creating docs/ structure manually...');
325
+ const dirs = [
326
+ 'Structure', 'Product Requirements Document', 'Architecture',
327
+ 'Functional Requirements', 'Non-Functional Requirements', 'Epics',
328
+ 'BDD Use Cases', 'Use Cases', 'Use Case Diagrams', 'Class Diagrams',
329
+ 'Data Model', 'Style Guide', 'Mockups', 'References', 'Skills',
330
+ 'Test Strategy', 'ScratchPad'
331
+ ];
332
+ for (const dir of dirs) {
333
+ fs.mkdirSync(path.join(projectDir, 'docs', dir), { recursive: true });
334
+ }
335
+ }
336
+
337
+ // ── Minimal ZIP writer / reader ──
338
+ //
339
+ // The installer has no runtime dependencies and must stay that way, so the
340
+ // upgrade backup is written with Node's built-in zlib and a hand-rolled ZIP
341
+ // container: local file headers, a central directory and an end-of-central-
342
+ // directory record, which is everything `unzip`, Expand-Archive and Finder
343
+ // need. No zip64 — fewer than 65,535 entries and under 4 GB — which is far
344
+ // beyond what a workbench backup holds.
345
+
346
+ const CRC32_TABLE = (() => {
347
+ const table = new Int32Array(256);
348
+ for (let n = 0; n < 256; n++) {
349
+ let c = n;
350
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
351
+ table[n] = c;
352
+ }
353
+ return table;
354
+ })();
355
+
356
+ function crc32(buf) {
357
+ let c = -1;
358
+ for (let i = 0; i < buf.length; i++) c = CRC32_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
359
+ return (c ^ -1) >>> 0;
360
+ }
361
+
362
+ // MS-DOS date/time fields as stored in ZIP headers (2-second resolution,
363
+ // nothing before 1980).
364
+ function dosDateTime(date) {
365
+ const d = date.getFullYear() < 1980 ? new Date(1980, 0, 1) : date;
366
+ return {
367
+ time: (d.getHours() << 11) | (d.getMinutes() << 5) | (d.getSeconds() >> 1),
368
+ date: ((d.getFullYear() - 1980) << 9) | ((d.getMonth() + 1) << 5) | d.getDate(),
369
+ };
370
+ }
371
+
372
+ const ZIP_MAX_ENTRIES = 0xffff;
373
+ const ZIP_MAX_BYTES = 0xffffffff;
374
+
375
+ // Write a ZIP archive. `entries` is an array of { name, data } or
376
+ // { name, file } (read from disk at write time, so a backup does not have
377
+ // to sit in memory all at once), with an optional `mtime`. Names use
378
+ // forward slashes. Each entry is deflated unless that would not save
379
+ // anything, in which case it is stored. Returns { entries, bytes }.
380
+ function writeZip(zipPath, entries) {
381
+ if (entries.length > ZIP_MAX_ENTRIES) {
382
+ throw new Error(`too many files for a plain ZIP archive (${entries.length})`);
383
+ }
384
+ const fd = fs.openSync(zipPath, 'w');
385
+ const central = [];
386
+ let offset = 0;
387
+ const write = (buf) => { fs.writeSync(fd, buf); offset += buf.length; };
388
+ try {
389
+ for (const entry of entries) {
390
+ const data = entry.data !== undefined ? entry.data : fs.readFileSync(entry.file);
391
+ const mtime = entry.mtime || (entry.file ? fs.statSync(entry.file).mtime : new Date());
392
+ if (data.length > ZIP_MAX_BYTES) throw new Error(`${entry.name} is too large for a plain ZIP archive`);
393
+ const name = Buffer.from(entry.name, 'utf8');
394
+ const crc = crc32(data);
395
+ let method = 8;
396
+ let payload = zlib.deflateRawSync(data);
397
+ if (payload.length >= data.length) { method = 0; payload = data; }
398
+ const { time, date } = dosDateTime(mtime);
399
+
400
+ const local = Buffer.alloc(30);
401
+ local.writeUInt32LE(0x04034b50, 0); // local file header signature
402
+ local.writeUInt16LE(20, 4); // version needed to extract (2.0)
403
+ local.writeUInt16LE(0x0800, 6); // flags: UTF-8 file names
404
+ local.writeUInt16LE(method, 8);
405
+ local.writeUInt16LE(time, 10);
406
+ local.writeUInt16LE(date, 12);
407
+ local.writeUInt32LE(crc, 14);
408
+ local.writeUInt32LE(payload.length, 18);
409
+ local.writeUInt32LE(data.length, 22);
410
+ local.writeUInt16LE(name.length, 26);
411
+ local.writeUInt16LE(0, 28); // extra field length
412
+ central.push({ name, method, time, date, crc, compressedSize: payload.length, size: data.length, offset });
413
+ write(local);
414
+ write(name);
415
+ write(payload);
416
+ if (offset > ZIP_MAX_BYTES) throw new Error('archive is too large for a plain ZIP archive');
417
+ }
418
+
419
+ const cdStart = offset;
420
+ for (const e of central) {
421
+ const header = Buffer.alloc(46);
422
+ header.writeUInt32LE(0x02014b50, 0); // central directory header signature
423
+ header.writeUInt16LE(20, 4); // version made by
424
+ header.writeUInt16LE(20, 6); // version needed to extract
425
+ header.writeUInt16LE(0x0800, 8); // flags: UTF-8 file names
426
+ header.writeUInt16LE(e.method, 10);
427
+ header.writeUInt16LE(e.time, 12);
428
+ header.writeUInt16LE(e.date, 14);
429
+ header.writeUInt32LE(e.crc, 16);
430
+ header.writeUInt32LE(e.compressedSize, 20);
431
+ header.writeUInt32LE(e.size, 24);
432
+ header.writeUInt16LE(e.name.length, 28);
433
+ header.writeUInt16LE(0, 30); // extra field length
434
+ header.writeUInt16LE(0, 32); // file comment length
435
+ header.writeUInt16LE(0, 34); // disk number start
436
+ header.writeUInt16LE(0, 36); // internal attributes
437
+ header.writeUInt32LE(0, 38); // external attributes
438
+ header.writeUInt32LE(e.offset, 42); // local header offset
439
+ write(header);
440
+ write(e.name);
441
+ }
442
+
443
+ const eocd = Buffer.alloc(22);
444
+ eocd.writeUInt32LE(0x06054b50, 0); // end of central directory signature
445
+ eocd.writeUInt16LE(0, 4); // this disk
446
+ eocd.writeUInt16LE(0, 6); // disk with the central directory
447
+ eocd.writeUInt16LE(central.length, 8); // entries on this disk
448
+ eocd.writeUInt16LE(central.length, 10); // entries total
449
+ eocd.writeUInt32LE(offset - cdStart, 12);
450
+ eocd.writeUInt32LE(cdStart, 16);
451
+ eocd.writeUInt16LE(0, 20); // comment length
452
+ write(eocd);
453
+ } finally {
454
+ fs.closeSync(fd);
455
+ }
456
+ return { entries: central.length, bytes: offset };
457
+ }
458
+
459
+ // Read a ZIP archive's central directory: [{ name, method, crc32, size,
460
+ // compressedSize, offset }]. With `verify`, every entry's data is also
461
+ // inflated and checked against its CRC, which is what makes the backup
462
+ // trustworthy before anything is deleted. Throws on a malformed archive.
463
+ function readZipEntries(zipPath, { verify = false } = {}) {
464
+ const buf = fs.readFileSync(zipPath);
465
+ let eocd = -1;
466
+ for (let i = buf.length - 22; i >= Math.max(0, buf.length - 22 - 0xffff); i--) {
467
+ if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break; }
468
+ }
469
+ if (eocd < 0) throw new Error(`${zipPath}: not a ZIP archive (no end-of-central-directory record)`);
470
+ const count = buf.readUInt16LE(eocd + 10);
471
+ const cdSize = buf.readUInt32LE(eocd + 12);
472
+ const cdOffset = buf.readUInt32LE(eocd + 16);
473
+
474
+ const entries = [];
475
+ let p = cdOffset;
476
+ for (let i = 0; i < count; i++) {
477
+ if (p + 46 > buf.length || buf.readUInt32LE(p) !== 0x02014b50) {
478
+ throw new Error(`${zipPath}: corrupt central directory at entry ${i}`);
479
+ }
480
+ const nameLen = buf.readUInt16LE(p + 28);
481
+ const extraLen = buf.readUInt16LE(p + 30);
482
+ const commentLen = buf.readUInt16LE(p + 32);
483
+ entries.push({
484
+ name: buf.toString('utf8', p + 46, p + 46 + nameLen),
485
+ method: buf.readUInt16LE(p + 10),
486
+ crc32: buf.readUInt32LE(p + 16),
487
+ compressedSize: buf.readUInt32LE(p + 20),
488
+ size: buf.readUInt32LE(p + 24),
489
+ offset: buf.readUInt32LE(p + 42),
490
+ });
491
+ p += 46 + nameLen + extraLen + commentLen;
492
+ }
493
+ if (p !== cdOffset + cdSize) throw new Error(`${zipPath}: central directory size mismatch`);
494
+
495
+ if (verify) {
496
+ for (const e of entries) {
497
+ const h = e.offset;
498
+ if (buf.readUInt32LE(h) !== 0x04034b50) throw new Error(`${zipPath}: bad local header for ${e.name}`);
499
+ const dataStart = h + 30 + buf.readUInt16LE(h + 26) + buf.readUInt16LE(h + 28);
500
+ const payload = buf.subarray(dataStart, dataStart + e.compressedSize);
501
+ let data;
502
+ try {
503
+ data = e.method === 8 ? zlib.inflateRawSync(payload) : payload;
504
+ } catch (err) {
505
+ throw new Error(`${zipPath}: ${e.name} does not verify (${err.message})`);
506
+ }
507
+ if (data.length !== e.size || crc32(data) !== e.crc32) {
508
+ throw new Error(`${zipPath}: ${e.name} does not verify (size or CRC mismatch)`);
509
+ }
510
+ }
511
+ }
512
+ return entries;
513
+ }
514
+
515
+ // ── Upgrade helpers ──
516
+
517
+ function isPidAlive(pid) {
518
+ try { process.kill(pid, 0); return true; } catch (err) { return err.code === 'EPERM'; }
519
+ }
520
+
521
+ // Executable name of a running process, or null if it cannot be determined.
522
+ function processImageName(pid) {
523
+ const opts = { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] };
524
+ try {
525
+ if (process.platform === 'win32') {
526
+ const out = execSync(`tasklist /FI "PID eq ${pid}" /FO CSV /NH`, opts);
527
+ const m = out.match(/^"([^"]+)","(\d+)"/m);
528
+ return m && Number(m[2]) === pid ? m[1] : null;
529
+ }
530
+ return execSync(`ps -p ${pid} -o comm=`, opts).trim() || null;
531
+ } catch {
532
+ return null;
533
+ }
534
+ }
535
+
536
+ // The workbench writes its PID to .ombutocode/.instance.lock on startup and
537
+ // removes the file on a clean exit (see acquireProjectLock in main.js). A
538
+ // crashed app, or a project scaffolded from a clone, leaves a stale PID
539
+ // behind, so a lock only counts when that PID is alive and — where the OS
540
+ // tells us — actually belongs to Electron / Ombuto Code rather than to some
541
+ // unrelated process that inherited the number. Returns { pid, image } for
542
+ // a running workbench, else null.
543
+ function findRunningWorkbench(ombutoDir) {
544
+ const lockPath = path.join(ombutoDir, '.instance.lock');
545
+ if (!fs.existsSync(lockPath)) return null;
546
+ const pid = parseInt(fs.readFileSync(lockPath, 'utf8').trim(), 10);
547
+ if (!Number.isFinite(pid) || pid <= 0 || pid === process.pid) return null;
548
+ if (!isPidAlive(pid)) return null;
549
+ const image = processImageName(pid);
550
+ if (image && !/electron|ombuto/i.test(image)) return null;
551
+ return { pid, image };
552
+ }
553
+
554
+ function readWorkbenchVersion(ombutoDir) {
555
+ const pkgPath = path.join(ombutoDir, 'src', 'package.json');
556
+ try {
557
+ const version = JSON.parse(fs.readFileSync(pkgPath, 'utf8')).version;
558
+ return typeof version === 'string' && version ? version : null;
559
+ } catch {
560
+ return null;
561
+ }
562
+ }
563
+
564
+ // Numeric dotted-version comparison: negative if a < b, positive if a > b.
565
+ function compareVersions(a, b) {
566
+ const pa = String(a).split('.').map((n) => parseInt(n, 10) || 0);
567
+ const pb = String(b).split('.').map((n) => parseInt(n, 10) || 0);
568
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
569
+ const diff = (pa[i] || 0) - (pb[i] || 0);
570
+ if (diff !== 0) return diff;
571
+ }
572
+ return 0;
573
+ }
574
+
575
+ // Every file under the preserved paths (UPGRADE_BACKUP_PATHS), as ZIP
576
+ // entries named `.ombutocode/<relative path>` so the archive extracts back
577
+ // into place from the project root.
578
+ function collectBackupEntries(ombutoDir) {
579
+ const entries = [];
580
+ const walk = (abs, rel) => {
581
+ for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
582
+ const absPath = path.join(abs, entry.name);
583
+ const relPath = `${rel}/${entry.name}`;
584
+ if (entry.isDirectory()) walk(absPath, relPath);
585
+ else if (entry.isFile()) entries.push({ name: relPath, file: absPath });
586
+ }
587
+ };
588
+ for (const p of UPGRADE_BACKUP_PATHS) {
589
+ const abs = path.join(ombutoDir, p);
590
+ if (!fs.existsSync(abs)) continue;
591
+ const rel = `.ombutocode/${p}`;
592
+ if (fs.statSync(abs).isDirectory()) walk(abs, rel);
593
+ else entries.push({ name: rel, file: abs });
594
+ }
595
+ return entries;
596
+ }
597
+
598
+ // Write `.ombutocode-backup-<version>-<YYYYMMDD-HHMMSS>.zip` into projectDir
599
+ // and verify it by re-reading the central directory (entry count, CRCs, and
600
+ // that ombutocode.db made it in whenever it existed). Returns
601
+ // { zipPath, entries, bytes }.
602
+ function backupWorkbenchState(projectDir, currentVersion, now = new Date()) {
603
+ const ombutoDir = path.join(projectDir, '.ombutocode');
604
+ const pad = (n) => String(n).padStart(2, '0');
605
+ const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
606
+ const zipPath = path.join(projectDir, `.ombutocode-backup-${currentVersion}-${stamp}.zip`);
607
+
608
+ const entries = collectBackupEntries(ombutoDir);
609
+ const written = writeZip(zipPath, entries);
610
+ const listed = readZipEntries(zipPath, { verify: true });
611
+ if (listed.length !== entries.length) {
612
+ throw new Error(`backup verification failed: wrote ${entries.length} entries, archive lists ${listed.length}`);
613
+ }
614
+ const dbName = '.ombutocode/data/ombutocode.db';
615
+ if (fs.existsSync(path.join(ombutoDir, 'data', 'ombutocode.db')) && !listed.some((e) => e.name === dbName)) {
616
+ throw new Error(`backup verification failed: ${dbName} is missing from the archive`);
617
+ }
618
+ return { zipPath, entries: listed.length, bytes: written.bytes };
619
+ }
620
+
621
+ // Replace the workbench code in targetOmbutoDir with the release in
622
+ // newOmbutoDir, following the upgrade contract above. newOmbutoDir is
623
+ // consumed (its directories are moved, not copied). Returns a summary:
624
+ // { replaced, removed, profilesAdded, codingagentsAdded, codingagentsNew }.
625
+ function replaceWorkbench(targetOmbutoDir, newOmbutoDir, logFn = log) {
626
+ const result = { replaced: [], removed: [], profilesAdded: [], codingagentsAdded: [], codingagentsNew: null };
627
+ const rm = (p) => fs.rmSync(p, { recursive: true, force: true, maxRetries: 3 });
628
+
629
+ // Directories: delete the old one entirely, then move the release's in.
630
+ for (const name of UPGRADE_REPLACE_DIRS) {
631
+ const target = path.join(targetOmbutoDir, name);
632
+ const source = path.join(newOmbutoDir, name);
633
+ const hadOld = fs.existsSync(target);
634
+ if (hadOld) rm(target);
635
+ if (fs.existsSync(source)) {
636
+ moveDirSync(source, target);
637
+ result.replaced.push(`${name}/`);
638
+ logFn(`Replaced ${name}/`);
639
+ } else if (hadOld) {
640
+ result.removed.push(`${name}/`);
641
+ logFn(`Removed ${name}/ (not shipped by this release)`);
642
+ }
643
+ }
644
+
645
+ // Plain files, including every launcher script (buildandrun*, initombuto*)
646
+ // present on either side, so a launcher the release dropped goes too.
647
+ const fileNames = new Set(UPGRADE_REPLACE_FILES);
648
+ for (const dir of [targetOmbutoDir, newOmbutoDir]) {
649
+ if (!fs.existsSync(dir)) continue;
650
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
651
+ if (entry.isFile() && UPGRADE_REPLACE_PREFIXES.some((p) => entry.name.startsWith(p))) {
652
+ fileNames.add(entry.name);
653
+ }
654
+ }
655
+ }
656
+ for (const name of fileNames) {
657
+ const target = path.join(targetOmbutoDir, name);
658
+ const source = path.join(newOmbutoDir, name);
659
+ const hadOld = fs.existsSync(target);
660
+ if (hadOld) rm(target);
661
+ if (fs.existsSync(source)) {
662
+ fs.copyFileSync(source, target);
663
+ try { fs.chmodSync(target, fs.statSync(source).mode); } catch {}
664
+ result.replaced.push(name);
665
+ logFn(`Replaced ${name}`);
666
+ } else if (hadOld) {
667
+ result.removed.push(name);
668
+ logFn(`Removed ${name} (not shipped by this release)`);
669
+ }
670
+ }
671
+
672
+ // profiles/: additive only — the same rule initombuto applies to skills.
673
+ result.profilesAdded = copyMissingFiles(path.join(newOmbutoDir, 'profiles'), path.join(targetOmbutoDir, 'profiles'));
674
+ for (const rel of result.profilesAdded) logFn(`Added profiles/${rel}`);
675
+
676
+ // codingagents/: codingagents.yml is the user's agent configuration and is
677
+ // never overwritten. When the release's copy differs it is written
678
+ // alongside as codingagents.yml.new for the user to merge. Any other file
679
+ // the release ships in that directory is added only if missing.
680
+ const ymlSource = path.join(newOmbutoDir, 'codingagents', 'codingagents.yml');
681
+ const ymlTarget = path.join(targetOmbutoDir, 'codingagents', 'codingagents.yml');
682
+ const ymlNew = `${ymlTarget}.new`;
683
+ if (fs.existsSync(ymlSource) && fs.existsSync(ymlTarget)) {
684
+ if (fs.readFileSync(ymlSource).equals(fs.readFileSync(ymlTarget))) {
685
+ if (fs.existsSync(ymlNew)) rm(ymlNew);
686
+ } else {
687
+ fs.copyFileSync(ymlSource, ymlNew);
688
+ result.codingagentsNew = ymlNew;
689
+ logFn('Kept codingagents/codingagents.yml; the release\'s version differs and was written as codingagents.yml.new');
690
+ }
691
+ }
692
+ result.codingagentsAdded = copyMissingFiles(path.join(newOmbutoDir, 'codingagents'), path.join(targetOmbutoDir, 'codingagents'));
693
+ for (const rel of result.codingagentsAdded) logFn(`Added codingagents/${rel}`);
694
+
695
+ return result;
696
+ }
697
+
698
+ // Seed docs/Skills/ with any skill template the release ships that the
699
+ // project does not have yet — the same file-by-file rule initombuto uses.
700
+ // initombuto itself is deliberately not run here: even with --keep-docs it
701
+ // deletes the database, ticket files, features and agent state first.
702
+ // Returns the relative paths added.
703
+ function seedMissingSkills(projectDir, ombutoDir, logFn = log) {
704
+ const docsDir = path.join(projectDir, 'docs');
705
+ if (!fs.existsSync(docsDir)) {
706
+ logFn('No docs/ directory — skipped skill seeding');
707
+ return [];
708
+ }
709
+ const added = copyMissingFiles(path.join(ombutoDir, 'templates', 'skills'), path.join(docsDir, 'Skills'));
710
+ for (const rel of added) logFn(`Added docs/Skills/${rel}`);
711
+ return added;
712
+ }
713
+
714
+ // ── CLI ──
715
+
716
+ const HELP = `
717
+ create-ombutocode v${VERSION}
718
+
719
+ Create a new Ombuto Code project — Agentic Software Engineering Workbench
720
+
721
+ Usage:
722
+ npx create-ombutocode <project-name> [--omit-dev]
723
+ npx create-ombutocode --into-existing <dir> [--omit-dev]
724
+ npx create-ombutocode --upgrade [<dir>] [--no-backup] [--force] [--omit-dev]
725
+
726
+ Options:
727
+ --into-existing <dir> Adopt Ombuto Code into an existing directory
728
+ instead of creating a new project. Adds
729
+ .ombutocode/ and seeds docs/ without touching
730
+ any file that is already there, and never runs
731
+ git init/add/commit. <dir> must exist and must
732
+ not already contain .ombutocode/.
733
+ --upgrade [<dir>] Upgrade the workbench (.ombutocode/) of an
734
+ existing project to this installer's release,
735
+ ${CLONE_REF}. <dir> defaults to the current directory.
736
+ Replaces only workbench code (src/, tools/,
737
+ templates/, scripts/, bench/, the launcher
738
+ scripts, the engineering guide, README, LICENSE
739
+ and codingagent-templates.json); the database,
740
+ tickets, codingagents.yml, profiles and docs/
741
+ are left alone. Zips the preserved state into
742
+ .ombutocode-backup-<version>-<timestamp>.zip
743
+ first, and refuses to run while the workbench
744
+ is open.
745
+ --no-backup Skip the backup zip (--upgrade only).
746
+ --force Upgrade even when the project is already at
747
+ ${CLONE_REF} or newer (--upgrade only).
748
+ --omit-dev Install with \`npm install --omit=dev
749
+ --legacy-peer-deps\`: no Electron, Vite or
750
+ electron-builder. For headless and CLI use only —
751
+ the workbench UI cannot be built from such an
752
+ install.
753
+ -h, --help Show this help.
754
+
755
+ Example:
756
+ npx create-ombutocode my-app
757
+ cd my-app
758
+ .ombutocode/buildandrun.bat # Windows
759
+ bash .ombutocode/buildandrun # macOS / Linux
760
+
761
+ Example (existing repository, headless):
762
+ npx create-ombutocode --into-existing /app --omit-dev
763
+ cd /app
764
+ node .ombutocode/src/headless.js status
765
+
766
+ Example (upgrade the workbench in the current project):
767
+ cd my-app
768
+ npx create-ombutocode@latest --upgrade
769
+ `;
770
+
771
+ function main() {
772
+ const args = process.argv.slice(2);
773
+ if (args.includes('--help') || args.includes('-h')) {
774
+ console.log(HELP);
775
+ process.exit(0);
776
+ }
777
+
778
+ let projectName = null;
779
+ let intoExisting = null;
780
+ let upgrade = null; // false: not requested; string: directory to upgrade
781
+ let omitDev = false;
782
+ let noBackup = false;
783
+ let force = false;
784
+
785
+ for (let i = 0; i < args.length; i++) {
786
+ const arg = args[i];
787
+ if (arg === '--omit-dev') {
788
+ omitDev = true;
789
+ } else if (arg === '--no-backup') {
790
+ noBackup = true;
791
+ } else if (arg === '--force') {
792
+ force = true;
793
+ } else if (arg === '--into-existing') {
794
+ intoExisting = args[i + 1];
795
+ i++;
796
+ if (!intoExisting || intoExisting.startsWith('-')) {
797
+ fatal('--into-existing requires a directory:\n\n npx create-ombutocode --into-existing /path/to/repo\n');
798
+ }
799
+ } else if (arg.startsWith('--into-existing=')) {
800
+ intoExisting = arg.slice('--into-existing='.length);
801
+ if (!intoExisting) {
802
+ fatal('--into-existing requires a directory:\n\n npx create-ombutocode --into-existing /path/to/repo\n');
803
+ }
804
+ } else if (arg === '--upgrade') {
805
+ // Optional directory; defaults to the current directory.
806
+ if (args[i + 1] !== undefined && !args[i + 1].startsWith('-')) {
807
+ upgrade = args[i + 1];
808
+ i++;
809
+ } else {
810
+ upgrade = '.';
811
+ }
812
+ } else if (arg.startsWith('--upgrade=')) {
813
+ upgrade = arg.slice('--upgrade='.length) || '.';
814
+ } else if (arg.startsWith('-')) {
815
+ fatal(`Unknown option "${arg}". Run with --help for usage.`);
816
+ } else if (projectName === null) {
817
+ projectName = arg;
818
+ } else {
819
+ fatal(`Unexpected argument "${arg}". Run with --help for usage.`);
820
+ }
821
+ }
822
+
823
+ if ((noBackup || force) && upgrade === null) {
824
+ fatal('--no-backup and --force only apply to --upgrade. Run with --help for usage.');
825
+ }
826
+
827
+ // --omit=dev alone still downloads Electron: @electron/remote (a runtime
828
+ // dependency) declares electron as a peer dependency and npm 7+ installs
829
+ // peers automatically. --legacy-peer-deps turns that off; --omit=peer does
830
+ // not (verified against npm 10). Nothing headless.js loads needs a peer.
831
+ const npmInstallCmd = omitDev
832
+ ? 'npm install --no-audit --no-fund --omit=dev --legacy-peer-deps'
833
+ : 'npm install --no-audit --no-fund';
834
+ // initombuto runs its own plain `npm install`; npm reads npm_config_* from
835
+ // the environment, so this keeps that second install from adding the dev
836
+ // dependencies and Electron back.
837
+ const initEnv = omitDev
838
+ ? { ...process.env, npm_config_omit: 'dev', npm_config_legacy_peer_deps: 'true' }
839
+ : process.env;
840
+
841
+ function noteOmitDev() {
842
+ if (!omitDev) return;
843
+ log('--omit-dev: Electron, Vite and electron-builder were not installed.');
844
+ log('The workbench UI cannot be built from this install; use the headless CLI');
845
+ log('(node .ombutocode/src/headless.js) or re-run `npm install` in .ombutocode/src.');
846
+ }
847
+
848
+ const banner = () => console.log(`
849
+ ╔═══════════════════════════════════════════╗
850
+ ║ create-ombutocode v${VERSION} ║
851
+ ║ Agentic Software Engineering Workbench ║
852
+ ╚═══════════════════════════════════════════╝
853
+ `);
854
+
855
+ // ═════════════════════════════════════════════════════════════════════
856
+ // Upgrade the workbench in an existing project
857
+ // ═════════════════════════════════════════════════════════════════════
858
+
859
+ if (upgrade !== null) {
860
+ if (intoExisting !== null) {
861
+ fatal('--upgrade cannot be combined with --into-existing.');
862
+ }
863
+ // `create-ombutocode my-app --upgrade` reads as naturally as
864
+ // `--upgrade my-app`; treat the positional as the directory.
865
+ if (projectName !== null) {
866
+ if (upgrade !== '.') fatal(`Unexpected argument "${projectName}". Run with --help for usage.`);
867
+ upgrade = projectName;
868
+ }
869
+
870
+ const projectDir = path.resolve(upgrade);
871
+ const ombutoDir = path.join(projectDir, '.ombutocode');
872
+ if (!fs.existsSync(path.join(ombutoDir, 'src', 'package.json'))) {
873
+ fatal(`"${projectDir}" does not contain .ombutocode/src/package.json — nothing to upgrade.\n To add Ombuto Code to a directory that does not have it yet, use:\n\n npx create-ombutocode --into-existing "${projectDir}"\n`);
874
+ }
875
+
876
+ banner();
877
+ console.log(`Upgrading Ombuto Code in: ${projectDir}`);
878
+
879
+ // ── Step 1: Preflight ──
880
+
881
+ heading('Checking the project');
882
+ const running = findRunningWorkbench(ombutoDir);
883
+ if (running) {
884
+ fatal(`The workbench appears to be running for this project (PID ${running.pid}${running.image ? `, ${running.image}` : ''}).\n Close Ombuto Code and run the upgrade again. If the app is not running,\n delete the stale lock file .ombutocode/.instance.lock and retry.`);
885
+ }
886
+ const currentVersion = readWorkbenchVersion(ombutoDir) || 'unknown';
887
+ const targetVersion = CLONE_REF.replace(/^v/, '');
888
+ const cmp = currentVersion === 'unknown' ? -1 : compareVersions(currentVersion, targetVersion);
889
+ if (cmp === 0 && !force) {
890
+ log(`.ombutocode is already at ${targetVersion} — nothing to do. (Use --force to reinstall it anyway.)`);
891
+ process.exit(0);
892
+ }
893
+ if (cmp > 0 && !force) {
894
+ fatal(`.ombutocode is at ${currentVersion}, which is newer than this installer's release (${targetVersion}).\n Run \`npx create-ombutocode@latest --upgrade\` to use the newest installer, or pass --force to downgrade.`);
895
+ }
896
+ log(`Upgrading .ombutocode from ${currentVersion} to ${targetVersion}${cmp > 0 ? ' (downgrade, --force)' : cmp === 0 ? ' (reinstall, --force)' : ''}`);
897
+
898
+ // ── Step 2: Backup ──
899
+
900
+ let backup = null;
901
+ if (noBackup) {
902
+ heading('Backup');
903
+ log('--no-backup: skipping the backup zip.');
904
+ } else {
905
+ heading('Backing up project state');
906
+ try {
907
+ backup = backupWorkbenchState(projectDir, currentVersion);
908
+ } catch (err) {
909
+ fatal(`Could not write the backup: ${err.message}\n Nothing has been changed. Fix the problem and retry, or pass --no-backup.`);
910
+ }
911
+ log(`Wrote ${path.basename(backup.zipPath)} (${backup.entries} files, ${(backup.bytes / 1024).toFixed(0)} KB)`);
912
+ }
913
+
914
+ // ── Step 3: Fetch the release ──
915
+
916
+ const { clonedOmbutocode, cleanupTemp } = cloneWorkbench();
917
+
918
+ // ── Step 4: Replace the workbench code ──
919
+ //
920
+ // From here on the project is being modified. Any failure — including
921
+ // one inside `run()`, which exits the process — has to leave the user
922
+ // with clear recovery instructions, hence the exit hook.
923
+
924
+ heading('Replacing workbench code');
925
+ let replacing = true;
926
+ process.on('exit', (code) => {
927
+ if (code === 0 || !replacing) return;
928
+ console.error(`
929
+ ✖ The upgrade did not complete; .ombutocode/ may be half-replaced.
930
+ To restore the previous workbench:
931
+ git checkout -- .ombutocode # if it was committed, and
932
+ ${backup ? ` unzip -o "${path.basename(backup.zipPath)}" # or Expand-Archive on Windows\n` : ''} then re-run the upgrade once the cause is fixed.`);
933
+ });
934
+
935
+ let summary;
936
+ try {
937
+ summary = replaceWorkbench(ombutoDir, clonedOmbutocode);
938
+ makeLaunchersExecutable(ombutoDir);
939
+ seedMissingSkills(projectDir, ombutoDir);
940
+ } catch (err) {
941
+ fatal(`Replacing the workbench failed: ${err.message}`);
942
+ }
943
+ cleanupTemp();
944
+
945
+ // ── Step 5: Install dependencies ──
946
+
947
+ heading('Installing dependencies');
948
+ run(npmInstallCmd, { cwd: path.join(ombutoDir, 'src') });
949
+ makePtySpawnHelperExecutable(path.join(ombutoDir, 'src'));
950
+ noteOmitDev();
951
+ replacing = false;
952
+
953
+ // ── Done ──
954
+
955
+ const newVersion = readWorkbenchVersion(ombutoDir) || targetVersion;
956
+ console.log(`
957
+ ╔═══════════════════════════════════════════╗
958
+ ║ Workbench upgraded! ║
959
+ ╚═══════════════════════════════════════════╝
960
+
961
+ .ombutocode: ${currentVersion} → ${newVersion}
962
+ `);
963
+ if (backup) {
964
+ console.log(` Backup of your database, tickets, agent config and profiles:
965
+ ${backup.zipPath}
966
+ Delete it once you are happy with the upgrade (or ignore .ombutocode-backup-*.zip).
967
+ `);
968
+ }
969
+ if (summary.codingagentsNew) {
970
+ console.log(` codingagents/codingagents.yml was kept as-is. This release ships a
971
+ different default, written next to it as codingagents.yml.new — compare
972
+ and merge anything you want, then delete the .new file.
973
+ `);
974
+ }
975
+ console.log(` Next:
976
+ git status # review what changed under .ombutocode/ and docs/Skills/
977
+ git add -A .ombutocode docs && git commit -m "Upgrade Ombuto Code to ${newVersion}"
978
+
979
+ Check the release notes for version-specific steps:
980
+ https://github.com/FrancoisBotha/ombutocode/releases
981
+ ${omitDev ? `
982
+ # Headless CLI:
983
+ node .ombutocode/src/headless.js status
984
+ ` : `
985
+ # Launch the workbench:
986
+ .ombutocode/buildandrun.bat # Windows
987
+ bash .ombutocode/buildandrun # macOS / Linux
988
+ `}`);
989
+ process.exit(0);
990
+ }
991
+
992
+ // ═════════════════════════════════════════════════════════════════════
993
+ // Adopt into an existing directory
994
+ // ═════════════════════════════════════════════════════════════════════
995
+
996
+ if (intoExisting !== null) {
997
+ if (projectName !== null) {
998
+ fatal('Give either a <project-name> or --into-existing <dir>, not both.');
999
+ }
1000
+
1001
+ const targetDir = path.resolve(intoExisting);
1002
+ if (!fs.existsSync(targetDir) || !fs.statSync(targetDir).isDirectory()) {
1003
+ fatal(`Directory "${targetDir}" does not exist. --into-existing adopts an existing directory; use \`npx create-ombutocode <project-name>\` to create a new one.`);
1004
+ }
1005
+ if (fs.existsSync(path.join(targetDir, '.ombutocode'))) {
1006
+ fatal(`"${targetDir}" already contains .ombutocode/ — refusing to overwrite an existing Ombuto Code installation. To move it to this installer's release, use \`npx create-ombutocode --upgrade "${targetDir}"\`.`);
1007
+ }
1008
+ const targetName = path.basename(targetDir);
1009
+ const targetIsGitRepo = fs.existsSync(path.join(targetDir, '.git'));
1010
+
1011
+ banner();
1012
+ console.log(`Adopting Ombuto Code into: ${targetDir}`);
1013
+
1014
+ // ── Step 1: Clone the pinned release and reduce it to the workbench ──
1015
+ //
1016
+ // Only .ombutocode/ travels into the adopted directory. The clone's
1017
+ // docs/ holds the upstream project's own specs and epics, which must not
1018
+ // leak into someone else's repository — the docs/ skeleton is seeded by
1019
+ // initombuto below instead, file by file, only where nothing exists yet.
1020
+
1021
+ const { clonedOmbutocode, cleanupTemp } = cloneWorkbench();
1022
+ moveDirSync(clonedOmbutocode, path.join(targetDir, '.ombutocode'));
1023
+ makeLaunchersExecutable(path.join(targetDir, '.ombutocode'));
1024
+ log('Added .ombutocode/');
1025
+ cleanupTemp();
1026
+
1027
+ writeTemplateFiles(targetDir, targetName, { skipExisting: true });
1028
+ ensureGitignore(targetDir);
1029
+
1030
+ // ── Step 2: Install dependencies ──
1031
+
1032
+ heading('Installing dependencies');
1033
+ run(npmInstallCmd, { cwd: path.join(targetDir, '.ombutocode', 'src') });
1034
+ makePtySpawnHelperExecutable(path.join(targetDir, '.ombutocode', 'src'));
1035
+ noteOmitDev();
1036
+
1037
+ // ── Step 3: Initialise project data ──
1038
+ //
1039
+ // --keep-docs: never wipe docs/. initombuto still creates every missing
1040
+ // docs/ folder, starter document and skill file, and skips any file that
1041
+ // already exists, which is the non-destructive merge an adopted repo needs.
1042
+
1043
+ heading('Initialising project');
1044
+ runInitombuto(targetDir, ['--keep-docs', targetDir], initEnv);
1045
+
1046
+ // ── No Step 4: the directory's git history is the owner's business ──
1047
+
1048
+ console.log(`
1049
+ ╔═══════════════════════════════════════════╗
1050
+ ║ Workbench added! ║
1051
+ ╚═══════════════════════════════════════════╝
1052
+
1053
+ cd ${targetName}
1054
+ `);
1055
+ if (targetIsGitRepo) {
1056
+ console.log(` This directory is already a git repository. Nothing was committed;
1057
+ when you are ready, commit the workbench and its docs skeleton:
1058
+
1059
+ git add .ombutocode docs .gitignore
1060
+ git commit -m "Add Ombuto Code workbench"
1061
+ `);
1062
+ } else {
1063
+ console.log(` This directory is not a git repository. The workbench needs one
1064
+ (agents build in git worktrees), so initialise it before running agents:
1065
+
1066
+ git init && git add -A && git commit -m "Initial commit"
1067
+ `);
1068
+ }
1069
+ console.log(` # Read this first:
1070
+ GettingStarted.md — what's in the project and what to do next
1071
+ ${omitDev ? `
1072
+ # Headless CLI:
1073
+ node .ombutocode/src/headless.js status
1074
+ ` : `
1075
+ # Launch the workbench:
1076
+ .ombutocode/buildandrun.bat # Windows
1077
+ bash .ombutocode/buildandrun # macOS / Linux
1078
+ `}
1079
+ Happy building!
1080
+ `);
1081
+ process.exit(0);
1082
+ }
1083
+
1084
+ // ═════════════════════════════════════════════════════════════════════
1085
+ // Create a new project
1086
+ // ═════════════════════════════════════════════════════════════════════
1087
+
1088
+ if (!projectName) {
1089
+ fatal('Please specify a project name:\n\n npx create-ombutocode my-app\n');
1090
+ }
1091
+
1092
+ if (fs.existsSync(projectName)) {
1093
+ fatal(`Directory "${projectName}" already exists.`);
1094
+ }
1095
+
1096
+ // ── Banner ──
1097
+
1098
+ banner();
1099
+
1100
+ console.log(`Creating project: ${projectName}`);
1101
+
1102
+ // ── Step 1: Clone the repository at the pinned release tag ──
1103
+
1104
+ heading(`Cloning Ombuto Code ${CLONE_REF}`);
1105
+ run(`git clone --depth 1 --branch ${CLONE_REF} ${REPO_URL} "${projectName}"`);
1106
+
1107
+ const projectDir = path.resolve(projectName);
1108
+ makeLaunchersExecutable(path.join(projectDir, '.ombutocode'));
1109
+
1110
+ // Remove the .git directory so the user starts fresh
1111
+ const gitDir = path.join(projectDir, '.git');
1112
+ if (fs.existsSync(gitDir)) {
1113
+ log('Removing upstream .git history...');
1114
+ fs.rmSync(gitDir, { recursive: true, force: true });
1115
+ }
1116
+
1117
+ // Remove create-ombutocode directory (the installer itself)
1118
+ const installerDir = path.join(projectDir, 'create-ombutocode');
1119
+ if (fs.existsSync(installerDir)) {
1120
+ log('Removing installer package...');
1121
+ fs.rmSync(installerDir, { recursive: true, force: true });
1122
+ }
1123
+
1124
+ // ── Step 1b: Strip upstream maintainer files & write project templates ──
1125
+ //
1126
+ // The Ombuto Code repo we just cloned contains files that belong to the
1127
+ // upstream project (README, CLA, CONTRIBUTING, DeployInstructions, CLAUDE,
1128
+ // root LICENSE) — they should not travel into the user's new project.
1129
+ // Replace them with minimal project-specific templates.
1130
+
1131
+ heading('Preparing project files');
1132
+ stripUpstreamFiles(projectDir);
1133
+ writeTemplateFiles(projectDir, projectName);
1134
+
1135
+ // ── Step 2: Install dependencies ──
1136
+
1137
+ heading('Installing dependencies');
1138
+ const srcDir = path.join(projectDir, '.ombutocode', 'src');
1139
+ if (fs.existsSync(path.join(srcDir, 'package.json'))) {
1140
+ run(npmInstallCmd, { cwd: srcDir });
1141
+ makePtySpawnHelperExecutable(srcDir);
1142
+ noteOmitDev();
1143
+ } else {
1144
+ fatal('.ombutocode/src/package.json not found — repository may be corrupted.');
1145
+ }
1146
+
1147
+ // ── Step 3: Initialise project data ──
1148
+
1149
+ heading('Initialising project');
1150
+
1151
+ // Run initombuto with --clear to create fresh docs/
1152
+ runInitombuto(projectDir, ['--clear', projectDir], initEnv);
1153
+
1154
+ // ── Step 4: Initialise git ──
1155
+
1156
+ heading('Initialising Git repository');
1157
+ run('git init', { cwd: projectDir });
1158
+ run('git add -A', { cwd: projectDir });
1159
+ run('git commit -m "Initial commit — Ombuto Code project"', { cwd: projectDir });
1160
+
1161
+ // ── Done ──
1162
+
1163
+ console.log(`
1164
+ ╔═══════════════════════════════════════════╗
1165
+ ║ Project ready! ║
1166
+ ╚═══════════════════════════════════════════╝
1167
+
1168
+ cd ${projectName}
1169
+
1170
+ # Read this first:
1171
+ GettingStarted.md — what's in the project and what to do next
1172
+
1173
+ # Launch the workbench:
1174
+ .ombutocode/buildandrun.bat # Windows
1175
+ bash .ombutocode/buildandrun # macOS / Linux
1176
+
1177
+ Happy building!
1178
+ `);
1179
+ }
1180
+
1181
+ // Exported for the tests in ../test; the CLI only runs when this file is
1182
+ // executed directly.
1183
+ module.exports = {
1184
+ VERSION,
1185
+ CLONE_REF,
1186
+ UPGRADE_REPLACE_DIRS,
1187
+ UPGRADE_REPLACE_FILES,
1188
+ UPGRADE_REPLACE_PREFIXES,
1189
+ UPGRADE_BACKUP_PATHS,
1190
+ crc32,
1191
+ writeZip,
1192
+ readZipEntries,
1193
+ collectBackupEntries,
1194
+ backupWorkbenchState,
1195
+ replaceWorkbench,
1196
+ seedMissingSkills,
1197
+ findRunningWorkbench,
1198
+ compareVersions,
1199
+ copyMissingFiles,
1200
+ makeLaunchersExecutable,
1201
+ makePtySpawnHelperExecutable,
1202
+ };
1203
+
1204
+ if (require.main === module) {
1205
+ main();
1206
+ }