dreamteamer 0.40.0 → 0.42.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.
@@ -10,6 +10,7 @@
10
10
  //
11
11
  // A v1 source — a descriptor without `fields`, or a collection-template — is refused, all of them in
12
12
  // one message naming the converter. Nothing here reads the v1 shape.
13
+ import fs from 'node:fs';
13
14
  import path from 'node:path';
14
15
  import Ajv from 'ajv';
15
16
  import addFormats from 'ajv-formats';
@@ -18,7 +19,7 @@ import { resolveFields, toJsonSchema } from './fields.js';
18
19
  import { targetsOf } from './descriptor.js';
19
20
  import { defaultStoragePath, baseNameOf, singular, inflects, namespaceOf, storageOverlaps } from './namespace.js';
20
21
  import { subpathProblem } from './placement.js';
21
- import { patternRe } from './records.js';
22
+ import { patternRe, walk } from './records.js';
22
23
  import { renderTemplate } from './env-vars.js';
23
24
 
24
25
  import { CONVERTER } from './extensions.js';
@@ -65,7 +66,7 @@ const titleCase = (id) => String(id).split(/[_\-\s/]+/).filter(Boolean).map((w)
65
66
  * @param {Map<string,{root}>} ctx.dataOwners owns-data modules — every collection defaults to `storage.owner: module`
66
67
  * @param {Map<string,{name,root,channel}>} ctx.moduleSources every module source, for a descriptor that names `storage.owner: module`
67
68
  * @param {(source: object, rel: Function) => string|null} ctx.unownableBecause why a module's clone cannot hold records, or null
68
- * @param {{name,root,dataPath,records:string[]}[]} ctx.layers record layers — clones whose listed collections are read here
69
+ * @param {{name,root,dataPath,records:string[]|null}[]} ctx.layers record layers — clones whose data is read here; `records` narrows, null reads every collection both have
69
70
  * @param {(moduleRoot: string) => string} ctx.repoOf workspace-relative git repo of a module root
70
71
  * @param {(p: string) => string} ctx.rel
71
72
  * @param {string} ctx.dataPath
@@ -76,7 +77,7 @@ const titleCase = (id) => String(id).split(/[_\-\s/]+/).filter(Boolean).map((w)
76
77
  * @returns {{ compiled: Map<string, {doc, sources}>, inert: {path, hash}[], moduleColls: Map<string, Set<string>> }}
77
78
  */
78
79
  export function compileCollections(ctx) {
79
- const { groups, mixins, namespaces, nsOwners, runtimeKinds, core, moduleDeps, modulePeers, channelOf, wsModuleName, engineName, dataOwners, moduleSources, unownableBecause, layers = [], repoOf, dataPath, vars, moduleId, fail, warn } = ctx;
80
+ const { groups, mixins, namespaces, nsOwners, runtimeKinds, core, moduleDeps, modulePeers, channelOf, wsModuleName, engineName, dataOwners, moduleSources, unownableBecause, layers = [], repoOf, dataPath, vars, moduleId, fail, warn, root = vars?.workspaceFolder ?? '.' } = ctx;
80
81
 
81
82
  // ---- v1 is refused, every file at once --------------------------------------------------
82
83
  const v1 = [];
@@ -86,6 +87,7 @@ export function compileCollections(ctx) {
86
87
  const typeNames = new Set([...groups.keys(), ...core]);
87
88
  const allPeers = new Set([...modulePeers.values()].flat());
88
89
  const out = new Map();
90
+ const layerClaims = new Map(); // layer name -> clone folders some collection here accounts for
89
91
  const inert = [];
90
92
  const moduleColls = new Map();
91
93
  const owners = new Map(); // collection -> owning module name
@@ -202,10 +204,21 @@ export function compileCollections(ctx) {
202
204
  // ---- record layers: the listed clones' data folders, read BELOW the write root ----
203
205
  const collLayers = [];
204
206
  for (const l of layers) {
205
- if (!l.records.includes(name)) continue;
207
+ // where this collection's records would sit in the clone — claimed, so the unread-folder
208
+ // pass below never names a folder some collection here accounts for
209
+ const at = `${l.root}/${a.path && !pointed && !runtime ? a.path : defaultStoragePath(name, namespaces, l.dataPath)}`;
210
+ (layerClaims.get(l.name) ?? layerClaims.set(l.name, new Set()).get(l.name)).add(at);
211
+ if (l.records && !l.records.includes(name)) continue;
206
212
  const why = runtime ? 'is a compiled source' : owner === 'module' ? `is \`storage.owner: module\` — one shared list read from the module's clone, which a layer would duplicate` : a.under ? 'is stored under another collection (storage.under) — a placed collection is not layered' : pointed ? 'is env-pointed (its storage.path is a template) — its records are per machine, not a clone\'s' : null;
207
- if (why) fail(`git_modules.${l.name}.records names "${name}", which ${why}`);
208
- collLayers.push({ name: l.name, path: `${l.root}/${a.path ?? defaultStoragePath(name, namespaces, l.dataPath)}`, repo: l.root });
213
+ if (why && l.records) fail(`git_modules.${l.name}.records names "${name}", which ${why}`);
214
+ if (why) {
215
+ // an INHERENT layer reads every collection both have, so one that cannot layer is skipped —
216
+ // said only when the clone actually holds records there, so a quiet compile stays quiet
217
+ const n = fileCount(path.join(root, at));
218
+ if (n) warn(`ℹ layer ${l.name}: ${name} is not read from the layer — it ${why} (${n} file${n === 1 ? '' : 's'} in ${at}/ unread)`);
219
+ continue;
220
+ }
221
+ collLayers.push({ name: l.name, path: at, repo: l.root });
209
222
  }
210
223
 
211
224
  // an opaque record's fields are the ones derived from the file itself
@@ -216,7 +229,7 @@ export function compileCollections(ctx) {
216
229
  fields.ext ??= { type: 'string', virtual: true, description: "The file's extension, lowercase and without the dot. Read from the file." };
217
230
  fields.bytes ??= { type: 'integer', virtual: true, description: "The file's size in bytes. Read from the file." };
218
231
  }
219
- const { fields: resolved, errors, warnings, defaults: fieldDefaults } = resolveFields(fields, { name, collections: typeNames, peers: allPeers, runtime });
232
+ const { fields: resolved, errors, warnings, defaults: fieldDefaults } = resolveFields(fields, { name, collections: typeNames, peers: allPeers, runtime, unlayerable: owner === 'module' || !!a.under || !!pointed });
220
233
  if (errors.length) fail(`collection "${name}" (${where}):\n ${errors.join('\n ')}`);
221
234
  for (const w of warnings) warn(`⚠ collection ${name}: ${w}`);
222
235
  const constraints = authored.constraints ?? [];
@@ -322,7 +335,13 @@ export function compileCollections(ctx) {
322
335
 
323
336
  for (const p of storageOverlaps(storageEntries)) fail(p);
324
337
  for (const l of layers) {
325
- for (const c of l.records) if (!staged.has(c)) fail(`git_modules.${l.name}.records names "${c}", which is not a collection here (have: ${[...staged.keys()].sort().join(', ')})`);
338
+ for (const c of l.records ?? []) if (!staged.has(c)) fail(`git_modules.${l.name}.records names "${c}", which is not a collection here (have: ${[...staged.keys()].sort().join(', ')})`);
339
+ }
340
+ // A layer folder no collection here accounts for — the project's own domain collections, read by a
341
+ // workspace that does not install their module — is WARNED, never failed: reading a project without
342
+ // its domain module is legitimate, but its records silently not appearing is not.
343
+ for (const l of layers) for (const [folder, n] of unreadFolders(root, `${l.root}/${l.dataPath}`, layerClaims.get(l.name) ?? new Set())) {
344
+ warn(`⚠ layer ${l.name}: ${folder}/ holds ${n} file${n === 1 ? '' : 's'} and no collection here reads it — install the module that defines it to read them${l.records ? '' : ', or list the collections to read in git_modules.' + l.name + '.records'}`);
326
345
  }
327
346
  {
328
347
  const words = new Map();
@@ -408,3 +427,32 @@ function placement(out, fail) {
408
427
  c.compiled.under_collection = parentName;
409
428
  }
410
429
  }
430
+
431
+ /** How many files sit under a folder, recursively — 0 when it is absent. */
432
+ function fileCount(dir) {
433
+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) return 0;
434
+ let n = 0;
435
+ for (const _ of walk(dir)) n++;
436
+ return n;
437
+ }
438
+
439
+ /** `[folder, fileCount]` for each folder under a layer's data path that no claimed path accounts for:
440
+ * a claimed folder is skipped, one that is a PREFIX of a claimed path (a namespace folder) is
441
+ * descended into, anything else is unread. Paths are workspace-relative, `/`-joined. */
442
+ function unreadFolders(root, dataDir, claimed) {
443
+ const out = [];
444
+ const visit = (rel) => {
445
+ const abs = path.join(root, rel);
446
+ if (!fs.existsSync(abs)) return;
447
+ for (const e of fs.readdirSync(abs, { withFileTypes: true }).sort((x, y) => x.name.localeCompare(y.name))) {
448
+ if (!e.isDirectory() || e.name.startsWith('.')) continue;
449
+ const p = `${rel}/${e.name}`;
450
+ if (claimed.has(p)) continue;
451
+ if ([...claimed].some((c) => c.startsWith(`${p}/`))) { visit(p); continue; }
452
+ const n = fileCount(path.join(root, p));
453
+ if (n) out.push([p, n]);
454
+ }
455
+ };
456
+ visit(dataDir);
457
+ return out;
458
+ }
package/src/compile.js CHANGED
@@ -9,14 +9,14 @@ import { load, dump } from './yaml.js';
9
9
  import { slug } from './template.js';
10
10
  import { walk } from './records.js';
11
11
  import { placedRecords } from './placement.js';
12
- import { viewErrors, viewDisplay, bindingErrors } from './views.js';
12
+ import { viewErrors, viewDisplay, bindingErrors, overlayView } from './views.js';
13
13
  import {
14
14
  normalizeNamespaces, namespaceProblems, unqualifiedProblems, defaultStoragePath, storageOverlaps,
15
15
  baseNameOf, singular, namespaceOf } from './namespace.js';
16
16
  // circular on paper in earlier versions — safe: both sides only
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
- import { ensureEditorRecommendation, ensureEnvExample, ensureGitignored } from './workspace.js';
19
+ import { ensureEditorRecommendation, ensureEnvExample, ensureGitignored, layerEntries } from './workspace.js';
20
20
  import { satisfies } 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';
@@ -175,10 +175,11 @@ export function discoverModules(root, pkg) {
175
175
  // caller (compile, status, install) sees the same set.
176
176
  const disable = pkg?.dreamteamer?.disable ?? [];
177
177
  const disabledHits = new Set();
178
- // A clone whose manifest entry lists `records` is a RECORD LAYER — another workspace's data read
179
- // here — never a bundle: its own modules/ would otherwise unpack and collide with ours. With
180
- // `module: true` its ONE workspace module is a source too (below).
181
- const layerList = layerEntries(pkg);
178
+ // A clone that is a WORKSPACE (its own manifest names `workspace_module`), or whose entry lists
179
+ // `records`, is a RECORD LAYER — another workspace's data read here — never a bundle: its own
180
+ // modules/ would otherwise unpack and collide with ours. With `module: true` its ONE workspace
181
+ // module is a source too (below).
182
+ const layerList = layerEntries(pkg, root);
182
183
  const layers = new Set(layerList.map((l) => l.name));
183
184
  // the same rule the extension loader applies (full package name, or its scope-stripped id), so a
184
185
  // disabled package loses its content AND its code together
@@ -293,29 +294,14 @@ function dataOwningModules(sources, fail, rel) {
293
294
  const toPosix = (p) => p.split(path.sep).join('/');
294
295
 
295
296
  // ---- record layers ----------------------------------------------------------------
296
- // A `git_modules` entry carrying `records: [<collection>…]` is another WORKSPACE cloned here for its
297
- // records: each listed collection reads that clone's data folder as a root below this workspace's
298
- // own. The clone contributes no sources — its shapes are the modules both workspaces install.
299
-
300
- /** The declared layers, validated: `{ name, records, module }` per entry. `records` is a non-empty list
301
- * of collection names; which collections exist is compile-collections' question. `module: true` also
302
- * compiles the clone's workspace module (discoverModules), and is refused on an entry with no `records`. */
303
- export function layerEntries(pkg) {
304
- const out = [];
305
- for (const [name, entry] of Object.entries(pkg?.dreamteamer?.git_modules ?? {})) {
306
- if (entry?.module !== undefined && typeof entry.module !== 'boolean') throw new Error(`git_modules.${name}.module must be true or false (got ${JSON.stringify(entry.module)})`);
307
- if (entry?.module === true && entry.records === undefined) {
308
- throw new Error(`git_modules.${name}.module: true without \`records\` — an entry without records is already a bundle: every module under its modules/ compiles. Drop \`module\`, or list the collections it layers.`);
309
- }
310
- if (!entry || entry.records === undefined) continue;
311
- const r = entry.records;
312
- if (!Array.isArray(r) || !r.length || r.some((c) => typeof c !== 'string' || !c.trim())) {
313
- throw new Error(`git_modules.${name}.records must be a non-empty list of collection names (got ${JSON.stringify(r)})`);
314
- }
315
- out.push({ name, records: r, module: entry.module === true });
316
- }
317
- return out;
318
- }
297
+ // A `git_modules` clone that is itself a WORKSPACE (its manifest names `workspace_module`) — or an
298
+ // entry that lists `records:` — is a record layer: every collection both have reads that clone's data
299
+ // folder as a root below this workspace's own, `records:` narrowing the set when present. The clone
300
+ // contributes no sources — its shapes are the modules both workspaces install.
301
+
302
+ // `layerEntries` lives in workspace.js — compile, status and the extension loader all ask it, and the
303
+ // loader cannot import this file (compile imports the loader). Re-exported under its old address.
304
+ export { layerEntries };
319
305
 
320
306
  /** A layer's data folder, from the clone's own manifest (its `data_path`), default `data`. The clone
321
307
  * may be absent — a fresh checkout before `dreamteamer install` — and then the default stands. */
@@ -440,6 +426,8 @@ export function compile(ws) {
440
426
  const moduleDeps = new Map(); // module name -> [module names] — HARD, must be acyclic
441
427
  const modulePeers = new Map(); // module name -> [collection names] — SOFT, cannot cycle
442
428
  const moduleNamespaces = new Map(); // module name -> [namespaces it DECLARES] (§8, option A)
429
+ const moduleVersions = new Map(); // module name -> its package.json version
430
+ const moduleFloors = new Map(); // module name -> npm `peerDependencies` — a version floor on a sibling module
443
431
  const moduleLocalAssets = []; // {rel, owner, base} — validated with the workspace's own, below
444
432
  // the package.json `dreamteamer` block is a closed set of snake_case keys, the workspace's and
445
433
  // every module's alike — a key outside it is a typo or a spelling this engine does not read
@@ -481,6 +469,10 @@ export function compile(ws) {
481
469
  }
482
470
  moduleNamespaces.set(source.name, ns);
483
471
  }
472
+ if (source.root !== root) {
473
+ moduleVersions.set(source.name, mpkg.version);
474
+ if (mpkg.peerDependencies && typeof mpkg.peerDependencies === 'object') moduleFloors.set(source.name, mpkg.peerDependencies);
475
+ }
484
476
  const range = mpkg.dreamteamer?.engine;
485
477
  if (range && satisfies(engineVer, range) === null) console.warn(`⚠ module ${source.name}: engine range "${range}" not understood by the built-in checker (see src/semver.js) — not verified`);
486
478
  // `dreamteamer.env` (keys the module needs) and, in a module, `dreamteamer.vars` (the
@@ -608,6 +600,21 @@ export function compile(ws) {
608
600
  }
609
601
  }
610
602
  }
603
+ // npm's `peerDependencies` naming ANOTHER discovered module is a VERSION FLOOR: npm refuses the install
604
+ // below it, and this refuses the channels npm never saw — a git_modules clone, an inline copy, an
605
+ // install that went around the peer check. An absent sibling is `dependencies`' business, not this one's.
606
+ {
607
+ const byName = new Map(sources.map((s) => [s.name, s]));
608
+ const misses = [];
609
+ for (const [mod, floors] of moduleFloors) for (const [dep, range] of Object.entries(floors)) {
610
+ const sib = byName.get(dep), have = moduleVersions.get(dep);
611
+ if (!sib || dep === mod) continue;
612
+ const ok = satisfies(have, range);
613
+ 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`);
614
+ 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}`}`);
615
+ }
616
+ if (misses.length) fail(misses.join('\n'));
617
+ }
611
618
  // DFS with an explicit path so the error can print the ring rather than just naming one module
612
619
  {
613
620
  const state = new Map(); // name -> 'open' | 'done'
@@ -626,14 +633,23 @@ export function compile(ws) {
626
633
 
627
634
  const dataOwners = dataOwningModules(sources, fail, rel);
628
635
  let layers;
629
- try { layers = layerEntries(pkg).map((l) => ({ ...l, root: path.posix.join('git_modules', l.name), dataPath: layerDataPath(root, l.name) })); }
636
+ try { layers = layerEntries(pkg, root).map((l) => ({ ...l, root: path.posix.join('git_modules', l.name), dataPath: layerDataPath(root, l.name) })); }
630
637
  catch (e) { fail(e.message); }
638
+ for (const l of layers) if (!fs.existsSync(path.join(root, l.root))) console.warn(`⚠ layer ${l.name} (${l.root}) is not installed — its records are not read; run dreamteamer install`);
631
639
 
632
640
  const disabled = new Set(config.disable ?? []);
633
641
  const disabledHits = new Set(disabledModules); // bare entries were applied at discovery
634
642
 
635
643
  /** entries: runtime-relative path -> { sources: [workspace-relative], bytes } */
636
644
  const entries = new Map();
645
+ /** ui-view sources carrying `overlay: true` — merged onto their base after discovery */
646
+ const viewOverlays = [];
647
+ const isViewOverlay = (srcPath) => {
648
+ const text = fs.readFileSync(srcPath, 'utf8');
649
+ // the regex is only a cheap pre-filter, so it must not be stricter than YAML: a trailing comment
650
+ // or space on the flag line still carries the flag (the parsed value is what decides)
651
+ return /^overlay:\s*true\b/m.test(text) && loadSource(text, rel(srcPath))?.overlay === true;
652
+ };
637
653
  const counts = {};
638
654
  /** collection descriptors collected per name, a base and its overlays: name -> [{src, doc, moduleName}] */
639
655
  const descriptorGroups = new Map();
@@ -731,6 +747,13 @@ export function compile(ws) {
731
747
  counts[kind]++;
732
748
  } else if (!isDir) {
733
749
  refuseEmptySource(srcPath);
750
+ // a view OVERLAY is merged onto the view it names once every source is in (below), so
751
+ // discovery order between the two modules never decides which is the base
752
+ if (kind === 'ui-views' && isViewOverlay(srcPath)) {
753
+ viewOverlays.push({ runtimePath: toPosix(path.join(kind, name)), srcPath, moduleName: source.name });
754
+ contributedBy.add(source.name);
755
+ continue;
756
+ }
734
757
  addEntry(path.join(kind, name), srcPath);
735
758
  contributedBy.add(source.name);
736
759
  counts[kind]++;
@@ -747,6 +770,26 @@ export function compile(ws) {
747
770
  }
748
771
  }
749
772
 
773
+ // ---- ui-view overlays: a same-id view carrying `overlay: true` MERGES onto the shipped one --------
774
+ // The way a collection overlay refines a descriptor it does not own, so a workspace changes a
775
+ // package's view in the few lines that differ instead of copying it (and losing every later fix
776
+ // the package ships). DEEP, overlay wins at the leaves, a list is replaced whole, and `null`
777
+ // REMOVES the key — the one spelling an overlay has for "the package sets this; I do not". A
778
+ // view without the flag and the same id is still the collision `addEntry` names.
779
+ const ownerOf = (file) => sources.map((s) => ({ s, at: rel(s.root) })).filter(({ at }) => !at || file.startsWith(`${at}/`)).sort((a, b) => b.at.length - a.at.length)[0]?.s;
780
+ for (const o of viewOverlays) {
781
+ const e = entries.get(o.runtimePath);
782
+ const id = path.posix.basename(o.runtimePath).replace(/\.ui-view\.yaml$/, '');
783
+ if (!e) fail(`${rel(o.srcPath)}: an overlay of ui-view "${id}" (overlay: true), but no module ships a view "${id}" — drop \`overlay: true\` to make it a view of its own, or install the module that ships it.`);
784
+ const bytes = fs.readFileSync(o.srcPath);
785
+ const { overlay: _flag, ...ov } = loadSource(bytes.toString('utf8'), rel(o.srcPath)) ?? {};
786
+ const merged = overlayView(loadSource(e.bytes.toString('utf8'), e.sources[0].path) ?? {}, ov);
787
+ e.bytes = Buffer.from(dump(merged));
788
+ e.sources.push({ path: rel(o.srcPath), hash: sha256(bytes) });
789
+ e.module ??= moduleId(ownerOf(e.sources[0].path)?.name ?? '');
790
+ (e.overlaidBy ??= []).push(moduleId(o.moduleName));
791
+ }
792
+
750
793
  // ---- stage module UI bundles ---------------------------------------------------
751
794
  // modules ship a PRE-BUILT app.js that registers components/layouts against the surface's
752
795
  // registry (design "the UI": components are module code, never records). staged under
@@ -897,7 +940,7 @@ export function compile(ws) {
897
940
  runtimeKinds: new Set([...kinds, ...DERIVED_KINDS]), core: CORE_COLLECTIONS,
898
941
  moduleDeps, modulePeers, channelOf, wsModuleName, engineName, dataOwners,
899
942
  moduleSources: new Map(sources.map((s) => [s.name, s])), unownableBecause, layers,
900
- repoOf: (moduleRoot) => repoRootOf(moduleRoot, root), rel, dataPath: config.data_path ?? 'data', vars: storageVars,
943
+ repoOf: (moduleRoot) => repoRootOf(moduleRoot, root), rel, root, dataPath: config.data_path ?? 'data', vars: storageVars,
901
944
  moduleId, fail: collectionsFail, warn: (m) => console.warn(m),
902
945
  });
903
946
  refusePlacementTransitions(root, compiledColls);
@@ -1055,7 +1098,8 @@ export function compile(ws) {
1055
1098
  if (errors.length) fail(errors.join('\n '));
1056
1099
  for (const w of warnings) console.warn(`⚠ ${w}`);
1057
1100
  const text = e.bytes.toString('utf8');
1058
- e.bytes = Buffer.from(`${text}${text.endsWith('\n') ? '' : '\n'}${dump({ compiled: { display: viewDisplay(d ? displayOf(d) : {}, view) } })}`);
1101
+ const provenance = e.overlaidBy ? { module: e.module, overlaid_by: e.overlaidBy } : {};
1102
+ e.bytes = Buffer.from(`${text}${text.endsWith('\n') ? '' : '\n'}${dump({ compiled: { display: viewDisplay(d ? displayOf(d) : {}, view), ...provenance } })}`);
1059
1103
  }
1060
1104
  // a command's id is its path under commands/, folders included: `commands/rnd/design.command.md` is
1061
1105
  // `rnd/design`, typed as `/rnd:design` — the folder is the namespace, as claude-code already reads it
package/src/events.js CHANGED
@@ -134,3 +134,68 @@ export function eventCommit(root, fromSha, toSha, relPath) {
134
134
  .toString().trim();
135
135
  return out || toSha;
136
136
  }
137
+
138
+ // ── the record-change report (0.42.0) ────────────────────────────────────────────────────────────
139
+ // What `dt changes` and `dt commit` print, and what a session appends to its reply after a write.
140
+ // A change is `{ collection, id, ref, path, repo, layer, change }` with `change` one of the three
141
+ // words the report uses; `deriveEvents`' `item-*` types are the same three facts, older spelling.
142
+ export const CHANGE_OF = { 'item-added': 'created', 'item-updated': 'updated', 'item-removed': 'deleted' };
143
+ export const TYPE_OF = { created: 'item-added', updated: 'item-updated', deleted: 'item-removed' };
144
+
145
+ /** `before` (the committed half, oldest first) folded with `after` (the pending half) — one entry per
146
+ * record per repo, `committed` true when no pending part is left. Inside one half a ref can appear
147
+ * twice only as a MOVE (a relocate, a placed record re-parented: deleted at one path, created at
148
+ * another), which is one update at the live path. Across the halves the net change wins: created
149
+ * then deleted never existed at either end and is dropped; created then edited is still created;
150
+ * deleted then re-created is an update. The SAME ref in two repos is two records — a layer's copy
151
+ * is not the workspace's. */
152
+ export function foldChanges(before, after) {
153
+ const key = (c) => `${c.repo}\0${c.ref}`;
154
+ const half = (list) => {
155
+ const m = new Map();
156
+ for (const c of list) {
157
+ const had = m.get(key(c));
158
+ m.set(key(c), had ? { ...(c.change === 'deleted' ? had : c), change: 'updated' } : c);
159
+ }
160
+ return m;
161
+ };
162
+ const out = new Map();
163
+ for (const [k, c] of half(before)) out.set(k, { ...c, committed: true });
164
+ for (const [k, c] of half(after)) {
165
+ const was = out.get(k)?.change;
166
+ const change = !was ? c.change
167
+ : was === 'created' ? (c.change === 'deleted' ? null : 'created')
168
+ : was === 'deleted' && c.change === 'created' ? 'updated' : c.change;
169
+ if (change) out.set(k, { ...c, change, committed: false });
170
+ else out.delete(k);
171
+ }
172
+ const order = (c) => [c.collection, c.layer ?? '', c.id];
173
+ return [...out.values()].sort((a, b) => {
174
+ const [x, y] = [order(a), order(b)];
175
+ for (let i = 0; i < x.length; i++) if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
176
+ return 0;
177
+ });
178
+ }
179
+
180
+ /** One group per collection AND layer, in the order `foldChanges` sorted them: a collection changed
181
+ * both here and in a layer is two entries, so the line never hides which repo a write landed in. */
182
+ export function groupChanges(changes) {
183
+ const groups = new Map();
184
+ for (const c of changes) {
185
+ const k = `${c.collection}\0${c.layer ?? ''}`;
186
+ if (!groups.has(k)) groups.set(k, { collection: c.collection, layer: c.layer ?? null, created: 0, updated: 0, deleted: 0, records: [] });
187
+ const g = groups.get(k);
188
+ g[c.change]++;
189
+ g.records.push(c);
190
+ }
191
+ return [...groups.values()];
192
+ }
193
+
194
+ /** `records — contacts: 1 created, 2 updated · issues (project-a): 1 created` — the report's first
195
+ * line, the one the skill tells a session to end its reply with. Empty when nothing changed: the
196
+ * rule is that nothing written appends nothing. */
197
+ export function reportLine(groups) {
198
+ if (!groups.length) return '';
199
+ const counts = (g) => ['created', 'updated', 'deleted'].filter((w) => g[w]).map((w) => `${g[w]} ${w}`).join(', ');
200
+ return `records — ${groups.map((g) => `${g.collection}${g.layer ? ` (${g.layer})` : ''}: ${counts(g)}`).join(' · ')}`;
201
+ }
package/src/extensions.js CHANGED
@@ -21,6 +21,7 @@
21
21
  // hooks { <ClaudeHookEvent>: '<dt verb args>' } rendered by `dt install --print-adapters`
22
22
  // check ({ root, ws, dt }) → [{ file, message }] cross-record rules `dt check` reports after the schema's
23
23
  // doctor ({ root, ws, dt }) → [{ label, state, detail?, fix? }] rows `dt doctor` renders as one capability
24
+ // next ({ root, ws, collection, ids }) → [{ id, text }] a line about a record `dt next` prints (sync)
24
25
  //
25
26
  // Two contributions claiming the same verb, kind or harness is a refusal — there is no "last one
26
27
  // wins", because the loser would be an extension the operator installed that silently does nothing.
@@ -29,6 +30,7 @@ import path from 'node:path';
29
30
  import { pathToFileURL } from 'node:url';
30
31
  import { satisfies } from './semver.js';
31
32
  import { engineVersion } from './runtime.js';
33
+ import { layerEntries } from './workspace.js';
32
34
 
33
35
  /** The keys a package.json `dreamteamer` block may carry — the workspace's and a module's alike. */
34
36
  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'];
@@ -51,7 +53,7 @@ export function v1ManifestRefusal(block, where) {
51
53
 
52
54
  export const EXTENSION_API = 1;
53
55
 
54
- const CONTRIBUTION_KEYS = new Set(['commands', 'sourceKinds', 'analyze', 'harnesses', 'orientation', 'hooks', 'check', 'doctor']);
56
+ const CONTRIBUTION_KEYS = new Set(['commands', 'sourceKinds', 'analyze', 'harnesses', 'orientation', 'hooks', 'check', 'doctor', 'next']);
55
57
 
56
58
  /** The modules that declare an extension entry: the workspace's own `modules/<id>/` first, then each
57
59
  * clone under `git_modules/` (the clone's root, then the modules it bundles under `modules/`), then its
@@ -80,7 +82,7 @@ export function declaredExtensions(ws) {
80
82
  try { inline = fs.readdirSync(path.join(ws.root, 'modules')).sort(); } catch { /* no modules/ */ }
81
83
  for (const id of inline) consider(path.join(ws.root, 'modules', id), id);
82
84
  const listed = (dir) => { try { return fs.readdirSync(dir).sort(); } catch { return []; } };
83
- const layers = new Set(Object.entries(ws.pkg?.dreamteamer?.git_modules ?? {}).filter(([, e]) => e?.records !== undefined).map(([n]) => n));
85
+ const layers = new Set(layerEntries(ws.pkg, ws.root).map((l) => l.name));
84
86
  for (const clone of listed(path.join(ws.root, 'git_modules'))) {
85
87
  if (layers.has(clone)) continue; // a record layer: another workspace's data, never its code
86
88
  const root = path.join(ws.root, 'git_modules', clone);
@@ -150,12 +152,32 @@ export async function loadExtensions(ws, api, reserved = {}) {
150
152
  const sourceKinds = (c.sourceKinds ?? []).map((k) => normalizeKind(ext.name, k));
151
153
  for (const k of sourceKinds) claim('kind', k.kind, ext.name);
152
154
  for (const id of Object.keys(c.harnesses ?? {})) claim('harness', id, ext.name);
153
- for (const fn of ['analyze', 'check', 'doctor']) if (c[fn] !== undefined && typeof c[fn] !== 'function') throw new Error(`extension ${ext.name}: ${fn} must be a function`);
154
- 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 });
155
+ 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`);
156
+ 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 });
155
157
  }
156
158
  return loaded;
157
159
  }
158
160
 
161
+ /**
162
+ * What every extension's `next` says about the records `ids` of `collection` — the lines `dt next`
163
+ * prints under the bound commands, and the editor draws on a row and a page. SYNCHRONOUS, like the
164
+ * store it reads: `dt next` is a sync verb. A line about an id that was not asked about, or one with no
165
+ * text, is dropped; a throw is ONE line attributed to the extension (`error: true`), never a failed
166
+ * `dt next` — what a record can do next does not depend on an optional tool being healthy.
167
+ */
168
+ export function contributedNotes(ws, collection, ids = []) {
169
+ const out = [];
170
+ const asked = new Set(ids);
171
+ for (const e of (ws.extensions ?? []).filter((x) => x.next)) {
172
+ try {
173
+ for (const n of e.next({ root: ws.root, ws, collection, ids: [...ids] }) ?? []) {
174
+ if (asked.has(n?.id) && typeof n.text === 'string' && n.text.trim()) out.push({ id: n.id, text: n.text.trim(), by: e.name });
175
+ }
176
+ } catch (err) { out.push({ id: null, text: `next failed — ${String(err?.message ?? err).split('\n')[0]}`, by: e.name, error: true }); }
177
+ }
178
+ return out;
179
+ }
180
+
159
181
  /** A contributed source kind: a plain folder name, and excluded subtrees that stay RELATIVE to it. */
160
182
  function normalizeKind(by, k) {
161
183
  const kind = typeof k === 'string' ? k : k?.kind;
package/src/fields.js CHANGED
@@ -28,11 +28,14 @@ export const DISPLAY_KEYS = new Set(['editable', 'hidden', 'form_section', 'plac
28
28
  /** JSON Schema keywords copied onto the emitted property unchanged. */
29
29
  const PASS_THROUGH = ['default', 'examples', 'pattern', 'minimum', 'maximum', 'minItems', 'maxItems', 'minLength', 'maxLength', 'const'];
30
30
 
31
- /** The three fields every collection has. `created` is stored (engine-written); the other two are computed on read. */
31
+ /** The fields every collection has. `created` is stored (engine-written); `id` and `last_modified` are
32
+ * computed on read; `stub` is stored and written by hand — the engine only READS it, to decide which
33
+ * of several roots answers an id (records.js `resolveClaims`). */
32
34
  export const INJECTED_FIELDS = {
33
35
  id: { type: 'string', title: 'Id', virtual: true, description: 'The record\'s path inside its collection.' },
34
36
  created: { type: 'datetime', title: 'Created', derived: true, description: 'When the record was first written. Stamped by the engine at add; read from the id\'s date or the first commit for a record written before it existed.' },
35
37
  last_modified: { type: 'datetime', title: 'Last modified', virtual: true, description: 'When the record was last committed, from git.' },
38
+ stub: { type: 'boolean', title: 'Stub', display: { hidden: ['list', 'form'] }, description: 'A placeholder: it yields to a real record of the same id in any other root (a record layer, or the workspace reading this one), and answers only where none exists.' },
36
39
  };
37
40
 
38
41
  /** Is `type` a reference to one or more collections, given the names that exist? */
@@ -58,9 +61,12 @@ export function resolveFields(authored, ctx) {
58
61
  const defaults = {};
59
62
  const known = new Set(Object.keys(authored ?? {}));
60
63
  const fields = {};
61
- // `created` is STAMPED by the store, which a kind whose records compile writes never goes through
64
+ // `created` is STAMPED by the store, which a kind whose records compile writes never goes through;
65
+ // `stub` exists only where a record can yield — a collection that can never be a layer root (a
66
+ // compiled source, module-owned, placed, env-pointed: ctx.unlayerable) has nothing to yield to
62
67
  for (const [k, v] of Object.entries(INJECTED_FIELDS)) {
63
68
  if (k === 'created' && ctx.runtime) continue;
69
+ if (k === 'stub' && (ctx.runtime || ctx.unlayerable)) continue;
64
70
  if (known.has(k)) errors.push(`field "${k}" is injected by the engine and cannot be authored`);
65
71
  fields[k] = { ...v };
66
72
  }
package/src/harnesses.js CHANGED
@@ -511,6 +511,9 @@ function orientationBlock(flavor, skillsIndex, sourceLayout = 'flat', namespaces
511
511
  'files; ids are paths; references are `<collection>/<id>`. run `dreamteamer check` (`npm run',
512
512
  'check`) after bulk edits; run `dreamteamer compile` (`npm run compile`) after changing any',
513
513
  'source or installing modules.',
514
+ // the record report (0.42.0): the RULE is here because this block is in every turn and the reply
515
+ // that owes it may be forty turns past the skill's loading; the FORMAT lives in the skill only
516
+ 'a reply that wrote records ends with the record report `dt changes` prints — the format is in the skill.',
514
517
  ];
515
518
  // an installed extension's own paragraph — how an optional tool tells every session it exists
516
519
  for (const p of extra.paragraphs) lines.push(p.trim());
package/src/records.js CHANGED
@@ -29,6 +29,31 @@ export function parseRecordText(text, d, bodyField) {
29
29
  return fields;
30
30
  }
31
31
 
32
+ // ---- stubs: a record that yields its id (0.41.0) --------------------------------------
33
+ // A record carrying `stub: true` is a placeholder — a thin copy a workspace keeps so its own references
34
+ // resolve standalone — and it YIELDS to any non-stub of the same id in any other root. The store and
35
+ // `check` both decide which file answers an id through `resolveClaims`, so they cannot disagree.
36
+
37
+ /** Does a record file carry `stub: true`? Read only for an id more than one root claims — never for the
38
+ * whole index. A file record (`format: binary`) has no fields and is never a stub; one that will not
39
+ * parse is not a stub either, and `check` reports the parse error on its own. */
40
+ export function isStubRecord(file, d) {
41
+ if (storageOf(d).format === 'binary') return false;
42
+ try { return parseRecordText(fs.readFileSync(file, 'utf8'), d).stub === true; } catch { return false; }
43
+ }
44
+
45
+ /** Which of an id's claimants answers, in root order. One non-stub wins wherever it sits and every stub
46
+ * is `shadowed`; two or more non-stubs are `conflicts` (the first answers, exactly as before stubs
47
+ * existed); stubs only — the first root answers and the rest are shadowed. A stub only ever weakens
48
+ * its own claim, so nothing a layer writes can displace a non-stub. */
49
+ export function resolveClaims(claims, isStub) {
50
+ if (claims.length < 2) return { winner: claims[0], conflicts: [], shadowed: [] };
51
+ const stub = claims.map(isStub);
52
+ const real = claims.filter((_, i) => !stub[i]);
53
+ if (!real.length) return { winner: claims[0], conflicts: [], shadowed: claims.slice(1) };
54
+ return { winner: real[0], conflicts: real.length > 1 ? real : [], shadowed: claims.filter((_, i) => stub[i]) };
55
+ }
56
+
32
57
  // id patterns may use unicode property escapes — compile with the u flag
33
58
  export function patternRe(pattern) {
34
59
  try { return new RegExp(pattern, 'u'); } catch { return new RegExp(pattern); }