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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dreamteamer",
3
- "version": "0.44.1",
3
+ "version": "0.46.0",
4
4
  "description": "A workspace compiler for coding agents — schema-validated records as plain files over git, compiled into every harness",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Gilad Khen <giladkhen@gmail.com>",
@@ -56,7 +56,8 @@
56
56
  "command-bindings",
57
57
  "ui-views",
58
58
  "mixins",
59
- "scripts/migrate-descriptors-v2.mjs"
59
+ "scripts/migrate-descriptors-v2.mjs",
60
+ "scripts/migrate-stubs.mjs"
60
61
  ],
61
62
  "dependencies": {
62
63
  "ajv": "^8.17.1",
@@ -0,0 +1,98 @@
1
+ #!/usr/bin/env node
2
+ // migrate-stubs — turn every stub record (`stub: true`, engines 0.41.0–0.44.x) into an entry of its repo's
3
+ // exports manifest, `dreamteamer-exports.json`, and delete the stub (cr-dt-004). Run it once per workspace
4
+ // that holds or reads stubs, on engine 0.45.0, right after `dt compile`:
5
+ //
6
+ // node node_modules/dreamteamer/scripts/migrate-stubs.mjs --root <workspace> [--layers] [--dry-run]
7
+ //
8
+ // --layers also migrates every installed record layer's stubs, from this workspace's view — so an entry
9
+ // gets the live label and holder of a record this workspace reads. Per stub: an entry when a record of its
10
+ // repo names the id, or when this workspace does not read that repo completely (it cannot know, so it never
11
+ // deletes without an entry); label and holder from a non-stub claimant of the id in any root read here,
12
+ // else the stub's own title and no holder; then the repo's manifest is regenerated exactly as `dt exports`
13
+ // would, and ONE commit per repo holds the manifest and the deleted stubs. --dry-run writes nothing.
14
+ import { execFileSync } from 'node:child_process';
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+ import { Store } from '../src/store.js';
18
+ import { parseRecord, idFromRecordPath, walk } from '../src/records.js';
19
+ import { exportsFacts } from '../src/runtime.js';
20
+ import { storageOf, bodyFieldOf, recordTitleOf } from '../src/descriptor.js';
21
+ import { EXPORTS_FILE, readExports, serializeExports, exportsContext, outsideRefs } from '../src/exports.js';
22
+ import { planExports } from '../src/exports-cli.js';
23
+
24
+ // `stub: true` in the FRONTMATTER only — a body quoting a stub is a real record
25
+ const isStubText = (text) => /^stub:\s*true\s*$/m.test(/^---\n([\s\S]*?)\n---(?:\n|$)/.exec(text)?.[1] ?? '');
26
+ const title = (d, fields, id) => String(fields[/\{\{\s*([A-Za-z_][\w]*)/.exec(recordTitleOf(d))?.[1]] ?? id);
27
+
28
+ /** Every record file of `repo` (null: the workspace), per collection: `[{ d, id, file, stub }]`. */
29
+ function filesOf(store, repo) {
30
+ const out = [];
31
+ for (const d of store.descriptors.values()) {
32
+ if (storageOf(d).runtime || storageOf(d).unavailable || storageOf(d).format === 'binary') continue;
33
+ for (const r of store.rootsOf(d)) {
34
+ if ((r.layer ?? null) !== repo || !fs.existsSync(r.abs)) continue;
35
+ for (const file of walk(r.abs)) {
36
+ const id = idFromRecordPath(d, path.relative(r.abs, file).split(path.sep).join('/'));
37
+ if (id !== null) out.push({ d, id, file, stub: isStubText(fs.readFileSync(file, 'utf8')) });
38
+ }
39
+ }
40
+ }
41
+ return out;
42
+ }
43
+
44
+ export function migrate(root, { layers = false, dryRun = false, log = console.log } = {}) {
45
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
46
+ const store = new Store({ root, pkg });
47
+ const facts = exportsFacts(root);
48
+ const ctx = exportsContext({ root, descriptors: store.descriptors, own: facts.own, layers: facts.layers, dataPath: facts.data });
49
+ const repos = [null, ...(layers ? (facts.layers ?? []).filter((l) => fs.existsSync(path.join(root, l.root))).map((l) => l.name) : [])];
50
+ const all = new Map(repos.map((repo) => [repo, filesOf(store, repo)]));
51
+ const report = [];
52
+ for (const repo of repos) {
53
+ const files = all.get(repo);
54
+ const stubs = files.filter((f) => f.stub);
55
+ if (!stubs.length) continue;
56
+ const own = files.filter((f) => !f.stub).map((f) => ({ collection: f.d.name, id: f.id, descriptor: f.d, fields: parseRecord(f.file, f.d, bodyFieldOf(f.d)) }));
57
+ const named = outsideRefs({ records: own, held: () => false, resolve: () => null, namespaces: store.namespaces });
58
+ const complete = ctx.complete(repo);
59
+ const entries = readExports(ctx.rootOf(repo)) ?? {};
60
+ const rows = [];
61
+ for (const s of stubs) {
62
+ const ref = `${s.d.name}/${s.id}`;
63
+ const referrers = named.get(ref)?.referrers ?? [];
64
+ if (!referrers.length && complete) { rows.push({ ref, fate: 'deleted — nothing in its repo references it' }); continue; }
65
+ const real = [...all.values()].flat().find((f) => !f.stub && f.d.name === s.d.name && f.id === s.id);
66
+ const e = real
67
+ ? { label: title(real.d, parseRecord(real.file, real.d, bodyFieldOf(real.d)), s.id), from: ctx.packageOf(store.layerOfFile(real.d, real.file)?.layer ?? null) }
68
+ : { label: title(s.d, parseRecord(s.file, s.d, bodyFieldOf(s.d)), s.id) };
69
+ (entries[s.d.name] ??= {})[s.id] = entries[s.d.name][s.id] ?? e;
70
+ rows.push({ ref, fate: `entry ${JSON.stringify(e)}${referrers.length ? ` — named by ${referrers.slice(0, 3).join(', ')}${referrers.length > 3 ? ` +${referrers.length - 3}` : ''}` : ' — kept: this workspace does not read the repo completely'}` });
71
+ }
72
+ const dir = ctx.rootOf(repo);
73
+ log(`${repo ?? 'this workspace'} · ${stubs.length} stub${stubs.length === 1 ? '' : 's'}${dryRun ? ' (dry run — nothing written)' : ''}`);
74
+ for (const r of rows) log(` ${r.ref} — ${r.fate}`);
75
+ report.push({ repo, rows });
76
+ if (dryRun) continue;
77
+ for (const s of stubs) fs.rmSync(s.file);
78
+ fs.writeFileSync(path.join(dir, EXPORTS_FILE), serializeExports(entries) ?? '{}\n');
79
+ const plan = planExports(new Store({ root, pkg }), repo); // as dt exports would, on the migrated tree
80
+ if (plan.text === null) fs.rmSync(plan.file, { force: true }); else fs.writeFileSync(plan.file, plan.text);
81
+ const git = (args) => execFileSync('git', args, { cwd: dir, stdio: ['ignore', 'pipe', 'pipe'] }).toString().trim();
82
+ // the manifest only when there is one or git tracks one: all-unreferenced stubs leave none to add
83
+ const tracked = git(['ls-files', '--', EXPORTS_FILE]) !== '';
84
+ const paths = [...(tracked || fs.existsSync(path.join(dir, EXPORTS_FILE)) ? [EXPORTS_FILE] : []), ...stubs.map((s) => path.relative(dir, s.file))];
85
+ git(['add', '-A', '--', ...paths]);
86
+ git(['commit', '--only', '-q', '-m', `dreamteamer: migrate ${stubs.length} stub record(s) to ${EXPORTS_FILE}`, '--', ...paths]);
87
+ log(` ✔ committed ${git(['rev-parse', '--short', 'HEAD'])}`);
88
+ }
89
+ if (!report.length) log('no stub records found');
90
+ return report;
91
+ }
92
+
93
+ if (import.meta.url === `file://${process.argv[1]}`) {
94
+ const argv = process.argv.slice(2);
95
+ const at = argv.indexOf('--root');
96
+ try { migrate(path.resolve(at >= 0 ? argv[at + 1] : '.'), { layers: argv.includes('--layers'), dryRun: argv.includes('--dry-run') }); }
97
+ catch (e) { console.error(`✖ ${e.message}`); process.exit(1); }
98
+ }
@@ -66,9 +66,9 @@ dispatch, so it cannot drift):
66
66
 
67
67
  - a collection may be spelled in the SINGULAR on any of these (`dt add task "call the bank"` — one bare positional is the title); references inside records still spell the full name
68
68
  - read & measure — `list` `get` `values` `history` `diff` `next` `relations` `resolve`
69
- - write & publish — `add` `stub` `set` `rm` `rename` `reorder` `revert` `commit` `relocate`
69
+ - write & publish — `add` `set` `rm` `rename` `reorder` `revert` `commit` `relocate`
70
70
  - fields (sources, through the compile gate) — `add-field` `set-field` `rm-field` `rename-field` `rename-value` (system entities — modules, collections, skills, ui-views… — take the RECORD verbs above)
71
- - workspace — `init` `install` `update` `compile` `check` `doctor` `status` `changes` `help`
71
+ - workspace — `init` `install` `update` `compile` `check` `exports` `doctor` `status` `changes` `help`
72
72
  - format descriptor sources (opt-in; block style, canonical key order, through the compile gate) — `fmt`
73
73
  - an EXTENSION (a workspace module or a dependency declaring `dreamteamer.extension`) adds verbs of
74
74
  its own, and `dt help` lists them under its name; each ships the skill that teaches it. A verb core
@@ -266,7 +266,7 @@ Keys are snake_case and closed: compile refuses an unknown one, naming the list.
266
266
  | `vars` | the `.env` keys records may reference as `${env:KEY}` (`records.md`) |
267
267
  | `auto_commit` | whether a record write also commits (default off) |
268
268
  | `harnesses` | which coding-agent adapters compile writes |
269
- | `git_modules` | the lockfile map `dt install` restores into `git_modules/` — `{ url, ref }` per clone; a clone whose own package.json names `workspace_module` is a RECORD LAYER (below), not a bundle, and `records: [<collection>…]` narrows it (or makes any clone a layer) — `module: true` adds its one workspace module |
269
+ | `git_modules` | the lockfile map `dt install` restores into `git_modules/` — `{ url, ref }` per clone; a clone whose own package.json names `workspace_module` is a RECORD LAYER (below), not a bundle, and `records: [<collection>…]` narrows it (or makes any clone a layer) — `module: true` adds its one workspace module; what a clone NEEDS (the holders its `dreamteamer-exports.json` names) is installed here too, once at the top and linked under the clone (0.46.0) |
270
270
  | `disable` | what to drop from the compile: `modules/<id>` (a whole module, its code included) or `<kind>/<id>` (one entity) |
271
271
  | `local_assets` · `postinstall` · `repos_path` · `gitignore_runtime_folder` | links a worktree gets · a script `dt install` runs · where `repos` records materialise · whether `.dreamteamer/` is gitignored |
272
272
 
@@ -444,7 +444,13 @@ HQ reads the projects' records by cloning each project under `git_modules/`:
444
444
  count, never a failure.
445
445
  - **A layer is never a bundle.** Its own `modules/` is not unpacked and it
446
446
  is not an extension; the shapes are the modules both workspaces install. Its nested
447
- `git_modules/` are never read.
447
+ `git_modules/` contribute no sources either — but what it NEEDS is installed here (0.46.0), the
448
+ npm way: the entries of its `git_modules` that provide a package its committed
449
+ `dreamteamer-exports.json` names as a holder, and only those. `dt install` clones each once at this
450
+ workspace's `git_modules/<name>` and links `<clone>/git_modules/<name>` to it; their records are read
451
+ here with the union of every declarer's `records` list, and `dt status` says `· via git_modules/<clone>`.
452
+ Your own declaration overrides a clone's (said in status); two clones that disagree get the second
453
+ copy nested under its declarer; nothing is refused.
448
454
  - **`module: true` also compiles the clone's WORKSPACE module** — `modules/<workspace_module>`, as
449
455
  the clone's own package.json names it — as a module source here, the way a bundle's module
450
456
  compiles: its agents, skills, commands, command-bindings, ui-views, mixins and collections, with a
@@ -460,29 +466,23 @@ HQ reads the projects' records by cloning each project under `git_modules/`:
460
466
  and reference resolution read the union. An id two roots hold is a `check` violation naming both
461
467
  files, and a write to it is refused until one is removed; the first root in order answers reads
462
468
  meanwhile, never silently.
463
- - **A record carrying `stub: true` YIELDS (0.41.0).** A stub is a thin placeholder a workspace keeps
464
- so its own references resolve standalone — a project's copy of a person the HQ holds in full. One
465
- non-stub plus any stubs of one id: the non-stub answers, in whichever root it sits (either
466
- direction), and `check` is clean with an `ℹ` counting the shadowed stubs. Two non-stubs are still
467
- the violation above; stubs only, the first root answers. `stub` is an engine-owned field on every
468
- collection that can be layered (hidden from lists and forms; a module may not declare one), and a stub still carries
469
- its collection's required fields. `dt set` writes the answering record in its own repo; `dt add`
470
- of an id only stubs hold is allowed and prints `shadows N stubs (<layer>…)` — that is how a stub
471
- is promoted; `dt rm` of the answering record says which stub now shows, and is not refused for
472
- references the stub keeps resolving. `dt get --json` carries
473
- `$stub: true` on a stub and `$shadows: [<file>…]` on a record that answers over stubs. A shadowed
474
- stub is still an owner in its own repo, so the mirrors it justifies there are expected by `check`
475
- and kept by `relations rebuild`. Only ids more than one root claims have their files read.
476
- - **A workspace read as a layer stands alone** — it is read WITHOUT its own layers, so a hard
477
- reference its own records make to a record only a layer answers dangles in every reader. `dt check`
478
- names each such target once (`⚠ <target> resolves only through layer <L> — named by N records here
479
- (…) … dt stub <target>`), and an own stub whose mirror only this repo's owners would keep true. `dt
480
- stub <collection>/<id>` fixes the first: it writes a stub here with the fields the schema requires of
481
- that record, `stub: true` and its incoming mirrors (never the body; `--<field> <value>` adds more),
482
- and every later owner write keeps that mirror current; `dt relations rebuild` fixes the second.
483
- `dt add … --stub true` over a layer-held id writes the same way. A `format: binary` target cannot be
484
- a stub: its line names the fix in the referring field instead. `dt check --strict-export` makes both
485
- violations — the gate for a workspace others read.
469
+ - **A workspace read as a layer stands alone, and `dreamteamer-exports.json` is how (0.45.0).** A
470
+ reader reads a layer WITHOUT that layer's own layers, so a reference a repo's records make to an id no
471
+ file of the repo holds — a person the reading HQ keeps, a record only the repo's own layer holds —
472
+ needs proof the id exists elsewhere. `dt exports` writes it: one generated, committed file at the
473
+ repo root listing, per such id, its display name and the package name of the workspace holding it
474
+ (ids and names only; never written by hand). `dt check` reads the manifest of the repo the referring
475
+ record sits in — never a layer's layers — and names a reference no root answers **external**, not
476
+ dangling, when the manifest lists it and its holder is not read here; where the holder IS read and
477
+ lacks the id, the reference is dangling. The live record always wins where it is read. A reference
478
+ this workspace's own records reach only through a layer, unlisted, is a `⚠ … dt exports` line, a
479
+ manifest `dt exports` would change or drop an entry of is named stale, and `dt check
480
+ --strict-export` makes both violations — the gate for a workspace others read. `dt exports --layer
481
+ <name>` writes a layer's manifest from this workspace's view (how a reader records the upward ids a
482
+ layer cannot see), and `dt get <ref> [--referrer <ref>]` names an external id. A conflicted manifest:
483
+ keep the union of both sides' lines, then `dt exports`. Stub records (0.41.0–0.44.x) are gone:
484
+ `node node_modules/dreamteamer/scripts/migrate-stubs.mjs --root . [--layers] [--dry-run]` turns each
485
+ into a manifest entry.
486
486
  - **A new record goes to the write root** (`storage.path` — this workspace, or the owning module's
487
487
  clone for `storage.owner: module`). **An edit or removal of a layer's record lands in place** and
488
488
  commits in the layer's repo; `dt commit` samples every layer and publishes one commit per repo.
package/src/check.js CHANGED
@@ -2,20 +2,20 @@
2
2
  // report-only: JSON Schema (ajv), id patterns, reference resolution, stray files, plus any
3
3
  // `extra` violations a caller gathered (extension checks), reported after the schema's — an item marked
4
4
  // `warning` is printed as a warning and never counted. Under `strictExport` a reference this workspace's
5
- // own records reach only through a layer, and an own stub whose mirror only the layer keeps true, are
6
- // violations rather than ⚠ lines: a workspace reading this one without its layers would see them break.
5
+ // own records reach only through a layer is a violation rather than a ⚠ line: a workspace reading this one without its layers would see them break.
7
6
  // NEVER modifies a file. returns the exit code.
8
7
  import fs from 'node:fs';
9
8
  import path from 'node:path';
10
9
  import Ajv from 'ajv';
11
10
  import addFormats from 'ajv-formats';
12
- import { parseRecord, patternRe, fmtAjvError, unknownFields, walk, idFromRecordPath, MAX_RECORD_BYTES, isStubRecord, resolveClaims } from './records.js';
13
- import { NO_RUNTIME, loadDescriptors, runtimeDir, namespaces as compiledNamespaces } from './runtime.js';
11
+ import { parseRecord, patternRe, fmtAjvError, unknownFields, walk, idFromRecordPath, MAX_RECORD_BYTES } from './records.js';
12
+ import { NO_RUNTIME, loadDescriptors, runtimeDir, namespaces as compiledNamespaces, exportsFacts } from './runtime.js';
14
13
  import { parseRef } from './namespace.js';
15
14
  import { relationsOf, expectedMirrors, ownersReadIn } from './relations.js';
15
+ import { collectRefFields, valuesAt, EXPORTS_FILE, readExports, exportsContext, sees, outsideRefs, regenerate, isStale } from './exports.js';
16
16
  import { placementOf, placedRecords, ownerIdOf, symlinkedChildRoots } from './placement.js';
17
17
 
18
- import { storageOf, jsonSchemaOf, fieldsOf, unresolvedPeersOf, bodyFieldOf, targetsOf, isSoft, idsOf } from './descriptor.js';
18
+ import { storageOf, jsonSchemaOf, fieldsOf, unresolvedPeersOf, bodyFieldOf, idsOf, recordTitleOf } from './descriptor.js';
19
19
  export function check({ root }, { extra = [], strictExport = false } = {}) {
20
20
  const RUNTIME = runtimeDir(root);
21
21
  const rel = (p) => path.relative(root, p);
@@ -51,7 +51,6 @@ export function check({ root }, { extra = [], strictExport = false } = {}) {
51
51
  const fileRepo = new Map();
52
52
  const fileLayer = new Map();
53
53
  const layerNotes = new Map(); // layer name -> note, printed once
54
- const shadowedStubs = []; // { name, id, f, repo, layer } — a placeholder another root's real record answers for
55
54
  for (const [name, d] of descriptors) {
56
55
  const ids = new Map();
57
56
  index.set(name, ids);
@@ -105,9 +104,8 @@ export function check({ root }, { extra = [], strictExport = false } = {}) {
105
104
  }
106
105
  continue;
107
106
  }
108
- // every root: the write root, then each record layer. Claimants are GATHERED first and then
109
- // resolved exactly as the store indexes (records.js resolveClaims): a stub yields to a non-stub
110
- // wherever it sits, and only a second non-stub is the duplicate reported above.
107
+ // every root: the write root, then each record layer. Claimants are GATHERED first, in root order:
108
+ // the first answers, exactly as the store indexes, and every other is the duplicate reported above.
111
109
  const offers = new Map(); // id -> [{ f, repo, layer }], root order
112
110
  const offer = (id, f, repo, layer) => { const o = offers.get(id); if (o) o.push({ f, repo, layer }); else offers.set(id, [{ f, repo, layer }]); };
113
111
  for (const r of storageOf(d).roots) {
@@ -149,10 +147,8 @@ export function check({ root }, { extra = [], strictExport = false } = {}) {
149
147
  const allowed = storageOf(d).accept; // undefined = any
150
148
  const max = storageOf(d).max_bytes ?? MAX_RECORD_BYTES;
151
149
  for (const [id, list] of offers) {
152
- const { winner, conflicts, shadowed } = resolveClaims(list, (c) => isStubRecord(c.f, d));
153
- claim(id, winner.f, winner.repo, winner.layer);
154
- for (const c of conflicts.slice(1)) claim(id, c.f, c.repo, c.layer); // reported as the duplicate
155
- for (const c of shadowed) shadowedStubs.push({ name, id, ...c });
150
+ const [winner] = list;
151
+ for (const c of list) claim(id, c.f, c.repo, c.layer); // the second and later are reported as duplicates
156
152
  if (!opaque) continue;
157
153
  const f = winner.f;
158
154
  const ext = path.extname(f).slice(1).toLowerCase();
@@ -172,12 +168,18 @@ export function check({ root }, { extra = [], strictExport = false } = {}) {
172
168
  // parsed fields, kept for the relations pass below (parse each record exactly once)
173
169
  const parsed = new Map();
174
170
  // cr-dt-003: what a reader of this workspace (without its layers) would see break — a target only a
175
- // layer answers and no root here claims, even as a stub; and an own stub whose mirror is stale
176
- const heldHere = new Set(shadowedStubs.filter((s) => !s.layer).map((s) => `${s.name}/${s.id}`));
171
+ // layer answers
177
172
  const layerOnly = new Map(); // target -> { layer, binary, refs: [{ file, field, value, referrer }] }
178
- const ownStubFields = new Map();
179
- const staleStubs = [];
180
173
  const softRefs = new Map(); // absent-but-declared peer collection -> how many refs point at it
174
+ // cr-dt-004: each repo's exports manifest (the write root is `null`), and the references it vouches for
175
+ const facts = exportsFacts(root);
176
+ const ctx = exportsContext({ root, descriptors, own: facts.own, layers: facts.layers, dataPath: facts.data });
177
+ const manifests = new Map();
178
+ for (const repo of [null, ...(facts.layers ?? []).map((l) => l.name)]) {
179
+ try { const m = readExports(ctx.rootOf(repo)); if (m) manifests.set(repo, m); }
180
+ catch (e) { violations.push({ file: rel(path.join(ctx.rootOf(repo), EXPORTS_FILE)), layer: repo ?? undefined, msg: e.message }); }
181
+ }
182
+ const external = new Map(); // repo -> { refs, targets: Set }
181
183
 
182
184
  for (const [name, d] of descriptors) {
183
185
  const validate = ajv.compile(jsonSchemaOf(d));
@@ -186,14 +188,9 @@ export function check({ root }, { extra = [], strictExport = false } = {}) {
186
188
  const bodyField = bodyFieldOf(d);
187
189
  parsed.set(name, new Map());
188
190
 
189
- // a stub THIS workspace holds is validated here even while a layer's record answers its id: no
190
- // other workspace reads that file, and it must stand on its own the moment the layer's record goes.
191
- // (A layer's shadowed stub is its own workspace's to validate.)
192
- const ownStubs = shadowedStubs.filter((x) => x.name === name && !x.layer).map((x) => [x.id, x.f, true]);
193
191
  // only a referrer a reader can read counts: its collection can be layered at all (D11)
194
- const exportable = Boolean(fieldsOf(d).stub);
195
- for (const [id, file, shadow] of [...[...index.get(name)].map(([i, f]) => [i, f, false]), ...ownStubs]) {
196
- if (shadow) fileRepo.set(file, storageOf(d).repo);
192
+ const exportable = d.compiled?.layerable === true;
193
+ for (const [id, file] of index.get(name)) {
197
194
  if (idsOf(d).pattern && !patternRe(idsOf(d).pattern).test(id)) {
198
195
  flag(file, `id "${id}" does not match pattern ${idsOf(d).pattern}`);
199
196
  }
@@ -241,8 +238,7 @@ export function check({ root }, { extra = [], strictExport = false } = {}) {
241
238
  flag(file, `placed ${where} but ${should} — the file is not where its owner puts it. Run: dreamteamer relocate ${name}/${id}`);
242
239
  }
243
240
  }
244
- if (!shadow) parsed.get(name).set(id, fields);
245
- else ownStubFields.set(`${name}/${id}`, fields);
241
+ parsed.get(name).set(id, fields);
246
242
  }
247
243
  // descriptor v2: `unique: true` on a scalar field — the second record holding a value is the
248
244
  // one reported, naming the first. Null and absent never claim.
@@ -268,13 +264,9 @@ export function check({ root }, { extra = [], strictExport = false } = {}) {
268
264
  const owners = [...(parsed.get(relation.owner) ?? [])].map(([id, fields]) => ({ id, fields, repo: fileRepo.get(index.get(relation.owner).get(id)) }));
269
265
  // PER REPO: a mirror is kept only between records of one repo (store.js applyMirrorEdits), so
270
266
  // the expectation on a target is computed from the owners in ITS repo — an owner in this
271
- // workspace naming a target a layer holds is not a link the layer's own check could see. A
272
- // shadowed STUB is still an owner in its own repo: the mirrors it justifies there are expected.
273
- const stubOwners = shadowedStubs.filter((s) => s.name === relation.owner).flatMap((s) => {
274
- try { return [{ id: s.id, fields: parseRecord(s.f, descriptors.get(s.name), bodyFieldOf(descriptors.get(s.name))), repo: s.repo }]; } catch { return []; }
275
- });
267
+ // workspace naming a target a layer holds is not a link the layer's own check could see.
276
268
  const byRepo = new Map();
277
- for (const o of [...owners, ...stubOwners]) { if (!byRepo.has(o.repo)) byRepo.set(o.repo, []); byRepo.get(o.repo).push(o); }
269
+ for (const o of owners) { if (!byRepo.has(o.repo)) byRepo.set(o.repo, []); byRepo.get(o.repo).push(o); }
278
270
  const expByRepo = new Map([...byRepo].map(([r, os]) => [r, expectedMirrors(relation, os)]));
279
271
 
280
272
  // a unique owner reference is one-to-one, so two owners naming one target is a conflict the mirror
@@ -299,11 +291,6 @@ export function check({ root }, { extra = [], strictExport = false } = {}) {
299
291
  const expected = expByRepo.get(fileRepo.get(index.get(relation.target).get(id)))?.get(id);
300
292
  if (!sameMirror(relation, fields?.[relation.mirror], expected)) flag(index.get(relation.target).get(id), `${relation.mirror}: stale — run: dreamteamer relations rebuild ${relation.target}`);
301
293
  }
302
- // an own stub a layer shadows: its mirror is what THIS repo's owners imply (D6) — alone, it is read
303
- for (const s of shadowedStubs) {
304
- const fields = !s.layer && s.name === relation.target && ownStubFields.get(`${s.name}/${s.id}`);
305
- if (fields && !sameMirror(relation, fields[relation.mirror], expByRepo.get(s.repo)?.get(s.id))) staleStubs.push({ file: rel(s.f), relation });
306
- }
307
294
  }
308
295
 
309
296
  function checkRef(file, fieldPath, value, targets, softTargets, soft = false, referrer = null) {
@@ -334,10 +321,18 @@ export function check({ root }, { extra = [], strictExport = false } = {}) {
334
321
  if (!index.get(coll).has(id)) {
335
322
  if (soft) return; // resolve if present, ignore if absent
336
323
  if (storageOf(descriptors.get(coll)).unavailable) return; // the collection is unread here, not empty
337
- return flag(file, `${fieldPath.join('.')}: dangling reference "${value}" — no such record`);
324
+ // listed by the referring record's OWN repo, its holder not read here: external (cr-dt-004)
325
+ const repo = fileLayer.get(file) ?? null;
326
+ const e = manifests.get(repo)?.[coll]?.[id];
327
+ if (e && !sees(e, coll, ctx)) {
328
+ const x = external.get(repo) ?? external.set(repo, { refs: 0, targets: new Set() }).get(repo);
329
+ x.refs++; x.targets.add(`${coll}/${id}`);
330
+ return;
331
+ }
332
+ return flag(file, `${fieldPath.join('.')}: dangling reference "${value}" — no such record${e ? ` (its holder ${e.from} is read here and does not have it)` : ''}`);
338
333
  }
339
334
  const at = index.get(coll).get(id);
340
- if (!referrer || soft || !fileLayer.has(at) || heldHere.has(`${coll}/${id}`)) return;
335
+ if (!referrer || soft || !fileLayer.has(at) || manifests.get(null)?.[coll]?.[id]) return;
341
336
  const key = `${coll}/${id}`;
342
337
  if (!layerOnly.has(key)) layerOnly.set(key, { layer: fileLayer.get(at), binary: storageOf(descriptors.get(coll)).format === 'binary', refs: [] });
343
338
  layerOnly.get(key).refs.push({ file, field: fieldPath.join('.'), value, referrer });
@@ -352,26 +347,39 @@ export function check({ root }, { extra = [], strictExport = false } = {}) {
352
347
  }
353
348
  for (const note of layerNotes.values()) console.log(note);
354
349
  const upTo3 = (xs) => (xs.length > 3 ? [...xs.slice(0, 3), `+${xs.length - 3} more`] : xs).join(', ');
350
+ for (const [repo, { refs, targets }] of external) {
351
+ console.log(`ℹ ${repo ? `layer ${repo}: ` : ''}${refs} reference${refs === 1 ? '' : 's'} to ${targets.size} record${targets.size === 1 ? '' : 's'} outside ${repo ? 'it' : 'this workspace'}, vouched for by its exports manifest (${upTo3([...targets].sort())})`);
352
+ }
353
+ // a manifest is stale exactly when `dt exports` here would change or drop one of its entries
354
+ for (const [repo, current] of manifests) {
355
+ const repoOf = (c, id) => { const f = index.get(c)?.get(id); return f ? fileLayer.get(f) ?? null : undefined; };
356
+ const records = [...parsed].flatMap(([c, m]) => [...m].filter(([id]) => repoOf(c, id) === repo).map(([id, fields]) => ({ collection: c, id, fields, descriptor: descriptors.get(c) })));
357
+ const resolve = (c, id) => {
358
+ if (repoOf(c, id) === undefined) return null;
359
+ const t = /\{\{\s*([A-Za-z_][\w]*)/.exec(recordTitleOf(descriptors.get(c)))?.[1];
360
+ return { label: String(parsed.get(c)?.get(id)?.[t] ?? id), from: ctx.packageOf(repoOf(c, id)) };
361
+ };
362
+ const outside = outsideRefs({ records, held: (c, id) => repoOf(c, id) === repo, resolve, namespaces });
363
+ const { changes } = regenerate({ current, outside, ctx, repo, held: (c, id) => repoOf(c, id) === repo });
364
+ if (!isStale(changes)) continue;
365
+ const stale = changes.filter((x) => x.kind !== 'add');
366
+ const msg = `stale — ${upTo3(stale.map((x) => `${x.ref} (${x.kind}: ${x.why})`))}. dt exports${repo ? ` --layer ${repo}` : ''}`;
367
+ if (strictExport && !repo) violations.push({ file: rel(path.join(root, EXPORTS_FILE)), msg });
368
+ else console.log(`⚠ ${rel(path.join(ctx.rootOf(repo), EXPORTS_FILE))} is ${msg}`);
369
+ }
355
370
  for (const [target, { layer, binary, refs }] of [...layerOnly].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
356
- const fix = (r) => (binary
357
- ? `a file record cannot be a stub: clear or repoint the field here (dt set ${r.referrer} ${r.field}=), hold the file in this workspace instead of the layer, or make the field soft: true`
358
- : `a workspace reading this one sees it dangle. dt stub ${target}`);
371
+ const fix = () => 'a workspace reading this one sees it dangle. dt exports';
359
372
  if (strictExport) { for (const r of refs) violations.push({ file: rel(r.file), msg: `${r.field}: "${r.value}" resolves only through layer ${layer} — ${fix(r)}` }); continue; }
360
373
  const who = [...new Set(refs.map((r) => r.referrer))];
361
- const named = binary ? upTo3(refs.map((r) => `${r.referrer}.${r.field}`)) : `${who.length} record${who.length === 1 ? '' : 's'} here (${upTo3(who)})`;
374
+ const named = `${who.length} record${who.length === 1 ? '' : 's'} here (${upTo3(who)})`;
362
375
  console.log(`⚠ ${target} resolves only through layer ${layer} — named by ${named}; ${fix(refs[0])}`);
363
376
  }
364
- for (const { file, relation: { mirror, target } } of staleStubs) {
365
- if (strictExport) violations.push({ file, msg: `${mirror}: stale — a stub a layer shadows, and alone it would fail check. run: dreamteamer relations rebuild ${target}` });
366
- else console.log(`⚠ ${file} is a stub a layer shadows, and its ${mirror} mirror is stale — alone it would fail check. dt relations rebuild ${target}`);
367
- }
368
377
  // Warned, never silent: the references are real and currently resolve to nothing. This is the
369
378
  // expected reading when a module is opened without the workspace that provides the concept.
370
379
  for (const [coll, n] of [...softRefs].sort()) {
371
380
  console.log(`⚠ peer collection "${coll}" is declared but not installed — ${n} reference${n === 1 ? '' : 's'} unresolvable`);
372
381
  }
373
382
  for (const w of extra.filter((v) => v.warning)) console.log(`⚠ ${w.file} — ${w.msg}`);
374
- if (shadowedStubs.length) console.log(`ℹ ${shadowedStubs.length} stub record${shadowedStubs.length === 1 ? '' : 's'} shadowed by a real record of ${shadowedStubs.length === 1 ? 'its' : 'their'} id`);
375
383
  if (violations.length === 0) {
376
384
  console.log(`✔ 0 violations (${[...index.values()].reduce((n, m) => n + m.size, 0)} records across ${descriptors.size} collections)`);
377
385
  return 0;
@@ -407,30 +415,3 @@ function sameMirror(relation, actual, expected) {
407
415
  ? (actual ?? null) === (expected ?? null)
408
416
  : JSON.stringify([...(actual ?? [])].sort()) === JSON.stringify(expected ?? []);
409
417
  }
410
-
411
- // collect [fieldPath, targets, soft] for every reference field, nested object fields included, where
412
- // `targets` is '*' or the list of collections it may target and `soft` says whether an absent target
413
- // is a finding. Relations are NOT read here — they are decoded once, by src/relations.js.
414
- function collectRefFields(fields, prefix = []) {
415
- const out = [];
416
- for (const [key, f] of Object.entries(fields ?? {})) {
417
- if (!f || typeof f !== 'object') continue;
418
- const p = [...prefix, key];
419
- const targets = targetsOf(f);
420
- if (targets) out.push([p, targets, isSoft(f)]);
421
- if (f.type === 'object' && f.fields) out.push(...collectRefFields(f.fields, p));
422
- }
423
- return out;
424
- }
425
-
426
- // yield all leaf values at a field path (flattening arrays)
427
- function* valuesAt(obj, fieldPath) {
428
- let vals = [obj];
429
- for (const key of fieldPath) {
430
- vals = vals
431
- .flatMap((v) => (Array.isArray(v) ? v : [v]))
432
- .flatMap((v) => (v && typeof v === 'object' ? [v[key]] : []));
433
- }
434
- for (const v of vals.flat(Infinity)) if (v != null) yield v;
435
- }
436
-
package/src/checkout.js CHANGED
@@ -6,6 +6,7 @@ import { execFileSync, spawnSync } from 'node:child_process';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import { staleness, compile, discoverModules } from './compile.js';
8
8
  import { install as restoreGitModules, offRef } from './init.js';
9
+ import { declaredGitModules } from './workspace.js';
9
10
 
10
11
  export const defaultGit = (args, cwd) => {
11
12
  try {
@@ -138,8 +139,13 @@ export function observeState(ws) {
138
139
  // ⚠ THE MISSING clones and the ones off their declared ref, not every declared one. A settled
139
140
  // worktree would otherwise print `▶ git modules: …` for ever, and this is the step whose result
140
141
  // nobody looks at — so the narrowing here is what makes the empty case mean "nothing to do".
141
- gitModules: Object.entries(ws.pkg.dreamteamer?.git_modules ?? {})
142
- .filter(([n, m]) => !resolves(here(path.join('git_modules', n))) || offRef(here(path.join('git_modules', n)), m?.ref ?? 'main')).map(([n]) => n),
142
+ // … and the ones a clone on disk NEEDS (`declaredGitModules`): missing, off their ref, nothing yet under
143
+ // a declarer (a clone of its own there is satisfied), or a nested copy missing or off its ref. Before
144
+ // the first install only this workspace's own are visible.
145
+ gitModules: [...new Set([
146
+ ...[...declaredGitModules(ws.pkg, ws.root).map].filter(([n, m]) => !resolves(here(path.join('git_modules', n))) || offRef(here(path.join('git_modules', n)), m.ref) || m.declarers.some((by) => by && !resolves(here(path.join(by, 'git_modules', n))))).map(([n]) => n),
147
+ ...declaredGitModules(ws.pkg, ws.root).nested.filter((c) => !resolves(here(path.join(c.by, 'git_modules', c.name))) || offRef(here(path.join(c.by, 'git_modules', c.name)), c.ref)).map((c) => c.name),
148
+ ])],
143
149
  stale: !s.compiled || s.stale.length > 0,
144
150
  postinstall: ws.pkg.dreamteamer?.postinstall ?? null,
145
151
  };
package/src/cli.js CHANGED
@@ -9,6 +9,7 @@
9
9
  //
10
10
  // This file TRANSLATES; it does not implement. Every record and schema verb lands on
11
11
  // `collectionCommand(ws, collection, verb, args)`, whose signature is unchanged.
12
+ import { runExports } from './exports-cli.js';
12
13
  import fs from 'node:fs';
13
14
  import path from 'node:path';
14
15
  import { execFileSync } from 'node:child_process';
@@ -20,6 +21,8 @@ import { collectionCommand, emit, relationsCommand, reportCommits } from './coll
20
21
  import { formatDescriptors } from './schema-ops.js';
21
22
  import { init, installClone, update, listRepos } from './init.js';
22
23
  import { installCommand, describeCheckout } from './checkout.js';
24
+ import { declaredGitModules } from './workspace.js';
25
+ const isOwnClone = (p) => { try { return !fs.lstatSync(p).isSymbolicLink() && fs.existsSync(path.join(p, '.git')); } catch { return false; } };
23
26
  import { foldChanges, groupChanges, reportLine } from './events.js';
24
27
  import { commitPending, recordChanges, rowChanges } from './commit.js';
25
28
  import { Store } from './store.js';
@@ -61,13 +64,8 @@ the longest DECLARED collection prefix, so finance/transactions/2026/03/coffee i
61
64
  get <collection>/<id> [--json] (--json, and each list --json row, adds $file and
62
65
  $repo: where the record is read from and the repo
63
66
  that commits it — null outside every repo here)
64
- stub <collection>/<id> [--<field> <value> …] [--json]
65
- (a placeholder of a record only a layer holds, in
66
- THIS workspace: the fields its schema requires,
67
- stub: true and its mirrors — never the body. It
68
- yields to the layer's record wherever both are read,
69
- and answers where the layer is not — so this
70
- workspace, read as a layer, stands alone)
67
+ [--referrer <collection>/<id>] an id no root holds is
68
+ named from the referrer's repo's exports manifest
71
69
  add <collection> ["<title>"] --<field> <value> … [--id <explicit-id>]
72
70
  (ONE bare positional fills the collection's title
73
71
  field — the one its record_title opens with — so
@@ -236,7 +234,12 @@ workspace verbs:
236
234
  check validate every record against the compiled descriptors (report-only), then every
237
235
  installed extension's own checks. A reference this workspace's own records reach only
238
236
  through a record layer is a ⚠ line (a reader without that layer sees it dangle)
239
- [--strict-export] makes each one, and each stale own stub, a violation
237
+ through a record layer is a ⚠ line until its exports manifest lists it; a reference no root
238
+ answers is external when the referring repo's manifest vouches for it
239
+ [--strict-export] makes each unlisted one, and a stale manifest, a violation
240
+ exports write this workspace's dreamteamer-exports.json — each id its records name that no file
241
+ here holds, with its label and the workspace holding it — and commit that one file
242
+ [--layer <name>] that layer's, from this workspace's view [--dry-run] [--json]
240
243
  doctor what works on this machine — the engine, then each extension's checks — as one board:
241
244
  READY / DEGRADED / UNAVAILABLE, each fix on its row. Exit 0 [--strict] exit 1 when
242
245
  anything is UNAVAILABLE [--json]
@@ -266,7 +269,7 @@ extension verbs — an extension (a workspace module, or a dependency, whose pac
266
269
  // caps one of its lists and not the next reads as a bug in whichever list ran long.
267
270
  const ROWS_SHOWN = 20;
268
271
 
269
- const REF_VERBS = new Set(['get', 'stub', 'set', 'rm', 'rename', 'history', 'diff', 'revert']);
272
+ const REF_VERBS = new Set(['get', 'set', 'rm', 'rename', 'history', 'diff', 'revert']);
270
273
  const COLLECTION_VERBS = new Set(['list', 'add', 'values']);
271
274
  const EITHER_VERBS = new Set(['reorder', 'next']);
272
275
 
@@ -294,7 +297,7 @@ export const GLOBAL_FLAGS = ['workspace', 'vault'];
294
297
  export const WORKSPACE_FLAGS = {
295
298
  init: ['name', 'data_path', 'harnesses', 'workspace_module'], update: [],
296
299
  install: ['clone', 'dry-run', 'json', 'link-env', 'all', 'hook', 'print-adapters'],
297
- compile: ['watch'], check: ['strict-export'], status: [], doctor: ['strict', 'json'],
300
+ compile: ['watch'], check: ['strict-export'], exports: ['layer', 'dry-run', 'json'], status: [], doctor: ['strict', 'json'],
298
301
  changes: ['since', 'json'], commit: ['dry-run', 'json'], fmt: ['dry-run'], relocate: ['dry-run', 'json', 'to-root'],
299
302
  };
300
303
 
@@ -302,8 +305,8 @@ export const WORKSPACE_FLAGS = {
302
305
  * spellings are in it too: they answer with their replacement, and an extension taking one over
303
306
  * would turn a loud translation into a different command. */
304
307
  export const CORE_VERBS = [
305
- 'init', 'install', 'update', 'compile', 'check', 'doctor', 'status', 'changes', 'commit', 'help', 'version', '--version', '-v',
306
- 'list', 'add', 'values', 'get', 'stub', 'set', 'rm', 'rename', 'history', 'diff', 'revert', 'reorder', 'next',
308
+ 'init', 'install', 'update', 'compile', 'check', 'exports', 'doctor', 'status', 'changes', 'commit', 'help', 'version', '--version', '-v',
309
+ 'list', 'add', 'values', 'get', 'set', 'rm', 'rename', 'history', 'diff', 'revert', 'reorder', 'next',
307
310
  'add-field', 'set-field', 'rm-field', 'rename-field', 'rename-value', 'relations', 'resolve', 'relocate', 'fmt',
308
311
  'schema', 'ensure', 'update-field', 'remove-field', 'commands',
309
312
  ];
@@ -430,6 +433,10 @@ export async function run(argv) {
430
433
  }
431
434
  case 'check':
432
435
  process.exit(check(ws, { extra: warnIfStale(ws.root).compiled ? await api.contributedViolations(ws) : [], strictExport: rest.includes('--strict-export') }));
436
+ case 'exports': {
437
+ const layers = rest.flatMap((a, i) => (a === '--layer' ? [rest[i + 1]] : a.startsWith('--layer=') ? [a.slice(8)] : [])).filter(Boolean);
438
+ process.exit(runExports(new Store(ws), { layers, dryRun: rest.includes('--dry-run'), json: rest.includes('--json') }));
439
+ }
433
440
  case 'doctor': {
434
441
  const caps = await doctorBoard(ws, api);
435
442
  if (rest.includes('--json')) emit(JSON.stringify({ capabilities: caps }, null, 2));
@@ -563,12 +570,22 @@ export async function run(argv) {
563
570
  console.log('layers:');
564
571
  let descriptors = [];
565
572
  try { descriptors = [...new Store(ws).descriptors.values()]; } catch { /* no runtime yet */ }
573
+ // a layer a clone needed says so (`via`); one this workspace's declaration overrides says whom; a
574
+ // copy nested under a clone, or a clone of its own where a link would be, is drawn under its clone
575
+ const declared = declaredGitModules(ws.pkg, ws.root);
576
+ const under = (by) => [
577
+ ...declared.nested.filter((c) => c.by === by).map((c) => { const d = path.join(ws.root, by, 'git_modules', c.name); return ` ↳ ${c.name} nested @ ${tryGit(d, ['rev-parse', '--short', 'HEAD']) ?? '?'} — ${c.url} (${c.ref}); git_modules/${c.name} is ${c.top.url} (${c.top.ref})`; }),
578
+ ...[...declared.map].filter(([n, m]) => m.declarers.includes(by) && isOwnClone(path.join(ws.root, by, 'git_modules', n))).map(([n]) => ` ↳ ${n} its own clone @ ${tryGit(path.join(ws.root, by, 'git_modules', n), ['rev-parse', '--short', 'HEAD']) ?? '?'}, not a link to git_modules/${n}`),
579
+ ];
566
580
  for (const l of layers) {
581
+ const over = declared.mismatches.filter((m) => m.name === l.name);
582
+ const asked = over.length ? ` · overrides ${over.map((m) => `${m.by} (${m.what} ${m.theirs})`).join(', ')}` : l.via.length ? ` · via ${l.via.join(', ')}` : '';
567
583
  const dir = path.join(ws.root, 'git_modules', l.name);
568
584
  const ref = fs.existsSync(dir) ? tryGit(dir, ['rev-parse', '--short', 'HEAD']) : null;
569
585
  const mod = l.module ? modules.find((m) => m.layer === l.name) : null;
570
586
  const found = descriptors.filter((d) => storageOf(d).roots.some((r) => r.layer === l.name && fs.existsSync(path.join(ws.root, r.path)))).map((d) => d.name).sort();
571
- console.log(` ${l.name.padEnd(20)} ${ref ? `git_modules @ ${ref}${tryGit(dir, ['status', '--porcelain']) ? ' (dirty)' : ''}` : 'not installed — dreamteamer install'} · records: ${found.join(', ') || '(none found)'}${l.module ? ` · module ${mod ? moduleIdOf(mod.name) : '-'}` : ''}`);
587
+ console.log(` ${l.name.padEnd(20)} ${ref ? `git_modules @ ${ref}${tryGit(dir, ['status', '--porcelain']) ? ' (dirty)' : ''}` : 'not installed — dreamteamer install'} · records: ${found.join(', ') || '(none found)'}${l.module ? ` · module ${mod ? moduleIdOf(mod.name) : '-'}` : ''}${asked}`);
588
+ for (const line of under(`git_modules/${l.name}`)) console.log(line);
572
589
  }
573
590
  }
574
591
  // env-pointed roots (`storage.path: ${env:NAME}/…`), rendered per machine by compile: the
@@ -628,7 +645,7 @@ export async function run(argv) {
628
645
  emit(USAGE);
629
646
  process.exit(0);
630
647
  case 'list': case 'add': case 'values':
631
- case 'get': case 'stub': case 'set': case 'rm': case 'rename': case 'history': case 'diff': case 'revert':
648
+ case 'get': case 'set': case 'rm': case 'rename': case 'history': case 'diff': case 'revert':
632
649
  case 'reorder': case 'next': {
633
650
  warnIfStale(ws.root);
634
651
  process.exit(dispatchRecordVerb(ws, cmd, rest));