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.
package/src/cli.js CHANGED
@@ -14,13 +14,14 @@ import fs from 'node:fs';
14
14
  import path from 'node:path';
15
15
  import { execFileSync } from 'node:child_process';
16
16
  import * as api from './api.js';
17
- import { openWorkspace } from './api.js';
17
+ import { openWorkspace, findWorkspace } from './api.js';
18
+ import { checkAlone } from './check-alone.js';
18
19
  import { compile, staleness, warnIfStale, discoverModules, CHANNEL_LABEL, locationOf, kindsOf, moduleIdOf, layerEntries } from './compile.js';
19
20
  import { check } from './check.js';
20
21
  import { collectionCommand, emit, relationsCommand, reportCommits } from './collections-cli.js';
21
22
  import { formatDescriptors } from './schema-ops.js';
22
23
  import { init, installClone, update, listRepos } from './init.js';
23
- import { installCommand, describeCheckout } from './checkout.js';
24
+ import { installCommand, describeCheckout, initCommand } from './checkout.js';
24
25
  import { declaredGitModules } from './workspace.js';
25
26
  const isOwnClone = (p) => { try { return !fs.lstatSync(p).isSymbolicLink() && fs.existsSync(path.join(p, '.git')); } catch { return false; } };
26
27
  import { foldChanges, groupChanges, reportLine } from './events.js';
@@ -29,6 +30,9 @@ import { Store } from './store.js';
29
30
  import { splitRef, canonicalCollection } from './ref.js';
30
31
  import { envContext, renderTemplate } from './env-vars.js';
31
32
  import { doctorBoard, renderBoard } from './doctor.js';
33
+ import { setupCommand, statusLines, renderStatusLines } from './setup.js';
34
+ import { installModules } from './install-modules.js';
35
+ import { updateModules, parseUpdateArgs } from './update.js';
32
36
  import { storageOf } from './descriptor.js';
33
37
 
34
38
  // git calls whose failure we CATCH must not print git's own error: execFileSync forwards the
@@ -125,11 +129,13 @@ commits there.
125
129
  health/doctors; a module declaring exactly ONE
126
130
  namespace infers it, and the resolved name is echoed.
127
131
  --namespace '' means no namespace)
128
- add modules --name <id> [--description "…"] [--namespace <ns>]
129
- (modules/<id>/ + every kind folder + package.json.
130
- --namespace DECLARES it in the module (§8), so every
131
- later \`add collections --module <id>\` infers it.
132
- folder = package name = id, so a module never forks.
132
+ add modules --name <id> [--description "…"] [--namespace <ns>] [--extension] [--package <npm name>]
133
+ (modules/<id>/ + every kind folder + package.json + README.md,
134
+ floored on this engine. --namespace DECLARES it in the module
135
+ (§8), so every later \`add collections --module <id>\` infers it.
136
+ --extension adds src/extension.js with a one-token setup unit;
137
+ --package names it for npm and makes it publishable — the
138
+ folder stays the id. Without it, folder = package name = id.
133
139
  the git shape is \`install --clone <url> [name]\`)
134
140
  add skills --name <id> --description "…" (skills/<id>/SKILL.md — --description is required,
135
141
  because an undescribed skill is undiscoverable)
@@ -209,8 +215,17 @@ Every verb that MOVES records or CLEARS values takes --dry-run and prints its pl
209
215
  records N · refs M · descriptors K · values cleared V
210
216
 
211
217
  workspace verbs:
212
- init write the workspace skeleton into the current directory (never compiles)
213
- [--harnesses claude-code,codex,pi,gemini-cli,cursor]
218
+ init from a folder to a workspace in ONE command: pins the engine that runs it (exactly),
219
+ writes the skeleton, installs, compiles, checks, runs the safe part of any declared
220
+ module's setup, makes the folder a git repository when it is not one and commits what
221
+ it wrote (inside a repository: the same scoped commit, your staged work untouched).
222
+ Refused before any write: an engine of another version declared, locked or installed
223
+ (never upgraded — dt update --engine), and a path it writes that links out of the
224
+ folder. Re-run it to resume — a repeat changes nothing.
225
+ [--no-git] [--git <remote-url>] (adds origin, never pushes) [--no-compile]
226
+ [--from <dir>] (a preset's missing packages from a folder of tarballs, offline)
227
+ [--input <id>=<value>]… [--allow <kind>]… [--no-input] (a preset's setup, as \`setup\`)
228
+ [--harnesses claude-code,codex,pi,gemini-cli,cursor] [--workspace_module <name>]
214
229
  --version print the engine version (works anywhere)
215
230
  install make THIS checkout ready — the engine, .env (linked from the primary when this is a
216
231
  worktree), declared local assets, git modules, compile, and a declared postinstall.
@@ -226,7 +241,21 @@ workspace verbs:
226
241
  install repos/<id> | repos --all [--json]
227
242
  materialize an attached repo's working tree ON DEMAND — never as part of making a
228
243
  checkout ready; --all is the explicit opt-in, e.g. before going offline
244
+ install <spec>… [--from <dir>] bring a MODULE in: a name, name@version, ./file.tgz,
245
+ ./folder (a development link) or a git URL — installs it and every module its
246
+ dreamteamer.dependencies names (refusing, before npm writes anything, a package with
247
+ no dreamteamer key, an engine floor this engine does not meet, a ring, a version
248
+ installed differently, and a package an installed one already provides), pins exact
249
+ versions, compiles, runs the safe part of the module's setup and commits package.json,
250
+ package-lock.json and what setup wrote. Without a version: npm's latest. --from
251
+ resolves names from a folder of tarballs (offline). Setup flags as for \`setup\`:
252
+ [--input <id>=<value>]… [--allow <kind>]… [--no-input]; [--no-commit] [--json]
253
+ Exit 0 done · 1 refused or failed (nothing half-written) · 2 usage · 3 input missing
229
254
  install --clone <url> [name] attach a git module to this workspace
255
+ update <name>[@<version>] | --engine move ONE npm pin forward on purpose: to the latest
256
+ release (or the named version), re-pinned exactly, closure-checked as install is,
257
+ compiled, committed. A downgrade needs [--allow downgrade]; a development link is
258
+ skipped and named; [--from <dir>] resolves from a folder of tarballs; [--no-commit]
230
259
  update pull git_modules clones forward (ff-only on the lockfile ref), rebuild,
231
260
  then compile; [<name>] updates just one. dirty clones are skipped
232
261
  compile materialize modules + workspace sources into .dreamteamer (+ harness adapters)
@@ -237,12 +266,25 @@ workspace verbs:
237
266
  through a record layer is a ⚠ line until its exports manifest lists it; a reference no root
238
267
  answers is external when the referring repo's manifest vouches for it
239
268
  [--strict-export] makes each unlisted one, and a stale manifest, a violation
269
+ modules/<id> --alone: is that inline module publishable — packed, installed into a fresh
270
+ workspace on this engine with only its declared dependencies, compiled, checked; exit 0
271
+ publishable, 1 refused naming why, 2 usage [--keep] leaves the temp workspace
240
272
  exports write this workspace's dreamteamer-exports.json — each id its records name that no file
241
273
  here holds, with its label and the workspace holding it — and commit that one file
242
274
  [--layer <name>] that layer's, from this workspace's view [--dry-run] [--json]
243
275
  doctor what works on this machine — the engine, then each extension's checks — as one board:
244
276
  READY / DEGRADED / UNAVAILABLE, each fix on its row. Exit 0 [--strict] exit 1 when
245
277
  anything is UNAVAILABLE [--json]
278
+ setup [<unit>] drive the setup a module declares — resume, repair, verify, sign in. The
279
+ engine names no module: a unit is what an installed package contributes (dt status
280
+ lists them). Inputs: [--input <id>=<value>]… (or <unit>.<id>=; then the environment,
281
+ then the declared default; a terminal asks for what is still missing, [--no-input]
282
+ never asks → exit 3 with the ids). Effects: workspace-file writes run; download,
283
+ network and machine ask y/n in a terminal or run under [--allow <kind>]…; an account
284
+ step (sign-in, consent) runs only under [--authorize], in a terminal. [--verify] runs
285
+ the unit's live check and writes its receipt. [--skip] records the skip in
286
+ package.json (dt setup <unit> clears it). [--json] the result as data.
287
+ Exit 0 done (pending and blocked steps printed) · 1 a unit's apply failed · 2 usage · 3 a required input missing
246
288
  status workspace status: compiled runtime freshness, per-module channel/ref, staleness
247
289
 
248
290
  changes the records created / updated / deleted in every repo that holds records — the
@@ -295,9 +337,10 @@ const FIELD_VERBS = ['add-field', 'set-field', 'rm-field', 'rename-field', 'rena
295
337
  export const GLOBAL_FLAGS = ['workspace', 'vault'];
296
338
 
297
339
  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'],
340
+ init: ['name', 'data_path', 'harnesses', 'workspace_module', 'no-git', 'git', 'no-compile', 'from', 'input', 'allow', 'no-input'], update: ['engine', 'allow', 'from', 'no-commit'],
341
+ install: ['clone', 'dry-run', 'json', 'link-env', 'all', 'hook', 'print-adapters', 'from', 'input', 'allow', 'no-input', 'no-commit'],
342
+ compile: ['watch'], check: ['strict-export', 'alone', 'keep'], exports: ['layer', 'dry-run', 'json'], status: ['json'], doctor: ['strict', 'json'],
343
+ setup: ['input', 'allow', 'authorize', 'verify', 'skip', 'no-input', 'json'],
301
344
  changes: ['since', 'json'], commit: ['dry-run', 'json'], fmt: ['dry-run'], relocate: ['dry-run', 'json', 'to-root'],
302
345
  };
303
346
 
@@ -305,7 +348,7 @@ export const WORKSPACE_FLAGS = {
305
348
  * spellings are in it too: they answer with their replacement, and an extension taking one over
306
349
  * would turn a loud translation into a different command. */
307
350
  export const CORE_VERBS = [
308
- 'init', 'install', 'update', 'compile', 'check', 'exports', 'doctor', 'status', 'changes', 'commit', 'help', 'version', '--version', '-v',
351
+ 'init', 'install', 'update', 'compile', 'check', 'exports', 'doctor', 'status', 'setup', 'changes', 'commit', 'help', 'version', '--version', '-v',
309
352
  'list', 'add', 'values', 'get', 'set', 'rm', 'rename', 'history', 'diff', 'revert', 'reorder', 'next',
310
353
  'add-field', 'set-field', 'rm-field', 'rename-field', 'rename-value', 'relations', 'resolve', 'relocate', 'fmt',
311
354
  'schema', 'ensure', 'update-field', 'remove-field', 'commands',
@@ -350,8 +393,10 @@ export async function run(argv) {
350
393
  if (cmd === 'init') {
351
394
  // init runs BEFORE a workspace exists — no findWorkspace
352
395
  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 }));
396
+ 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]; }
397
+ // boolean flags take no value: a following positional is not theirs
398
+ for (const b of ['no-git', 'no-compile', 'no-input']) if (b in flags) flags[b] = true;
399
+ process.exit(await initCommand(flags, { open: openWorkspace, argv: rest, verify: async (ws) => check(ws, { extra: await api.contributedViolations(ws) }) }));
355
400
  }
356
401
  if (!cmd || cmd === 'help') {
357
402
  // `help` works OUTSIDE a workspace too — a person who just ran `npm i -g dreamteamer` on a
@@ -362,7 +407,25 @@ export async function run(argv) {
362
407
  emit(USAGE + extensionUsage(ws));
363
408
  process.exit(0);
364
409
  }
365
- const ws = await openWorkspace();
410
+ // `dt check modules/<id> --alone` judges one inline module in a fresh workspace (src/check-alone.js) —
411
+ // dispatched before the host is opened, because the module's own problem (a missing dependency, a
412
+ // floor above this engine) would otherwise surface as the host's refusal instead of the gate's verdict
413
+ if (cmd === 'check') {
414
+ const target = rest.find((a) => !a.startsWith('--'));
415
+ if (rest.includes('--alone')) process.exit(checkAlone(findWorkspace(), { target, keep: rest.includes('--keep') }));
416
+ if (target) { console.error(`✖ check takes no target — did you mean --alone? (dt check ${target} --alone judges one inline module)`); process.exit(2); }
417
+ }
418
+ let ws;
419
+ try { ws = await openWorkspace(); } catch (e) {
420
+ // `status` is read-only and always answers: a runtime whose extensions refuse to load (two
421
+ // packages claiming one unit, a bad declaration) is reported as the status, exit 0
422
+ if (cmd === 'status') {
423
+ console.log(`✖ extensions did not load — ${String(e.message).split('\n')[0]}`);
424
+ console.log(' the setup section cannot be read until that is fixed; records and the compiled runtime are untouched');
425
+ process.exit(0);
426
+ }
427
+ throw e;
428
+ }
366
429
  // An EXTENSION'S VERB runs in-process, handed this workspace — the same engine instance, the
367
430
  // same loaded extensions. Its exit code is the process's.
368
431
  const ext = ws.extensions.find((e) => cmd in e.commands);
@@ -400,8 +463,16 @@ export async function run(argv) {
400
463
  const args = target === 'repos' ? given : [target.slice('repos/'.length), ...given];
401
464
  process.exit(collectionCommand(ws, 'repos', 'ensure', args));
402
465
  }
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`);
466
+ // THE SPEC FORM (src/install-modules.js): any positional that is not `repos…` is an npm spec —
467
+ // a name, name@version, ./file.tgz, ./folder, a git URL — and `--from` resolves names from a
468
+ // folder of tarballs. The flags are its own; the checkout form's are refused on it below.
469
+ if (target || given.includes('--from')) {
470
+ // the muscle memory `dt ensure <id>` taught: a bare repo id is named with its spelling, never sent to npm
471
+ let repoIds = [];
472
+ try { repoIds = listRepos(ws).map((r) => r.id); } catch { /* no repos descriptor */ }
473
+ if (target && repoIds.includes(target)) throw new Error(`"${target}" is an attached repo, not an npm spec — \`dt install repos/${target}\` materializes it`);
474
+ refuse('dt install <spec…>', ['--from', '--input', '--allow', '--no-input', '--no-commit', '--json']);
475
+ process.exit(await installModules(ws, rest, { open: openWorkspace, verify: async (w) => check(w, { extra: await api.contributedViolations(w) }) }));
405
476
  }
406
477
  // ⚠ TWO MORE FORMS, EACH ITS OWN VOCABULARY. `--hook` reads a JSON payload off stdin
407
478
  // and installs the checkout that payload names; `--print-adapters` installs nothing
@@ -420,7 +491,12 @@ export async function run(argv) {
420
491
  process.exit(await installCommand(ws, rest, { open: openWorkspace }));
421
492
  }
422
493
  case 'update': {
423
- const code = update(ws, rest.find((a) => !a.startsWith('--')));
494
+ // an npm module or the engine moves through src/update.js; a git module (or no target) keeps
495
+ // the fast-forward path below
496
+ const u = parseUpdateArgs(rest);
497
+ const gitMods = Object.fromEntries(declaredGitModules(ws.pkg, ws.root).map);
498
+ if (u.engine || (u.name && !gitMods[u.name])) process.exit(await updateModules(ws, u, { open: openWorkspace }));
499
+ const code = update(ws, u.name);
424
500
  compile(ws); // pulled modules may carry new sources — prints its own summary
425
501
  process.exit(code);
426
502
  }
@@ -437,9 +513,13 @@ export async function run(argv) {
437
513
  const layers = rest.flatMap((a, i) => (a === '--layer' ? [rest[i + 1]] : a.startsWith('--layer=') ? [a.slice(8)] : [])).filter(Boolean);
438
514
  process.exit(runExports(new Store(ws), { layers, dryRun: rest.includes('--dry-run'), json: rest.includes('--json') }));
439
515
  }
516
+ // `dt setup [<unit>] …` — the generic driver of the units installed modules declare (src/setup.js):
517
+ // inputs, consent per effect, inspect → plan → apply, the receipt. The engine names no module.
518
+ case 'setup':
519
+ process.exit(await setupCommand(ws, rest, { api }));
440
520
  case 'doctor': {
441
521
  const caps = await doctorBoard(ws, api);
442
- if (rest.includes('--json')) emit(JSON.stringify({ capabilities: caps }, null, 2));
522
+ if (rest.includes('--json')) emit(JSON.stringify({ workspace: { root: ws.root, name: ws.pkg?.name ?? null }, capabilities: caps }, null, 2));
443
523
  else console.log(renderBoard(caps));
444
524
  process.exit(rest.includes('--strict') && caps.some((c) => c.verdict === 'UNAVAILABLE') ? 1 : 0);
445
525
  }
@@ -530,6 +610,11 @@ export async function run(argv) {
530
610
  console.log(`✖ ${s.message}`);
531
611
  process.exit(1);
532
612
  }
613
+ if (rest.includes('--json')) {
614
+ const { modules: mods } = discoverModules(ws.root, ws.pkg);
615
+ 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));
616
+ process.exit(0);
617
+ }
533
618
  console.log(`compiled: ${s.manifest.compiled}`);
534
619
  // THE EDITOR, from the marker the extension writes on activation (`.dreamteamer/editor.json`).
535
620
  // Without it an agent working inside the editor could not tell whether the extension was
@@ -549,6 +634,8 @@ export async function run(argv) {
549
634
  // §10: the folder name IS the label. `hr git_modules @ 3f2a1c (dirty)` needs no
550
635
  // legend, and `[inline]` needed one every single time.
551
636
  let line = ` ${m.name.padEnd(20)} ${locationOf(m, ws.root)}`;
637
+ // a development link (a folder spec): never pinned, skipped by update
638
+ 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
639
  if (m.channel === 'git') {
553
640
  const ref = tryGit(m.root, ['rev-parse', '--short', 'HEAD']);
554
641
  const dirty = tryGit(m.root, ['status', '--porcelain']);
@@ -633,6 +720,9 @@ export async function run(argv) {
633
720
  for (const r of pending) console.log(` ${r.repo === '.' ? 'workspace' : r.repo}: ${r.rows.length}`);
634
721
  }
635
722
  } catch { /* no runtime yet, or not a git repo — status must still print */ }
723
+ // the SETUP section (src/setup.js): one line per unit the installed modules declare, folded
724
+ // from each unit's own inspect — read-only, and never from a stored success flag
725
+ 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
726
  if (s.stale.length) {
637
727
  for (const line of s.stale) console.log(` stale: ${line}`);
638
728
  console.log(`✖ .dreamteamer is stale (${s.stale.length}) — run \`dreamteamer compile\``);
@@ -756,10 +846,6 @@ export async function run(argv) {
756
846
  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
847
  process.exit(2);
758
848
  }
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
849
  console.error(`✖ unknown verb "${cmd}" — the verb comes first: dt <verb> [<target>]`);
764
850
  emit(USAGE, 2);
765
851
  process.exit(1);
@@ -358,9 +358,11 @@ function metaModulesAdd(ws, store, flags) {
358
358
  name: oneValue(flags, 'name'),
359
359
  description: oneValue(flags, 'description'),
360
360
  namespace: oneValue(flags, 'namespace'),
361
+ extension: flags.extension === true || flags.extension === 'true',
362
+ pkg: flags.package === undefined ? null : flags.package === true ? true : oneValue(flags, 'package'),
361
363
  });
362
364
  if (flags.json) { emit(JSON.stringify(out)); return 0; }
363
- console.log(`✔ ${out.root}/ — package.json + ${KIND_COUNT} kind folder(s)`);
365
+ console.log(`✔ ${out.root}/ — ${out.files.join(' · ')} + ${KIND_COUNT} kind folder(s)`);
364
366
  // §6.2 promises the namespace is DECLARED IN THE MODULE, and §8 makes every later
365
367
  // `add collections --module <id>` infer it — so the declaration is echoed, because an inferred
366
368
  // identity the operator did not type is one they must be able to read back.
@@ -1322,7 +1324,7 @@ export const VERB_FLAGS = {
1322
1324
  'collections:add': ['json', 'module', 'name', 'namespace', 'mixins', 'id-from', 'description', 'suffix'],
1323
1325
  'collections:get': ['json', 'module'], 'collections:set': ['json', 'module', 'dry-run'],
1324
1326
  'collections:rm': FORCE_RM, 'collections:rename': ['json', 'namespace', 'dry-run'], 'collections:reorder': NAV_MOVE,
1325
- 'modules:add': ['json', 'name', 'description', 'namespace'], 'modules:rename': JSON_ONLY, 'modules:rm': FORCE_RM,
1327
+ 'modules:add': ['json', 'name', 'description', 'namespace', 'extension', 'package'], 'modules:rename': JSON_ONLY, 'modules:rm': FORCE_RM,
1326
1328
  'modules:set': ['json', 'description', 'namespaces', 'dependencies', 'peer_collections'],
1327
1329
  // the identity kinds: `add` scaffolds, `rm`/`rename` fall through to the generic rows, and `set`
1328
1330
  // is deliberately UNCHECKED — a skill's frontmatter is an open document (`allowed-tools`, `model`,
package/src/compile.js CHANGED
@@ -616,7 +616,7 @@ export function compile(ws) {
616
616
  if (!sib || dep === mod) continue;
617
617
  const ok = satisfies(have, range);
618
618
  if (ok === null) console.warn(`⚠ module ${mod}: peerDependencies range "${range}" for "${dep}" (${have ?? 'no version'}) not understood by the built-in checker (see src/semver.js) — not verified`);
619
- else if (!ok) misses.push(`module "${mod}" ${moduleVersions.get(mod)} needs "${dep}" ${range} (its peerDependencies) — this workspace has ${have}, from ${CHANNEL_LABEL[sib.channel]}.\n fix: ${sib.channel === 'npm' ? `npm install "${dep}@${range}"` : `bring ${rel(sib.root)} to a version in ${range}`}`);
619
+ else if (!ok) misses.push(`module "${mod}" ${moduleVersions.get(mod)} needs "${dep}" ${range} (its peerDependencies) — this workspace has ${have}, from ${CHANNEL_LABEL[sib.channel]}.\n fix: ${dep === 'dreamteamer' ? `dt update --engine (the engine is the workspace's pin; init and install never change it)` : sib.channel === 'npm' ? `npm install "${dep}@${range}"` : `bring ${rel(sib.root)} to a version in ${range}`}`);
620
620
  }
621
621
  if (misses.length) fail(misses.join('\n'));
622
622
  }
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, safeInspect } 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
+ checks = safeInspect(u, { root: ws.root, ws, dt, env, tty: false, receiptDir: receiptDir(ws, u.id) }).map((c) => (c.id === `${u.id}.inspect` ? { ...c, id: 'inspect', fix: `report it to ${u.module}` } : c));
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;
@@ -0,0 +1,162 @@
1
+ // The `.env` writer behind a unit's env action (cr-dt-007, D61): the engine performs the one write
2
+ // every module's setup used to carry its own copy of — a key's value span replaced in place or
3
+ // appended, every other byte kept, the file replaced whole by rename, and only while it still has
4
+ // the fingerprint the plan saw. What is written reads back through `parseEnvValues` identically:
5
+ // `envSpans` follows that reader's grammar (an unquoted value runs to end of line; a quoted one may
6
+ // span lines), so this file is the writer half of one grammar, not a second grammar.
7
+ //
8
+ // Refusals are `EnvRefusal` with a `code`, so the driver (src/setup.js) can turn the ones it can see
9
+ // before writing into a plan-time `blocked` and keep only `changed` (the file moved after the plan)
10
+ // and an I/O error as a write-time failure. Nothing here reads a value back to the caller.
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import { createHash, randomBytes } from 'node:crypto';
14
+ import { spawnSync } from 'node:child_process';
15
+
16
+ export class EnvRefusal extends Error {
17
+ constructor(code, message) { super(message); this.code = code; }
18
+ }
19
+
20
+ const ENV_KEY = /^[A-Z][A-Z0-9_]*$/;
21
+ // the reader's assignment, with the value token captured: KEY=value · KEY="…" (spans lines) · KEY='…'
22
+ const ASSIGNMENT = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("(?:[^"\\]|\\.)*"|'[^']*'|[^\n]*)$/gm;
23
+
24
+ /** Every assignment in `.env` text, in file order: `{ key, start, end, raw, value, quoted }` where
25
+ * `[start, end)` is the value token's span (an unquoted value without its trailing whitespace, so a
26
+ * CRLF file keeps its `\r`), `raw` the text there, `value` what parseEnvValues reads, `quoted` the
27
+ * quote character or false. */
28
+ export function envSpans(text) {
29
+ const out = [];
30
+ // a leading byte-order mark is not part of the first key: scanned as if absent, offsets kept (it is one
31
+ // UTF-16 unit, replaced by one newline so `^` still matches the first line)
32
+ const body = String(text).replace(/^\uFEFF/, '\n');
33
+ for (const m of body.matchAll(ASSIGNMENT)) {
34
+ let raw = m[2];
35
+ const quoted = raw.startsWith('"') && raw.endsWith('"') && raw.length >= 2 ? '"' : raw.startsWith("'") && raw.endsWith("'") && raw.length >= 2 ? "'" : false;
36
+ if (!quoted) raw = raw.replace(/\s+$/, '');
37
+ const start = m.index + m[0].length - m[2].length;
38
+ out.push({ key: m[1], start, end: start + raw.length, raw, value: quoted ? raw.slice(1, -1) : raw.trim(), quoted });
39
+ }
40
+ return out;
41
+ }
42
+
43
+ /** The token written for `value`: plain when nothing in it needs quoting (a backslash reads back as
44
+ * itself unquoted — a Windows path), else double-quoted. Inside double quotes the reader treats `\x` as
45
+ * one unit, so a backslash there could swallow the closing quote: refused. */
46
+ function token(key, value, preferQuoted) {
47
+ const plain = /^[^\s#"']*$/.test(value) && value === value.trim() && !(preferQuoted && !value.includes('\\'));
48
+ if (plain) return value;
49
+ if (value.includes('\\')) throw new EnvRefusal('value', `${key}: a value with characters this action does not write — set it by hand`);
50
+ return `"${value}"`;
51
+ }
52
+
53
+ /**
54
+ * `.env` text with every key of `values` set, every other byte kept: a present key's value span is
55
+ * replaced in place (its quoting kept when it was double-quoted); an absent key is appended as its
56
+ * own line. `changed` lists the keys whose value differs from what the file held.
57
+ * Refuses, by code: `twice` (a key assigned more than once — which assignment wins is the reader's
58
+ * accident, so neither is rewritten) and `value` (a value holding `"` or NUL — the reader does not
59
+ * unescape, so such a value cannot read back as written).
60
+ */
61
+ export function setEnvValues(text, values) {
62
+ let out = String(text);
63
+ // a byte-order mark stays where it is; envSpans scans past it (the engine's reader of the unit's
64
+ // environment, unitEnv, skips it too — held-out he1)
65
+ const changed = [];
66
+ for (const [key, value] of Object.entries(values)) {
67
+ if (!ENV_KEY.test(key)) throw new EnvRefusal('key', `${key} is not an environment key`);
68
+ if (typeof value !== 'string') throw new EnvRefusal('value', `${key}: a value that is not a string`);
69
+ const found = envSpans(out).filter((s) => s.key === key);
70
+ if (found.length > 1) throw new EnvRefusal('twice', `${key} is assigned more than once in .env — resolve that by hand first`);
71
+ // a value the file already holds is done, whatever it holds: one a person set by hand after a refusal
72
+ // is never refused again
73
+ if (found.length === 1 && found[0].value === value) continue;
74
+ // a `"` the reader does not unescape; `$`, a backtick or a carriage return a shell that sources .env
75
+ // would expand or split; NUL — refused, so what is written reads back as written everywhere
76
+ if (/["$`\r\0]/.test(value)) throw new EnvRefusal('value', `${key}: a value with characters this action does not write — set it by hand`);
77
+ if (found.length === 1) {
78
+ const s = found[0];
79
+ out = out.slice(0, s.start) + token(key, value, s.quoted === '"') + out.slice(s.end);
80
+ } else {
81
+ const nl = out.includes('\r\n') ? '\r\n' : '\n';
82
+ out = `${out}${out && !out.endsWith('\n') ? nl : ''}${key}=${token(key, value, false)}${nl}`;
83
+ }
84
+ changed.push(key);
85
+ }
86
+ return { text: out, changed };
87
+ }
88
+
89
+ /** `sha256:<hex>` of a regular file, `absent` when there is none; a symlink or a non-file is refused. */
90
+ export function fingerprint(file) {
91
+ let st;
92
+ try { st = fs.lstatSync(file); } catch (error) { if (error.code === 'ENOENT') return 'absent'; throw error; }
93
+ if (st.isSymbolicLink()) throw new EnvRefusal('symlink', `${path.basename(file)} is a symlink — a symlinked file is never written; replace the link with a regular file first`);
94
+ if (!st.isFile()) throw new EnvRefusal('not-file', `${path.basename(file)} is not a regular file`);
95
+ return `sha256:${createHash('sha256').update(fs.readFileSync(file)).digest('hex')}`;
96
+ }
97
+
98
+ const tempPrefix = (target) => `${path.basename(target)}.setup-`;
99
+ /** Temporary files an interrupted write of `target` left beside it — a reason to stop and name them. */
100
+ export function leftoverTemps(target) {
101
+ try { return fs.readdirSync(path.dirname(target)).filter((f) => f.startsWith(tempPrefix(target)) && f.endsWith('.tmp')).sort(); }
102
+ catch { return []; }
103
+ }
104
+
105
+ // read-only git, scoped to the root: no optional locks, no fsmonitor, no GIT_* from the environment
106
+ const GIT_ENV_KEYS = ['PATH', 'HOME', 'USERPROFILE', 'SystemRoot', 'SYSTEMROOT', 'TMPDIR', 'TEMP', 'TMP', 'LANG', 'LC_ALL', 'XDG_CONFIG_HOME'];
107
+ function git(root, args) {
108
+ const env = { GIT_TERMINAL_PROMPT: '0' };
109
+ for (const k of GIT_ENV_KEYS) if (process.env[k] !== undefined) env[k] = process.env[k];
110
+ const r = spawnSync('git', ['--no-optional-locks', '-c', 'core.fsmonitor=false', '-C', root, ...args], { env, encoding: 'utf8', timeout: 10_000, stdio: ['ignore', 'pipe', 'pipe'] });
111
+ return { status: r.error ? null : r.status, stderr: r.stderr ?? '' };
112
+ }
113
+
114
+ /** Could workspace-relative `rel` end up in a commit? `{ safe }` or `{ safe: false, reason }`: in a
115
+ * repository git decides (not tracked, and ignored); outside any repository nothing can be committed. */
116
+ export function gitExposure(root, rel) {
117
+ const top = git(root, ['rev-parse', '--show-toplevel']);
118
+ if (top.status !== 0) {
119
+ if (top.status === 128 && /not a git repository/i.test(top.stderr)) return { safe: true };
120
+ if (top.status === null) return { safe: true }; // no git on this machine: nothing commits
121
+ return { safe: false, reason: `git could not inspect this workspace — nothing was written` };
122
+ }
123
+ if (git(root, ['ls-files', '--error-unmatch', '--', rel]).status === 0) return { safe: false, reason: `${rel} is tracked by git, so its contents would be committed — untrack it (git rm --cached ${rel}) and ignore it first` };
124
+ if (git(root, ['check-ignore', '-q', '--', rel]).status === 0) return { safe: true };
125
+ return { safe: false, reason: `git would commit ${rel} — add it to .gitignore first` };
126
+ }
127
+
128
+ /** Is any component of `.env` under `root` a symlink, or does the path leave the root? */
129
+ function confinedEnv(root) {
130
+ const real = fs.realpathSync(root);
131
+ const target = path.join(real, '.env');
132
+ let st = null;
133
+ try { st = fs.lstatSync(target); } catch (error) { if (error.code !== 'ENOENT') throw error; }
134
+ if (st?.isSymbolicLink()) throw new EnvRefusal('symlink', '.env is a symlink — a symlinked file is never written; replace the link with a regular file first');
135
+ return target;
136
+ }
137
+
138
+ /**
139
+ * Replace `<root>/.env` with `content` by rename, only while it still has fingerprint `expect`
140
+ * (`absent` for a file that did not exist). The temporary file is removed on every failure this
141
+ * process survives; an existing file keeps its mode, a new one is created owner-only. The last check
142
+ * and the rename are two calls, not a compare-and-swap — optimistic, kept as short as it can be.
143
+ */
144
+ export function writeEnvAtomic(root, content, expect) {
145
+ const target = confinedEnv(root);
146
+ const stale = () => new EnvRefusal('changed', '.env changed after the preview — nothing was written; plan again');
147
+ if (fingerprint(target) !== expect) throw stale();
148
+ let mode = 0o600;
149
+ try { mode = fs.statSync(target).mode & 0o777; } catch { /* a new file */ }
150
+ const temp = path.join(path.dirname(target), `${tempPrefix(target)}${process.pid}.${randomBytes(6).toString('hex')}.tmp`);
151
+ const fd = fs.openSync(temp, 'wx', mode);
152
+ try {
153
+ try { fs.writeFileSync(fd, content); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
154
+ confinedEnv(root);
155
+ if (fingerprint(target) !== expect) throw stale();
156
+ fs.renameSync(temp, target);
157
+ } catch (error) {
158
+ fs.rmSync(temp, { force: true });
159
+ throw error;
160
+ }
161
+ return fingerprint(target);
162
+ }
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,18 @@ 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
+ /** What `dt check` holds every discovered package's manifest to, beyond the `dreamteamer` block: the
61
+ * engine never under `dependencies` — npm nests a second engine there whenever the pin differs from the
62
+ * workspace's, and a module reaching that copy disagrees with the engine the operator ran (D66).
63
+ * `devDependencies` (a module's own tests) and `peerDependencies` are the two places it belongs. */
64
+ export function manifestViolations(pkg, file) {
65
+ if (pkg?.dependencies && typeof pkg.dependencies === 'object' && 'dreamteamer' in pkg.dependencies) {
66
+ return [{ file, message: `${pkg.name ?? file} lists dreamteamer under dependencies — a second engine would be installed beside this one; move it to devDependencies or peerDependencies` }];
67
+ }
68
+ return [];
69
+ }
70
+
71
+ const CONTRIBUTION_KEYS = new Set(['commands', 'sourceKinds', 'analyze', 'harnesses', 'orientation', 'hooks', 'check', 'doctor', 'next', 'setup']);
58
72
 
59
73
  /** The modules that declare an extension entry: the workspace's own `modules/<id>/` first, then each
60
74
  * clone under `git_modules/` (the clone's root, then the modules it bundles under `modules/`), then its
@@ -77,7 +91,7 @@ export function declaredExtensions(ws) {
77
91
  // a module whose engine floor is unmet is refused whole, its code with its content
78
92
  const range = pkg.dreamteamer.engine;
79
93
  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) });
94
+ out.push({ name, version: pkg.version ?? '0.0.0', dir, entry: path.join(dir, entry), env: pkg.dreamteamer.env ?? [], vars: pkg.dreamteamer.vars ?? [] });
81
95
  };
82
96
  let inline = [];
83
97
  try { inline = fs.readdirSync(path.join(ws.root, 'modules')).sort(); } catch { /* no modules/ */ }
@@ -125,13 +139,15 @@ export async function loadExtensions(ws, api, reserved = {}) {
125
139
  const v1 = v1ManifestRefusal(ws.pkg?.dreamteamer, 'package.json');
126
140
  if (v1) throw new Error(v1);
127
141
  const loaded = [];
128
- const owner = { command: new Map(), kind: new Map(), harness: new Map() };
142
+ const owner = { command: new Map(), kind: new Map(), harness: new Map(), unit: new Map() };
129
143
  for (const r of reserved.verbs ?? []) owner.command.set(r, 'the engine');
130
144
  for (const r of reserved.kinds ?? []) owner.kind.set(r, 'the engine');
131
145
  for (const r of reserved.harnesses ?? []) owner.harness.set(r, 'the engine');
132
146
  const claim = (what, key, by) => {
133
147
  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`);
148
+ if (prev) throw new Error(what === 'unit'
149
+ ? `setup unit "${key}" is contributed by ${by} and ${prev} — uninstall one, or switch it off: add "modules/${by}" to dreamteamer.disable in package.json`
150
+ : `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
151
  owner[what].set(key, by);
136
152
  };
137
153
  for (const ext of declaredExtensions(ws)) {
@@ -154,7 +170,21 @@ export async function loadExtensions(ws, api, reserved = {}) {
154
170
  for (const k of sourceKinds) claim('kind', k.kind, ext.name);
155
171
  for (const id of Object.keys(c.harnesses ?? {})) claim('harness', id, ext.name);
156
172
  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 });
173
+ // setup units: validated here so an uncompilable declaration never reaches `dt install`; a unit id is
174
+ // claimed like a verb, because two packages answering `dt setup <id>` is the same silent loser
175
+ const setup = validateSetup(ext.name, c.setup, { env: ext.env, vars: ext.vars });
176
+ if (setup.errors.length) throw new Error(setup.errors.join('\n'));
177
+ for (const u of setup.units) claim('unit', u.id, ext.name);
178
+ 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 });
179
+ }
180
+ // one env key, one kind (D39): two inputs — in one package or across packages — that name the same
181
+ // key with different kinds are refused here, naming the pair, before any setup runs on them
182
+ const keyKinds = new Map();
183
+ for (const ext of loaded) for (const u of ext.setup ?? []) for (const i of u.inputs ?? []) {
184
+ if (!i.env) continue;
185
+ const prev = keyKinds.get(i.env);
186
+ 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`);
187
+ if (!prev) keyKinds.set(i.env, { kind: i.kind, by: ext.name, unit: u.id, input: i.id });
158
188
  }
159
189
  return loaded;
160
190
  }