dreamteamer 0.48.1 → 0.49.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +41 -39
  2. package/collections/modules.collection.yaml +11 -0
  3. package/package.json +1 -1
  4. package/skills/using-dreamteamer/SKILL.md +8 -6
  5. package/skills/using-dreamteamer/references/before-you-build.md +8 -6
  6. package/skills/using-dreamteamer/references/collections.md +16 -7
  7. package/skills/using-dreamteamer/references/commands.md +4 -3
  8. package/skills/using-dreamteamer/references/data-modeling.md +3 -2
  9. package/skills/using-dreamteamer/references/extensions.md +13 -12
  10. package/skills/using-dreamteamer/references/getting-started.md +4 -3
  11. package/skills/using-dreamteamer/references/records.md +4 -4
  12. package/skills/using-dreamteamer/references/setup.md +7 -5
  13. package/skills/using-dreamteamer/references/ui-components.md +1 -1
  14. package/skills/using-dreamteamer/references/ui-views.md +39 -1
  15. package/skills/using-dreamteamer/references/writing-a-module.md +3 -2
  16. package/src/api.d.ts +18 -0
  17. package/src/api.js +7 -0
  18. package/src/check-alone.js +58 -8
  19. package/src/check.js +10 -0
  20. package/src/cli.js +36 -18
  21. package/src/collections-cli.js +9 -41
  22. package/src/compile-collections.js +20 -3
  23. package/src/compile.js +59 -8
  24. package/src/extensions.js +1 -1
  25. package/src/init.js +1 -1
  26. package/src/install-modules.js +113 -46
  27. package/src/nav-fragments.js +190 -0
  28. package/src/nav.js +185 -0
  29. package/src/schema-ops.js +4 -4
  30. package/src/semver.js +4 -0
  31. package/src/setup.js +6 -3
  32. package/src/store.js +35 -11
  33. package/src/unread-data.js +74 -0
  34. package/src/update-setup.js +6 -5
  35. package/src/update.js +43 -12
  36. package/src/workspace.js +52 -13
package/src/compile.js CHANGED
@@ -17,7 +17,7 @@ import {
17
17
  // call at run time, same pattern as store.js ↔ compile.js.
18
18
  import { runHarnessAdapters, renderContributions, BEGIN, END, INSTRUCTIONS_BEGIN, INSTRUCTIONS_END } from './harnesses.js';
19
19
  import { ensureEditorRecommendation, ensureEnvExample, ensureGitignored, layerEntries } from './workspace.js';
20
- import { satisfies } from './semver.js';
20
+ import { satisfies, EXACT } from './semver.js';
21
21
  import { parseEnvValues } from './env-vars.js';
22
22
  import { DERIVED_KINDS, readManifest, runtimeDir, engineId, engineVersion, loadDescriptors as loadCompiledDescriptors, STALE_RUNTIME } from './runtime.js';
23
23
  import { excludedFromKind, disablesPackage, isPackageEntry, MANIFEST_KEYS, v1ManifestRefusal } from './extensions.js';
@@ -218,8 +218,10 @@ export function discoverModules(root, pkg) {
218
218
  // ⚠ THE PACKAGE FIRST: disabling a bundle disables every module in it. Only the children used to
219
219
  // be checked, so `disable: ['@x/bundle']` stopped its code and compiled all of its content.
220
220
  if (disabled(name)) return;
221
+ // A MODULE PRESET is never a bundle: it lists modules and ships none, so a `modules/` folder in
222
+ // one is the package pass's refusal to make, not a family to unpack.
221
223
  const bundle = path.join(srcRoot, 'modules');
222
- if (fs.existsSync(bundle) && fs.statSync(bundle).isDirectory()) { scanDir(bundle, channel, false); return; }
224
+ if (!readPkg(srcRoot)?.dreamteamer?.preset && fs.existsSync(bundle) && fs.statSync(bundle).isDirectory()) { scanDir(bundle, channel, false); return; }
223
225
  tryAdd(name, srcRoot, channel);
224
226
  };
225
227
  scanDir(path.join(root, 'modules'), 'inline', false);
@@ -433,6 +435,7 @@ export function compile(ws) {
433
435
  const moduleNamespaces = new Map(); // module name -> [namespaces it DECLARES] (§8, option A)
434
436
  const moduleVersions = new Map(); // module name -> its package.json version
435
437
  const moduleFloors = new Map(); // module name -> npm `peerDependencies` — a version floor on a sibling module
438
+ const modulePresets = new Map(); // module preset name -> { member name: exact version } (CR-dt-008)
436
439
  const moduleLocalAssets = []; // {rel, owner, base} — validated with the workspace's own, below
437
440
  // the package.json `dreamteamer` block is a closed set of snake_case keys, the workspace's and
438
441
  // every module's alike — a key outside it is a typo or a spelling this engine does not read
@@ -444,6 +447,7 @@ export function compile(ws) {
444
447
  if (bad.length) fail(`${where}: unknown dreamteamer key(s) ${bad.join(', ')} — the keys are ${MANIFEST_KEYS.join(' · ')}`);
445
448
  };
446
449
  refuseUnknownKeys(config, 'package.json');
450
+ if (config.preset !== undefined || config.nav !== undefined) fail('package.json: dreamteamer.preset and dreamteamer.nav belong to a module package, not the workspace');
447
451
  for (const source of sources) {
448
452
  let mpkg;
449
453
  try { mpkg = JSON.parse(fs.readFileSync(path.join(source.root, 'package.json'), 'utf8')); } catch { continue; }
@@ -474,6 +478,27 @@ export function compile(ws) {
474
478
  }
475
479
  moduleNamespaces.set(source.name, ns);
476
480
  }
481
+ // A MODULE PRESET (CR-dt-008): `preset` maps member module names to EXACT versions — the set
482
+ // `dt install` pins and `dt update` moves. It lists modules and ships no sources of its own.
483
+ // `nav` names the package's nav fragment, a path inside the package.
484
+ if (source.root !== root) {
485
+ const preset = mpkg.dreamteamer?.preset;
486
+ if (preset !== undefined) {
487
+ if (!preset || typeof preset !== 'object' || Array.isArray(preset)) fail(`module "${source.name}": dreamteamer.preset must map module names to exact versions (got ${JSON.stringify(preset)})`);
488
+ for (const [member, v] of Object.entries(preset)) {
489
+ if (typeof v !== 'string' || !EXACT.test(v)) fail(`module "${source.name}": dreamteamer.preset["${member}"] must be an exact version (got ${JSON.stringify(v)})`);
490
+ }
491
+ // every folder compile would read from a package: the kind folders (an extension's kinds
492
+ // too), a modules/ bundle, and a UI bundle (ui/, or its pre-archive name studio/)
493
+ const shipped = [...new Set([...KINDS, ...kinds]), 'modules', 'ui', 'studio'].find((k) => fs.existsSync(k === 'modules' || k === 'ui' || k === 'studio' ? path.join(source.root, k) : kindDir(source.root, k)));
494
+ if (shipped) fail(`module "${source.name}": a module preset lists modules; it ships none (found ${shipped}/)`);
495
+ modulePresets.set(source.name, preset);
496
+ }
497
+ const nav = mpkg.dreamteamer?.nav;
498
+ if (nav !== undefined && (typeof nav !== 'string' || !nav || path.isAbsolute(nav) || path.posix.isAbsolute(nav) || nav.split(/[\\/]/).includes('..'))) {
499
+ fail(`module "${source.name}": dreamteamer.nav must be a relative path inside the package (got ${JSON.stringify(nav)})`);
500
+ }
501
+ }
477
502
  if (source.root !== root) {
478
503
  moduleVersions.set(source.name, mpkg.version);
479
504
  if (mpkg.peerDependencies && typeof mpkg.peerDependencies === 'object') moduleFloors.set(source.name, mpkg.peerDependencies);
@@ -557,9 +582,22 @@ export function compile(ws) {
557
582
  // points at a file that actually names them; `.vscode/extensions.json` recommends the editor
558
583
  // extension, so the first window offers it. Both are append/merge-only — nothing authored moves.
559
584
  {
560
- const added = ensureEnvExample(root, [...declaredEnv, ...requestedVars].map(([key, mods]) => ({ key, modules: mods, ...(envMeta.get(key) ?? {}) })),
561
- '# secrets for skills and modules go here (copy to .env; .env is never committed).\n# modules declare the env keys they require in their package.json dreamteamer.env list.\n');
562
- if (added.length) console.log(`✔ .env.example now names ${added.join(', ')}`);
585
+ // one entry per key: a key one package declares as env and another requests as a var is one block
586
+ const byKey = new Map();
587
+ for (const [key, mods] of [...declaredEnv, ...requestedVars]) {
588
+ const e = byKey.get(key) ?? byKey.set(key, { key, modules: [], ...(envMeta.get(key) ?? {}) }).get(key);
589
+ for (const m of mods) if (!e.modules.includes(m)) e.modules.push(m);
590
+ }
591
+ // the workspace's own declarations are never dropped; and a declared module not on disk yet (a git
592
+ // module before `dt install`, a dependency before `npm install`) would drop keys it still declares
593
+ const keep = [...declaredVars, ...(config.env ?? []).map((e) => (typeof e === 'string' ? e : e?.name))];
594
+ const complete = !Object.keys(config.git_modules ?? {}).some((n) => !fs.existsSync(path.join(root, 'git_modules', n)))
595
+ && !Object.keys(pkg.dependencies ?? {}).some((n) => !fs.existsSync(path.join(root, 'node_modules', n, 'package.json')));
596
+ const env = ensureEnvExample(root, [...byKey.values()],
597
+ '# secrets for skills and modules go here (copy to .env; .env is never committed).\n# modules declare the env keys they require in their package.json dreamteamer.env list.\n', { keep, complete });
598
+ if (env.added.length) console.log(`✔ .env.example now names ${env.added.join(', ')}`);
599
+ for (const k of env.moved) console.log(`✔ .env.example re-attributes ${k} (now declared by ${byKey.get(k).modules.join(', ')})`);
600
+ for (const k of env.dropped) console.log(`✔ .env.example drops ${k} — no installed package declares it`);
563
601
  ensureEditorRecommendation(root);
564
602
  }
565
603
 
@@ -601,10 +639,17 @@ export function compile(ws) {
601
639
  if (dep === mod) fail(`module "${mod}" declares itself as a dependency`);
602
640
  if (refused.has(dep)) fail(`module "${mod}" depends on "${dep}", which needs engine "${refused.get(dep)}" — this is ${engineVer}. Upgrade dreamteamer, or disable both.`);
603
641
  if (!moduleNames.has(dep)) {
604
- fail(`module "${mod}" depends on "${dep}", which is not installed — modules present: ${[...moduleNames].sort().join(', ')}`);
642
+ fail(`module "${mod}" depends on "${dep}", which is not installed — modules present: ${[...moduleNames].sort().join(', ')}\n run: dt install ${dep}`);
605
643
  }
606
644
  }
607
645
  }
646
+ // A module preset's absent member is a WARNING, never a failure: the preset is a list, and the
647
+ // operator may have uninstalled a member on purpose.
648
+ for (const [mod, members] of modulePresets) {
649
+ for (const [member, v] of Object.entries(members)) {
650
+ if (!moduleNames.has(member)) console.warn(`⚠ module preset ${moduleId(mod)} names ${member} ${v}, which is not installed — dt install ${member}`);
651
+ }
652
+ }
608
653
  // npm's `peerDependencies` naming ANOTHER discovered module is a VERSION FLOOR: npm refuses the install
609
654
  // below it, and this refuses the channels npm never saw — a git_modules clone, an inline copy, an
610
655
  // install that went around the peer check. An absent sibling is `dependencies`' business, not this one's.
@@ -839,7 +884,7 @@ export function compile(ws) {
839
884
  // is a genuine existence test on either spelling.
840
885
  const extensionNames = new Set(extensions.map((e) => e.name));
841
886
  for (const source of sources) {
842
- if (contributedBy.has(source.name) || extensionNames.has(source.name)) continue;
887
+ if (contributedBy.has(source.name) || extensionNames.has(source.name) || modulePresets.has(source.name)) continue;
843
888
  if (kinds.some((k) => fs.existsSync(kindDir(source.root, k)))) continue;
844
889
  console.warn(`⚠ module "${source.name}" (${rel(source.root)}) contributed no recognised sources — its folder names must match a known kind (${kinds.join(', ')}) or it must ship a UI bundle at ui/app.js`);
845
890
  }
@@ -943,7 +988,7 @@ export function compile(ws) {
943
988
  const { compiled: compiledColls, inert: inertSources, moduleColls, layerReads } = compileCollections({
944
989
  groups: descriptorGroups, mixins: mixinDocs, namespaces, nsOwners,
945
990
  runtimeKinds: new Set([...kinds, ...DERIVED_KINDS]), core: CORE_COLLECTIONS,
946
- moduleDeps, modulePeers, channelOf, wsModuleName, engineName, dataOwners,
991
+ moduleDeps, modulePresets, modulePeers, channelOf, wsModuleName, engineName, dataOwners,
947
992
  moduleSources: new Map(sources.map((s) => [s.name, s])), unownableBecause, layers,
948
993
  repoOf: (moduleRoot) => repoRootOf(moduleRoot, root), rel, root, dataPath: config.data_path ?? 'data', vars: storageVars,
949
994
  moduleId, fail: collectionsFail, warn: (m) => console.warn(m),
@@ -973,6 +1018,10 @@ export function compile(ws) {
973
1018
  if (clash && clash !== source.name) fail(`modules "${clash}" and "${source.name}" both resolve to the id "${id}" — rename one.`);
974
1019
  idByModule.set(id, source.name);
975
1020
  }
1021
+ const presetProjection = (names) => {
1022
+ const installed = names.filter((n) => sources.some((s) => s.name === n)).length;
1023
+ return { preset: true, members: names.map((n) => `modules/${moduleId(n)}`), preset_summary: `preset · ${names.length} members · ${installed} installed` };
1024
+ };
976
1025
  for (const source of sources) {
977
1026
  const id = moduleId(source.name);
978
1027
  let pkg = {};
@@ -1022,6 +1071,8 @@ export function compile(ws) {
1022
1071
  ...(moduleColls.get(source.name)?.size
1023
1072
  ? { collections: [...moduleColls.get(source.name)].sort().map((c) => `collections/${c}`) }
1024
1073
  : {}),
1074
+ // A MODULE PRESET (CR-dt-008): its members as references, and how many of them are here.
1075
+ ...(modulePresets.has(source.name) ? presetProjection(Object.keys(modulePresets.get(source.name))) : {}),
1025
1076
  };
1026
1077
  const bytes = Buffer.from(dump(record));
1027
1078
  // ⚠ The source hash is the hash of the SOURCE FILE, not of the projected record. Hashing the
package/src/extensions.js CHANGED
@@ -37,7 +37,7 @@ import { layerEntries } from './workspace.js';
37
37
  import { validateSetup } from './setup-contract.js';
38
38
 
39
39
  /** The keys a package.json `dreamteamer` block may carry — the workspace's and a module's alike. */
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'];
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', 'preset', 'nav'];
41
41
  /** The one command that converts a workspace to descriptor format v2. */
42
42
  export const CONVERTER = 'node node_modules/dreamteamer/scripts/migrate-descriptors-v2.mjs --root .';
43
43
 
package/src/init.js CHANGED
@@ -91,7 +91,7 @@ export function seedBlock(flags = {}, existing = {}) {
91
91
  // `default` is deliberately the same word `RESERVED_NAMESPACES` holds (namespace.js): this module
92
92
  // owns the DEFAULT-namespace collections, and the default namespace is the empty prefix. The one
93
93
  // misreading it invites — `default/tasks` — is a compile error whose message states the rule.
94
- // Override with `--workspace-module <name>` if a workspace wants its own spelling.
94
+ // Override with `--workspace_module <name>` if a workspace wants its own spelling.
95
95
  'workspace_module': flags.workspace_module ?? 'default',
96
96
  'git_modules': {},
97
97
  disable: [],
@@ -11,15 +11,17 @@ import fs from 'node:fs';
11
11
  import os from 'node:os';
12
12
  import path from 'node:path';
13
13
  import zlib from 'node:zlib';
14
+ import { fileURLToPath } from 'node:url';
14
15
  import { spawnSync, execFileSync } from 'node:child_process';
15
- import { satisfies } from './semver.js';
16
+ import { satisfies, EXACT } from './semver.js';
16
17
  import { engineVersion } from './runtime.js';
17
18
  import { parseEnvValues } from './env-vars.js';
18
- import { compile, discoverModules, staleness } from './compile.js';
19
+ import { compile, discoverModules, staleness, moduleIdOf } from './compile.js';
19
20
  import { resolveNpm, childEnv } from './checkout.js';
20
21
  import { units, runUnit, fillInputs, parseInputFlags, parseAllow, skippedUnits, fold, SetupUsage, EXIT, ttyIO, droppedKeys } from './setup.js';
22
+ import { planNavFragments, navGuard, navDocGuard, shipsFragment, NavFragmentRefusal, NAV_SETTINGS_LINE, NAV_GUARD_LINE } from './nav-fragments.js';
23
+ import { writeNavDoc, NavDocError } from './nav.js';
21
24
 
22
- const EXACT = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
23
25
  /** Numeric major.minor.patch order; a prerelease sorts below its release. */
24
26
  export function compareVersions(a, b) {
25
27
  const pa = String(a).split(/[-+]/)[0].split('.').map(Number), pb = String(b).split(/[-+]/)[0].split('.').map(Number);
@@ -124,63 +126,69 @@ export function installedModules(ws) {
124
126
  }
125
127
 
126
128
  /**
127
- * Resolve the specs and the closure of their `dreamteamer.dependencies`, and refuse — before npm
128
- * writes anything — a package that is not a module, an engine floor this engine does not meet, a
129
- * ring, a version already installed differently, and `provides` conflicts in both directions.
130
- * Returns the ordered install list (dependencies first) and the names already satisfied.
129
+ * Every installed MODULE PRESET (CR-dt-008) and its members as the preset pins them against what is
130
+ * installed: `installed` is the member's installed version, or null when it is absent. `dt status`
131
+ * reads it (text and --json).
131
132
  */
132
- export function resolveClosure(specs, { installed, from = null, npm = resolveNpm(), cwd = process.cwd(), engine = engineVersion() } = {}) {
133
+ export function presetMembers(ws) {
134
+ const mods = installedModules(ws);
135
+ const out = new Map();
136
+ for (const [name, m] of mods) {
137
+ const preset = m.manifest?.dreamteamer?.preset;
138
+ if (!preset || typeof preset !== 'object') continue;
139
+ out.set(name, { id: moduleIdOf(name), members: Object.entries(preset).map(([member, pinned]) => ({ name: member, pinned, installed: mods.get(member)?.version ?? null })) });
140
+ }
141
+ return out;
142
+ }
143
+
144
+ /**
145
+ * Resolve the specs and the closure of their `dreamteamer.dependencies` and, for a MODULE PRESET, its
146
+ * members at their pins (`dreamteamer.preset`, CR-dt-008), and refuse — before npm writes anything — a
147
+ * package that is not a module, an engine floor this engine does not meet, a ring, and a version
148
+ * already installed differently. Returns the ordered install list (members and dependencies first,
149
+ * the preset itself after them) and the names already satisfied. `skipMembers` names members the
150
+ * walk leaves out (`dt update` passes the ones the operator removed on purpose).
151
+ */
152
+ export function resolveClosure(specs, { installed, from = null, npm = resolveNpm(), cwd = process.cwd(), engine = engineVersion(), skipMembers = new Set() } = {}) {
133
153
  const index = from ? indexFolder(from) : null;
134
154
  const list = [];
135
155
  const already = [];
136
156
  const seen = new Map(); // name → entry
137
- // a package an INSTALLED one already provides: present for the walk (never resolved again), and refused
138
- // the moment it is asked for by name — before any of its dependencies are looked up anywhere
139
- const providedBy = (name) => [...installed].find(([, i]) => (i.manifest?.dreamteamer?.provides ?? []).includes(name))?.[0] ?? null;
140
157
  const judge = (entry, askedAs, stack = []) => {
141
158
  const m = entry.manifest;
142
159
  if (!m.dreamteamer || typeof m.dreamteamer !== 'object') throw refuse(`${m.name}@${m.version} is not a dreamteamer module (no dreamteamer key in its package.json)${stack.length ? ` — needed by ${stack.at(-1)}` : ''}`);
143
- const provider = providedBy(m.name);
144
- if (provider) throw refuse(`${provider} already provides ${m.name} — it is installed; nothing to add`);
145
160
  const range = m.dreamteamer.engine;
146
161
  if (range && satisfies(engine, range) === false) throw refuse(`${m.name}@${m.version} needs engine "${range}" — this is ${engine}; choose a version: dt install ${m.name}@<version>`);
147
162
  const here = installed.get(m.name);
148
163
  if (here?.linked) throw refuse(`${m.name} is a development link (not pinned) — remove the link to pin a version`);
149
- if (here && here.version && here.version !== m.version && askedAs === 'spec') throw refuse(`${m.name} is installed at ${here.version}, not ${m.version} — move it on purpose: dt update ${m.name}@${m.version}`);
164
+ if (here && here.version && here.version !== m.version && (askedAs === 'spec' || askedAs === 'member')) throw refuse(`${m.name} is installed at ${here.version}, not ${m.version} — move it on purpose: dt update ${m.name}@${m.version}`);
150
165
  };
151
166
  const walk = (spec, stack, askedAs) => {
152
- // asked for by name and already provided: refuse by name, without reading any manifest
153
- if (askedAs === 'spec' && !isPathSpec(spec, cwd)) { const p = providedBy(splitSpec(spec).name); if (p) throw refuse(`${p} already provides ${splitSpec(spec).name} — it is installed; nothing to add`); }
154
167
  const entry = readSpecManifest(spec, { from, index, npm, cwd });
155
168
  const name = entry.manifest.name;
156
- if (stack.includes(name)) throw refuse(`ring in dreamteamer.dependencies: ${[...stack.slice(stack.indexOf(name)), name].join(' → ')}`);
169
+ if (stack.includes(name)) throw refuse(`ring in dreamteamer.dependencies or preset: ${[...stack.slice(stack.indexOf(name)), name].join(' → ')}`);
157
170
  if (seen.has(name)) {
158
171
  // the same module asked for twice at different versions is a conflict, never a silent first-wins
159
172
  const prev = seen.get(name).manifest.version;
160
- if (askedAs === 'spec' && prev !== entry.manifest.version) throw refuse(`${name} is asked for at ${prev} and at ${entry.manifest.version} — one version per call`);
173
+ if ((askedAs === 'spec' || askedAs === 'member') && prev !== entry.manifest.version) throw refuse(`${name} is asked for at ${prev} and at ${entry.manifest.version} — one version per call`);
161
174
  return;
162
175
  }
163
176
  judge(entry, askedAs, stack);
164
177
  const here = installed.get(name);
165
178
  if (here && here.version === entry.manifest.version) { already.push(name); seen.set(name, entry); return; }
166
179
  seen.set(name, entry);
180
+ // a module preset's members first, each at its pin, a nested preset recursing the same way
181
+ for (const [member, version] of Object.entries(entry.manifest.dreamteamer.preset ?? {})) {
182
+ if (skipMembers.has(member)) continue;
183
+ walk(`${member}@${version}`, [...stack, name], 'member');
184
+ }
167
185
  for (const dep of entry.manifest.dreamteamer.dependencies ?? []) {
168
- if ((installed.has(dep) || providedBy(dep)) && !stack.includes(dep)) continue; // present (or composed in): its own closure was judged when it came in
186
+ if (installed.has(dep) && !stack.includes(dep)) continue; // present: its own closure was judged when it came in
169
187
  walk(dep, [...stack, name], 'dependency');
170
188
  }
171
189
  list.push(entry);
172
190
  };
173
191
  for (const s of specs) walk(s, [], 'spec');
174
- // provides, both ways — against what is installed and within the call itself
175
- const names = new Set(list.map((e) => e.manifest.name));
176
- for (const e of list) {
177
- const name = e.manifest.name;
178
- for (const p of e.manifest.dreamteamer.provides ?? []) {
179
- if (installed.has(p)) throw refuse(`${name} provides ${p}, which is installed — remove ${p} first (npm uninstall ${p}, then dt compile), or keep the small modules`);
180
- if (names.has(p)) throw refuse(`${name} provides ${p} — install one or the other, not both in one call`);
181
- }
182
- for (const o of list) if (o !== e && (o.manifest.dreamteamer.provides ?? []).includes(name)) throw refuse(`${o.manifest.name} provides ${name} — install one or the other, not both in one call`);
183
- }
184
192
  return { list, already };
185
193
  }
186
194
 
@@ -200,14 +208,25 @@ const gitIgnored = (root, rel) => gitOk(root, ['check-ignore', '-q', '--', rel])
200
208
  /** `git status --porcelain` of one path: '' when clean (modified AND untracked both count as dirty). */
201
209
  const gitStatus = (root, rel) => { try { return execFileSync('git', ['status', '--porcelain', '--', rel], { cwd: root, encoding: 'utf8' }).trim(); } catch { return ''; } };
202
210
 
211
+ const BIN = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'dreamteamer.js');
212
+
203
213
  // ---- steps 2–4 and 5–6, shared with `dt update` (install one pin later) ----------------------------
204
214
 
205
215
  /**
206
216
  * Steps 2–4: npm on the resolved list (the two files it rewrites copied aside), verify every package
207
- * resolves at the version asked for, compile (a refusal restores the pre-image and prunes). Returns
208
- * `{ fresh }`, or `{ code }`.
217
+ * resolves at the version asked for, compile (a refusal restores the pre-image and prunes), then the
218
+ * nav fragments of the listed packages judged and merged (cr-dt-008) — inside the same restore, so a
219
+ * fragment placing another module's collection, or a nav.yaml that does not read, undoes the call
220
+ * like a compile refusal. Returns `{ fresh, nav }` (nav: the plan setupAndCommit writes), or `{ code }`.
221
+ *
222
+ * `childCompile` (dt update): this process opened the workspace before npm, and ESM caches an extension's
223
+ * entry and every file it imports by path — so an in-process compile would run the version npm just
224
+ * replaced, blind to a source kind or harness the new one contributes (rnd/issues …dt-update-compiles-with-
225
+ * the-replaced-version-s-extension). The compile then runs in a child, this engine's own `dt compile`; a
226
+ * non-zero exit is a refusal like any other, and `fresh` is only `{ root, pkg }` — the nav plan reads no
227
+ * extension, and activating the cached ones could refuse on a collision the new versions do not have.
209
228
  */
210
- export async function npmAndCompile(ws, list, { npm = resolveNpm(), open, json = false, log = console.log, hooks = {}, what = 'install' } = {}) {
229
+ export async function npmAndCompile(ws, list, { npm = resolveNpm(), open, json = false, log = console.log, hooks = {}, what = 'install', ignoreSettings = false, childCompile = false } = {}) {
211
230
  const names = list.map((e) => e.manifest.name);
212
231
  const pkgFile = path.join(ws.root, 'package.json'), lockFile = path.join(ws.root, 'package-lock.json');
213
232
  const versionOf = (n) => { try { return JSON.parse(fs.readFileSync(path.join(ws.root, 'node_modules', n, 'package.json'), 'utf8')).version ?? null; } catch { return null; } };
@@ -222,12 +241,23 @@ export async function npmAndCompile(ws, list, { npm = resolveNpm(), open, json =
222
241
  const still = list.filter((e) => { const v = versionOf(e.manifest.name); return v === null || (e.kind !== 'folder' && v !== e.manifest.version); }).map((e) => e.manifest.name);
223
242
  if (still.length) { console.error(`✖ npm exited 0, but ${still.join(', ')} still do${still.length === 1 ? 'es' : ''} not resolve in node_modules at the version asked for`); return { code: EXIT.failed }; }
224
243
  // 4. compile — a refusal restores the pre-image and prunes
244
+ let compiled = false; // a refusal AFTER a compile (the nav fragments) owes the runtime a recompile
225
245
  try {
226
- const fresh = await open(ws.root);
227
- const stdout = console.log;
228
- if (json) console.log = console.error;
229
- try { compile(fresh); } finally { console.log = stdout; }
230
- return { fresh };
246
+ let fresh;
247
+ if (childCompile) {
248
+ // --workspace pins the root: a layer under git_modules/ would otherwise be climbed out of to the reader
249
+ const c = spawnSync(process.execPath, [BIN, '--workspace', ws.root, 'compile'], { cwd: ws.root, stdio: json ? ['ignore', 2, 2] : 'inherit', env: childEnv() });
250
+ if (c.status !== 0) throw new Error(`compile exited ${c.status ?? c.error?.message ?? c.signal}`);
251
+ compiled = true;
252
+ fresh = { root: ws.root, pkg: JSON.parse(fs.readFileSync(pkgFile, 'utf8')) };
253
+ } else {
254
+ fresh = await open(ws.root);
255
+ const stdout = console.log;
256
+ if (json) console.log = console.error;
257
+ try { compile(fresh); compiled = true; } finally { console.log = stdout; }
258
+ }
259
+ const nav = planNavFragments(fresh, { names, ignoreSettings });
260
+ return { fresh, nav };
231
261
  } catch (e) {
232
262
  fs.writeFileSync(pkgFile, before.pkg);
233
263
  if (before.lock !== null) fs.writeFileSync(lockFile, before.lock); else fs.rmSync(lockFile, { force: true });
@@ -244,7 +274,18 @@ export async function npmAndCompile(ws, list, { npm = resolveNpm(), open, json =
244
274
  console.error(`✖ ${what} refused: ${e.message.split('\n')[0]}\n restore FAILED (npm exited ${back.status ?? back.error?.message})${notBack.length ? `: ${notBack.map((n) => `${n} is not back at ${before.versions[n]}`).join(', ')}` : ''} — package.json and package-lock.json were put back; node_modules was NOT: run npm install to bring it back`);
245
275
  return { code: EXIT.failed };
246
276
  }
247
- console.error(`✖ ${what} refused: ${e.message.split('\n')[0]}\n package.json, package-lock.json and node_modules are as before the call`);
277
+ // compile succeeded before the refusal, so .dreamteamer and the harness folders hold the refused
278
+ // packages' sources: compile again over the restored node_modules, so the runtime is the pre-image's.
279
+ // In this process even after a child compile: the versions it cached are the restored ones.
280
+ if (compiled) {
281
+ const stdout = console.log;
282
+ console.log = () => {};
283
+ try { compile(await open(ws.root)); } catch (e2) {
284
+ console.error(`✖ ${what} refused: ${e.message.split('\n')[0]}\n package.json, package-lock.json and node_modules are as before the call, but the runtime could not be recompiled (${e2.message.split('\n')[0]}) — run dt compile`);
285
+ return { code: EXIT.failed };
286
+ } finally { console.log = stdout; }
287
+ }
288
+ console.error(`✖ ${what} refused: ${e.message.split('\n')[0]}\n package.json, package-lock.json and node_modules are as before the call${compiled ? ', and the runtime is compiled from them again' : ''}`);
248
289
  return { code: EXIT.failed };
249
290
  }
250
291
  }
@@ -252,10 +293,12 @@ export async function npmAndCompile(ws, list, { npm = resolveNpm(), open, json =
252
293
  /**
253
294
  * Steps 5–6: the safe part of the named packages' units (inputs filled leniently — npm has written,
254
295
  * so a mistyped --input is a named warning, never an abort), then one scoped commit: the two files
255
- * npm rewrites, .env.example if compile touched it, and every path an applied action reported that
256
- * git does not ignore. Returns `{ code, results, committed, ignored }`.
296
+ * npm rewrites, .env.example if compile touched it, nav.yaml when `nav` (the merge npmAndCompile
297
+ * planned) placed something, and every path an applied action reported that git does not ignore.
298
+ * Never plans and never refuses for nav: it only writes what it is handed. Returns
299
+ * `{ code, results, committed, ignored }`.
257
300
  */
258
- export async function setupAndCommit(ws, fresh, names, { subject, inputFlags = [], allow = new Set(), tty = false, noInput = true, io = null, processEnv = process.env, noCommit = false } = {}) {
301
+ export async function setupAndCommit(ws, fresh, names, { subject, inputFlags = [], allow = new Set(), tty = false, noInput = true, io = null, processEnv = process.env, noCommit = false, nav = null } = {}) {
259
302
  const skipped = new Set(skippedUnits(fresh));
260
303
  const fresh_units = units(fresh).filter((u) => names.includes(u.module) && !skipped.has(u.id));
261
304
  let code = EXIT.done;
@@ -278,10 +321,13 @@ export async function setupAndCommit(ws, fresh, names, { subject, inputFlags = [
278
321
  }
279
322
  } finally { term?.close(); }
280
323
  }
324
+ // the merged nav document — only when this call placed something, so an uncommitted hand edit of
325
+ // nav.yaml is never swept into a commit that did not touch it
326
+ const navPaths = nav?.changed ? (writeNavDoc(ws.root, nav.doc), ['nav.yaml']) : [];
281
327
  let committed = null;
282
328
  if (!noCommit && gitOk(ws.root, ['rev-parse', '--git-dir'])) {
283
329
  const changed = results.flatMap((r) => r.applied.flatMap((a) => a.changed ?? [])).map((p) => path.relative(ws.root, path.resolve(ws.root, p))).filter((rel) => rel && !rel.startsWith('..') && !path.isAbsolute(rel) && fs.existsSync(path.join(ws.root, rel)) && !gitIgnored(ws.root, rel));
284
- const paths = [...new Set(['package.json', 'package-lock.json', '.env.example', ...changed])].filter((rel) => fs.existsSync(path.join(ws.root, rel)));
330
+ const paths = [...new Set(['package.json', 'package-lock.json', '.env.example', ...navPaths, ...changed])].filter((rel) => fs.existsSync(path.join(ws.root, rel)));
285
331
  if (gitOk(ws.root, ['add', '--', ...paths]) && gitOk(ws.root, ['commit', '--quiet', '-m', subject, '--', ...paths])) committed = paths;
286
332
  }
287
333
  return { code, results, committed, ignored };
@@ -322,7 +368,9 @@ export async function installModules(ws, argv, { open, npm = resolveNpm(), verif
322
368
  const specs = argv.filter((a, i) => !a.startsWith('--') && !valueFlags.has(argv[i - 1]));
323
369
  if (!specs.length) { console.error('✖ dt install takes one or more specs: a name, name@version, ./file.tgz, ./folder or a git URL'); return EXIT.usage; }
324
370
  let allow, inputFlags;
325
- try { allow = parseAllow(argv); inputFlags = parseInputFlags(argv); } catch (e) { if (e instanceof SetupUsage) { console.error(`✖ ${e.message}`); return EXIT.usage; } throw e; }
371
+ try { allow = parseAllow(argv, { also: ['nav-reset'] }); inputFlags = parseInputFlags(argv); } catch (e) { if (e instanceof SetupUsage) { console.error(`✖ ${e.message}`); return EXIT.usage; } throw e; }
372
+ // `--allow nav-reset` is install's, never a setup unit's: taken out of the set the units see
373
+ const ignoreSettings = allow.delete('nav-reset');
326
374
 
327
375
  const floor = npmFloor(npm);
328
376
  if (floor) { console.error(`✖ ${floor}`); return EXIT.failed; }
@@ -331,6 +379,18 @@ export async function installModules(ws, argv, { open, npm = resolveNpm(), verif
331
379
  const installed = installedModules(ws);
332
380
  let plan;
333
381
  try { plan = resolveClosure(specs, { installed, from, npm, cwd: ws.root }); } catch (e) { if (e instanceof InstallRefusal) { console.error(`✖ ${e.message}`); return EXIT.failed; } throw e; }
382
+ // the nav guard (cr-dt-008): a package that ships a nav fragment or is a module preset would redraw a
383
+ // tree that still draws by old nav settings — refused before npm until they are migrated, or until
384
+ // --allow nav-reset says to start from the fragments. A package with neither installs, and the merge
385
+ // says the settings are still there.
386
+ if (!ignoreSettings && plan.list.some((e) => e.manifest.dreamteamer?.nav || e.manifest.dreamteamer?.preset) && navGuard(ws.root)) {
387
+ console.error(`✖ ${NAV_GUARD_LINE}`);
388
+ return EXIT.failed;
389
+ }
390
+ // a fragment merges into the workspace's nav.yaml, so a nav.yaml that does not read refuses before npm
391
+ // writes; a call that ships no fragment never reads it
392
+ const navBad = shipsFragment(plan.list) ? navDocGuard(ws.root) : null;
393
+ if (navBad) { console.error(`✖ install refused: ${navBad} — dt check names what is wrong; fix it, then run this again`); return EXIT.failed; }
334
394
  const setupOpts = { inputFlags, allow, tty, noInput, io, processEnv, noCommit };
335
395
  if (!plan.list.length) {
336
396
  // everything is here — but an earlier run cut off anywhere after npm (a kill, a Ctrl-D at a prompt,
@@ -347,7 +407,13 @@ export async function installModules(ws, argv, { open, npm = resolveNpm(), verif
347
407
  fresh = await open(ws.root);
348
408
  if (stale) { const stdout = console.log; if (json) console.log = console.error; try { compile(fresh); } finally { console.log = stdout; } }
349
409
  } catch (e) { console.error(`✖ compile: ${e.message.split('\n')[0]}`); return EXIT.failed; }
350
- const out = await setupAndCommit(ws, fresh, names, { subject: `dreamteamer: install ${names.join(', ')}`, ...setupOpts });
410
+ let nav;
411
+ try { nav = planNavFragments(fresh, { names, ignoreSettings }); } catch (e) {
412
+ if (e instanceof NavFragmentRefusal || e instanceof NavDocError) { console.error(`✖ install refused: ${e.message}`); return EXIT.failed; }
413
+ throw e;
414
+ }
415
+ if (nav.skipped === 'settings') log(NAV_SETTINGS_LINE);
416
+ const out = await setupAndCommit(ws, fresh, names, { subject: `dreamteamer: install ${names.join(', ')}`, ...setupOpts, nav });
351
417
  const did = [stale ? 'the stale runtime was compiled' : null, out.committed ? `the pending changes were committed (${out.committed.join(', ')})` : null, out.results.length ? 'the setup ran' : null].filter(Boolean);
352
418
  if (json) { logOut(JSON.stringify({ workspace: { root: ws.root }, installed: [], already: names, committed: out.committed, units: out.results }, null, 2)); return out.code; }
353
419
  log(`✔ already installed: ${names.join(', ')} — ${did.join('; ') || 'nothing to do'}`);
@@ -358,9 +424,10 @@ export async function installModules(ws, argv, { open, npm = resolveNpm(), verif
358
424
  log(`▶ install: ${plan.list.map((e) => `${e.manifest.name}@${e.manifest.version}${e.kind === 'folder' ? ' (linked)' : ''}`).join(', ')}${plan.already.length ? ` — already here: ${plan.already.join(', ')}` : ''}`);
359
425
 
360
426
  // 2–4. npm, verify, compile (a refusal restores the pre-image)
361
- const step = await npmAndCompile(ws, plan.list, { npm, open, json, log, hooks, what: 'install' });
427
+ const step = await npmAndCompile(ws, plan.list, { npm, open, json, log, hooks, what: 'install', ignoreSettings });
362
428
  if (step.code !== undefined) return step.code;
363
429
  const fresh = step.fresh;
430
+ if (step.nav.skipped === 'settings') log(NAV_SETTINGS_LINE);
364
431
  if (verify) {
365
432
  const stdout = console.log;
366
433
  if (json) console.log = console.error;
@@ -370,7 +437,7 @@ export async function installModules(ws, argv, { open, npm = resolveNpm(), verif
370
437
  }
371
438
 
372
439
  // 5–6. the safe part of the new units' setup, one scoped commit
373
- const out = await setupAndCommit(ws, fresh, names, { subject: `dreamteamer: install ${names.join(', ')}`, ...setupOpts });
440
+ const out = await setupAndCommit(ws, fresh, names, { subject: `dreamteamer: install ${names.join(', ')}`, ...setupOpts, nav: step.nav });
374
441
  if (json) { logOut(JSON.stringify({ workspace: { root: ws.root }, installed: names, already: plan.already, committed: out.committed, units: out.results }, null, 2)); return out.code; }
375
442
  log(`✔ installed ${names.join(', ')} — compiled${out.committed ? `, committed (${out.committed.join(', ')})` : noCommit ? ', not committed (--no-commit)' : ', not committed (not a git repository)'}`);
376
443
  printUnitResults(out.results, out.ignored, log);