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.
package/src/schema-ops.js CHANGED
@@ -11,11 +11,11 @@ import { load, dump, writeSource, renameKeys, commentCount, formatSource } from
11
11
  import { compile, kindDir, KINDS, repoRootOf, discoverModules } from './compile.js';
12
12
  import { V2_KEYS, isV2 } from './descriptor-v2.js';
13
13
  import { v1Refusal } from './compile-collections.js';
14
- import { readManifest, loadDescriptors } from './runtime.js';
14
+ import { readManifest, loadDescriptors, engineId } from './runtime.js';
15
15
  import { normalizeNamespaces, namespaceOf, baseNameOf, qualify, defaultStoragePath, singular } from './namespace.js';
16
16
  import { fieldsOf, targetsOf, storageOf, isRuntime, bodyFieldOf, moduleOf } from './descriptor.js';
17
- import { SCALAR_TYPES, enumValues } from './fields.js';
18
- import { FIELD_OPTIONS, TEMPLATE_OPTIONS } from './views.js';
17
+ import { SCALAR_TYPES, enumValues, INJECTED_FIELDS } from './fields.js';
18
+ import { FIELD_OPTIONS, TEMPLATE_OPTIONS, viewOverlayOf } from './views.js';
19
19
 
20
20
  // Same rule as store.js: a git failure we CATCH must not also print git's own error on top of the
21
21
  // clean message we throw. stdout stays piped because some callers read it.
@@ -849,7 +849,12 @@ export function setCollectionScalars(ws, store, name, changes, { moduleId } = {}
849
849
  // silently win over the owner's choice.
850
850
  const owned = baseDescriptorSource(ws, name).base;
851
851
  if (owned && IN_NODE_MODULES(owned)) {
852
- throw new Error(`"${name}" ships from node_modules (${owned}) — a write there is erased by the next \`npm install\`, and a collection-level key belongs to the module that owns it. Add "collections/${name}" to dreamteamer.disable and declare your own instead.`);
852
+ // How the collection is DRAWN is the one collection-level thing a workspace may change about a
853
+ // package's collection — compile already merges an overlay's `display` per sub-block — so a
854
+ // display write becomes that overlay. Every other key belongs to the module that owns it.
855
+ const notDisplay = Object.keys(changes).filter((k) => !k.startsWith('display.'));
856
+ if (!notDisplay.length) return setCollectionDisplayOverlay(ws, store, name, changes, owned);
857
+ throw new Error(`"${name}" ships from node_modules (${owned}) — a write there is erased by the next \`npm install\`, and a collection-level key (${notDisplay.join(', ')}) belongs to the module that owns it. Its display.* keys can be changed from here (they are written as an overlay in the workspace module); for the rest, add "collections/${name}" to dreamteamer.disable and declare your own instead.`);
853
858
  }
854
859
  const { file } = collectionSourceFile(ws, store, name, moduleId, { subject: name });
855
860
  if (!fs.existsSync(file)) throw new Error(`${path.relative(ws.root, file)} is not on disk — run \`dreamteamer compile\` and re-run.`);
@@ -868,6 +873,64 @@ export function setCollectionScalars(ws, store, name, changes, { moduleId } = {}
868
873
  return { name, file, changed, commits: gate.commits, unchanged: gate.unchanged };
869
874
  }
870
875
 
876
+ /**
877
+ * A package collection's DISPLAY, changed from the workspace: the `display.*` keys that differ from the
878
+ * package's own source, written into the workspace module's overlay of it (created, updated, or removed
879
+ * when nothing differs any more). A cleared key falls back to the package's value — an overlay can
880
+ * refine a block and cannot delete from it. `options` is written WHOLE when any option differs:
881
+ * compile merges `display.<block>` one key deep, so a lone option would drop every option the package
882
+ * sets beside it.
883
+ */
884
+ function setCollectionDisplayOverlay(ws, store, name, changes, owned) {
885
+ const { file } = collectionSourceFile(ws, store, name, undefined, { subject: name });
886
+ const base = load(fs.readFileSync(path.join(ws.root, owned), 'utf8')) ?? {};
887
+ const existed = fs.existsSync(file);
888
+ const previousText = existed ? fs.readFileSync(file, 'utf8') : null;
889
+ // `fields: {}` is what makes a source v2 at all (`isV2`), the same scaffold add-field writes
890
+ const doc = existed ? load(previousText) : { name, overlay: true, fields: {} };
891
+ const at = (o, dotted) => dotted.split('.').reduce((n, k) => (n && typeof n === 'object' ? n[k] : undefined), o);
892
+ const same = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
893
+ const changed = [];
894
+ for (const [k, raw] of Object.entries(changes)) {
895
+ const clear = raw === '' || raw === null;
896
+ const opt = /^(display\.[^.]+\.options)\.(.+)$/.exec(k);
897
+ if (opt) {
898
+ const options = structuredClone(at(doc, opt[1]) ?? at(base, opt[1]) ?? {});
899
+ if (clear) delete options[opt[2]];
900
+ else options[opt[2]] = settableOf(k)(raw);
901
+ if (same(options, at(base, opt[1]))) deletePath(doc, opt[1]);
902
+ else setPath(doc, opt[1], options);
903
+ } else {
904
+ const value = clear ? undefined : settableOf(k)(raw);
905
+ if (clear || same(value, at(base, k))) deletePath(doc, k);
906
+ else setPath(doc, k, value);
907
+ }
908
+ changed.push(k);
909
+ }
910
+ const empty = Object.keys(doc).every((k) => ['name', 'overlay'].includes(k) || (k === 'fields' && !Object.keys(doc.fields ?? {}).length));
911
+ if (empty && !existed) return { name, file, changed, overlay: true, unchanged: true };
912
+ // compile refuses an overlay whose module neither depends on the base's module nor lists the
913
+ // collection in `peer_collections`. The PEER declaration is the one that fits a display overlay —
914
+ // it applies while the package is installed and is inert once it is not — so it is written for the
915
+ // person in the same gated write, rather than handed back as compile's remedy to type.
916
+ const wmPkg = path.join(ws.pkg.dreamteamer?.workspace_module ? path.join(ws.root, 'modules', ws.pkg.dreamteamer.workspace_module) : ws.root, 'package.json');
917
+ const owner = moduleRows(store).filter((r) => owned.startsWith(`${r.fields.path}/`)).sort((a, b) => b.fields.path.length - a.fields.path.length)[0];
918
+ const declared = (JSON.parse(fs.readFileSync(wmPkg, 'utf8')).dreamteamer ?? {});
919
+ const ownerPkg = owner ? packageNameOf(store, owner.id) : null;
920
+ // the engine's own collections are every module's to overlay (compile asks nothing of those)
921
+ const needsPeer = !empty && ownerPkg !== engineId().replace(/@[^@]*$/, '') && !(declared.peer_collections ?? []).includes(name)
922
+ && !(ownerPkg && (declared.dependencies ?? []).includes(ownerPkg));
923
+ const gate = writeGated(ws, store, needsPeer ? [file, wmPkg] : [file], `dreamteamer: collections set ${name} ${Object.keys(changes).join(' ')} (overlay)`, () => {
924
+ if (empty) return fs.rmSync(file);
925
+ fs.mkdirSync(path.dirname(file), { recursive: true });
926
+ fs.writeFileSync(file, writeSource(previousText, doc));
927
+ if (needsPeer) editModulePkg(wmPkg, (dt) => { dt.peer_collections = [...(dt.peer_collections ?? []), name]; });
928
+ }, undefined, { commentsMayDecrease: true });
929
+ // the declaration is a write to the module's manifest, so the result names it for every surface to say
930
+ const peer = needsPeer ? { collection: name, module: ws.pkg.dreamteamer?.workspace_module ?? ws.pkg.name } : undefined;
931
+ return { name, file, changed, overlay: true, removed: empty || undefined, peer, commits: gate.commits, unchanged: gate.unchanged };
932
+ }
933
+
871
934
  // ---- the positions that name a field, and a value ----------------------------------------------
872
935
  // A field is referenced BY NAME, not as a `<collection>/<id>` reference, so `store.rewriteRefs` can
873
936
  // see none of it. Rule 6 is the list of every position a descriptor, a view or a binding may name a
@@ -2145,8 +2208,8 @@ function pruneEmpty(dir, stopAt) {
2145
2208
  /** The order a field's keys are written in (§3.4.1): facts about the data, `display`, then what it means. */
2146
2209
  const FIELD_KEY_ORDER = ['type', 'title', 'required', 'many', 'default', 'enum', 'unique', 'mirror_of', 'on_delete', 'soft', 'sensitive', 'body', 'derived', 'virtual', 'deprecated', 'passthrough', 'fields', 'values', 'item_title', 'examples', 'pattern', 'minimum', 'maximum', 'minItems', 'maxItems', 'minLength', 'maxLength', 'const', 'display', 'description'];
2147
2210
 
2148
- /** The three fields compile injects into every collection — no source declares one. */
2149
- const INJECTED = new Set(['id', 'created', 'last_modified']);
2211
+ /** The fields compile injects into every collection — no source declares one. */
2212
+ const INJECTED = new Set(Object.keys(INJECTED_FIELDS));
2150
2213
 
2151
2214
  /** `--type`: a built-in type, a collection, `a,b` for a union of collections, or `reference`. A
2152
2215
  * collection may not be named after a built-in type (compile refuses it), so the two never collide. */
@@ -2549,14 +2612,21 @@ export function saveUiView(ws, store, { id, view, moduleId }) {
2549
2612
  // would later object to. An explicit target module resolves the destination; without one the
2550
2613
  // manifest answers (an existing view is edited where it lives), and the workspace module is the
2551
2614
  // fallback for a new one.
2552
- const { file: dest, shipped } = moduleId
2553
- ? { file: path.join(kindDir(path.join(ws.root, moduleRecord(store, moduleId).fields.path), 'ui-views'), `${id}.ui-view.yaml`), shipped: null }
2615
+ const target = moduleId ? moduleRecord(store, moduleId) : null;
2616
+ if (target && IN_NODE_MODULES(target.fields.path)) {
2617
+ throw new Error(`module "${moduleId}" ships from node_modules (${target.fields.path}) — a write there is erased by the next npm install.\n pick a module whose sources are in this workspace (the workspace module is the default).`);
2618
+ }
2619
+ const { file: dest, shipped } = target
2620
+ ? { file: path.join(kindDir(path.join(ws.root, target.fields.path), 'ui-views'), `${id}.ui-view.yaml`), shipped: null }
2554
2621
  : uiViewSourceFile(ws, id);
2555
- if (shipped && /(^|\/)node_modules\//.test(shipped))
2556
- throw new Error(`ui-view "${id}" is shipped by an installed package (${shipped}) — a write there is erased by the next npm install.\n save it under a different name, or disable it (dreamteamer.disable) and re-create it.`);
2557
- const existed = fs.existsSync(dest);
2558
2622
  // `compiled` is compile's: a view read back from the runtime carries it, and a source never does
2559
- view = Object.fromEntries(Object.entries(view).filter(([k]) => k !== 'compiled'));
2623
+ view = Object.fromEntries(Object.entries(view).filter(([k]) => k !== 'compiled' && k !== 'overlay'));
2624
+ // A view an installed package ships is never written where npm would erase it, and never refused
2625
+ // either: the save becomes an OVERLAY in the workspace module carrying only what differs from the
2626
+ // package's source, which compile merges onto it (`overlay: true`, compile.js). A changed column
2627
+ // list is a few lines, and every later fix the package ships still reaches the rest of the view.
2628
+ if (shipped && IN_NODE_MODULES(shipped)) return saveUiViewOverlay(ws, store, id, view, shipped);
2629
+ const existed = fs.existsSync(dest);
2560
2630
  // A module source is where this project writes down WHY a view exists; `dump` cannot keep that.
2561
2631
  const previous = existed ? fs.readFileSync(dest, 'utf8') : null;
2562
2632
  // ⚠ opted OUT of the comment invariant, on the same rule `rm-field` is: this write REPLACES
@@ -2570,6 +2640,66 @@ export function saveUiView(ws, store, { id, view, moduleId }) {
2570
2640
  return { id, file: dest, updated: existed, commits: gate.commits, unchanged: gate.unchanged };
2571
2641
  }
2572
2642
 
2643
+ /** The save of a package's view: the workspace module's overlay, rewritten from the package source
2644
+ * each time (never stacked on the previous overlay), and removed when the view equals the package's. */
2645
+ function saveUiViewOverlay(ws, store, id, view, shipped) {
2646
+ const dest = path.join(workspaceSystemDir(ws, 'ui-views'), `${id}.ui-view.yaml`);
2647
+ const existed = fs.existsSync(dest);
2648
+ const delta = viewOverlayOf(load(fs.readFileSync(path.join(ws.root, shipped), 'utf8')) ?? {}, view);
2649
+ const out = { id, file: dest, overlay: true, overlays: shipped };
2650
+ if (!Object.keys(delta).length && !existed) return { ...out, updated: false, unchanged: true };
2651
+ const previous = existed ? fs.readFileSync(dest, 'utf8') : null;
2652
+ const gate = writeGated(ws, store, [dest], `dreamteamer: ui-views overlay ${id}`, () => {
2653
+ if (!Object.keys(delta).length) return fs.rmSync(dest);
2654
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
2655
+ fs.writeFileSync(dest, writeSource(previous, { overlay: true, ...delta }));
2656
+ }, undefined, { commentsMayDecrease: true });
2657
+ return { ...out, updated: existed, removed: !Object.keys(delta).length || undefined, commits: gate.commits, unchanged: gate.unchanged };
2658
+ }
2659
+
2660
+ /**
2661
+ * `dt set ui-views/<id> module=<m>` — MOVE a view's source to another module, the way `moveCollection`
2662
+ * moves a descriptor: the same bytes at the new path (a view's comments are its module's reasoning),
2663
+ * the old file gone, one compile gate, one commit per repo it touches — so a move into a linked
2664
+ * clone's module commits there, ready to publish with that module.
2665
+ */
2666
+ export function moveUiView(ws, store, id, toModule, { dryRun = false } = {}) {
2667
+ const { shipped } = uiViewSourceFile(ws, id);
2668
+ if (!shipped) throw new Error(`ui-view "${id}" does not exist`);
2669
+ if (IN_NODE_MODULES(shipped)) {
2670
+ throw new Error(`ui-view "${id}" is shipped by an installed package (${shipped}) — it moves with its package, not from here.\n save it under a new name, then move that one.`);
2671
+ }
2672
+ const to = moduleRecord(store, toModule); // throws with the known-module list
2673
+ if (IN_NODE_MODULES(to.fields.path)) {
2674
+ throw new Error(`module "${toModule}" ships from node_modules (${to.fields.path}) — a write there is erased by the next npm install.\n pick a module whose sources are in this workspace.`);
2675
+ }
2676
+ const owner = moduleRows(store).filter((r) => shipped.startsWith(`${r.fields.path}/`)).sort((a, b) => b.fields.path.length - a.fields.path.length)[0];
2677
+ const src = path.join(ws.root, shipped);
2678
+ const dest = path.join(kindDir(path.join(ws.root, to.fields.path), 'ui-views'), `${id}.ui-view.yaml`);
2679
+ const plan = { id, from: owner?.id ?? null, to: toModule, file: path.relative(ws.root, dest) };
2680
+ if (path.resolve(dest) === path.resolve(src)) return { ...plan, moved: false };
2681
+ if (fs.existsSync(dest)) throw new Error(`${plan.file} already exists — move or remove it first; nothing was moved`);
2682
+ if (dryRun) return { ...plan, moved: false, dryRun: true };
2683
+ const bytes = fs.readFileSync(src);
2684
+ let moved = false;
2685
+ const out = gatedTreeOp(ws, store, {
2686
+ subject: `dreamteamer: ui-views set ${id} module=${toModule}`,
2687
+ paths: [shipped, plan.file],
2688
+ mutate: () => {
2689
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
2690
+ fs.writeFileSync(dest, bytes);
2691
+ fs.rmSync(src);
2692
+ moved = true;
2693
+ },
2694
+ undo: () => {
2695
+ if (moved && fs.existsSync(dest)) fs.rmSync(dest);
2696
+ fs.mkdirSync(path.dirname(src), { recursive: true });
2697
+ fs.writeFileSync(src, bytes);
2698
+ },
2699
+ });
2700
+ return { ...plan, moved: true, commits: out.commits };
2701
+ }
2702
+
2573
2703
  export function removeUiView(ws, store, id) {
2574
2704
  // Same source resolution as the save above — an inline module's view is under this repo's git
2575
2705
  // history like everything else, so deleting it is one revertable commit. Refusing it while
package/src/store.js CHANGED
@@ -9,7 +9,7 @@ import Ajv from 'ajv';
9
9
  import addFormats from 'ajv-formats';
10
10
  import { dump, writeSource } from './yaml.js';
11
11
  import { generateId } from './template.js';
12
- import { parseRecord, parseRecordText, patternRe, fmtAjvError, unknownFields, walk, EXT, assertSafeId, idFromRecordPath, MAX_RECORD_BYTES } from './records.js';
12
+ import { parseRecord, parseRecordText, patternRe, fmtAjvError, unknownFields, walk, EXT, assertSafeId, idFromRecordPath, MAX_RECORD_BYTES, isStubRecord, resolveClaims } from './records.js';
13
13
  import { normalizeRecord, normalizeTemporal } from './temporal.js';
14
14
  import { NO_RUNTIME, sourceHint, loadDescriptors, runtimeDir, namespaces as compiledNamespaces, sourceRoots as compiledSourceRoots } from './runtime.js';
15
15
  import { parseRef } from './namespace.js';
@@ -36,6 +36,8 @@ export class Store {
36
36
  this.ajv.addFormat('markdown', true);
37
37
  this._idsCache = new Map(); // collection -> { key, ids } (see ids())
38
38
  this._duplicates = new Map(); // placed collection -> id -> [files], refreshed by every walk (see assertUnambiguous)
39
+ this._stubs = new Map(); // layered collection -> id -> [stub files the answering record shadows]
40
+ this._claimFiles = new Map(); // layered collection -> every file of a contested id at the last walk (see _claimStamps)
39
41
  this._head = undefined; // memoized `git rev-parse HEAD` (see gitHead())
40
42
  const descriptors = loadDescriptors(root);
41
43
  if (!descriptors) throw new Error(NO_RUNTIME);
@@ -417,10 +419,22 @@ export class Store {
417
419
  const hit = this._idsCache.get(collection);
418
420
  if (hit?.key === key) return hit.ids;
419
421
  const ids = this._walkIds(d, dir);
420
- this._idsCache.set(collection, { key, ids });
422
+ // the folder half as measured BEFORE the walk (a change during it invalidates the next read), the
423
+ // claimant half AFTER it — the walk is what decides which files are contested
424
+ this._idsCache.set(collection, { key: key.replace(/\|claims:.*$/, '') + this._claimStamps(d), ids });
421
425
  return ids;
422
426
  }
423
427
 
428
+ /** Which file answers a contested id depends on file CONTENT (`stub: true`), which an in-place edit
429
+ * changes without moving any folder or HEAD — so the files of every id more than one root claimed at
430
+ * the last walk are stamped too (mtime and size). Empty for an uncontested collection. */
431
+ _claimStamps(d) {
432
+ const files = this._claimFiles.get(d.name);
433
+ if (!files?.length) return '';
434
+ const st = (f) => { try { const s = fs.statSync(f); return `${s.mtimeMs}:${s.size}`; } catch { return '-'; } };
435
+ return `|claims:${files.map(st).join(',')}`;
436
+ }
437
+
424
438
  /** The validity key `ids()` compares against, as its own method because `add` restates it AFTER
425
439
  * its write — the only way an index it just extended can still be accepted by the next call.
426
440
  * For a placed collection the PARENT root's mtime is in it too: a new parent folder is a new
@@ -435,7 +449,7 @@ export class Store {
435
449
  // vanished folder changes the string as surely as a changed one. A LAYER is the same shape:
436
450
  // `dt update` pulls files into it without moving this workspace's HEAD or any root's mtime.
437
451
  const dirs = this.recordDirs(d);
438
- return `${this.gitHead()}:${dirs.map(dirTreeStamps).join('|')}`;
452
+ return `${this.gitHead()}:${dirs.map(dirTreeStamps).join('|')}${this._claimStamps(d)}`;
439
453
  }
440
454
 
441
455
  /** Refuse a placed write whose path crosses a symlink inside the parent collection's root — a link
@@ -493,14 +507,29 @@ export class Store {
493
507
  // Across every root, write root first. FIRST claimant wins and the rest are left for `check`
494
508
  // to report — the same rule placement follows, for the same reason: a `get` that answered
495
509
  // from whichever layer sorted later would make the answer depend on the clone order.
496
- const dupes = new Map();
510
+ //
511
+ // A STUB yields (records.js resolveClaims): an id two roots claim has its claimants' frontmatter
512
+ // read — only those files, never the whole index — and a non-stub answers wherever it sits.
513
+ // Only two non-stubs are the duplicate that refuses a write.
514
+ const claims = new Map();
497
515
  for (const root of this.rootsOf(d)) {
498
516
  for (const [id, f] of this._walkRoot(d, root.abs)) {
499
- if (!ids.has(id)) { ids.set(id, f); continue; }
500
- dupes.set(id, [...(dupes.get(id) ?? [ids.get(id)]), f]);
517
+ const c = claims.get(id);
518
+ if (c) c.push(f); else claims.set(id, [f]);
501
519
  }
502
520
  }
521
+ const dupes = new Map();
522
+ const stubs = new Map();
523
+ for (const [id, files] of claims) {
524
+ if (files.length === 1) { ids.set(id, files[0]); continue; }
525
+ const { winner, conflicts, shadowed } = resolveClaims(files, (f) => isStubRecord(f, d));
526
+ ids.set(id, winner);
527
+ if (conflicts.length) dupes.set(id, conflicts);
528
+ if (shadowed.length) stubs.set(id, shadowed);
529
+ }
503
530
  this._duplicates.set(d.name, dupes);
531
+ this._stubs.set(d.name, stubs);
532
+ this._claimFiles.set(d.name, [...claims.values()].filter((f) => f.length > 1).flat());
504
533
  return ids;
505
534
  }
506
535
  if (storageOf(d).shape === 'folder') {
@@ -970,7 +999,9 @@ export class Store {
970
999
  // `check` would report, and refusing it here is what keeps the id unique across every root.
971
1000
  const file = this.filePath(d, id, undefined, fields);
972
1001
  this._assertContained(d, file);
973
- if (fs.existsSync(file) || ((placementOf(d) || this.layered(d)) && this.ids(collection).has(id))) throw new Error(`${collection}/${id} already exists — nothing was written.`);
1002
+ // An id held ONLY by stubs in other roots is free: this write promotes it, and says so (`shadows`).
1003
+ const shadows = this.layered(d) && !fs.existsSync(file) && this.ids(collection).has(id) ? this._stubOnlyClaims(d, id) : [];
1004
+ if (fs.existsSync(file) || ((placementOf(d) || this.layered(d)) && this.ids(collection).has(id) && !shadows.length)) throw new Error(`${collection}/${id} already exists — nothing was written.`);
974
1005
  return this.withWriteLock(() => {
975
1006
  // captured before the invalidation and handed back, one entry richer, on the success path
976
1007
  // below — see _indexAdd for why an add that throws it away is the expensive shape.
@@ -1008,7 +1039,7 @@ export class Store {
1008
1039
  }, storageOf(d).repo);
1009
1040
  // LAST, after the commit: the key it is re-stated under carries the sha, and `commit` moves it
1010
1041
  this._indexAdd(collection, memo, id, file);
1011
- return { id, file, idFallback, ...(deprecated.length && { deprecated }) };
1042
+ return { id, file, idFallback, ...(deprecated.length && { deprecated }), ...(shadows.length && { shadows }) };
1012
1043
  });
1013
1044
  }
1014
1045
 
@@ -1127,6 +1158,26 @@ export class Store {
1127
1158
  return null;
1128
1159
  }
1129
1160
 
1161
+ /** Every file claiming `id` when ALL of them are stubs, else `[]` — the case where `add` may promote. */
1162
+ _stubOnlyClaims(d, id) {
1163
+ const files = [this.ids(d.name).get(id), ...this.shadowedStubs(d.name, id)];
1164
+ return files.every((f) => isStubRecord(f, d)) ? files : [];
1165
+ }
1166
+
1167
+ /** The stub files an id's answering record shadows, in root order — `[]` for an id only one root
1168
+ * claims. What `dt get --json` reports as `$shadows`, and what `rm` of the winner leaves showing. */
1169
+ shadowedStubs(collection, id) {
1170
+ this.ids(collection); // ensures the memo is current
1171
+ return this._stubs.get(collection)?.get(id) ?? [];
1172
+ }
1173
+
1174
+ /** Every shadowed stub of a collection, `{ id, file }` — a stub is a real OWNER in its own repo, so
1175
+ * the mirrors it justifies there are still expected (check, relations rebuild). */
1176
+ *shadowedStubRecords(collection) {
1177
+ this.ids(collection);
1178
+ for (const [id, files] of this._stubs.get(collection) ?? []) for (const file of files) yield { id, file };
1179
+ }
1180
+
1130
1181
  /** Refuse to WRITE to an id that two files claim. The index keeps the first claimant so reads
1131
1182
  * still answer, but a write would land on one copy and leave the other saying something else —
1132
1183
  * the exact ambiguity `check` reports, made worse under a verb that printed ✔. */
@@ -1218,6 +1269,13 @@ export class Store {
1218
1269
  }
1219
1270
  }
1220
1271
 
1272
+ // ---- an id a STUB keeps answering does not go away -----------------------------------
1273
+ // Removing the record that answers over a stub leaves the id resolving — to the stub. So every
1274
+ // reference to it still resolves: nothing is refused for them, nothing is set to null, and
1275
+ // nothing is reported dangling. (Its own mirror entries are still detached below.)
1276
+ const keepsResolving = this.shadowedStubs(collection, id).length > 0;
1277
+ if (keepsResolving) setNullEdits.length = 0;
1278
+
1221
1279
  // ---- what the text scan finds that is NOT the engine's own bookkeeping -------------
1222
1280
  // The scan is per FILE, and one file can name this record TWICE — a mirror the engine wrote, and
1223
1281
  // a wikilink somebody typed in the same record's body. So excluding a file WHOLESALE is wrong:
@@ -1262,7 +1320,7 @@ export class Store {
1262
1320
  // shape, which is what this sentence has always said. What the scan misses (a bare FK, or an
1263
1321
  // owner file excluded because it also holds a mirror of ours) is named as record + field.
1264
1322
  const extraRestrict = restrictHits.filter((h) => !inbound.includes(h.file));
1265
- if ((inbound.length || extraRestrict.length) && !force) {
1323
+ if ((inbound.length || extraRestrict.length) && !force && !keepsResolving) {
1266
1324
  const all = [...inbound, ...extraRestrict.map((h) => `${h.file} (${h.ref}.${h.field})`)];
1267
1325
  throw new Error(`${self} is referenced by:\n${all.map((f) => ` ${f}`).join('\n')}\nfix the references or pass --force. nothing was removed.`);
1268
1326
  }
@@ -1329,7 +1387,8 @@ export class Store {
1329
1387
  // target is gone but its owners still name it is a history that never held a consistent
1330
1388
  // workspace.
1331
1389
  this.commit([unit, ...mirrors.files, ...nullFiles], `dreamteamer: ${collection} rm ${id}`, rollback, this.repoOfFile(d, unit));
1332
- return { id, inboundIgnored: force ? inbound.length + extraRestrict.length : 0 };
1390
+ const inboundCount = inbound.length + extraRestrict.length;
1391
+ return { id, inboundIgnored: force && !keepsResolving ? inboundCount : 0, ...(keepsResolving ? { inboundResolveToStub: inboundCount } : {}) };
1333
1392
  });
1334
1393
  }
1335
1394
 
package/src/views.js CHANGED
@@ -174,3 +174,33 @@ export function viewDisplay(collectionDisplay, view) {
174
174
  }
175
175
  return out;
176
176
  }
177
+
178
+ // ---- view overlays ---------------------------------------------------------------------------------
179
+ // A ui-view source with `overlay: true` and the id of a view another module ships is MERGED onto it at
180
+ // compile (compile.js). These two are the whole grammar, and inverse: `overlayView(base, viewOverlayOf(
181
+ // base, view))` is `view` again, which is what lets a save over a package's view write only what differs.
182
+
183
+ /** `base` refined by `overlay`: deep, overlay wins at a leaf, a list is replaced whole, `null` removes. */
184
+ export function overlayView(base, overlay) {
185
+ const out = structuredClone(base ?? {});
186
+ for (const [k, v] of Object.entries(overlay ?? {})) {
187
+ if (v === null) delete out[k];
188
+ else if (isMap(v) && isMap(out[k])) out[k] = overlayView(out[k], v);
189
+ else out[k] = structuredClone(v);
190
+ }
191
+ return out;
192
+ }
193
+
194
+ /** The smallest overlay turning `base` into `view` — `{}` when they agree. */
195
+ export function viewOverlayOf(base, view) {
196
+ const out = {};
197
+ for (const [k, v] of Object.entries(view ?? {})) {
198
+ const b = base?.[k];
199
+ if (isMap(v) && isMap(b)) {
200
+ const inner = viewOverlayOf(b, v);
201
+ if (Object.keys(inner).length) out[k] = inner;
202
+ } else if (JSON.stringify(v) !== JSON.stringify(b)) out[k] = structuredClone(v);
203
+ }
204
+ for (const k of Object.keys(base ?? {})) if (!(k in (view ?? {}))) out[k] = null;
205
+ return out;
206
+ }
package/src/workspace.js CHANGED
@@ -36,12 +36,48 @@ export function findWorkspace(start = process.cwd()) {
36
36
  // as something OTHER than a module.
37
37
  let found = candidates[0];
38
38
  for (const higher of candidates.slice(1)) {
39
+ // a workspace named with `--workspace` (bin/dreamteamer.js pins it, for THIS process only — never
40
+ // in the environment, so no child inherits it) is never climbed out of, even when it is a clone
41
+ // under another workspace's git_modules/ — that is exactly the case it names.
42
+ if (found.root === globalThis[Symbol.for('dreamteamer.workspace')]) break;
39
43
  if (!nestedAsModule(higher.root, found.root)) break;
40
44
  found = higher;
41
45
  }
42
46
  return found;
43
47
  }
44
48
 
49
+ /** The declared record layers, validated: `{ name, records, module }` per entry. WHAT THE CLONE IS
50
+ * decides it, not the reader's key (0.41.0): a clone whose own manifest names `workspace_module` is a
51
+ * workspace, so its data is a layer for every collection both have (`records: null`); a clone that
52
+ * names none is a bundle and is not listed here; a clone not on disk is listed (not installed). `records:` still makes an entry a layer and NARROWS
53
+ * it to the listed collections; `module: true` declares one too (and is refused downstream when the
54
+ * clone has no workspace module to contribute). `root` absent reads only the declarations. */
55
+ export function layerEntries(pkg, root = null) {
56
+ const out = [];
57
+ for (const [name, entry] of Object.entries(pkg?.dreamteamer?.git_modules ?? {})) {
58
+ 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)})`);
59
+ const r = entry?.records;
60
+ if (r !== undefined && (!Array.isArray(r) || !r.length || r.some((c) => typeof c !== 'string' || !c.trim()))) {
61
+ throw new Error(`git_modules.${name}.records must be a non-empty list of collection names (got ${JSON.stringify(r)})`);
62
+ }
63
+ // a clone ON DISK that names no workspace module is a bundle. One NOT on disk cannot say what it is,
64
+ // and is read as a layer that is not installed — announced by compile, check and status — rather
65
+ // than vanishing: reading a project is the default since 0.41.0, and silence is how an absent
66
+ // layer passed for an empty one.
67
+ const clone = root ? path.join(root, 'git_modules', name) : null;
68
+ if (r === undefined && entry?.module !== true && clone && fs.existsSync(clone) && !cloneWorkspaceModule(clone)) continue;
69
+ if (r === undefined && entry?.module !== true && !clone) continue;
70
+ out.push({ name, records: r ?? null, module: entry?.module === true });
71
+ }
72
+ return out;
73
+ }
74
+
75
+ /** The `workspace_module` a directory's own manifest names, or null — what makes a clone a workspace. */
76
+ export function cloneWorkspaceModule(dir) {
77
+ try { return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).dreamteamer?.workspace_module || null; }
78
+ catch { return null; }
79
+ }
80
+
45
81
  /** Is `inner` reached from `outer` by descending through a module folder? */
46
82
  export function nestedAsModule(outer, inner) {
47
83
  return path