dreamteamer 0.44.1 → 0.46.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/init.js CHANGED
@@ -8,7 +8,7 @@ import { discoverModules, KINDS } from './compile.js';
8
8
  import { KNOWN_HARNESSES } from './harnesses.js';
9
9
  import { Store } from './store.js';
10
10
  import { envContext, renderTemplate } from './env-vars.js';
11
- import { ensureEditorRecommendation } from './workspace.js';
11
+ import { declaredGitModules, ensureEditorRecommendation } from './workspace.js';
12
12
 
13
13
  // git calls whose failure we CATCH must not print git's own error: execFileSync forwards the
14
14
  // child's stderr to ours unless told otherwise, so a handled "not a git repository" still
@@ -169,21 +169,15 @@ export function init({ flags = {} } = {}) {
169
169
  return 0;
170
170
  }
171
171
 
172
- // dreamteamer install — restore git_modules/ working clones from the committed lockfile map
172
+ // dreamteamer install — restore git_modules/ working clones from the committed lockfile map, and what each
173
+ // restored clone NEEDS in turn (`declaredGitModules`, the npm model): a layer a clone's manifest names is
174
+ // cloned ONCE at the top level and linked under the clone — or, where it disagrees with what the top holds,
175
+ // cloned under the clone itself — to a fixpoint, since a clone just restored may need more. Never refuses.
173
176
  export function install({ root, pkg }) {
174
- const map = pkg.dreamteamer?.git_modules ?? {};
175
- const names = Object.keys(map);
176
- if (!names.length) { console.log('✔ no git_modules declared — nothing to restore'); return 0; }
177
- fs.mkdirSync(path.join(root, 'git_modules'), { recursive: true });
178
- const unreachable = [];
179
- for (const name of names) {
180
- const { url, ref = 'main' } = map[name];
181
- const dest = path.join(root, 'git_modules', name);
182
- if (fs.existsSync(dest)) {
183
- if (!repoint(dest, name, ref)) unreachable.push(name);
184
- continue;
185
- }
186
- console.log(`… cloning ${url} → git_modules/${name} (${ref})`);
177
+ const unreachable = [], done = new Set();
178
+ let declared;
179
+ const clone = (url, ref, dest, name, note) => {
180
+ console.log(`… cloning ${url} → ${path.relative(root, dest)} (${ref})${note}`);
187
181
  try {
188
182
  execFileSync('git', ['clone', '--branch', ref, url, dest], { stdio: 'inherit' });
189
183
  } catch {
@@ -193,27 +187,71 @@ export function install({ root, pkg }) {
193
187
  // half-restored workspace and named only the first failure.
194
188
  fs.rmSync(dest, { recursive: true, force: true }); // git leaves the partial dir behind
195
189
  unreachable.push(name);
196
- console.warn(`⚠ git_modules/${name}: clone failed — skipped (${url})`);
197
- continue;
190
+ console.warn(`⚠ ${path.relative(root, dest)}: clone failed — skipped (${url})`);
191
+ return;
198
192
  }
199
193
  buildClone(dest, name);
194
+ };
195
+ for (;;) {
196
+ declared = declaredGitModules(pkg, root);
197
+ const top = [...declared.map].filter(([n]) => !done.has(n)).map(([name, e]) => ({ ...e, name, dest: path.join(root, 'git_modules', name), note: e.declarers.some(Boolean) ? ` — for ${e.declarers.filter(Boolean).join(', ')}` : '' }));
198
+ const under = declared.nested.filter((n) => !done.has(`${n.by}/${n.name}`)).map((n) => ({ ...n, dest: path.join(root, n.by, 'git_modules', n.name), note: ` — nested: git_modules/${n.name} is ${n.top.url} (${n.top.ref})` }));
199
+ if (!top.length && !under.length) break;
200
+ for (const t of [...top, ...under]) {
201
+ done.add(t.by ? `${t.by}/${t.name}` : t.name);
202
+ fs.mkdirSync(path.dirname(t.dest), { recursive: true });
203
+ if (fs.existsSync(t.dest)) { if (!repoint(t.dest, path.relative(path.join(root, 'git_modules'), t.dest), t.ref)) unreachable.push(t.name); continue; }
204
+ clone(t.url, t.ref, t.dest, t.name, t.note);
205
+ if (t.by) excludeIn(path.join(root, t.by), `git_modules/${t.name}`);
206
+ }
207
+ }
208
+ if (!done.size) { console.log('✔ no git_modules declared — nothing to restore'); return 0; }
209
+ for (const [name, { declarers }] of declared.map) for (const by of declarers) if (by && !unreachable.includes(name)) linkLayer(root, by, name);
210
+ for (const [name, list] of declared.mismatches.reduce((g, m) => g.set(m.name, [...(g.get(m.name) ?? []), m]), new Map())) { // Map.groupBy is Node 21+
211
+ console.warn(`⚠ git_modules/${name}: this workspace's declaration overrides ${list.map((m) => `${m.by} (${m.what} ${m.theirs})`).join(', ')}`);
200
212
  }
213
+ for (const u of declared.unmet) console.warn(`⚠ ${u.by}: dreamteamer-exports.json names ${u.holder}, which no git_modules entry of the clone provides`);
201
214
  // non-zero, because the workspace is NOT what the lockfile describes: modules are missing or off
202
215
  // their ref, and `check` will report references into them as unknown collections.
203
216
  if (unreachable.length) console.error(`✖ ${unreachable.length} module(s) are not what the lockfile declares: ${unreachable.join(', ')}`);
204
217
  return unreachable.length ? 1 : 0;
205
218
  }
206
219
 
220
+ /** The link a declarer finds its layer through — `<by>/git_modules/<name> -> ../../<name>`, the pnpm shape:
221
+ * explicit on disk, resolved by a tool that knows nothing of dreamteamer. A clone of its own standing there
222
+ * may hold work: left as it is, and said — `dt status` draws it too. */
223
+ function linkLayer(root, by, name) {
224
+ const at = path.join(root, by, 'git_modules', name), want = path.join('..', '..', name);
225
+ let st = null;
226
+ try { st = fs.lstatSync(at); } catch { /* nothing there */ }
227
+ if (st && !st.isSymbolicLink()) { console.log(`… ${by}/git_modules/${name} is a clone of its own — left as it is`); return; }
228
+ if (st && fs.readlinkSync(at) === want) return;
229
+ if (st) fs.unlinkSync(at);
230
+ fs.mkdirSync(path.dirname(at), { recursive: true });
231
+ fs.symlinkSync(want, at);
232
+ excludeIn(path.join(root, by), `git_modules/${name}`);
233
+ console.log(`✔ ${by}/git_modules/${name} → git_modules/${name}`);
234
+ }
235
+
236
+ /** Ignore `rel` in a clone's own `.git/info/exclude` when its .gitignore does not already cover it — never
237
+ * in a tracked file, which would dirty the clone. */
238
+ function excludeIn(clone, rel) {
239
+ if (ran(clone, ['check-ignore', '-q', rel])) return;
240
+ const exclude = path.resolve(clone, tryGit(clone, ['rev-parse', '--git-path', 'info/exclude']) ?? path.join('.git', 'info', 'exclude'));
241
+ fs.mkdirSync(path.dirname(exclude), { recursive: true });
242
+ appendMissing(exclude, rel);
243
+ }
244
+
207
245
  // dreamteamer update [<name>] — pull each lockfile-declared git_modules clone forward
208
246
  // (ff-only on its recorded ref) and rebuild it. dirty clones are skipped, never touched.
209
247
  // the caller (cli) runs compile afterwards — a pulled module may change sources.
210
248
  export function update({ root, pkg }, only) {
211
- const map = pkg.dreamteamer?.git_modules ?? {};
249
+ const map = Object.fromEntries(declaredGitModules(pkg, root).map); // a hoisted layer is pulled forward too
212
250
  if (only && !map[only]) throw new Error(`"${only}" is not in dreamteamer.git_modules (known: ${Object.keys(map).join(', ') || 'none'})`);
213
251
  const names = only ? [only] : Object.keys(map);
214
252
  if (!names.length) { console.log('✔ no git_modules declared — nothing to update'); return 0; }
215
253
  for (const name of names) {
216
- const { ref = 'main' } = map[name];
254
+ const { ref } = map[name];
217
255
  const dest = path.join(root, 'git_modules', name);
218
256
  if (!fs.existsSync(dest)) { console.warn(`⚠ git_modules/${name} missing — run \`dreamteamer install\` first; skipped`); continue; }
219
257
  if (tryGit(dest, ['status', '--porcelain'])) { console.warn(`⚠ git_modules/${name} is dirty — skipped (commit or stash there, then re-run)`); continue; }
@@ -60,6 +60,9 @@ export class Store {
60
60
  recordDirs(d: Descriptor): string[];
61
61
  /** id → record file, across every folder the collection's records sit in */
62
62
  ids(collection: string): Map<string, string>;
63
+ /** An id no root here holds that an exports manifest vouches for — the referring record's repo's when
64
+ * `referrer` names it, else this workspace's — answered only where `check` says external (cr-dt-004). */
65
+ external(collection: string, id: string, opts?: { referrer?: string }): { label: string; from?: string; manifest: string } | null;
63
66
  read(collection: string, id: string): { fields: Fields; file: string };
64
67
  /** Where a record is read from: `file` workspace-relative (absolute for a root outside every repo
65
68
  * here) and `repo`, the workspace-relative repo root that commits it — null when none does. */
package/src/records.js CHANGED
@@ -29,41 +29,6 @@ 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
-
57
- /** The fields a stub of a record must carry to validate on its own (cr-dt-003): the schema's root
58
- * `required`, plus each `allOf` branch's `then.required` whose `if` holds for this record (`holds`
59
- * evaluates a subschema against it), kept to the keys the record carries. Nothing optional and nothing
60
- * a branch that does not apply requires — a stub is read by every workspace that reads this one. */
61
- export function stubFields(schema, fields, holds) {
62
- const keys = new Set(schema?.required ?? []);
63
- for (const b of schema?.allOf ?? []) if (b?.then?.required && (b.if === undefined || holds(b.if))) for (const k of b.then.required) keys.add(k);
64
- return [...keys].filter((k) => fields[k] !== undefined);
65
- }
66
-
67
32
  // id patterns may use unicode property escapes — compile with the u flag
68
33
  export function patternRe(pattern) {
69
34
  try { return new RegExp(pattern, 'u'); } catch { return new RegExp(pattern); }
package/src/runtime.js CHANGED
@@ -119,6 +119,14 @@ function walkDescriptors(dir, out = []) {
119
119
  return out;
120
120
  }
121
121
 
122
+ /** What compile recorded for the exports manifest (cr-dt-004): this workspace's package name and data
123
+ * folder, and per layer `{ name, root, data, package, reads, narrowed }` — `layers: null` from a runtime
124
+ * older than them, which a caller reads as "nothing is known". */
125
+ export function exportsFacts(root) {
126
+ const m = readManifest(root);
127
+ return { own: m?.package ?? null, data: m?.data_path ?? 'data', layers: m?.layers ?? null };
128
+ }
129
+
122
130
  /**
123
131
  * The workspace's declared namespaces, longest-first — the closed set every reference is split
124
132
  * against. Read off the MANIFEST rather than package.json so the record layer keeps its single
package/src/store.js CHANGED
@@ -9,9 +9,10 @@ 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, isStubRecord, resolveClaims } from './records.js';
12
+ import { parseRecord, parseRecordText, patternRe, fmtAjvError, unknownFields, walk, EXT, assertSafeId, idFromRecordPath, MAX_RECORD_BYTES } from './records.js';
13
13
  import { normalizeRecord, normalizeTemporal } from './temporal.js';
14
- import { NO_RUNTIME, sourceHint, loadDescriptors, runtimeDir, namespaces as compiledNamespaces, sourceRoots as compiledSourceRoots } from './runtime.js';
14
+ import { NO_RUNTIME, sourceHint, loadDescriptors, runtimeDir, namespaces as compiledNamespaces, sourceRoots as compiledSourceRoots, exportsFacts } from './runtime.js';
15
+ import { EXPORTS_FILE, readExports, exportsContext, sees } from './exports.js';
15
16
  import { parseRef } from './namespace.js';
16
17
  import { relationsOf, expectedMirrors } from './relations.js';
17
18
  import { placementOf, placedRecords, rootRecords, placedRoot, placementOfFile, ownerIdOf, symlinkBelow, dirTreeStamps, isNested, parentOfNestedId, localOfNestedId } from './placement.js';
@@ -37,8 +38,6 @@ export class Store {
37
38
  this.ajv.addFormat('markdown', true);
38
39
  this._idsCache = new Map(); // collection -> { key, ids } (see ids())
39
40
  this._duplicates = new Map(); // placed collection -> id -> [files], refreshed by every walk (see assertUnambiguous)
40
- this._stubs = new Map(); // layered collection -> id -> [stub files the answering record shadows]
41
- this._claimFiles = new Map(); // layered collection -> every file of a contested id at the last walk (see _claimStamps)
42
41
  this._head = undefined; // memoized `git rev-parse HEAD` (see gitHead())
43
42
  const descriptors = loadDescriptors(root);
44
43
  if (!descriptors) throw new Error(NO_RUNTIME);
@@ -196,8 +195,7 @@ export class Store {
196
195
  // to edit and `read` would throw, turning someone else's stale data into a refusal of
197
196
  // this write. An attach never lands here missing — checkRefs proved it before the lock.
198
197
  if (!this.ids(rel.target).has(parsed.id)) return;
199
- // another repo answers: no mirror there (see above) — but this repo's own STUB of the id,
200
- // if it keeps one, is a record of this repo and its mirror is kept like any other
198
+ // another repo answers: no mirror there (see above) — mirrors stay per repo
201
199
  const file = this.mirrorFileFor(rel.target, parsed.id, ownerRepo);
202
200
  if (!file) return;
203
201
  const fields = parseRecord(file, td, bodyField(td));
@@ -284,33 +282,14 @@ export class Store {
284
282
  layered(d) { return storageOf(d).layers.length > 0; }
285
283
 
286
284
  /** The file an owner in `ownerRepo` keeps the mirror of `collection/id` in: the record that answers
287
- * the id when it sits in that repo, else that repo's own shadowed STUB of the id, else null (the id
288
- * is another repo's, and mirrors stay per repo). The one place the choice is made — the mirror
285
+ * the id when it sits in that repo, else null (the id is another repo's, and mirrors stay per repo). The one place the choice is made — the mirror
289
286
  * pass writes it and rm's guard credits it, so the two cannot disagree. */
290
287
  mirrorFileFor(collection, id, ownerRepo) {
291
288
  const d = this.descriptor(collection);
292
289
  const answering = this.ids(collection).get(id);
293
290
  if (!answering) return null;
294
291
  if (this.repoOfFile(d, answering) === ownerRepo) return answering;
295
- return this.shadowedStubs(collection, id).find((f) => this.repoOfFile(d, f) === ownerRepo) ?? null;
296
- }
297
-
298
- /** What a record written over an id another root already answers is owed by the owners of ITS repo:
299
- * every incoming mirror, computed as `relations rebuild` and `check` compute it — the repo's
300
- * answering owners plus its shadowed stub owners. Nothing attached to an id this repo did not hold,
301
- * so no owner write ever wrote these. */
302
- incomingMirrors(d, id, repo) {
303
- const out = {};
304
- for (const rel of this.relations()) {
305
- if (rel.target !== d.name) continue;
306
- const od = this.descriptor(rel.owner);
307
- if (storageOf(od).unavailable) continue; // an owner collection this machine cannot read holds no owners here
308
- const rows = [...this.ids(rel.owner)].map(([oid, file]) => ({ id: oid, file })).concat([...this.shadowedStubRecords(rel.owner)]);
309
- const owners = rows.filter((r) => this.repoOfFile(od, r.file) === repo).map((r) => ({ id: r.id, fields: parseRecord(r.file, od, bodyField(od)) }));
310
- const v = expectedMirrors(rel, owners).get(id);
311
- if (v !== undefined) out[rel.mirror] = v;
312
- }
313
- return out;
292
+ return null;
314
293
  }
315
294
 
316
295
  /** The layer an existing file of `d` was read from — `{ layer, path, repo, abs }` — or null for a
@@ -453,22 +432,10 @@ export class Store {
453
432
  const hit = this._idsCache.get(collection);
454
433
  if (hit?.key === key) return hit.ids;
455
434
  const ids = this._walkIds(d, dir);
456
- // the folder half as measured BEFORE the walk (a change during it invalidates the next read), the
457
- // claimant half AFTER it — the walk is what decides which files are contested
458
- this._idsCache.set(collection, { key: key.replace(/\|claims:.*$/, '') + this._claimStamps(d), ids });
435
+ this._idsCache.set(collection, { key, ids });
459
436
  return ids;
460
437
  }
461
438
 
462
- /** Which file answers a contested id depends on file CONTENT (`stub: true`), which an in-place edit
463
- * changes without moving any folder or HEAD — so the files of every id more than one root claimed at
464
- * the last walk are stamped too (mtime and size). Empty for an uncontested collection. */
465
- _claimStamps(d) {
466
- const files = this._claimFiles.get(d.name);
467
- if (!files?.length) return '';
468
- const st = (f) => { try { const s = fs.statSync(f); return `${s.mtimeMs}:${s.size}`; } catch { return '-'; } };
469
- return `|claims:${files.map(st).join(',')}`;
470
- }
471
-
472
439
  /** The validity key `ids()` compares against, as its own method because `add` restates it AFTER
473
440
  * its write — the only way an index it just extended can still be accepted by the next call.
474
441
  * For a placed collection the PARENT root's mtime is in it too: a new parent folder is a new
@@ -483,7 +450,7 @@ export class Store {
483
450
  // vanished folder changes the string as surely as a changed one. A LAYER is the same shape:
484
451
  // `dt update` pulls files into it without moving this workspace's HEAD or any root's mtime.
485
452
  const dirs = this.recordDirs(d);
486
- return `${this.gitHead()}:${dirs.map(dirTreeStamps).join('|')}${this._claimStamps(d)}`;
453
+ return `${this.gitHead()}:${dirs.map(dirTreeStamps).join('|')}`;
487
454
  }
488
455
 
489
456
  /** Refuse a placed write whose path crosses a symlink inside the parent collection's root — a link
@@ -541,10 +508,6 @@ export class Store {
541
508
  // Across every root, write root first. FIRST claimant wins and the rest are left for `check`
542
509
  // to report — the same rule placement follows, for the same reason: a `get` that answered
543
510
  // from whichever layer sorted later would make the answer depend on the clone order.
544
- //
545
- // A STUB yields (records.js resolveClaims): an id two roots claim has its claimants' frontmatter
546
- // read — only those files, never the whole index — and a non-stub answers wherever it sits.
547
- // Only two non-stubs are the duplicate that refuses a write.
548
511
  const claims = new Map();
549
512
  for (const root of this.rootsOf(d)) {
550
513
  for (const [id, f] of this._walkRoot(d, root.abs)) {
@@ -553,17 +516,11 @@ export class Store {
553
516
  }
554
517
  }
555
518
  const dupes = new Map();
556
- const stubs = new Map();
557
519
  for (const [id, files] of claims) {
558
- if (files.length === 1) { ids.set(id, files[0]); continue; }
559
- const { winner, conflicts, shadowed } = resolveClaims(files, (f) => isStubRecord(f, d));
560
- ids.set(id, winner);
561
- if (conflicts.length) dupes.set(id, conflicts);
562
- if (shadowed.length) stubs.set(id, shadowed);
520
+ ids.set(id, files[0]);
521
+ if (files.length > 1) dupes.set(id, files);
563
522
  }
564
523
  this._duplicates.set(d.name, dupes);
565
- this._stubs.set(d.name, stubs);
566
- this._claimFiles.set(d.name, [...claims.values()].filter((f) => f.length > 1).flat());
567
524
  return ids;
568
525
  }
569
526
  if (storageOf(d).shape === 'folder') {
@@ -664,6 +621,27 @@ export class Store {
664
621
  if (where?.parentId) pruneEmptyDirs(root, path.join(this.parentDir(d), where.parentId));
665
622
  }
666
623
 
624
+ /** An id no root here holds that an exports manifest vouches for (cr-dt-004): `{ label, from?, manifest }`,
625
+ * or null. The manifest is the referring record's repo's — `referrer` (`<collection>/<id>`), else this
626
+ * workspace's — and it answers only where its holder is not read here: exactly where `check` says
627
+ * external. A referrer this workspace does not read is refused, naming it. */
628
+ external(collection, id, { referrer } = {}) {
629
+ if (this.ids(collection).has(id)) return null;
630
+ let repo = null;
631
+ if (referrer) {
632
+ const r = parseRef(referrer, this.namespaces);
633
+ const rd = r && this.descriptors.get(r.collection);
634
+ const f = rd && this.ids(r.collection).get(r.id);
635
+ if (!f) throw new Error(`${referrer}: no such record here — a referrer is a record this workspace reads`);
636
+ repo = this.layerOfFile(rd, f)?.layer ?? null;
637
+ }
638
+ const facts = exportsFacts(this.root);
639
+ const ctx = exportsContext({ root: this.root, descriptors: this.descriptors, own: facts.own, layers: facts.layers, dataPath: facts.data });
640
+ const e = readExports(ctx.rootOf(repo))?.[collection]?.[id];
641
+ if (!e || sees(e, collection, ctx)) return null;
642
+ return { label: e.label, ...(e.from ? { from: e.from } : {}), manifest: path.relative(this.root, path.join(ctx.rootOf(repo), EXPORTS_FILE)) };
643
+ }
644
+
667
645
  read(collection, id) {
668
646
  const d = this.descriptor(collection);
669
647
  const file = this.ids(collection).get(id);
@@ -1035,14 +1013,7 @@ export class Store {
1035
1013
  // `check` would report, and refusing it here is what keeps the id unique across every root.
1036
1014
  const file = this.filePath(d, id, undefined, fields);
1037
1015
  this._assertContained(d, file);
1038
- // An id held ONLY by stubs in other roots is free: this write promotes it, and says so (`shadows`).
1039
- // CONTESTED: another root already claims the id and this one holds no file of it. A stub may be
1040
- // written there — it yields to the record that answers (cr-dt-003) — and so may a record that
1041
- // promotes stubs-only claims; either way it is owed the incoming mirrors no owner write could make.
1042
- const contested = this.layered(d) && !fs.existsSync(file) && this.ids(collection).has(id);
1043
- const shadows = contested ? this._stubOnlyClaims(d, id) : [];
1044
- if (fs.existsSync(file) || ((placementOf(d) || this.layered(d)) && this.ids(collection).has(id) && !shadows.length && !(contested && fields.stub === true))) throw new Error(`${collection}/${id} already exists — nothing was written.`);
1045
- if (contested) Object.assign(fields, this.incomingMirrors(d, id, storageOf(d).repo));
1016
+ if (fs.existsSync(file) || ((placementOf(d) || this.layered(d)) && this.ids(collection).has(id))) throw new Error(`${collection}/${id} already exists — nothing was written.`);
1046
1017
  return this.withWriteLock(() => {
1047
1018
  // captured before the invalidation and handed back, one entry richer, on the success path
1048
1019
  // below — see _indexAdd for why an add that throws it away is the expensive shape.
@@ -1080,7 +1051,7 @@ export class Store {
1080
1051
  }, storageOf(d).repo);
1081
1052
  // LAST, after the commit: the key it is re-stated under carries the sha, and `commit` moves it
1082
1053
  this._indexAdd(collection, memo, id, file);
1083
- return { id, file, idFallback, ...(deprecated.length && { deprecated }), ...(shadows.length && { shadows }) };
1054
+ return { id, file, idFallback, ...(deprecated.length && { deprecated }) };
1084
1055
  });
1085
1056
  }
1086
1057
 
@@ -1199,26 +1170,6 @@ export class Store {
1199
1170
  return null;
1200
1171
  }
1201
1172
 
1202
- /** Every file claiming `id` when ALL of them are stubs, else `[]` — the case where `add` may promote. */
1203
- _stubOnlyClaims(d, id) {
1204
- const files = [this.ids(d.name).get(id), ...this.shadowedStubs(d.name, id)];
1205
- return files.every((f) => isStubRecord(f, d)) ? files : [];
1206
- }
1207
-
1208
- /** The stub files an id's answering record shadows, in root order — `[]` for an id only one root
1209
- * claims. What `dt get --json` reports as `$shadows`, and what `rm` of the winner leaves showing. */
1210
- shadowedStubs(collection, id) {
1211
- this.ids(collection); // ensures the memo is current
1212
- return this._stubs.get(collection)?.get(id) ?? [];
1213
- }
1214
-
1215
- /** Every shadowed stub of a collection, `{ id, file }` — a stub is a real OWNER in its own repo, so
1216
- * the mirrors it justifies there are still expected (check, relations rebuild). */
1217
- *shadowedStubRecords(collection) {
1218
- this.ids(collection);
1219
- for (const [id, files] of this._stubs.get(collection) ?? []) for (const file of files) yield { id, file };
1220
- }
1221
-
1222
1173
  /** Refuse to WRITE to an id that two files claim. The index keeps the first claimant so reads
1223
1174
  * still answer, but a write would land on one copy and leave the other saying something else —
1224
1175
  * the exact ambiguity `check` reports, made worse under a verb that printed ✔. */
@@ -1310,13 +1261,6 @@ export class Store {
1310
1261
  }
1311
1262
  }
1312
1263
 
1313
- // ---- an id a STUB keeps answering does not go away -----------------------------------
1314
- // Removing the record that answers over a stub leaves the id resolving — to the stub. So every
1315
- // reference to it still resolves: nothing is refused for them, nothing is set to null, and
1316
- // nothing is reported dangling. (Its own mirror entries are still detached below.)
1317
- const keepsResolving = this.shadowedStubs(collection, id).length > 0;
1318
- if (keepsResolving) setNullEdits.length = 0;
1319
-
1320
1264
  // ---- what the text scan finds that is NOT the engine's own bookkeeping -------------
1321
1265
  // The scan is per FILE, and one file can name this record TWICE — a mirror the engine wrote, and
1322
1266
  // a wikilink somebody typed in the same record's body. So excluding a file WHOLESALE is wrong:
@@ -1361,7 +1305,7 @@ export class Store {
1361
1305
  // shape, which is what this sentence has always said. What the scan misses (a bare FK, or an
1362
1306
  // owner file excluded because it also holds a mirror of ours) is named as record + field.
1363
1307
  const extraRestrict = restrictHits.filter((h) => !inbound.includes(h.file));
1364
- if ((inbound.length || extraRestrict.length) && !force && !keepsResolving) {
1308
+ if ((inbound.length || extraRestrict.length) && !force) {
1365
1309
  const all = [...inbound, ...extraRestrict.map((h) => `${h.file} (${h.ref}.${h.field})`)];
1366
1310
  throw new Error(`${self} is referenced by:\n${all.map((f) => ` ${f}`).join('\n')}\nfix the references or pass --force. nothing was removed.`);
1367
1311
  }
@@ -1429,7 +1373,7 @@ export class Store {
1429
1373
  // workspace.
1430
1374
  this.commit([unit, ...mirrors.files, ...nullFiles], `dreamteamer: ${collection} rm ${id}`, rollback, this.repoOfFile(d, unit));
1431
1375
  const inboundCount = inbound.length + extraRestrict.length;
1432
- return { id, inboundIgnored: force && !keepsResolving ? inboundCount : 0, ...(keepsResolving ? { inboundResolveToStub: inboundCount } : {}) };
1376
+ return { id, inboundIgnored: force ? inboundCount : 0 };
1433
1377
  });
1434
1378
  }
1435
1379
 
package/src/workspace.js CHANGED
@@ -10,6 +10,7 @@
10
10
  // real workspace and now resolves as one.
11
11
  import fs from 'node:fs';
12
12
  import path from 'node:path';
13
+ import { readExports } from './exports.js';
13
14
 
14
15
  // path segments that mean "the thing below me is a module of the thing above me", never a workspace
15
16
  const MODULE_SEGMENTS = new Set(['node_modules', 'git_modules', 'modules']);
@@ -46,28 +47,84 @@ export function findWorkspace(start = process.cwd()) {
46
47
  return found;
47
48
  }
48
49
 
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)})`);
50
+ /** Every git module this workspace installs, by name — THE NPM MODEL. Its own declarations first, all of
51
+ * them (a root installs its devDependencies too). Then, with `root`, what each clone on disk NEEDS: the
52
+ * entries of the clone's own `git_modules` that provide a package its committed `dreamteamer-exports.json`
53
+ * names as holding ids its records reference. A clone with no manifest needs nothing — the rest of its list
54
+ * is its devDependencies, never installed here, which is what keeps a transitive install from dragging in
55
+ * everything a nested workspace happens to read. A need is matched to an entry by package name, scoped or
56
+ * not (`@northwind/org` → `org`); one no entry provides is returned in `unmet`.
57
+ *
58
+ * Resolution, as npm's: a need the root declares is the root's (`overrides` — a differing ref or url is
59
+ * returned in `mismatches`, never acted on); a need another clone already hoisted at the same url and ref
60
+ * is shared; a need nobody has is hoisted to the top-level `git_modules/<name>`, once; a need that disagrees
61
+ * with what the top holds is `nested` — a second clone under its declarer, as npm nests a second version.
62
+ * `install` lays a symlink under each declarer of a top-level clone. Nothing here refuses; every
63
+ * disagreement is returned to be said. `records` is the union of the lists, `open` when some declarer
64
+ * named none; a nested `module: true` is not hoisted. */
65
+ export function declaredGitModules(pkg, root = null) {
66
+ const map = new Map(), nested = [], mismatches = [], unmet = [];
67
+ const validate = (at, entry) => {
68
+ if (entry?.module !== undefined && typeof entry.module !== 'boolean') throw new Error(`${at}.module must be true or false (got ${JSON.stringify(entry.module)})`);
59
69
  const r = entry?.records;
60
70
  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)})`);
71
+ throw new Error(`${at}.records must be a non-empty list of collection names (got ${JSON.stringify(r)})`);
72
+ }
73
+ const { url, ref = 'main' } = entry ?? {};
74
+ return { url, ref, records: r, open: r === undefined };
75
+ };
76
+ for (const [name, entry] of Object.entries(pkg?.dreamteamer?.git_modules ?? {})) {
77
+ map.set(name, { ...validate(`git_modules.${name}`, entry), module: entry?.module === true, declarers: [null] });
78
+ }
79
+ if (!root) return { map, nested, mismatches, unmet };
80
+ const widen = (have, e) => { if (e.open) have.open = true; else have.records = [...new Set([...(have.records ?? []), ...e.records])]; };
81
+ // clones to read, by workspace-relative path; a Map visits entries appended while it is walked
82
+ const clones = new Map([...map.keys()].map((n) => [`git_modules/${n}`, n]));
83
+ for (const [by, name] of clones) {
84
+ const dir = path.join(root, by);
85
+ let own, holders;
86
+ try { own = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).dreamteamer?.git_modules ?? {}; } catch { continue; }
87
+ holders = new Set(Object.values(readExports(dir) ?? {}).flatMap((ids) => Object.values(ids).map((e) => e.from)).filter(Boolean));
88
+ for (const holder of holders) {
89
+ const found = Object.entries(own).find(([n]) => n === holder || n === holder.split('/').pop());
90
+ if (!found) { unmet.push({ by, holder }); continue; }
91
+ const [need, entry] = found;
92
+ const e = validate(`${by}: git_modules.${need}`, entry);
93
+ const have = map.get(need);
94
+ if (!have) { map.set(need, { ...e, module: false, declarers: [by] }); clones.set(`git_modules/${need}`, need); continue; }
95
+ if (have.declarers[0] === null) { // the root's — it overrides
96
+ if (have.url !== e.url) mismatches.push({ name: need, by, what: 'url', theirs: e.url });
97
+ else if (have.ref !== e.ref) mismatches.push({ name: need, by, what: 'ref', theirs: e.ref });
98
+ } else if (have.url !== e.url || have.ref !== e.ref) {
99
+ nested.push({ by, name: need, ...e, top: { url: have.url, ref: have.ref } });
100
+ clones.set(`${by}/git_modules/${need}`, need);
101
+ continue;
102
+ }
103
+ have.declarers.push(by);
104
+ widen(have, e);
62
105
  }
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.
106
+ }
107
+ return { map, nested, mismatches, unmet };
108
+ }
109
+
110
+ /** The declared record layers, validated: `{ name, records, module, via }` per entry — `via` the nested
111
+ * declarers a hoisted layer was asked for by (`declaredGitModules`). WHAT THE CLONE IS decides it, not the
112
+ * reader's key (0.41.0): a clone whose own manifest names `workspace_module` is a workspace, so its data is
113
+ * a layer for every collection both have (`records: null`); a clone that names none is a bundle and is not
114
+ * listed here; a clone not on disk is listed (not installed). `records:` still makes an entry a layer and
115
+ * NARROWS it to the listed collections; `module: true` declares one too (and is refused downstream when the
116
+ * clone has no workspace module to contribute). `root` absent reads only the declarations. */
117
+ export function layerEntries(pkg, root = null) {
118
+ const out = [];
119
+ for (const [name, e] of declaredGitModules(pkg, root).map) {
67
120
  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 });
121
+ // a declaration naming no records reads every shared collection of a WORKSPACE clone — or of one not on
122
+ // disk, which cannot say what it is, and is read as a layer that is not installed (announced by compile,
123
+ // check and status) rather than vanishing: silence is how an absent layer passed for an empty one. Of a
124
+ // bundle it reads nothing, so another declarer's list stands
125
+ const wide = e.open && (clone ? !fs.existsSync(clone) || !!cloneWorkspaceModule(clone) : e.module);
126
+ if (!wide && !e.records && !(clone && e.module)) continue;
127
+ out.push({ name, records: wide ? null : e.records ?? null, module: e.module, via: e.declarers.filter(Boolean) });
71
128
  }
72
129
  return out;
73
130
  }