dreamteamer 0.44.1 → 0.45.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/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