dreamteamer 0.44.0 → 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/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,13 +9,15 @@ 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';
18
19
  import { pathToRecord } from './events.js';
20
+ import { commitArg } from './history.js';
19
21
 
20
22
  import { storageOf, fieldsOf, targetsOf, isSoft, jsonSchemaOf, unresolvedPeersOf, bodyFieldOf, idsOf } from './descriptor.js';
21
23
  // git calls whose failure we CATCH must not print git's own error: execFileSync forwards the
@@ -36,8 +38,6 @@ export class Store {
36
38
  this.ajv.addFormat('markdown', true);
37
39
  this._idsCache = new Map(); // collection -> { key, ids } (see ids())
38
40
  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)
41
41
  this._head = undefined; // memoized `git rev-parse HEAD` (see gitHead())
42
42
  const descriptors = loadDescriptors(root);
43
43
  if (!descriptors) throw new Error(NO_RUNTIME);
@@ -195,8 +195,7 @@ export class Store {
195
195
  // to edit and `read` would throw, turning someone else's stale data into a refusal of
196
196
  // this write. An attach never lands here missing — checkRefs proved it before the lock.
197
197
  if (!this.ids(rel.target).has(parsed.id)) return;
198
- // another repo answers: no mirror there (see above) — but this repo's own STUB of the id,
199
- // 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
200
199
  const file = this.mirrorFileFor(rel.target, parsed.id, ownerRepo);
201
200
  if (!file) return;
202
201
  const fields = parseRecord(file, td, bodyField(td));
@@ -283,33 +282,14 @@ export class Store {
283
282
  layered(d) { return storageOf(d).layers.length > 0; }
284
283
 
285
284
  /** The file an owner in `ownerRepo` keeps the mirror of `collection/id` in: the record that answers
286
- * the id when it sits in that repo, else that repo's own shadowed STUB of the id, else null (the id
287
- * 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
288
286
  * pass writes it and rm's guard credits it, so the two cannot disagree. */
289
287
  mirrorFileFor(collection, id, ownerRepo) {
290
288
  const d = this.descriptor(collection);
291
289
  const answering = this.ids(collection).get(id);
292
290
  if (!answering) return null;
293
291
  if (this.repoOfFile(d, answering) === ownerRepo) return answering;
294
- return this.shadowedStubs(collection, id).find((f) => this.repoOfFile(d, f) === ownerRepo) ?? null;
295
- }
296
-
297
- /** What a record written over an id another root already answers is owed by the owners of ITS repo:
298
- * every incoming mirror, computed as `relations rebuild` and `check` compute it — the repo's
299
- * answering owners plus its shadowed stub owners. Nothing attached to an id this repo did not hold,
300
- * so no owner write ever wrote these. */
301
- incomingMirrors(d, id, repo) {
302
- const out = {};
303
- for (const rel of this.relations()) {
304
- if (rel.target !== d.name) continue;
305
- const od = this.descriptor(rel.owner);
306
- if (storageOf(od).unavailable) continue; // an owner collection this machine cannot read holds no owners here
307
- const rows = [...this.ids(rel.owner)].map(([oid, file]) => ({ id: oid, file })).concat([...this.shadowedStubRecords(rel.owner)]);
308
- const owners = rows.filter((r) => this.repoOfFile(od, r.file) === repo).map((r) => ({ id: r.id, fields: parseRecord(r.file, od, bodyField(od)) }));
309
- const v = expectedMirrors(rel, owners).get(id);
310
- if (v !== undefined) out[rel.mirror] = v;
311
- }
312
- return out;
292
+ return null;
313
293
  }
314
294
 
315
295
  /** The layer an existing file of `d` was read from — `{ layer, path, repo, abs }` — or null for a
@@ -452,22 +432,10 @@ export class Store {
452
432
  const hit = this._idsCache.get(collection);
453
433
  if (hit?.key === key) return hit.ids;
454
434
  const ids = this._walkIds(d, dir);
455
- // the folder half as measured BEFORE the walk (a change during it invalidates the next read), the
456
- // claimant half AFTER it — the walk is what decides which files are contested
457
- this._idsCache.set(collection, { key: key.replace(/\|claims:.*$/, '') + this._claimStamps(d), ids });
435
+ this._idsCache.set(collection, { key, ids });
458
436
  return ids;
459
437
  }
460
438
 
461
- /** Which file answers a contested id depends on file CONTENT (`stub: true`), which an in-place edit
462
- * changes without moving any folder or HEAD — so the files of every id more than one root claimed at
463
- * the last walk are stamped too (mtime and size). Empty for an uncontested collection. */
464
- _claimStamps(d) {
465
- const files = this._claimFiles.get(d.name);
466
- if (!files?.length) return '';
467
- const st = (f) => { try { const s = fs.statSync(f); return `${s.mtimeMs}:${s.size}`; } catch { return '-'; } };
468
- return `|claims:${files.map(st).join(',')}`;
469
- }
470
-
471
439
  /** The validity key `ids()` compares against, as its own method because `add` restates it AFTER
472
440
  * its write — the only way an index it just extended can still be accepted by the next call.
473
441
  * For a placed collection the PARENT root's mtime is in it too: a new parent folder is a new
@@ -482,7 +450,7 @@ export class Store {
482
450
  // vanished folder changes the string as surely as a changed one. A LAYER is the same shape:
483
451
  // `dt update` pulls files into it without moving this workspace's HEAD or any root's mtime.
484
452
  const dirs = this.recordDirs(d);
485
- return `${this.gitHead()}:${dirs.map(dirTreeStamps).join('|')}${this._claimStamps(d)}`;
453
+ return `${this.gitHead()}:${dirs.map(dirTreeStamps).join('|')}`;
486
454
  }
487
455
 
488
456
  /** Refuse a placed write whose path crosses a symlink inside the parent collection's root — a link
@@ -540,10 +508,6 @@ export class Store {
540
508
  // Across every root, write root first. FIRST claimant wins and the rest are left for `check`
541
509
  // to report — the same rule placement follows, for the same reason: a `get` that answered
542
510
  // from whichever layer sorted later would make the answer depend on the clone order.
543
- //
544
- // A STUB yields (records.js resolveClaims): an id two roots claim has its claimants' frontmatter
545
- // read — only those files, never the whole index — and a non-stub answers wherever it sits.
546
- // Only two non-stubs are the duplicate that refuses a write.
547
511
  const claims = new Map();
548
512
  for (const root of this.rootsOf(d)) {
549
513
  for (const [id, f] of this._walkRoot(d, root.abs)) {
@@ -552,17 +516,11 @@ export class Store {
552
516
  }
553
517
  }
554
518
  const dupes = new Map();
555
- const stubs = new Map();
556
519
  for (const [id, files] of claims) {
557
- if (files.length === 1) { ids.set(id, files[0]); continue; }
558
- const { winner, conflicts, shadowed } = resolveClaims(files, (f) => isStubRecord(f, d));
559
- ids.set(id, winner);
560
- if (conflicts.length) dupes.set(id, conflicts);
561
- if (shadowed.length) stubs.set(id, shadowed);
520
+ ids.set(id, files[0]);
521
+ if (files.length > 1) dupes.set(id, files);
562
522
  }
563
523
  this._duplicates.set(d.name, dupes);
564
- this._stubs.set(d.name, stubs);
565
- this._claimFiles.set(d.name, [...claims.values()].filter((f) => f.length > 1).flat());
566
524
  return ids;
567
525
  }
568
526
  if (storageOf(d).shape === 'folder') {
@@ -663,6 +621,27 @@ export class Store {
663
621
  if (where?.parentId) pruneEmptyDirs(root, path.join(this.parentDir(d), where.parentId));
664
622
  }
665
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
+
666
645
  read(collection, id) {
667
646
  const d = this.descriptor(collection);
668
647
  const file = this.ids(collection).get(id);
@@ -737,6 +716,7 @@ export class Store {
737
716
 
738
717
  // restore a record to its content at `hash` — validated like any other write, one commit.
739
718
  revert(collection, id, hash) {
719
+ commitArg(hash);
740
720
  const d = this.writableDescriptor(collection);
741
721
  this.assertUnambiguous(collection, id);
742
722
  const { fields: currentFields, file } = this.read(collection, id);
@@ -749,7 +729,7 @@ export class Store {
749
729
  const relPath = this.pathAt(d, id, hash) ?? path.relative(fileRepo, file).split(path.sep).join('/');
750
730
  let previousContent;
751
731
  try {
752
- previousContent = execFileSync('git', ['show', `${hash}:${relPath}`], { cwd: fileRepo, stdio: QUIET }).toString();
732
+ previousContent = execFileSync('git', ['show', '--end-of-options', `${hash}:${relPath}`], { cwd: fileRepo, stdio: QUIET }).toString();
753
733
  } catch {
754
734
  throw new Error(`${collection}/${id}: no content at ${hash} for ${relPath} — nothing was reverted.`);
755
735
  }
@@ -1033,14 +1013,7 @@ export class Store {
1033
1013
  // `check` would report, and refusing it here is what keeps the id unique across every root.
1034
1014
  const file = this.filePath(d, id, undefined, fields);
1035
1015
  this._assertContained(d, file);
1036
- // An id held ONLY by stubs in other roots is free: this write promotes it, and says so (`shadows`).
1037
- // CONTESTED: another root already claims the id and this one holds no file of it. A stub may be
1038
- // written there — it yields to the record that answers (cr-dt-003) — and so may a record that
1039
- // promotes stubs-only claims; either way it is owed the incoming mirrors no owner write could make.
1040
- const contested = this.layered(d) && !fs.existsSync(file) && this.ids(collection).has(id);
1041
- const shadows = contested ? this._stubOnlyClaims(d, id) : [];
1042
- 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.`);
1043
- 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.`);
1044
1017
  return this.withWriteLock(() => {
1045
1018
  // captured before the invalidation and handed back, one entry richer, on the success path
1046
1019
  // below — see _indexAdd for why an add that throws it away is the expensive shape.
@@ -1078,7 +1051,7 @@ export class Store {
1078
1051
  }, storageOf(d).repo);
1079
1052
  // LAST, after the commit: the key it is re-stated under carries the sha, and `commit` moves it
1080
1053
  this._indexAdd(collection, memo, id, file);
1081
- return { id, file, idFallback, ...(deprecated.length && { deprecated }), ...(shadows.length && { shadows }) };
1054
+ return { id, file, idFallback, ...(deprecated.length && { deprecated }) };
1082
1055
  });
1083
1056
  }
1084
1057
 
@@ -1188,7 +1161,7 @@ export class Store {
1188
1161
  const cwd = path.resolve(this.root, storageOf(d).repo);
1189
1162
  const dirs = this.recordDirs(d).map((p) => path.relative(cwd, p));
1190
1163
  let out = '';
1191
- try { out = execFileSync('git', ['ls-tree', '-r', '--name-only', hash, '--', ...dirs], { cwd, stdio: QUIET }).toString(); } catch { return null; }
1164
+ try { out = execFileSync('git', ['ls-tree', '-r', '--name-only', '--end-of-options', hash, '--', ...dirs], { cwd, stdio: QUIET }).toString(); } catch { return null; }
1192
1165
  const prefix = (storageOf(d).repo) === '.' ? '' : `${storageOf(d).repo}/`;
1193
1166
  for (const p of out.split('\n').filter(Boolean)) {
1194
1167
  const rec = pathToRecord(this.descriptors, prefix + p);
@@ -1197,26 +1170,6 @@ export class Store {
1197
1170
  return null;
1198
1171
  }
1199
1172
 
1200
- /** Every file claiming `id` when ALL of them are stubs, else `[]` — the case where `add` may promote. */
1201
- _stubOnlyClaims(d, id) {
1202
- const files = [this.ids(d.name).get(id), ...this.shadowedStubs(d.name, id)];
1203
- return files.every((f) => isStubRecord(f, d)) ? files : [];
1204
- }
1205
-
1206
- /** The stub files an id's answering record shadows, in root order — `[]` for an id only one root
1207
- * claims. What `dt get --json` reports as `$shadows`, and what `rm` of the winner leaves showing. */
1208
- shadowedStubs(collection, id) {
1209
- this.ids(collection); // ensures the memo is current
1210
- return this._stubs.get(collection)?.get(id) ?? [];
1211
- }
1212
-
1213
- /** Every shadowed stub of a collection, `{ id, file }` — a stub is a real OWNER in its own repo, so
1214
- * the mirrors it justifies there are still expected (check, relations rebuild). */
1215
- *shadowedStubRecords(collection) {
1216
- this.ids(collection);
1217
- for (const [id, files] of this._stubs.get(collection) ?? []) for (const file of files) yield { id, file };
1218
- }
1219
-
1220
1173
  /** Refuse to WRITE to an id that two files claim. The index keeps the first claimant so reads
1221
1174
  * still answer, but a write would land on one copy and leave the other saying something else —
1222
1175
  * the exact ambiguity `check` reports, made worse under a verb that printed ✔. */
@@ -1308,13 +1261,6 @@ export class Store {
1308
1261
  }
1309
1262
  }
1310
1263
 
1311
- // ---- an id a STUB keeps answering does not go away -----------------------------------
1312
- // Removing the record that answers over a stub leaves the id resolving — to the stub. So every
1313
- // reference to it still resolves: nothing is refused for them, nothing is set to null, and
1314
- // nothing is reported dangling. (Its own mirror entries are still detached below.)
1315
- const keepsResolving = this.shadowedStubs(collection, id).length > 0;
1316
- if (keepsResolving) setNullEdits.length = 0;
1317
-
1318
1264
  // ---- what the text scan finds that is NOT the engine's own bookkeeping -------------
1319
1265
  // The scan is per FILE, and one file can name this record TWICE — a mirror the engine wrote, and
1320
1266
  // a wikilink somebody typed in the same record's body. So excluding a file WHOLESALE is wrong:
@@ -1359,7 +1305,7 @@ export class Store {
1359
1305
  // shape, which is what this sentence has always said. What the scan misses (a bare FK, or an
1360
1306
  // owner file excluded because it also holds a mirror of ours) is named as record + field.
1361
1307
  const extraRestrict = restrictHits.filter((h) => !inbound.includes(h.file));
1362
- if ((inbound.length || extraRestrict.length) && !force && !keepsResolving) {
1308
+ if ((inbound.length || extraRestrict.length) && !force) {
1363
1309
  const all = [...inbound, ...extraRestrict.map((h) => `${h.file} (${h.ref}.${h.field})`)];
1364
1310
  throw new Error(`${self} is referenced by:\n${all.map((f) => ` ${f}`).join('\n')}\nfix the references or pass --force. nothing was removed.`);
1365
1311
  }
@@ -1427,7 +1373,7 @@ export class Store {
1427
1373
  // workspace.
1428
1374
  this.commit([unit, ...mirrors.files, ...nullFiles], `dreamteamer: ${collection} rm ${id}`, rollback, this.repoOfFile(d, unit));
1429
1375
  const inboundCount = inbound.length + extraRestrict.length;
1430
- return { id, inboundIgnored: force && !keepsResolving ? inboundCount : 0, ...(keepsResolving ? { inboundResolveToStub: inboundCount } : {}) };
1376
+ return { id, inboundIgnored: force ? inboundCount : 0 };
1431
1377
  });
1432
1378
  }
1433
1379