dreamteamer 0.46.1 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,121 @@
1
+ // `dt check modules/<id> --alone` — is this inline module publishable? (cr-dt-007, G3, D63, D65)
2
+ //
3
+ // The gate does to a module what a stranger's workspace will: packs it with `npm pack` (so its `files`
4
+ // list is what is judged), `init`s a fresh workspace on THIS engine, `dt install`s the tarball with only
5
+ // the module's declared `dreamteamer.dependencies` (each packed from this workspace — `modules/` or
6
+ // `node_modules` — never fetched, so the gate is offline), then compiles and checks it and prints the
7
+ // module's setup line. It learns nothing about the module beyond its manifest, and it runs no package
8
+ // script of the author's (D63: the author's `npm test` is the author's).
9
+ //
10
+ // exit 0 publishable — including a unit that still needs an input a stranger supplies later (install 3)
11
+ // exit 1 refused, the first reason named: a dependency not held here, a floor above this engine, a
12
+ // refused install, a compile error, a check violation
13
+ // exit 2 usage
14
+ //
15
+ // Dispatched from src/cli.js before the host workspace is opened: a module whose dependency is
16
+ // missing would fail the HOST's compile, and the gate's whole point is to say so by name.
17
+ import fs from 'node:fs';
18
+ import os from 'node:os';
19
+ import path from 'node:path';
20
+ import { spawnSync } from 'node:child_process';
21
+ import { fileURLToPath } from 'node:url';
22
+ import { resolveNpm, childEnv } from './checkout.js';
23
+
24
+ const ENGINE = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
25
+ const IDENTITY = { GIT_AUTHOR_NAME: 'dreamteamer check', GIT_AUTHOR_EMAIL: 'check@example.invalid', GIT_COMMITTER_NAME: 'dreamteamer check', GIT_COMMITTER_EMAIL: 'check@example.invalid' };
26
+
27
+ /** Run `engine`'s CLI in `cwd`, output captured, no stdin. */
28
+ export function engineRun(engine, cwd, args, { env = {}, timeoutMs = 300_000, input } = {}) {
29
+ const r = spawnSync(process.execPath, [path.join(engine, 'bin', 'dreamteamer.js'), ...args], {
30
+ cwd, encoding: 'utf8', timeout: timeoutMs, killSignal: 'SIGKILL',
31
+ env: { ...process.env, ...IDENTITY, NO_COLOR: '1', ...env },
32
+ ...(input !== undefined ? { input } : { stdio: ['ignore', 'pipe', 'pipe'] }),
33
+ });
34
+ return { status: r.status, stdout: r.stdout ?? '', stderr: r.stderr ?? '' };
35
+ }
36
+
37
+ /** A fresh workspace in `root` on `engine`: the engine declared as a `file:` dependency and linked
38
+ * before `init`, so init finds it present and asks no registry. Throws with init's words on failure. */
39
+ export function freshWorkspace(root, engine = ENGINE) {
40
+ fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify({ name: path.basename(root).toLowerCase().replace(/[^a-z0-9-]/g, '-'), private: true, dependencies: { dreamteamer: `file:${engine}` } }, null, '\t') + '\n');
41
+ fs.mkdirSync(path.join(root, 'node_modules'), { recursive: true });
42
+ fs.symlinkSync(engine, path.join(root, 'node_modules', 'dreamteamer'), 'dir');
43
+ const r = engineRun(engine, root, ['init', '--no-input'], { timeoutMs: 180_000 });
44
+ if (r.status !== 0) throw new Error(`dt init failed (exit ${r.status}): ${(r.stderr || r.stdout).trim().split('\n')[0]}`);
45
+ return root;
46
+ }
47
+
48
+ const readPkg = (dir) => JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
49
+
50
+ /** Where this workspace holds a package by name: an inline module whose package.json names it, or node_modules/<name>. */
51
+ function locate(root, name) {
52
+ const inline = path.join(root, 'modules');
53
+ if (fs.existsSync(inline)) for (const d of fs.readdirSync(inline)) {
54
+ try { if (readPkg(path.join(inline, d)).name === name) return path.join(inline, d); } catch { /* not a module folder */ }
55
+ }
56
+ const npm = path.join(root, 'node_modules', name);
57
+ return fs.existsSync(path.join(npm, 'package.json')) ? fs.realpathSync(npm) : null;
58
+ }
59
+
60
+ function npmPack(npm, dir, dest) {
61
+ const before = new Set(fs.readdirSync(dest));
62
+ const r = spawnSync(npm, ['pack', '--silent', '--ignore-scripts', '--pack-destination', dest], { cwd: dir, encoding: 'utf8', timeout: 120_000, env: childEnv() });
63
+ if (r.status !== 0) throw new Error(`npm pack failed in ${dir}: ${(r.stderr || r.stdout).trim().split('\n')[0]}`);
64
+ return fs.readdirSync(dest).find((f) => f.endsWith('.tgz') && !before.has(f));
65
+ }
66
+
67
+ /** The gate. `target` is the positional (`modules/<id>`); returns the exit code. */
68
+ export function checkAlone(ws, { target, keep = false, log = console.log, error = console.error } = {}) {
69
+ const usage = (m) => { error(`✖ ${m}`); return 2; };
70
+ if (!target) return usage('check --alone takes modules/<id> — the inline module to judge');
71
+ const m = /^modules\/([^/]+)\/?$/.exec(target);
72
+ const dir = m && path.join(ws.root, 'modules', m[1]);
73
+ if (!dir || !fs.existsSync(path.join(dir, 'package.json'))) return usage(`${target} is not an inline module of this workspace — check --alone takes modules/<id>`);
74
+ const label = `modules/${m[1]}`;
75
+ let pkg;
76
+ try { pkg = readPkg(dir); } catch (e) { error(`✖ ${label}: package.json does not parse — ${e.message}`); return 1; }
77
+ if (!pkg.dreamteamer) { error(`✖ ${label}: package.json has no "dreamteamer" block — the engine would not see it as a module`); return 1; }
78
+ const npm = resolveNpm();
79
+ if (!npm) { error(`✖ ${label}: no npm beside this node or on PATH — the gate packs the module with it`); return 1; }
80
+
81
+ const tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'dt-check-alone-')));
82
+ const refuse = (why) => { error(`✖ ${label}: ${why}`); if (keep) log(` kept: ${path.join(tmp, 'ws')}`); else fs.rmSync(tmp, { recursive: true, force: true }); return 1; };
83
+ try {
84
+ // the module and its declared dependency closure, packed into one folder `dt install --from` reads
85
+ const from = path.join(tmp, 'from');
86
+ fs.mkdirSync(from);
87
+ npmPack(npm, dir, from);
88
+ const deps = [];
89
+ const seen = new Set([pkg.name]);
90
+ const queue = [...(pkg.dreamteamer.dependencies ?? [])];
91
+ while (queue.length) {
92
+ const name = queue.shift();
93
+ if (seen.has(name)) continue;
94
+ seen.add(name);
95
+ const at = locate(ws.root, name);
96
+ if (!at) return refuse(`dependency ${name} is not installed here — install it, or drop it from dreamteamer.dependencies`);
97
+ npmPack(npm, at, from);
98
+ deps.push(name);
99
+ queue.push(...(readPkg(at).dreamteamer?.dependencies ?? []));
100
+ }
101
+ // a fresh workspace on this engine, the module installed the way a stranger installs it
102
+ const root = path.join(tmp, 'ws');
103
+ fs.mkdirSync(root);
104
+ freshWorkspace(root);
105
+ const inst = engineRun(ENGINE, root, ['install', pkg.name, '--from', from, '--no-input']);
106
+ if (inst.status !== 0 && inst.status !== 3) return refuse((inst.stderr || inst.stdout).trim().split('\n').find((l) => l.trim()) ?? `dt install exited ${inst.status}`);
107
+ const comp = engineRun(ENGINE, root, ['compile']);
108
+ if (comp.status !== 0) return refuse(`compile: ${(comp.stderr || comp.stdout).trim().split('\n')[0]}`);
109
+ const chk = engineRun(ENGINE, root, ['check']);
110
+ if (chk.status !== 0) return refuse(`check: ${(chk.stdout + chk.stderr).trim().split('\n').find((l) => l.startsWith('✖')) ?? `exited ${chk.status}`}`);
111
+ // the module's setup line(s), as a stranger's `dt status` will draw them
112
+ const status = engineRun(ENGINE, root, ['status']);
113
+ const setup = (status.stdout.split('setup:\n')[1] ?? '').split('\n').filter((l) => l.startsWith(' ') && !/^\s+dreamteamer\b/.test(l));
114
+ log(`✔ ${label} is publishable — packed, installed alone${deps.length ? ` (with ${deps.join(', ')})` : ''}, compiled, checked`);
115
+ for (const l of setup) log(l);
116
+ if (keep) log(` kept: ${root}`); else fs.rmSync(tmp, { recursive: true, force: true });
117
+ return 0;
118
+ } catch (e) {
119
+ return refuse(e.message);
120
+ }
121
+ }
package/src/checkout.js CHANGED
@@ -5,8 +5,10 @@ import fs, { realpathSync } from 'node:fs';
5
5
  import { execFileSync, spawnSync } from 'node:child_process';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import { staleness, compile, discoverModules } from './compile.js';
8
- import { install as restoreGitModules, offRef } from './init.js';
8
+ import { init, initFootprint, seedBlock, install as restoreGitModules, offRef } from './init.js';
9
9
  import { declaredGitModules } from './workspace.js';
10
+ import { engineVersion, readManifest, RUNTIME_DIR } from './runtime.js';
11
+ import { satisfies } from './semver.js';
10
12
 
11
13
  export const defaultGit = (args, cwd) => {
12
14
  try {
@@ -451,3 +453,253 @@ export async function installCommand(ws, rest, { open } = {}) {
451
453
  }
452
454
  return code;
453
455
  }
456
+
457
+ // ---- `dt init` — one command from a folder to a compiled, checked, committed workspace ------------
458
+
459
+ const EXACT = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
460
+ const readJson = (f) => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return null; } };
461
+
462
+ /** Where a write to `p` actually lands: every component resolved in order, a link's target spliced in
463
+ * and resolved in turn — so a link whose leaf does not exist yet is still followed through each link
464
+ * among its ancestors, and `..` means the parent of what was REACHED, never the lexical parent. A
465
+ * missing component ends resolution (nothing below it can be a link). Null past 40 links: a loop. */
466
+ function landing(p) {
467
+ // the root (`/`, or `C:\` on Windows — never a segment to join, which made every path land at `C:\C:\…`)
468
+ // is the starting point; the segments after it are walked, either separator accepted
469
+ // the separator is the platform's ONLY: a backslash is a legal character in a POSIX name, and a link named
470
+ // `a\\b` that points out of the folder must be followed as one segment, never read as `a/b`; Windows takes both
471
+ const segments = (q) => q.slice(path.parse(q).root.length).split(process.platform === 'win32' ? /[\\/]/ : path.sep);
472
+ const pending = segments(p);
473
+ let at = path.parse(p).root, hops = 0;
474
+ while (pending.length) {
475
+ const seg = pending.shift();
476
+ if (!seg || seg === '.') continue;
477
+ if (seg === '..') { at = path.dirname(at); continue; }
478
+ const next = path.join(at, seg);
479
+ let st = null;
480
+ try { st = fs.lstatSync(next); } catch { /* absent: created where it is named */ }
481
+ if (!st?.isSymbolicLink()) { at = next; continue; }
482
+ if (++hops > 40) return null;
483
+ const to = fs.readlinkSync(next);
484
+ pending.unshift(...segments(to));
485
+ if (path.isAbsolute(to)) at = path.parse(to).root;
486
+ }
487
+ return at;
488
+ }
489
+
490
+ /** Would a write to `rel` (root-relative, unnormalised — `a/../b` resolves through `a`) land outside `root`? */
491
+ export function escapes(root, rel) {
492
+ // the native realpath: on Windows the JS one leaves an 8.3 short name (RUNNER~1) that the walk below
493
+ // expands, and the two spellings of one folder would read as different places; case is folded there too
494
+ const canon = (q) => { try { return fs.realpathSync.native(q); } catch { return fs.realpathSync(q); } };
495
+ const fold = (q) => (process.platform === 'win32' ? q.toLowerCase() : q);
496
+ const base = canon(root), to = landing(`${base}${path.sep}${rel}`);
497
+ if (to === null) return true;
498
+ const r = path.relative(fold(base), fold(to));
499
+ return r.startsWith('..') || path.isAbsolute(r);
500
+ }
501
+
502
+ /** The links under `rel` (lstat, never descending through one) — compile writes and prunes whole
503
+ * trees there, so a link anywhere below is a place it writes through. */
504
+ function linksUnder(root, rel, out = []) {
505
+ let entries = [];
506
+ try { entries = fs.readdirSync(path.join(root, rel), { withFileTypes: true }); } catch { return out; }
507
+ for (const e of entries) {
508
+ const r = path.join(rel, e.name);
509
+ if (e.isSymbolicLink()) out.push(r);
510
+ else if (e.isDirectory()) linksUnder(root, r, out);
511
+ }
512
+ return out;
513
+ }
514
+
515
+ // compile's built-in outputs: the runtime and the harness trees it writes AND prunes (harnesses.js)
516
+ const OUTPUT_TREES = [RUNTIME_DIR, '.claude/skills', '.claude/agents', '.claude/commands', '.agents/skills', '.cursor/rules'];
517
+
518
+ /** Every DIRECTORY link at or under an output tree — the tree's own root included — wherever it points.
519
+ * ⚠ FAIL CLOSED, not "follow and judge": a link to a folder INSIDE the workspace is harmless as a path
520
+ * and still hides what is below it (`linksUnder` never descends through a link), so a file link in the
521
+ * aliased folder carried compile's write outside (third review). Compile makes none of these itself. */
522
+ function aliasedOutputDirs(root) {
523
+ const isDirLink = (rel) => { try { return fs.lstatSync(path.join(root, rel)).isSymbolicLink() && fs.statSync(path.join(root, rel)).isDirectory(); } catch { return false; } };
524
+ return OUTPUT_TREES.flatMap((t) => [t, ...linksUnder(root, t)]).filter(isDirLink);
525
+ }
526
+
527
+ /** Every path `init --ready` may write, as init and compile will compute them — the effective block,
528
+ * the built-in output trees with every link inside them, the managed-block files the last compile
529
+ * recorded, and any top-level file-position link (a contributed harness writes its block at the root).
530
+ * `.env` is exempt: never written here, and a worktree's is a link to its primary by design. A folder
531
+ * link in an output tree never reaches here — `aliasedOutputDirs` refuses it first. NOT covered: a
532
+ * nested file a newly installed extension's harness writes that no earlier compile recorded. */
533
+ function writeFootprint(root, block, flags) {
534
+ let prev = {};
535
+ try { prev = readManifest(root) ?? {}; } catch { /* unreadable: the walk below still judges .dreamteamer/ */ }
536
+ const top = fs.readdirSync(root, { withFileTypes: true }).filter((e) => e.isSymbolicLink() && e.name !== '.env')
537
+ .filter((e) => { try { return !fs.statSync(path.join(root, e.name)).isDirectory(); } catch { return true; } }).map((e) => e.name);
538
+ return [...new Set([...initFootprint(block, flags), 'package-lock.json', 'node_modules',
539
+ 'CLAUDE.md', 'AGENTS.md', 'GEMINI.md', ...(prev['adapter-blocks'] ?? []), ...(prev['adapter-outputs'] ?? []),
540
+ ...OUTPUT_TREES, ...OUTPUT_TREES.flatMap((t) => linksUnder(root, t)), ...top].map(String))];
541
+ }
542
+
543
+ /**
544
+ * `dt init [--no-git] [--git <url>] [--no-compile] [--from <dir>] [--input k=v]… [--allow <kind>]… [--no-input]`
545
+ * — from a folder (empty, or a cloned preset, or an existing repo) to a workspace that is pinned to the
546
+ * RUNNING engine, compiled, checked, set up as far as its modules' safe actions go, and committed.
547
+ *
548
+ * - every path it or compile writes is judged BEFORE the first write (links out of the folder, aliased
549
+ * output trees, a configured path climbing out), as `init --ready` did
550
+ * - an engine of another version — declared, locked or installed — is the workspace's choice: refused,
551
+ * never upgraded (`dt update --engine` is the deliberate move)
552
+ * - npm runs once: `--save-exact dreamteamer@<this version>` from nothing, or a plain `install` that
553
+ * restores a preset's lockfile and every module it selected; with `--from <dir>` a missing declared
554
+ * package comes from that folder of tarballs (`npm install --no-save`), so package.json is untouched
555
+ * - git: no repository → `git init` and one commit of what init wrote; inside one → the same scoped
556
+ * commit, the operator's staged work untouched; `--no-git` or no git on PATH → written, not committed,
557
+ * and the last line says so; `--git <url>` adds `origin` and never pushes
558
+ * - re-running changes nothing: every step re-checks what is already done
559
+ */
560
+ export async function initCommand(flags, { root = process.cwd(), open, verify, npm = resolveNpm(), stdio = 'inherit', log = console.log, processEnv = process.env, tty = !!(process.stdin.isTTY && process.stdout.isTTY), argv = [] } = {}) {
561
+ const want = engineVersion();
562
+ const pkgPath = path.join(root, 'package.json');
563
+ const pkg = fs.existsSync(pkgPath) ? readJson(pkgPath) : {};
564
+ if (!pkg || typeof pkg !== 'object') throw new Error('package.json is not a JSON object — nothing was written');
565
+ // ⚠ EVERY PATH THIS RUN WRITES IS JUDGED BEFORE THE FIRST WRITE. init and compile write through
566
+ // whatever stands at a path, so a `.gitignore` (or `.claude/skills`, or `modules/`) linked out of the
567
+ // folder would have been rewritten wherever it points, and the run would have said ✔. The block is
568
+ // init's OWN merge (`seedBlock`): a safe flag can never hide an unsafe stored value.
569
+ const block = seedBlock(flags, pkg.dreamteamer);
570
+ for (const k of ['workspace_module', 'data_path']) {
571
+ if (block[k] != null && block[k] !== false && typeof block[k] !== 'string') throw new Error(`dreamteamer.${k} must be a path (got ${JSON.stringify(block[k])}) — nothing was written`);
572
+ }
573
+ const aliased = aliasedOutputDirs(root);
574
+ if (aliased.length) throw new Error(`${aliased.join(', ')}: a folder link inside compile's output — compile writes through it, so nothing was written. Replace it with a real folder (or remove it; compile regenerates what it holds)`);
575
+ const out = writeFootprint(root, block, flags).filter((rel) => escapes(root, rel));
576
+ if (out.length) throw new Error(`${out.join(', ')} ${out.length > 1 ? 'resolve' : 'resolves'} outside this workspace — init writes there, so nothing was written. Replace the link (or the configured path) with one inside the folder`);
577
+
578
+ // ⚠ THE DECLARATION, THE LOCKFILE AND THE INSTALLED COPY ARE JUDGED EACH ON ITS OWN. Reading only the
579
+ // installed copy let a package.json still declaring an older engine pass — the next clone installs that one.
580
+ const specs = [...new Set(['dependencies', 'devDependencies'].map((k) => pkg[k]?.dreamteamer).filter(Boolean))];
581
+ const locked = readJson(path.join(root, 'package-lock.json'))?.packages?.['node_modules/dreamteamer']?.version ?? null;
582
+ const installed = () => readJson(path.join(root, 'node_modules', 'dreamteamer', 'package.json'))?.version ?? null;
583
+ const upgrade = `init never changes an existing engine — run that version itself (npx dreamteamer@<version> init), or upgrade on purpose: dt update --engine`;
584
+ if (specs.length > 1) throw new Error(`package.json declares dreamteamer twice, differently (${specs.join(' and ')}) — keep one declaration`);
585
+ if (specs[0] && (EXACT.test(specs[0]) ? specs[0] !== want : satisfies(want, specs[0]) === false)) throw new Error(`package.json declares dreamteamer "${specs[0]}", which ${want} is not — ${upgrade}`);
586
+ if (locked && locked !== want) throw new Error(`package-lock.json locks dreamteamer ${locked}, not ${want} — ${upgrade}`);
587
+ if (installed() && installed() !== want) throw new Error(`node_modules holds dreamteamer ${installed()}, not ${want} — ${upgrade}`);
588
+ const fromDir = flags.from ? path.resolve(root, flags.from) : null;
589
+ const fail = (why) => { log(`✖ ${why}\n the steps after this one did not run — fix it, then run the same command again: every step re-checks what is already done`); return 1; };
590
+
591
+ // --from: every package this init will need is looked for in the folder BEFORE anything is written —
592
+ // a folder lacking one is refused with the folder untouched (no skeleton, no registry call)
593
+ if (fromDir) {
594
+ const { indexFolder } = await import('./install-modules.js');
595
+ let index;
596
+ try { index = indexFolder(fromDir); } catch (e) { return fail(e.message); }
597
+ const pkg0 = readJson(pkgPath) ?? {};
598
+ const declared0 = !!(pkg0.dependencies?.dreamteamer ?? pkg0.devDependencies?.dreamteamer);
599
+ const missing0 = Object.keys({ ...pkg0.dependencies, ...pkg0.devDependencies }).sort().filter((d) => !fs.existsSync(path.join(root, 'node_modules', d, 'package.json')));
600
+ for (const n of declared0 ? missing0 : ['dreamteamer', ...missing0]) {
601
+ const hit = n === 'dreamteamer' ? (index.get('dreamteamer') ?? []).find((c) => c.version === want) : (index.get(n) ?? [])[0];
602
+ if (!hit) return fail(`--from ${fromDir}: no ${n === 'dreamteamer' ? `dreamteamer@${want}` : n} in it — nothing was written`);
603
+ }
604
+ }
605
+ init({ flags, root, commit: false });
606
+ log('✔ skeleton: the package.json dreamteamer block, the workspace module, .gitignore, .env.example — kept where present');
607
+ // EVERY declared package, not just the engine: a preset whose npm install was interrupted holds the
608
+ // engine and lacks the modules it selected, and compile then succeeds without them (`planInstall`'s lesson).
609
+ const now = () => readJson(pkgPath) ?? {};
610
+ const missing = () => Object.keys({ ...now().dependencies, ...now().devDependencies }).sort().filter((d) => !fs.existsSync(path.join(root, 'node_modules', d, 'package.json')));
611
+ const declared = !!(now().dependencies?.dreamteamer ?? now().devDependencies?.dreamteamer);
612
+ let fresh = false;
613
+ if (declared && !missing().length) log(`✔ dependencies: dreamteamer@${want} and every declared package installed`);
614
+ else {
615
+ if (!npm) return fail('cannot install — node found, npm not on PATH');
616
+ let args;
617
+ if (fromDir) {
618
+ // offline: every missing declared package (the engine too, from nothing) comes from the folder
619
+ const { indexFolder } = await import('./install-modules.js');
620
+ let index;
621
+ try { index = indexFolder(fromDir); } catch (e) { return fail(e.message); }
622
+ const need = declared ? missing() : ['dreamteamer', ...missing()];
623
+ const files = [];
624
+ for (const n of need) {
625
+ const hit = n === 'dreamteamer' ? (index.get('dreamteamer') ?? []).find((c) => c.version === want) : (index.get(n) ?? [])[0];
626
+ if (!hit) return fail(`--from ${fromDir}: no ${n === 'dreamteamer' ? `dreamteamer@${want}` : n} in it — nothing was installed`);
627
+ files.push(hit.file);
628
+ }
629
+ args = declared ? ['install', '--no-save', '--no-audit', '--no-fund', ...files] : ['install', '--save-exact', '--no-audit', '--no-fund', ...files];
630
+ } else args = declared ? ['install', '--no-audit', '--no-fund'] : ['install', '--save-exact', '--no-audit', '--no-fund', `dreamteamer@${want}`];
631
+ log(`▶ dependencies: npm ${args.join(' ')}${missing().length ? ` — missing ${missing().join(', ')}` : ''} — downloads packages and runs their npm lifecycle scripts`);
632
+ const r = spawnSync(npm, args, { cwd: root, stdio, env: childEnv(), timeout: 600_000 });
633
+ if (r.status !== 0) return fail(`npm exited ${r.status ?? r.error?.message}`);
634
+ if (missing().length) return fail(`npm finished, but ${missing().join(', ')} ${missing().length > 1 ? 'are' : 'is'} still not installed`);
635
+ if (installed() !== want) return fail(`npm finished, but node_modules/dreamteamer is ${installed() ?? 'missing'}, not ${want}`);
636
+ fresh = true;
637
+ }
638
+ let ws = null;
639
+ let code = 0;
640
+ if (flags['no-compile']) log('— compile: skipped (--no-compile) — run dt compile before a session reads this workspace');
641
+ else {
642
+ try {
643
+ ws = await open(root);
644
+ const s = staleness(root);
645
+ if (fresh || !s.compiled || s.stale.length) { log('▶ compile'); compile(ws); } else log('✔ compile: fresh');
646
+ } catch (e) { return fail(`compile: ${e.message.split('\n')[0]}`); }
647
+ if (await verify(ws)) return fail('check: the violations above');
648
+ // a preset's modules: the safe part of every unit's setup, exactly as `dt install` runs it
649
+ const { units, runUnit, fillInputs, parseInputFlags, parseAllow, skippedUnits, fold, SetupUsage, ttyIO, unitEnv, EXIT, droppedKeys } = await import('./setup.js');
650
+ const skipped = new Set(skippedUnits(ws));
651
+ const all = units(ws).filter((u) => !skipped.has(u.id));
652
+ if (all.length) {
653
+ const noInput = !!flags['no-input'];
654
+ const term = tty && !noInput ? ttyIO() : null;
655
+ try {
656
+ const filled = await fillInputs(all, { flags: parseInputFlags(argv), env: unitEnv(ws, processEnv), tty, noInput, prompt: term?.prompt ?? null, lenient: true });
657
+ for (const text of filled.ignored) log(`⚠ ${text} — ignored`);
658
+ const allow = parseAllow(argv);
659
+ const written = new Map(); // one run never lets two units disagree on a key (he3)
660
+ for (const u of all) {
661
+ const r = await runUnit(ws, u, { inputs: filled.inputs.get(u.id) ?? {}, allow, tty, ask: term?.ask ?? null, processEnv, drop: droppedKeys(filled.problems, u.id), written });
662
+ const problems = filled.problems.filter((m) => m.unit === u.id);
663
+ const miss = [...filled.missing.filter((m) => m.unit === u.id).map((m) => m.id), ...problems.filter((m) => m.required).map((m) => m.id)];
664
+ const f = fold(r.checks, {});
665
+ log(`${f.state === 'ready' ? '✔' : '—'} ${u.id}: ${f.state}${f.detail ? ` — ${f.detail}` : ''}`);
666
+ for (const a of r.applied) log(` ✔ ${a.id}${a.message ? ` — ${a.message}` : ''}`);
667
+ for (const x of r.failed) log(` ✖ ${x.id} — ${x.message}`);
668
+ if (r.failed.length && code === 0) code = 1; // D57: a failed apply is a failure; the workspace itself stands
669
+ for (const x of problems) log(` ✖ ${x.id} — ${x.reason}`);
670
+ for (const pnd of r.pending) log(` … ${pnd.id} (${pnd.why})${pnd.reason ? ` — ${pnd.reason}` : ''}`);
671
+ if (miss.length) { log(` needs input: ${miss.join(', ')} — dt setup ${u.id} --input ${miss[0]}=<value>`); code = 3; }
672
+ if (r.pending.some((p) => p.runBy === 'owner' || (p.effects ?? []).some((e) => e.kind === 'account'))) log(` the owner's step (opens a browser): dt setup ${u.id}${miss.map((n) => ` --input ${n}=<value>`).join('')} --authorize`);
673
+ }
674
+ } catch (e) {
675
+ if (e instanceof SetupUsage) { fail(e.message); return EXIT.usage; }
676
+ throw e;
677
+ } finally { term?.close(); }
678
+ }
679
+ }
680
+ // git — a repository, a remote, one scoped commit; never the operator's own staged work
681
+ const hasGit = spawnSync('git', ['--version'], { stdio: 'ignore' }).status === 0;
682
+ const isRepo = () => hasGit && spawnSync('git', ['rev-parse', '--git-dir'], { cwd: root, stdio: 'ignore' }).status === 0;
683
+ if (flags['no-git']) log('— git: skipped (--no-git) — `git status` shows what init wrote');
684
+ else if (!hasGit) log('— git: not on PATH — nothing was committed; `git status` shows what init wrote once it is');
685
+ else {
686
+ if (!isRepo()) { spawnSync('git', ['init', '--quiet'], { cwd: root, stdio: 'ignore' }); log('✔ git: repository created (local, no account)'); }
687
+ if (flags.git) {
688
+ const has = spawnSync('git', ['remote', 'get-url', 'origin'], { cwd: root, stdio: 'ignore' }).status === 0;
689
+ if (!has) { spawnSync('git', ['remote', 'add', 'origin', flags.git], { cwd: root, stdio: 'ignore' }); log(`✔ git: origin → ${flags.git} (never pushed)`); } else log('✔ git: origin already set — left as it is');
690
+ }
691
+ const wm = now().dreamteamer?.workspace_module;
692
+ const paths = ['package.json', 'package-lock.json', '.gitignore', '.env.example', '.vscode/extensions.json', ...(wm ? [`modules/${wm}/package.json`, `modules/${wm}/collections/notes.collection.yaml`] : ['collections/notes.collection.yaml'])].filter((rel) => fs.existsSync(path.join(root, rel)));
693
+ const r = spawnSync('git', ['add', '--', ...paths], { cwd: root, stdio: 'ignore' });
694
+ const c = r.status === 0 ? spawnSync('git', ['commit', '--quiet', '-m', `dreamteamer: init workspace ${now().name ?? path.basename(root)}`, '--', ...paths], { cwd: root, encoding: 'utf8' }) : r;
695
+ if (c.status === 0) log(`✔ git: committed ${paths.join(', ')}`);
696
+ else if (/nothing to commit|no changes added/.test(`${c.stdout ?? ''}${c.stderr ?? ''}`)) log('✔ git: nothing new to commit');
697
+ else log(`⚠ git: commit did not happen (${(c.stderr ?? '').trim().split('\n')[0] || `exit ${c.status}`}) — \`git status\` shows what init wrote`);
698
+ }
699
+ if (ws) {
700
+ const { statusLines, renderStatusLines } = await import('./setup.js');
701
+ try { for (const line of renderStatusLines(statusLines(ws, { processEnv }))) log(line); } catch { /* status is a courtesy here */ }
702
+ }
703
+ log(`\nready: dreamteamer@${want}${flags['no-compile'] ? ' (not compiled)' : ', compiled and checked'}. Next: dt install <package> adds a module; dt status says what works here.`);
704
+ return code;
705
+ }