dreamteamer 0.46.0 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.js CHANGED
@@ -20,7 +20,7 @@ import { check } from './check.js';
20
20
  import { collectionCommand, emit, relationsCommand, reportCommits } from './collections-cli.js';
21
21
  import { formatDescriptors } from './schema-ops.js';
22
22
  import { init, installClone, update, listRepos } from './init.js';
23
- import { installCommand, describeCheckout } from './checkout.js';
23
+ import { installCommand, describeCheckout, initCommand } from './checkout.js';
24
24
  import { declaredGitModules } from './workspace.js';
25
25
  const isOwnClone = (p) => { try { return !fs.lstatSync(p).isSymbolicLink() && fs.existsSync(path.join(p, '.git')); } catch { return false; } };
26
26
  import { foldChanges, groupChanges, reportLine } from './events.js';
@@ -29,6 +29,9 @@ import { Store } from './store.js';
29
29
  import { splitRef, canonicalCollection } from './ref.js';
30
30
  import { envContext, renderTemplate } from './env-vars.js';
31
31
  import { doctorBoard, renderBoard } from './doctor.js';
32
+ import { setupCommand, statusLines, renderStatusLines } from './setup.js';
33
+ import { installModules } from './install-modules.js';
34
+ import { updateModules, parseUpdateArgs } from './update.js';
32
35
  import { storageOf } from './descriptor.js';
33
36
 
34
37
  // git calls whose failure we CATCH must not print git's own error: execFileSync forwards the
@@ -209,8 +212,17 @@ Every verb that MOVES records or CLEARS values takes --dry-run and prints its pl
209
212
  records N · refs M · descriptors K · values cleared V
210
213
 
211
214
  workspace verbs:
212
- init write the workspace skeleton into the current directory (never compiles)
213
- [--harnesses claude-code,codex,pi,gemini-cli,cursor]
215
+ init from a folder to a workspace in ONE command: pins the engine that runs it (exactly),
216
+ writes the skeleton, installs, compiles, checks, runs the safe part of any declared
217
+ module's setup, makes the folder a git repository when it is not one and commits what
218
+ it wrote (inside a repository: the same scoped commit, your staged work untouched).
219
+ Refused before any write: an engine of another version declared, locked or installed
220
+ (never upgraded — dt update --engine), and a path it writes that links out of the
221
+ folder. Re-run it to resume — a repeat changes nothing.
222
+ [--no-git] [--git <remote-url>] (adds origin, never pushes) [--no-compile]
223
+ [--from <dir>] (a preset's missing packages from a folder of tarballs, offline)
224
+ [--input <id>=<value>]… [--allow <kind>]… [--no-input] (a preset's setup, as \`setup\`)
225
+ [--harnesses claude-code,codex,pi,gemini-cli,cursor] [--workspace_module <name>]
214
226
  --version print the engine version (works anywhere)
215
227
  install make THIS checkout ready — the engine, .env (linked from the primary when this is a
216
228
  worktree), declared local assets, git modules, compile, and a declared postinstall.
@@ -226,7 +238,21 @@ workspace verbs:
226
238
  install repos/<id> | repos --all [--json]
227
239
  materialize an attached repo's working tree ON DEMAND — never as part of making a
228
240
  checkout ready; --all is the explicit opt-in, e.g. before going offline
241
+ install <spec>… [--from <dir>] bring a MODULE in: a name, name@version, ./file.tgz,
242
+ ./folder (a development link) or a git URL — installs it and every module its
243
+ dreamteamer.dependencies names (refusing, before npm writes anything, a package with
244
+ no dreamteamer key, an engine floor this engine does not meet, a ring, a version
245
+ installed differently, and a package an installed one already provides), pins exact
246
+ versions, compiles, runs the safe part of the module's setup and commits package.json,
247
+ package-lock.json and what setup wrote. Without a version: npm's latest. --from
248
+ resolves names from a folder of tarballs (offline). Setup flags as for \`setup\`:
249
+ [--input <id>=<value>]… [--allow <kind>]… [--no-input]; [--no-commit] [--json]
250
+ Exit 0 done · 1 refused or failed (nothing half-written) · 2 usage · 3 input missing
229
251
  install --clone <url> [name] attach a git module to this workspace
252
+ update <name>[@<version>] | --engine move ONE npm pin forward on purpose: to the latest
253
+ release (or the named version), re-pinned exactly, closure-checked as install is,
254
+ compiled, committed. A downgrade needs [--allow downgrade]; a development link is
255
+ skipped and named; [--from <dir>] resolves from a folder of tarballs; [--no-commit]
230
256
  update pull git_modules clones forward (ff-only on the lockfile ref), rebuild,
231
257
  then compile; [<name>] updates just one. dirty clones are skipped
232
258
  compile materialize modules + workspace sources into .dreamteamer (+ harness adapters)
@@ -243,6 +269,16 @@ workspace verbs:
243
269
  doctor what works on this machine — the engine, then each extension's checks — as one board:
244
270
  READY / DEGRADED / UNAVAILABLE, each fix on its row. Exit 0 [--strict] exit 1 when
245
271
  anything is UNAVAILABLE [--json]
272
+ setup [<unit>] drive the setup a module declares — resume, repair, verify, sign in. The
273
+ engine names no module: a unit is what an installed package contributes (dt status
274
+ lists them). Inputs: [--input <id>=<value>]… (or <unit>.<id>=; then the environment,
275
+ then the declared default; a terminal asks for what is still missing, [--no-input]
276
+ never asks → exit 3 with the ids). Effects: workspace-file writes run; download,
277
+ network and machine ask y/n in a terminal or run under [--allow <kind>]…; an account
278
+ step (sign-in, consent) runs only under [--authorize], in a terminal. [--verify] runs
279
+ the unit's live check and writes its receipt. [--skip] records the skip in
280
+ package.json (dt setup <unit> clears it). [--json] the result as data.
281
+ Exit 0 done (pending and blocked steps printed) · 1 a unit's apply failed · 2 usage · 3 a required input missing
246
282
  status workspace status: compiled runtime freshness, per-module channel/ref, staleness
247
283
 
248
284
  changes the records created / updated / deleted in every repo that holds records — the
@@ -295,9 +331,10 @@ const FIELD_VERBS = ['add-field', 'set-field', 'rm-field', 'rename-field', 'rena
295
331
  export const GLOBAL_FLAGS = ['workspace', 'vault'];
296
332
 
297
333
  export const WORKSPACE_FLAGS = {
298
- init: ['name', 'data_path', 'harnesses', 'workspace_module'], update: [],
299
- install: ['clone', 'dry-run', 'json', 'link-env', 'all', 'hook', 'print-adapters'],
300
- compile: ['watch'], check: ['strict-export'], exports: ['layer', 'dry-run', 'json'], status: [], doctor: ['strict', 'json'],
334
+ init: ['name', 'data_path', 'harnesses', 'workspace_module', 'no-git', 'git', 'no-compile', 'from', 'input', 'allow', 'no-input'], update: ['engine', 'allow', 'from', 'no-commit'],
335
+ install: ['clone', 'dry-run', 'json', 'link-env', 'all', 'hook', 'print-adapters', 'from', 'input', 'allow', 'no-input', 'no-commit'],
336
+ compile: ['watch'], check: ['strict-export'], exports: ['layer', 'dry-run', 'json'], status: ['json'], doctor: ['strict', 'json'],
337
+ setup: ['input', 'allow', 'authorize', 'verify', 'skip', 'no-input', 'json'],
301
338
  changes: ['since', 'json'], commit: ['dry-run', 'json'], fmt: ['dry-run'], relocate: ['dry-run', 'json', 'to-root'],
302
339
  };
303
340
 
@@ -305,7 +342,7 @@ export const WORKSPACE_FLAGS = {
305
342
  * spellings are in it too: they answer with their replacement, and an extension taking one over
306
343
  * would turn a loud translation into a different command. */
307
344
  export const CORE_VERBS = [
308
- 'init', 'install', 'update', 'compile', 'check', 'exports', 'doctor', 'status', 'changes', 'commit', 'help', 'version', '--version', '-v',
345
+ 'init', 'install', 'update', 'compile', 'check', 'exports', 'doctor', 'status', 'setup', 'changes', 'commit', 'help', 'version', '--version', '-v',
309
346
  'list', 'add', 'values', 'get', 'set', 'rm', 'rename', 'history', 'diff', 'revert', 'reorder', 'next',
310
347
  'add-field', 'set-field', 'rm-field', 'rename-field', 'rename-value', 'relations', 'resolve', 'relocate', 'fmt',
311
348
  'schema', 'ensure', 'update-field', 'remove-field', 'commands',
@@ -350,8 +387,10 @@ export async function run(argv) {
350
387
  if (cmd === 'init') {
351
388
  // init runs BEFORE a workspace exists — no findWorkspace
352
389
  const flags = {};
353
- for (let i = 0; i < rest.length; i++) if (rest[i].startsWith('--')) flags[rest[i].slice(2)] = rest[i + 1];
354
- process.exit(init({ flags }));
390
+ for (let i = 0; i < rest.length; i++) if (rest[i].startsWith('--')) { const [k, v] = rest[i].slice(2).split(/=(.*)/s); flags[k] = v ?? rest[i + 1]; }
391
+ // boolean flags take no value: a following positional is not theirs
392
+ for (const b of ['no-git', 'no-compile', 'no-input']) if (b in flags) flags[b] = true;
393
+ process.exit(await initCommand(flags, { open: openWorkspace, argv: rest, verify: async (ws) => check(ws, { extra: await api.contributedViolations(ws) }) }));
355
394
  }
356
395
  if (!cmd || cmd === 'help') {
357
396
  // `help` works OUTSIDE a workspace too — a person who just ran `npm i -g dreamteamer` on a
@@ -362,7 +401,17 @@ export async function run(argv) {
362
401
  emit(USAGE + extensionUsage(ws));
363
402
  process.exit(0);
364
403
  }
365
- const ws = await openWorkspace();
404
+ let ws;
405
+ try { ws = await openWorkspace(); } catch (e) {
406
+ // `status` is read-only and always answers: a runtime whose extensions refuse to load (two
407
+ // packages claiming one unit, a bad declaration) is reported as the status, exit 0
408
+ if (cmd === 'status') {
409
+ console.log(`✖ extensions did not load — ${String(e.message).split('\n')[0]}`);
410
+ console.log(' the setup section cannot be read until that is fixed; records and the compiled runtime are untouched');
411
+ process.exit(0);
412
+ }
413
+ throw e;
414
+ }
366
415
  // An EXTENSION'S VERB runs in-process, handed this workspace — the same engine instance, the
367
416
  // same loaded extensions. Its exit code is the process's.
368
417
  const ext = ws.extensions.find((e) => cmd in e.commands);
@@ -400,8 +449,16 @@ export async function run(argv) {
400
449
  const args = target === 'repos' ? given : [target.slice('repos/'.length), ...given];
401
450
  process.exit(collectionCommand(ws, 'repos', 'ensure', args));
402
451
  }
403
- if (target) {
404
- throw new Error(`dt install takes no target "${target}" — \`dt install\` makes THIS checkout ready, and \`dt install repos/${target}\` materializes an attached repo`);
452
+ // THE SPEC FORM (src/install-modules.js): any positional that is not `repos…` is an npm spec —
453
+ // a name, name@version, ./file.tgz, ./folder, a git URL — and `--from` resolves names from a
454
+ // folder of tarballs. The flags are its own; the checkout form's are refused on it below.
455
+ if (target || given.includes('--from')) {
456
+ // the muscle memory `dt ensure <id>` taught: a bare repo id is named with its spelling, never sent to npm
457
+ let repoIds = [];
458
+ try { repoIds = listRepos(ws).map((r) => r.id); } catch { /* no repos descriptor */ }
459
+ if (target && repoIds.includes(target)) throw new Error(`"${target}" is an attached repo, not an npm spec — \`dt install repos/${target}\` materializes it`);
460
+ refuse('dt install <spec…>', ['--from', '--input', '--allow', '--no-input', '--no-commit', '--json']);
461
+ process.exit(await installModules(ws, rest, { open: openWorkspace, verify: async (w) => check(w, { extra: await api.contributedViolations(w) }) }));
405
462
  }
406
463
  // ⚠ TWO MORE FORMS, EACH ITS OWN VOCABULARY. `--hook` reads a JSON payload off stdin
407
464
  // and installs the checkout that payload names; `--print-adapters` installs nothing
@@ -420,7 +477,12 @@ export async function run(argv) {
420
477
  process.exit(await installCommand(ws, rest, { open: openWorkspace }));
421
478
  }
422
479
  case 'update': {
423
- const code = update(ws, rest.find((a) => !a.startsWith('--')));
480
+ // an npm module or the engine moves through src/update.js; a git module (or no target) keeps
481
+ // the fast-forward path below
482
+ const u = parseUpdateArgs(rest);
483
+ const gitMods = Object.fromEntries(declaredGitModules(ws.pkg, ws.root).map);
484
+ if (u.engine || (u.name && !gitMods[u.name])) process.exit(await updateModules(ws, u, { open: openWorkspace }));
485
+ const code = update(ws, u.name);
424
486
  compile(ws); // pulled modules may carry new sources — prints its own summary
425
487
  process.exit(code);
426
488
  }
@@ -437,9 +499,13 @@ export async function run(argv) {
437
499
  const layers = rest.flatMap((a, i) => (a === '--layer' ? [rest[i + 1]] : a.startsWith('--layer=') ? [a.slice(8)] : [])).filter(Boolean);
438
500
  process.exit(runExports(new Store(ws), { layers, dryRun: rest.includes('--dry-run'), json: rest.includes('--json') }));
439
501
  }
502
+ // `dt setup [<unit>] …` — the generic driver of the units installed modules declare (src/setup.js):
503
+ // inputs, consent per effect, inspect → plan → apply, the receipt. The engine names no module.
504
+ case 'setup':
505
+ process.exit(await setupCommand(ws, rest, { api }));
440
506
  case 'doctor': {
441
507
  const caps = await doctorBoard(ws, api);
442
- if (rest.includes('--json')) emit(JSON.stringify({ capabilities: caps }, null, 2));
508
+ if (rest.includes('--json')) emit(JSON.stringify({ workspace: { root: ws.root, name: ws.pkg?.name ?? null }, capabilities: caps }, null, 2));
443
509
  else console.log(renderBoard(caps));
444
510
  process.exit(rest.includes('--strict') && caps.some((c) => c.verdict === 'UNAVAILABLE') ? 1 : 0);
445
511
  }
@@ -530,6 +596,11 @@ export async function run(argv) {
530
596
  console.log(`✖ ${s.message}`);
531
597
  process.exit(1);
532
598
  }
599
+ if (rest.includes('--json')) {
600
+ const { modules: mods } = discoverModules(ws.root, ws.pkg);
601
+ emit(JSON.stringify({ workspace: { root: ws.root, name: ws.pkg?.name ?? null }, compiled: s.manifest.compiled, stale: s.stale, modules: mods.map((m) => ({ name: m.name, location: locationOf(m, ws.root) })), setup: statusLines(ws) }, null, 2));
602
+ process.exit(0);
603
+ }
533
604
  console.log(`compiled: ${s.manifest.compiled}`);
534
605
  // THE EDITOR, from the marker the extension writes on activation (`.dreamteamer/editor.json`).
535
606
  // Without it an agent working inside the editor could not tell whether the extension was
@@ -549,6 +620,8 @@ export async function run(argv) {
549
620
  // §10: the folder name IS the label. `hr git_modules @ 3f2a1c (dirty)` needs no
550
621
  // legend, and `[inline]` needed one every single time.
551
622
  let line = ` ${m.name.padEnd(20)} ${locationOf(m, ws.root)}`;
623
+ // a development link (a folder spec): never pinned, skipped by update
624
+ try { if (m.channel === 'npm' && fs.lstatSync(path.join(ws.root, 'node_modules', m.name)).isSymbolicLink() && m.name !== 'dreamteamer') line += ' (linked)'; } catch { /* not under node_modules */ }
552
625
  if (m.channel === 'git') {
553
626
  const ref = tryGit(m.root, ['rev-parse', '--short', 'HEAD']);
554
627
  const dirty = tryGit(m.root, ['status', '--porcelain']);
@@ -633,6 +706,9 @@ export async function run(argv) {
633
706
  for (const r of pending) console.log(` ${r.repo === '.' ? 'workspace' : r.repo}: ${r.rows.length}`);
634
707
  }
635
708
  } catch { /* no runtime yet, or not a git repo — status must still print */ }
709
+ // the SETUP section (src/setup.js): one line per unit the installed modules declare, folded
710
+ // from each unit's own inspect — read-only, and never from a stored success flag
711
+ try { for (const line of renderStatusLines(statusLines(ws))) console.log(line); } catch (e) { console.log(`setup: could not be read — ${e.message.split('\n')[0]}`); }
636
712
  if (s.stale.length) {
637
713
  for (const line of s.stale) console.log(` stale: ${line}`);
638
714
  console.log(`✖ .dreamteamer is stale (${s.stale.length}) — run \`dreamteamer compile\``);
@@ -756,10 +832,6 @@ export async function run(argv) {
756
832
  console.error(`✖ \`dt ${cmd}\` is not a workspace verb — containers are managed by dt-docker:\n npm i -g @dreamteamer/docker-workspaces\n dt-docker ${cmd} container <name>`);
757
833
  process.exit(2);
758
834
  }
759
- if (cmd === 'setup') {
760
- console.error('✖ `dt setup` is gone — `dt doctor` shows what works on this machine, each fix on its row');
761
- process.exit(2);
762
- }
763
835
  console.error(`✖ unknown verb "${cmd}" — the verb comes first: dt <verb> [<target>]`);
764
836
  emit(USAGE, 2);
765
837
  process.exit(1);
package/src/doctor.js CHANGED
@@ -7,8 +7,10 @@ import path from 'node:path';
7
7
  import { engineId, readManifest } from './runtime.js';
8
8
  import { satisfies } from './semver.js';
9
9
  import { MANAGED_BLOCKS } from './harnesses.js';
10
+ import { units, unitEnv, receiptDir, redact } from './setup.js';
10
11
 
11
12
  const STATES = new Set(['ok', 'warn', 'bad']);
13
+ const UNIT_STATE = { ready: 'ok', configured: 'ok', unverified: 'warn', missing: 'warn', blocked: 'bad' };
12
14
  const GLYPH = { ok: '✔', warn: '⚠', bad: '✖' };
13
15
 
14
16
  export const verdictOf = (checks) => (checks.some((k) => k.state === 'bad') ? 'UNAVAILABLE'
@@ -42,6 +44,14 @@ function engineChecks(root) {
42
44
  * unknown state, reads as a failure of that extension rather than a crash. */
43
45
  export async function doctorBoard(ws, dt) {
44
46
  const caps = [{ name: 'engine', checks: engineChecks(ws.root) }];
47
+ // a setup unit's inspect, as rows: ready/configured → ok, unverified/missing → warn, blocked → bad —
48
+ // so `--strict` fails on what blocks and a never-verified capability reads degraded, never ready
49
+ const env = unitEnv(ws);
50
+ for (const u of units(ws)) {
51
+ let checks;
52
+ try { checks = (u.inspect({ root: ws.root, ws, dt, env, tty: false, receiptDir: receiptDir(ws, u.id) })?.checks ?? []); } catch (err) { checks = [{ id: 'inspect', title: 'inspect', status: 'blocked', detail: redact(err.message), fix: `report it to ${u.module}` }]; }
53
+ caps.push({ name: u.id, checks: checks.map((c) => ({ label: c.title ?? c.id, state: UNIT_STATE[c.status] ?? 'bad', detail: c.detail ?? (UNIT_STATE[c.status] ? '' : `unknown status ${JSON.stringify(c.status)}`), fix: c.fix })) });
54
+ }
45
55
  for (const e of (ws.extensions ?? []).filter((x) => x.doctor)) {
46
56
  const name = e.name.replace(/^@[^/]+\//, '');
47
57
  let checks;
package/src/extensions.js CHANGED
@@ -23,6 +23,8 @@
23
23
  // the schema's; `warning: true` prints a warning that does not count (`dt.CHECK_WARNINGS` says so)
24
24
  // doctor ({ root, ws, dt }) → [{ label, state, detail?, fix? }] rows `dt doctor` renders as one capability
25
25
  // next ({ root, ws, collection, ids }) → [{ id, text }] a line about a record `dt next` prints (sync)
26
+ // setup [{ id, version: 1, inputs, inspect, plan, apply }] setup UNITS `dt install`, `dt setup` and `dt status`
27
+ // drive without knowing the module (src/setup-contract.js is the shape, src/setup.js the runner)
26
28
  //
27
29
  // Two contributions claiming the same verb, kind or harness is a refusal — there is no "last one
28
30
  // wins", because the loser would be an extension the operator installed that silently does nothing.
@@ -32,9 +34,10 @@ import { pathToFileURL } from 'node:url';
32
34
  import { satisfies } from './semver.js';
33
35
  import { engineVersion } from './runtime.js';
34
36
  import { layerEntries } from './workspace.js';
37
+ import { validateSetup } from './setup-contract.js';
35
38
 
36
39
  /** The keys a package.json `dreamteamer` block may carry — the workspace's and a module's alike. */
37
- export const MANIFEST_KEYS = ['title', 'description', 'workspace_module', 'data_path', 'namespaces', 'vars', 'env', 'auto_commit', 'harnesses', 'git_modules', 'disable', 'local_assets', 'postinstall', 'gitignore_runtime_folder', 'repos_path', 'dependencies', 'peer_collections', 'owns_data', 'engine', 'extension', 'ignore'];
40
+ export const MANIFEST_KEYS = ['title', 'description', 'workspace_module', 'data_path', 'namespaces', 'vars', 'env', 'auto_commit', 'harnesses', 'git_modules', 'disable', 'local_assets', 'postinstall', 'gitignore_runtime_folder', 'repos_path', 'dependencies', 'peer_collections', 'owns_data', 'engine', 'extension', 'ignore', 'provides', 'setup'];
38
41
  /** The one command that converts a workspace to descriptor format v2. */
39
42
  export const CONVERTER = 'node node_modules/dreamteamer/scripts/migrate-descriptors-v2.mjs --root .';
40
43
 
@@ -54,7 +57,7 @@ export function v1ManifestRefusal(block, where) {
54
57
 
55
58
  export const EXTENSION_API = 1;
56
59
 
57
- const CONTRIBUTION_KEYS = new Set(['commands', 'sourceKinds', 'analyze', 'harnesses', 'orientation', 'hooks', 'check', 'doctor', 'next']);
60
+ const CONTRIBUTION_KEYS = new Set(['commands', 'sourceKinds', 'analyze', 'harnesses', 'orientation', 'hooks', 'check', 'doctor', 'next', 'setup']);
58
61
 
59
62
  /** The modules that declare an extension entry: the workspace's own `modules/<id>/` first, then each
60
63
  * clone under `git_modules/` (the clone's root, then the modules it bundles under `modules/`), then its
@@ -77,7 +80,7 @@ export function declaredExtensions(ws) {
77
80
  // a module whose engine floor is unmet is refused whole, its code with its content
78
81
  const range = pkg.dreamteamer.engine;
79
82
  if (range && satisfies(engineVersion(), range) === false) return void console.warn(`✖ extension ${name} needs engine "${range}" — this is ${engineVersion()}, so it is not loaded`);
80
- out.push({ name, version: pkg.version ?? '0.0.0', dir, entry: path.join(dir, entry) });
83
+ out.push({ name, version: pkg.version ?? '0.0.0', dir, entry: path.join(dir, entry), env: pkg.dreamteamer.env ?? [], vars: pkg.dreamteamer.vars ?? [] });
81
84
  };
82
85
  let inline = [];
83
86
  try { inline = fs.readdirSync(path.join(ws.root, 'modules')).sort(); } catch { /* no modules/ */ }
@@ -125,13 +128,15 @@ export async function loadExtensions(ws, api, reserved = {}) {
125
128
  const v1 = v1ManifestRefusal(ws.pkg?.dreamteamer, 'package.json');
126
129
  if (v1) throw new Error(v1);
127
130
  const loaded = [];
128
- const owner = { command: new Map(), kind: new Map(), harness: new Map() };
131
+ const owner = { command: new Map(), kind: new Map(), harness: new Map(), unit: new Map() };
129
132
  for (const r of reserved.verbs ?? []) owner.command.set(r, 'the engine');
130
133
  for (const r of reserved.kinds ?? []) owner.kind.set(r, 'the engine');
131
134
  for (const r of reserved.harnesses ?? []) owner.harness.set(r, 'the engine');
132
135
  const claim = (what, key, by) => {
133
136
  const prev = owner[what].get(key);
134
- if (prev) throw new Error(`extension ${by} contributes the ${what} "${key}", which ${prev} already owns — uninstall one, or switch it off: add "modules/${by}" to dreamteamer.disable in package.json`);
137
+ if (prev) throw new Error(what === 'unit'
138
+ ? `setup unit "${key}" is contributed by ${by} and ${prev} — uninstall one, or switch it off: add "modules/${by}" to dreamteamer.disable in package.json`
139
+ : `extension ${by} contributes the ${what} "${key}", which ${prev} already owns — uninstall one, or switch it off: add "modules/${by}" to dreamteamer.disable in package.json`);
135
140
  owner[what].set(key, by);
136
141
  };
137
142
  for (const ext of declaredExtensions(ws)) {
@@ -154,7 +159,21 @@ export async function loadExtensions(ws, api, reserved = {}) {
154
159
  for (const k of sourceKinds) claim('kind', k.kind, ext.name);
155
160
  for (const id of Object.keys(c.harnesses ?? {})) claim('harness', id, ext.name);
156
161
  for (const fn of ['analyze', 'check', 'doctor', 'next']) if (c[fn] !== undefined && typeof c[fn] !== 'function') throw new Error(`extension ${ext.name}: ${fn} must be a function`);
157
- loaded.push({ name: ext.name, version: ext.version, commands, sourceKinds, analyze: c.analyze ?? null, harnesses: c.harnesses ?? {}, orientation: c.orientation ?? null, hooks: c.hooks ?? {}, check: c.check ?? null, doctor: c.doctor ?? null, next: c.next ?? null });
162
+ // setup units: validated here so an uncompilable declaration never reaches `dt install`; a unit id is
163
+ // claimed like a verb, because two packages answering `dt setup <id>` is the same silent loser
164
+ const setup = validateSetup(ext.name, c.setup, { env: ext.env, vars: ext.vars });
165
+ if (setup.errors.length) throw new Error(setup.errors.join('\n'));
166
+ for (const u of setup.units) claim('unit', u.id, ext.name);
167
+ loaded.push({ name: ext.name, version: ext.version, dir: ext.dir, env: ext.env, vars: ext.vars, commands, sourceKinds, analyze: c.analyze ?? null, harnesses: c.harnesses ?? {}, orientation: c.orientation ?? null, hooks: c.hooks ?? {}, check: c.check ?? null, doctor: c.doctor ?? null, next: c.next ?? null, setup: setup.units });
168
+ }
169
+ // one env key, one kind (D39): two inputs — in one package or across packages — that name the same
170
+ // key with different kinds are refused here, naming the pair, before any setup runs on them
171
+ const keyKinds = new Map();
172
+ for (const ext of loaded) for (const u of ext.setup ?? []) for (const i of u.inputs ?? []) {
173
+ if (!i.env) continue;
174
+ const prev = keyKinds.get(i.env);
175
+ if (prev && prev.kind !== i.kind) throw new Error(`${i.env} is declared as ${prev.kind} by ${prev.by} (unit ${prev.unit}, input ${prev.input}) and as ${i.kind} by ${ext.name} (unit ${u.id}, input ${i.id}) — one key, one kind`);
176
+ if (!prev) keyKinds.set(i.env, { kind: i.kind, by: ext.name, unit: u.id, input: i.id });
158
177
  }
159
178
  return loaded;
160
179
  }
package/src/init.js CHANGED
@@ -63,10 +63,10 @@ const ENV_EXAMPLE = `# secrets for skills and modules go here (copy to .env; .en
63
63
  # modules declare the env keys they require in their package.json dreamteamer.env list.
64
64
  `;
65
65
 
66
- export function init({ flags = {} } = {}) {
67
- const root = process.cwd();
68
- const name = flags.name ?? path.basename(root);
69
- const dataPath = flags.data_path ?? 'data';
66
+ /** The `dreamteamer` block init leaves in package.json: its seeds, under whatever the EXISTING block
67
+ * already says — the existing key always wins over a flag. One function, because `init --ready` must
68
+ * judge exactly the paths init will write, and a second copy of this precedence is how it did not. */
69
+ export function seedBlock(flags = {}, existing = {}) {
70
70
  // EVERY known harness by default, and this is the operator's explicit call over the architecture
71
71
  // review's dissent — recorded, not elided: it writes AGENTS.md, GEMINI.md and .cursor/rules/ into
72
72
  // every new workspace, which is real clutter. The decision stands on the ASYMMETRY. A missing
@@ -78,12 +78,8 @@ export function init({ flags = {} } = {}) {
78
78
  const harnesses = typeof flags.harnesses === 'string'
79
79
  ? flags.harnesses.split(',').map((s) => s.trim())
80
80
  : [...KNOWN_HARNESSES];
81
-
82
- // package.json: create or update — the single manifest
83
- const pkgPath = path.join(root, 'package.json');
84
- const pkg = fs.existsSync(pkgPath) ? JSON.parse(fs.readFileSync(pkgPath, 'utf8')) : { name, private: true, version: '0.0.1' };
85
- pkg.dreamteamer = {
86
- 'data_path': dataPath,
81
+ return {
82
+ 'data_path': flags.data_path ?? 'data',
87
83
  harnesses,
88
84
  gitignore_runtime_folder: true,
89
85
  // The workspace's own sources live in `modules/default/`, and the folder is named for its ROLE,
@@ -99,9 +95,30 @@ export function init({ flags = {} } = {}) {
99
95
  'workspace_module': flags.workspace_module ?? 'default',
100
96
  'git_modules': {},
101
97
  disable: [],
102
- ...pkg.dreamteamer,
98
+ ...existing,
103
99
  };
104
- fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, '\t') + '\n');
100
+ }
101
+
102
+ /** Every path `init` writes or creates for this effective block, root-relative. ⚠ The data folder is
103
+ * the FLAG's (or `data`), not the block's — what init has always created, so both are listed. */
104
+ export function initFootprint(block, flags = {}) {
105
+ const wm = block.workspace_module, base = wm ? `modules/${wm}` : '.';
106
+ return ['package.json', '.gitignore', '.env.example', '.vscode/extensions.json', flags.data_path ?? 'data', block.data_path,
107
+ ...SKELETON_KINDS.map((k) => `${base}/${k}`), ...(wm ? [`${base}/package.json`] : []), `${base}/collections/notes.collection.yaml`];
108
+ }
109
+
110
+ // `commit: false` is `init --ready`'s: a bootstrap writes and never commits (checkout.js `bootstrap`).
111
+ export function init({ flags = {}, root = process.cwd(), commit = true } = {}) {
112
+ const name = flags.name ?? path.basename(root);
113
+ const dataPath = flags.data_path ?? 'data';
114
+ // package.json: create or update — the single manifest
115
+ const pkgPath = path.join(root, 'package.json');
116
+ const pkg = fs.existsSync(pkgPath) ? JSON.parse(fs.readFileSync(pkgPath, 'utf8')) : { name, private: true, version: '0.0.1' };
117
+ const existed = fs.existsSync(pkgPath), had = pkg.dreamteamer ?? {};
118
+ pkg.dreamteamer = seedBlock(flags, pkg.dreamteamer);
119
+ // an existing block already holding every seeded key is left BYTE-FOR-BYTE: re-running init (or a
120
+ // repeated `init --ready`) must not reformat the operator's file into a diff that changes nothing
121
+ if (!existed || Object.keys(pkg.dreamteamer).some((k) => !(k in had))) fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, '\t') + '\n');
105
122
 
106
123
  // folder skeleton — the workspace's own sources are an inline module, kinds FLAT at its root
107
124
  const wm = pkg.dreamteamer.workspace_module;
@@ -154,6 +171,7 @@ export function init({ flags = {} } = {}) {
154
171
  // `git add --all`, which in an existing repo swept every unrelated staged and unstaged change into
155
172
  // a commit titled "init workspace": the one write in this engine that was not pathspec-scoped.
156
173
  // `commit -- <paths>` also leaves anything the operator had already staged exactly as it was.
174
+ if (!commit) return 0;
157
175
  const written = ['package.json', '.gitignore', '.env.example', '.vscode/extensions.json',
158
176
  ...(wm ? [path.join('modules', wm, 'package.json')] : []), path.relative(root, starter)]
159
177
  .filter((f) => fs.existsSync(path.join(root, f)));
@@ -200,6 +218,11 @@ export function install({ root, pkg }) {
200
218
  for (const t of [...top, ...under]) {
201
219
  done.add(t.by ? `${t.by}/${t.name}` : t.name);
202
220
  fs.mkdirSync(path.dirname(t.dest), { recursive: true });
221
+ // ⚠ A LINK IS NOT A CLONE. A declarer that agreed with the top at the first install was given a
222
+ // link; once its declaration diverges its copy is nested HERE, and the link standing where the
223
+ // nested clone goes must be replaced — never re-pointed through, which would move the shared
224
+ // top-level clone every other reader sits on (the first review of 0.46.0, finding eng-01).
225
+ if (t.by && isLink(t.dest)) fs.unlinkSync(t.dest);
203
226
  if (fs.existsSync(t.dest)) { if (!repoint(t.dest, path.relative(path.join(root, 'git_modules'), t.dest), t.ref)) unreachable.push(t.name); continue; }
204
227
  clone(t.url, t.ref, t.dest, t.name, t.note);
205
228
  if (t.by) excludeIn(path.join(root, t.by), `git_modules/${t.name}`);
@@ -221,7 +244,8 @@ export function install({ root, pkg }) {
221
244
  * explicit on disk, resolved by a tool that knows nothing of dreamteamer. A clone of its own standing there
222
245
  * may hold work: left as it is, and said — `dt status` draws it too. */
223
246
  function linkLayer(root, by, name) {
224
- const at = path.join(root, by, 'git_modules', name), want = path.join('..', '..', name);
247
+ // relative from wherever the declarer sits — a nested copy's own needs link from two levels deeper
248
+ const at = path.join(root, by, 'git_modules', name), want = path.relative(path.dirname(at), path.join(root, 'git_modules', name));
225
249
  let st = null;
226
250
  try { st = fs.lstatSync(at); } catch { /* nothing there */ }
227
251
  if (st && !st.isSymbolicLink()) { console.log(`… ${by}/git_modules/${name} is a clone of its own — left as it is`); return; }
@@ -291,6 +315,7 @@ function tryGit(cwd, args, timeout = 30_000) {
291
315
  try { return execFileSync('git', args, { cwd, stdio: QUIET, timeout }).toString().trim() || null; } catch { return null; }
292
316
  }
293
317
 
318
+ const isLink = (p) => { try { return fs.lstatSync(p).isSymbolicLink(); } catch { return false; } };
294
319
  const ran = (cwd, args, timeout) => { try { execFileSync('git', args, { cwd, stdio: QUIET, timeout }); return true; } catch { return false; } };
295
320
  const commitOf = (dest, rev) => tryGit(dest, ['rev-parse', '--verify', '--quiet', `${rev}^{commit}`]);
296
321
 
@@ -299,7 +324,7 @@ const commitOf = (dest, rev) => tryGit(dest, ['rev-parse', '--verify', '--quiet'
299
324
  * what the clone already knows, so a settled clone costs no fetch. A folder that is not itself a
300
325
  * clone is never re-pointed: git would walk up and act on the workspace repo. */
301
326
  export function offRef(dest, ref) {
302
- if (!fs.existsSync(path.join(dest, '.git'))) return false;
327
+ if (isLink(dest) || !fs.existsSync(path.join(dest, '.git'))) return false; // never judged, never moved, through a link
303
328
  if (tryGit(dest, ['symbolic-ref', '--quiet', '--short', 'HEAD']) === ref) return false;
304
329
  const branch = ['refs/heads/', 'refs/remotes/origin/'].some((p) => tryGit(dest, ['rev-parse', '--verify', '--quiet', p + ref]));
305
330
  return branch || !commitOf(dest, ref) || commitOf(dest, ref) !== commitOf(dest, 'HEAD');