dreamteamer 0.40.0 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/check.js CHANGED
@@ -6,7 +6,7 @@ import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import Ajv from 'ajv';
8
8
  import addFormats from 'ajv-formats';
9
- import { parseRecord, patternRe, fmtAjvError, unknownFields, walk, idFromRecordPath, MAX_RECORD_BYTES } from './records.js';
9
+ import { parseRecord, patternRe, fmtAjvError, unknownFields, walk, idFromRecordPath, MAX_RECORD_BYTES, isStubRecord, resolveClaims } from './records.js';
10
10
  import { NO_RUNTIME, loadDescriptors, runtimeDir, namespaces as compiledNamespaces } from './runtime.js';
11
11
  import { parseRef } from './namespace.js';
12
12
  import { relationsOf, expectedMirrors, ownersReadIn } from './relations.js';
@@ -48,6 +48,7 @@ export function check({ root }, { extra = [] } = {}) {
48
48
  const fileRepo = new Map();
49
49
  const fileLayer = new Map();
50
50
  const layerNotes = new Map(); // layer name -> note, printed once
51
+ const shadowedStubs = []; // { name, id, f, repo, layer } — a placeholder another root's real record answers for
51
52
  for (const [name, d] of descriptors) {
52
53
  const ids = new Map();
53
54
  index.set(name, ids);
@@ -101,8 +102,11 @@ export function check({ root }, { extra = [] } = {}) {
101
102
  }
102
103
  continue;
103
104
  }
104
- // every root: the write root, then each record layer — first claimant keeps the id, exactly as
105
- // the store indexes, and a later claimant is the duplicate reported above
105
+ // every root: the write root, then each record layer. Claimants are GATHERED first and then
106
+ // resolved exactly as the store indexes (records.js resolveClaims): a stub yields to a non-stub
107
+ // wherever it sits, and only a second non-stub is the duplicate reported above.
108
+ const offers = new Map(); // id -> [{ f, repo, layer }], root order
109
+ 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 }]); };
106
110
  for (const r of storageOf(d).roots) {
107
111
  const rootDir = r.layer ? path.join(root, r.path) : dir;
108
112
  if (!fs.existsSync(rootDir)) {
@@ -125,29 +129,36 @@ export function check({ root }, { extra = [] } = {}) {
125
129
  continue;
126
130
  }
127
131
  const main = path.join(p, storageOf(d).entry ?? 'SKILL.md');
128
- if (fs.existsSync(main)) claim(entry, main, r.repo, r.layer);
132
+ if (fs.existsSync(main)) offer(entry, main, r.repo, r.layer);
129
133
  else strays.push({ collection: name, file: rel(p), note: `missing entry file ${storageOf(d).entry}` });
130
134
  }
131
135
  continue;
132
136
  }
133
- const opaque = storageOf(d).format === 'binary';
134
- const allowed = storageOf(d).accept; // undefined = any
135
- const max = storageOf(d).max_bytes ?? MAX_RECORD_BYTES;
136
137
  for (const f of walk(rootDir)) {
137
138
  const id = idFromRecordPath(d, path.relative(rootDir, f));
138
139
  if (id === null) { strays.push({ collection: name, file: rel(f) }); continue; }
139
140
  // One id is one file. Under a fixed-extension format this cannot happen within one root;
140
141
  // under `binary` it can, and across roots it is a layer and this workspace disagreeing.
141
- if (!claim(id, f, r.repo, r.layer)) continue;
142
- if (!opaque) continue;
143
- const ext = path.extname(f).slice(1).toLowerCase();
144
- if (allowed && !allowed.includes(ext)) {
145
- violations.push({ file: rel(f), layer: r.layer, msg: `collection "${name}" does not accept .${ext} — its declared extensions are ${allowed.join(', ')}` });
146
- }
147
- const size = fs.statSync(f).size;
148
- if (size > max) {
149
- violations.push({ file: rel(f), layer: r.layer, msg: `is ${size} bytes, over collection "${name}"'s max_bytes of ${max} — a record is a small file; a big one belongs outside the vault` });
150
- }
142
+ offer(id, f, r.repo, r.layer);
143
+ }
144
+ }
145
+ const opaque = storageOf(d).format === 'binary';
146
+ const allowed = storageOf(d).accept; // undefined = any
147
+ const max = storageOf(d).max_bytes ?? MAX_RECORD_BYTES;
148
+ for (const [id, list] of offers) {
149
+ const { winner, conflicts, shadowed } = resolveClaims(list, (c) => isStubRecord(c.f, d));
150
+ claim(id, winner.f, winner.repo, winner.layer);
151
+ for (const c of conflicts.slice(1)) claim(id, c.f, c.repo, c.layer); // reported as the duplicate
152
+ for (const c of shadowed) shadowedStubs.push({ name, id, ...c });
153
+ if (!opaque) continue;
154
+ const f = winner.f;
155
+ const ext = path.extname(f).slice(1).toLowerCase();
156
+ if (allowed && !allowed.includes(ext)) {
157
+ violations.push({ file: rel(f), layer: winner.layer, msg: `collection "${name}" does not accept .${ext} — its declared extensions are ${allowed.join(', ')}` });
158
+ }
159
+ const size = fs.statSync(f).size;
160
+ if (size > max) {
161
+ violations.push({ file: rel(f), layer: winner.layer, msg: `is ${size} bytes, over collection "${name}"'s max_bytes of ${max} — a record is a small file; a big one belongs outside the vault` });
151
162
  }
152
163
  }
153
164
  }
@@ -166,7 +177,12 @@ export function check({ root }, { extra = [] } = {}) {
166
177
  const bodyField = bodyFieldOf(d);
167
178
  parsed.set(name, new Map());
168
179
 
169
- for (const [id, file] of index.get(name)) {
180
+ // a stub THIS workspace holds is validated here even while a layer's record answers its id: no
181
+ // other workspace reads that file, and it must stand on its own the moment the layer's record goes.
182
+ // (A layer's shadowed stub is its own workspace's to validate.)
183
+ const ownStubs = shadowedStubs.filter((x) => x.name === name && !x.layer).map((x) => [x.id, x.f, true]);
184
+ for (const [id, file, shadow] of [...[...index.get(name)].map(([i, f]) => [i, f, false]), ...ownStubs]) {
185
+ if (shadow) fileRepo.set(file, storageOf(d).repo);
170
186
  if (idsOf(d).pattern && !patternRe(idsOf(d).pattern).test(id)) {
171
187
  flag(file, `id "${id}" does not match pattern ${idsOf(d).pattern}`);
172
188
  }
@@ -213,7 +229,7 @@ export function check({ root }, { extra = [] } = {}) {
213
229
  flag(file, `placed ${where} but ${should} — the file is not where its owner puts it. Run: dreamteamer relocate ${name}/${id}`);
214
230
  }
215
231
  }
216
- parsed.get(name).set(id, fields);
232
+ if (!shadow) parsed.get(name).set(id, fields);
217
233
  }
218
234
  // descriptor v2: `unique: true` on a scalar field — the second record holding a value is the
219
235
  // one reported, naming the first. Null and absent never claim.
@@ -236,13 +252,16 @@ export function check({ root }, { extra = [] } = {}) {
236
252
  // therefore mechanical (`relations rebuild`), which is what the message says, rather than a
237
253
  // judgement call about which side is right.
238
254
  for (const relation of relationsOf(descriptors)) {
239
- const owners = [...(parsed.get(relation.owner) ?? [])].map(([id, fields]) => ({ id, fields }));
255
+ const owners = [...(parsed.get(relation.owner) ?? [])].map(([id, fields]) => ({ id, fields, repo: fileRepo.get(index.get(relation.owner).get(id)) }));
240
256
  // PER REPO: a mirror is kept only between records of one repo (store.js applyMirrorEdits), so
241
257
  // the expectation on a target is computed from the owners in ITS repo — an owner in this
242
- // workspace naming a target a layer holds is not a link the layer's own check could see.
243
- const repoOfOwner = (id) => fileRepo.get(index.get(relation.owner).get(id));
258
+ // workspace naming a target a layer holds is not a link the layer's own check could see. A
259
+ // shadowed STUB is still an owner in its own repo: the mirrors it justifies there are expected.
260
+ const stubOwners = shadowedStubs.filter((s) => s.name === relation.owner).flatMap((s) => {
261
+ try { return [{ id: s.id, fields: parseRecord(s.f, descriptors.get(s.name), bodyFieldOf(descriptors.get(s.name))), repo: s.repo }]; } catch { return []; }
262
+ });
244
263
  const byRepo = new Map();
245
- for (const o of owners) { const r = repoOfOwner(o.id); if (!byRepo.has(r)) byRepo.set(r, []); byRepo.get(r).push(o); }
264
+ for (const o of [...owners, ...stubOwners]) { if (!byRepo.has(o.repo)) byRepo.set(o.repo, []); byRepo.get(o.repo).push(o); }
246
265
  const expByRepo = new Map([...byRepo].map(([r, os]) => [r, expectedMirrors(relation, os)]));
247
266
 
248
267
  // a unique owner reference is one-to-one, so two owners naming one target is a conflict the mirror
@@ -318,6 +337,7 @@ export function check({ root }, { extra = [] } = {}) {
318
337
  for (const [coll, n] of [...softRefs].sort()) {
319
338
  console.log(`⚠ peer collection "${coll}" is declared but not installed — ${n} reference${n === 1 ? '' : 's'} unresolvable`);
320
339
  }
340
+ 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`);
321
341
  if (violations.length === 0) {
322
342
  console.log(`✔ 0 violations (${[...index.values()].reduce((n, m) => n + m.size, 0)} records across ${descriptors.size} collections)`);
323
343
  return 0;
package/src/cli.js CHANGED
@@ -14,14 +14,14 @@ import path from 'node:path';
14
14
  import { execFileSync } from 'node:child_process';
15
15
  import * as api from './api.js';
16
16
  import { openWorkspace } from './api.js';
17
- import { compile, staleness, warnIfStale, discoverModules, CHANNEL_LABEL, locationOf, kindsOf, moduleIdOf } from './compile.js';
17
+ import { compile, staleness, warnIfStale, discoverModules, CHANNEL_LABEL, locationOf, kindsOf, moduleIdOf, layerEntries } from './compile.js';
18
18
  import { check } from './check.js';
19
19
  import { collectionCommand, emit, relationsCommand, reportCommits } from './collections-cli.js';
20
20
  import { formatDescriptors } from './schema-ops.js';
21
21
  import { init, installClone, update, listRepos } from './init.js';
22
22
  import { installCommand, describeCheckout } from './checkout.js';
23
- import { deriveEvents } from './events.js';
24
- import { commitPending } from './commit.js';
23
+ import { foldChanges, groupChanges, reportLine } from './events.js';
24
+ import { commitPending, recordChanges, rowChanges } from './commit.js';
25
25
  import { Store } from './store.js';
26
26
  import { splitRef, canonicalCollection } from './ref.js';
27
27
  import { envContext, renderTemplate } from './env-vars.js';
@@ -36,9 +36,13 @@ const QUIET = ['ignore', 'pipe', 'ignore'];
36
36
 
37
37
  export const USAGE = `usage: dreamteamer <verb> [<target>] [flags]
38
38
 
39
- --vault <path> run against another workspace. The path resolves from the directory you typed it
40
- in; every other path in the command resolves inside the target. The working
41
- directory is unchanged.
39
+ --workspace, -w <name|path>
40
+ run the verb in another workspace: a record layer this workspace declares, by
41
+ its git_modules name, or any workspace by path. A path resolves from the
42
+ directory you typed it in; every other path in the command resolves inside the
43
+ target. The working directory is unchanged, and the flag reaches this command
44
+ only: a process it starts resolves its own workspace from its own directory.
45
+ --vault <path> deprecated — the old spelling of --workspace, still honoured.
42
46
 
43
47
  record verbs (hard validation — invalid writes are rejected before disk).
44
48
  A <target> is either a collection name or a <collection>/<id> reference; the reference splits at
@@ -229,13 +233,17 @@ workspace verbs:
229
233
  anything is UNAVAILABLE [--json]
230
234
  status workspace status: compiled runtime freshness, per-module channel/ref, staleness
231
235
 
232
- changes what changed in every repo that holds records, as record events
233
- [--since <sha|YYYY-MM-DD>] (default: HEAD~1 — the last commit's own changes) [--json]
236
+ changes the records created / updated / deleted in every repo that holds records — the
237
+ workspace and each record layer — grouped by collection, each with its path, layer
238
+ and whether it is committed. Its first line is the report a reply ends with
239
+ [--since <sha|YYYY-MM-DD>] (default: HEAD — what is written but not committed;
240
+ a sha or date adds the commits since then, e.g. --since HEAD~1) [--json]
234
241
  commit publish records already written to disk: samples git status over every
235
242
  collection's record dirs, one commit PER REPO, subject composed from the
236
243
  status letters. Scope it with any number of targets, each either a whole
237
244
  <collection> or one <collection>/<id> — the record form is what keeps a
238
- concurrent session's pending records out of your commit.
245
+ concurrent session's pending records out of your commit. Ends with the same
246
+ record report \`changes\` prints, for what it published.
239
247
  [<collection>|<collection>/<id> …] [-m <subject>] [--dry-run] [--json]
240
248
  help this text
241
249
 
@@ -268,10 +276,11 @@ const FIELD_VERBS = ['add-field', 'set-field', 'rm-field', 'rename-field', 'rena
268
276
  //
269
277
  // ⚠ Listing one here EXEMPTS it from the "documented flags are accepted by some verb" guard, which
270
278
  // exists because 0.19.0 shipped a flag that was documented and silently swallowed. The exemption is
271
- // only safe while the behaviour is pinned somewhere else: `--vault` is covered end-to-end in
272
- // test/integration/cross-workspace-targeting.test.js. A global flag with no such file is the exact
273
- // defect that guard was written to catch \u2014 add the coverage, not the entry.
274
- export const GLOBAL_FLAGS = ['vault'];
279
+ // only safe while the behaviour is pinned somewhere else: `--workspace` / `-w` is covered end-to-end in
280
+ // test/integration/workspace-flag.test.js and `--vault` in cross-workspace-targeting.test.js. A global
281
+ // flag with no such file is the exact defect that guard was written to catch \u2014 add the coverage,
282
+ // not the entry.
283
+ export const GLOBAL_FLAGS = ['workspace', 'vault'];
275
284
 
276
285
  export const WORKSPACE_FLAGS = {
277
286
  init: ['name', 'data_path', 'harnesses', 'workspace_module'], update: [],
@@ -298,6 +307,21 @@ const VERB_PACKAGES = {
298
307
  };
299
308
  const DOCKER_VERBS = new Set(['start', 'stop', 'open', 'export', 'import']);
300
309
 
310
+ /** The record-change report: the report line, then one row per record — its change, ref, workspace
311
+ * path (what a reply links to), committed or not, and the layer it landed in — capped like every
312
+ * other listing here. `dt changes` and `dt commit` print it identically, so what a session copies
313
+ * into its reply does not depend on which of the two it ran. */
314
+ function printChanges(changes) {
315
+ const groups = groupChanges(changes);
316
+ console.log(reportLine(groups));
317
+ const rows = groups.flatMap((g) => g.records);
318
+ for (const c of rows.slice(0, ROWS_SHOWN)) {
319
+ const state = c.committed ? `committed${c.sha ? ` ${c.sha}` : ''}` : 'uncommitted';
320
+ console.log(` ${c.change.padEnd(7)} ${c.ref} ${c.path} · ${state}${c.layer ? ` · layer ${c.layer}` : ''}`);
321
+ }
322
+ if (rows.length > ROWS_SHOWN) console.log(` + ${rows.length - ROWS_SHOWN} more — --json lists every record`);
323
+ }
324
+
301
325
  export async function run(argv) {
302
326
  const [cmd, ...rest] = argv;
303
327
  try {
@@ -407,25 +431,23 @@ export async function run(argv) {
407
431
  // record events from git history was the genuinely used half (catch-up — "what happened
408
432
  // while I was away"), while creating run records from triggers was not. Read-only by
409
433
  // construction: no cursor to advance, nothing to store, so it is safe to run twice.
434
+ // Since 0.42.0 its default is the UNCOMMITTED state (`HEAD`), because the question a
435
+ // session asks after a write is "what did I just change" — and its first line is the
436
+ // report line the skill tells a session to end its reply with.
410
437
  case 'changes': {
411
438
  warnIfStale(ws.root);
412
439
  const si = rest.indexOf('--since');
413
- const since = si > -1 ? rest[si + 1] : 'HEAD~1';
414
- const store = new Store(ws);
415
- const events = deriveEvents(ws.root, store.descriptors, since, 'HEAD');
416
- if (rest.includes('--json')) { emit(JSON.stringify({ since, head: 'HEAD', events }, null, 2)); process.exit(0); }
417
- if (!events.length) { console.log(`✔ no record changes since ${since}`); process.exit(0); }
418
- const byCollection = new Map();
419
- for (const e of events) {
420
- if (!byCollection.has(e.collection)) byCollection.set(e.collection, []);
421
- byCollection.get(e.collection).push(e);
422
- }
423
- console.log(`${events.length} record change(s) since ${since}:`);
424
- for (const [c, list] of [...byCollection].sort()) {
425
- const n = (t) => list.filter((e) => e.type === t).length;
426
- console.log(` ${c}: ${n('item-added')} added, ${n('item-updated')} updated, ${n('item-removed')} removed`);
427
- for (const e of list) console.log(` ${e.type.replace('item-', '').padEnd(7)} ${c}/${e.id}`);
440
+ if (si > -1 && (!rest[si + 1] || rest[si + 1].startsWith('-'))) throw new Error('--since needs a commit or a date: dt changes --since <sha|YYYY-MM-DD> (bare `dt changes` is the uncommitted state)');
441
+ const since = si > -1 ? rest[si + 1] : 'HEAD';
442
+ const events = recordChanges(new Store(ws), { since });
443
+ if (rest.includes('--json')) {
444
+ emit(JSON.stringify({ since, head: 'HEAD', events, collections: groupChanges(events).map(({ records, ...g }) => g) }, null, 2));
445
+ process.exit(0);
428
446
  }
447
+ if (!events.length) { console.log(`✔ no record changes since ${since}`); process.exit(0); }
448
+ printChanges(events);
449
+ const open = events.filter((e) => !e.committed).length;
450
+ console.log(`${events.length} record change(s) since ${since} — ${open ? `${open} uncommitted` : 'all committed'}`);
429
451
  process.exit(0);
430
452
  }
431
453
  // the other half of `auto-commit: false` — record writes land on disk uncommitted, and
@@ -442,6 +464,7 @@ export async function run(argv) {
442
464
  const results = commitPending(store, { only, message, dryRun: rest.includes('--dry-run') });
443
465
  if (rest.includes('--json')) { emit(JSON.stringify(results, null, 2)); process.exit(0); }
444
466
  if (!results.some((r) => !r.outside)) console.log('nothing pending');
467
+ const published = [];
445
468
  for (const r of results) {
446
469
  // an env-pointed collection's folder is outside every repo here: kept, never committed, said
447
470
  if (r.outside) { console.log(`· ${r.outside}: ${r.repo} is outside every git repo here (storage.path ${r.template}) — its records are kept on this machine, never committed`); continue; }
@@ -450,8 +473,8 @@ export async function run(argv) {
450
473
  if (r.pending) { console.error(`⚠ ${r.repo}: ${r.rows.length} record(s) left pending — ${r.pending}; run dreamteamer commit again once it is fixed`); continue; }
451
474
  if (r.warning) console.warn(`⚠ ${r.repo}: ${r.warning}`);
452
475
  console.log(`✔ ${r.repo === '.' ? 'workspace' : r.repo}${r.sha ? ` ${r.sha}` : ' (dry run)'} — ${r.subject}`);
453
- for (const row of r.rows.slice(0, ROWS_SHOWN)) console.log(` ${row.verb} ${row.collection}/${row.id}`);
454
- if (r.rows.length > ROWS_SHOWN) console.log(` + ${r.rows.length - ROWS_SHOWN} more`);
476
+ // what this repo published, for the ONE report block printed after every repo
477
+ for (const c of rowChanges(store.descriptors, r.repo, r.rows)) published.push({ ...c, sha: r.sha });
455
478
  // Half a pair was published — name the records that finish it. `dt commit
456
479
  // <collection>` publishes exactly that collection by design, so this is an honest
457
480
  // report of what it left behind, not a failure: HEAD fails `check` until they land.
@@ -481,6 +504,8 @@ export async function run(argv) {
481
504
  console.warn(' (if that refuses as entangled, the refusal names the other pending records — add them to the same command)');
482
505
  }
483
506
  }
507
+ // the same block `dt changes` prints, for what was published — a dry run's rows are uncommitted
508
+ if (published.length) printChanges(foldChanges(published.filter((c) => c.sha), published.filter((c) => !c.sha)));
484
509
  process.exit(results.some((r) => r.blocked || r.failed) ? 1 : 0);
485
510
  }
486
511
  case 'status': {
@@ -521,15 +546,20 @@ export async function run(argv) {
521
546
  if (sh) line += ` — shadows ${CHANNEL_LABEL[sh.loser]} copy`;
522
547
  console.log(line);
523
548
  }
524
- // record layers: other workspaces cloned here for their records (dreamteamer.git_modules.<name>.records)
525
- const layers = Object.entries(ws.pkg.dreamteamer?.git_modules ?? {}).filter(([, e]) => e?.records !== undefined);
549
+ // record layers: other workspaces cloned here for their records. The collections listed are
550
+ // the ones FOUND — compiled with this layer as a root and holding a folder in the clone —
551
+ // never the declared `records:`, which narrows and may name a folder that does not exist.
552
+ const layers = layerEntries(ws.pkg, ws.root);
526
553
  if (layers.length) {
527
554
  console.log('layers:');
528
- for (const [name, e] of layers) {
529
- const dir = path.join(ws.root, 'git_modules', name);
555
+ let descriptors = [];
556
+ try { descriptors = [...new Store(ws).descriptors.values()]; } catch { /* no runtime yet */ }
557
+ for (const l of layers) {
558
+ const dir = path.join(ws.root, 'git_modules', l.name);
530
559
  const ref = fs.existsSync(dir) ? tryGit(dir, ['rev-parse', '--short', 'HEAD']) : null;
531
- const mod = e.module === true ? modules.find((m) => m.layer === name) : null;
532
- console.log(` ${name.padEnd(20)} ${ref ? `git_modules @ ${ref}${tryGit(dir, ['status', '--porcelain']) ? ' (dirty)' : ''}` : 'not installed — dreamteamer install'} · records: ${e.records.join(', ')}${e.module === true ? ` · module ${mod ? moduleIdOf(mod.name) : '-'}` : ''}`);
560
+ const mod = l.module ? modules.find((m) => m.layer === l.name) : null;
561
+ 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();
562
+ 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) : '-'}` : ''}`);
533
563
  }
534
564
  }
535
565
  // env-pointed roots (`storage.path: ${env:NAME}/…`), rendered per machine by compile: the
@@ -567,8 +597,8 @@ export async function run(argv) {
567
597
  for (const r of repos) if (!r.present) console.log(` absent: ${r.id} → ${r.path}${r.unresolved ? ` — ${r.unresolved}` : ` (dreamteamer install repos/${r.id})`}`);
568
598
  }
569
599
  } catch { /* no repos descriptor compiled — nothing to report */ }
570
- // Uncommitted records are invisible to `dt changes` (it diffs commits), so the
571
- // count belongs here — otherwise deferred work accumulates silently.
600
+ // `dt changes` lists the uncommitted records one by one (0.42.0); status keeps the
601
+ // COUNT per repo, so deferred work is visible at a glance here too.
572
602
  try {
573
603
  const pending = commitPending(new Store(ws), { dryRun: true });
574
604
  const total = pending.reduce((n, r) => n + r.rows.length, 0);
@@ -9,7 +9,7 @@ import { Store, bodyField, serialize, atomicWrite } from './store.js';
9
9
  import { load, dump } from './yaml.js';
10
10
  import { slug } from './template.js';
11
11
  import {
12
- createCollection, removeCollection, renameCollection, addField, updateField, removeField, fieldFromFlags, saveUiView, removeUiView,
12
+ createCollection, removeCollection, renameCollection, addField, updateField, removeField, fieldFromFlags, saveUiView, removeUiView, moveUiView,
13
13
  // was copy-pasted here, and the copy went stale the moment the source layout gained a second
14
14
  // spelling — one implementation, two callers
15
15
  workspaceSystemDir,
@@ -20,6 +20,7 @@ import {
20
20
  import { KINDS } from './compile.js';
21
21
  import { history, historyDiff } from './history.js';
22
22
  import { commandsFor, recordResolver } from './record-commands.js';
23
+ import { contributedNotes } from './extensions.js';
23
24
  import { distinctValues } from './field-values.js';
24
25
  import { matchesFilter, unknownTokens, VALUE_TOKENS } from './filter.js';
25
26
  import { baseNameOf, defaultStoragePath } from './namespace.js';
@@ -144,7 +145,9 @@ export function collectionCommand(ws, collection, verb, args) {
144
145
  // descriptor v2: a record older than the `created` stamp still answers it — read, never written
145
146
  const created = store.createdOf(collection, id, fields, file);
146
147
  if (created !== undefined && fields.created === undefined) fields.created = created;
147
- if (flags.json) { emit(JSON.stringify({ ...fields, id, ...whereKeys(store.locationOf(d, file)) }, null, 2)); return 0; }
148
+ // stubs (0.41.0): `$stub` on a placeholder, `$shadows` on whatever answers over placeholders
149
+ const shadows = store.shadowedStubs(collection, id).map((f) => store.locationOf(d, f).file);
150
+ if (flags.json) { emit(JSON.stringify({ ...fields, id, ...whereKeys(store.locationOf(d, file)), ...(fields.stub === true ? { $stub: true } : {}), ...(shadows.length ? { $shadows: shadows } : {}) }, null, 2)); return 0; }
148
151
  console.log(dump(fields).trimEnd());
149
152
  return 0;
150
153
  }
@@ -170,11 +173,13 @@ export function collectionCommand(ws, collection, verb, args) {
170
173
  flags[titleField] = pos[0];
171
174
  }
172
175
  const fields = coerceArrays(d, stripMeta(flags));
173
- const { id, file, idFallback, deprecated } = store.add(collection, fields, { id: flags.id });
176
+ const { id, file, idFallback, deprecated, shadows } = store.add(collection, fields, { id: flags.id });
174
177
  for (const k of deprecated ?? []) console.warn(`⚠ ${k} is deprecated on ${collection} — it still validates, and nothing draws it. Check the collection's description for what replaced it.`);
178
+ // promoting a stub is a choice the operator should see made: name every placeholder it now covers
179
+ const covers = (shadows ?? []).map((f) => store.layerOfFile(d, f)?.layer ?? 'this workspace');
175
180
  flags.json
176
- ? emit(JSON.stringify({ id, path: rel(ws.root, file), ...(idFallback ? { idFallback } : {}) }))
177
- : console.log(`✔ ${at}${rel(ws.root, file)}`);
181
+ ? emit(JSON.stringify({ id, path: rel(ws.root, file), ...(idFallback ? { idFallback } : {}), ...(shadows?.length ? { $shadows: shadows.map((f) => store.locationOf(d, f).file) } : {}) }))
182
+ : console.log(`✔ ${at}${rel(ws.root, file)}${covers.length ? ` — shadows ${covers.length} stub${covers.length === 1 ? '' : 's'} (${covers.join(', ')})` : ''}`);
178
183
  // ⚠ SAY IT, EVERY TIME. The id was derived from a hash because the value it is generated
179
184
  // from carries no a-z0-9 — the write succeeded and the record is fine, but the id is
180
185
  // unreadable and unguessable, and nobody finds that out until they try to type it. By
@@ -235,8 +240,12 @@ export function collectionCommand(ws, collection, verb, args) {
235
240
  const id = need(pos, 0, 'id');
236
241
  if (flags['dry-run']) return dryRunPlan(`rm ${collection}/${id}`, { records: store.ids(collection).has(id) ? 1 : 0, refs: store.findInboundRefs(`${collection}/${id}`).length });
237
242
  const where = store.ids(collection).has(id) ? store.locate(collection, id) : null; // a missing id is store.rm's to refuse
238
- const { inboundIgnored } = store.rm(collection, id, { force: !!flags.force });
239
- flags.json ? emit(JSON.stringify({ id, removed: true, inboundIgnored })) : console.log(`✔ ${at}removed${landedIn(where)}${inboundIgnored ? ` (${inboundIgnored} inbound reference(s) left dangling — run \`dreamteamer check\`)` : ''}`);
243
+ const { inboundIgnored, inboundResolveToStub } = store.rm(collection, id, { force: !!flags.force });
244
+ // the id does not vanish when a stub was shadowed by what was just removed — say which now answers
245
+ const next = store.ids(collection).get(id);
246
+ const showing = next ? store.layerOfFile(d, next) : null;
247
+ const nowShows = next ? `${inboundResolveToStub ? ` — ${inboundResolveToStub} inbound reference(s) now resolve to the stub` : ''}; stub ${showing ? `in layer ${showing.layer}` : 'in this workspace'} now shows (${store.locationOf(d, next).file})` : '';
248
+ flags.json ? emit(JSON.stringify({ id, removed: true, inboundIgnored, ...(next ? { $now: store.locationOf(d, next).file } : {}) })) : console.log(`✔ ${at}removed${landedIn(where)}${inboundIgnored ? ` (${inboundIgnored} inbound reference(s) left dangling — run \`dreamteamer check\`)` : ''}${nowShows}`);
240
249
  return 0;
241
250
  }
242
251
  case 'rename': {
@@ -308,13 +317,17 @@ function metaCommandsFor(ws, store, flags, pos) {
308
317
  const collection = need(pos, 0, 'collection');
309
318
  const ids = (oneValue(flags, 'ids') ?? '').split(',').map((s) => s.trim()).filter(Boolean);
310
319
  const out = commandsFor(store, collection, ids);
311
- if (flags.json) { emit(JSON.stringify(out, null, 2)); return 0; }
312
- if (!out.commands.length) { console.log(`(no commands bound to ${collection})`); return 0; }
320
+ // what an installed extension says about these records (a session holding one, say) — after the
321
+ // commands, because the commands are the answer and a note is context for it
322
+ const notes = contributedNotes(ws, collection, ids);
323
+ if (flags.json) { emit(JSON.stringify({ ...out, notes }, null, 2)); return 0; }
324
+ if (!out.commands.length) console.log(`(no commands bound to ${collection})`);
313
325
  for (const c of out.commands) {
314
326
  if (c.scope === 'collection') { console.log(`${c.name} [collection] ${c.invocation}`); continue; }
315
327
  const counts = ids.length ? ` ${c.eligible.length}/${ids.length} eligible${c.done.length ? `, ${c.done.length} done` : ''}` : ' (no ids given)';
316
328
  console.log(`${c.name} [record]${counts}${c.invocation ? `\n ${c.invocation}` : ''}`);
317
329
  }
330
+ for (const n of notes) console.log(n.error ? `✖ ${n.by}: ${n.text}` : `● ${collection}/${n.id} — ${n.text} (${n.by})`);
318
331
  return 0;
319
332
  }
320
333
 
@@ -509,7 +522,7 @@ function metaCollectionsSet(ws, store, flags, pos) {
509
522
  const out = setCollectionScalars(ws, store, name, changes, { moduleId: undefined });
510
523
  if (flags.json) { emit(JSON.stringify(out)); return 0; }
511
524
  if (out.unchanged) return alreadyThat(`collections/${name} ${out.changed.join(', ')}`);
512
- console.log(`✔ ${rel(ws.root, out.file)} — ${out.changed.join(', ')}`);
525
+ console.log(`✔ ${rel(ws.root, out.file)} — ${out.changed.join(', ')}${out.peer ? `, and declared ${out.peer.collection} as a peer collection of ${out.peer.module}` : ''}`);
513
526
  console.log('✔ compiled — the descriptor is up to date');
514
527
  reportCommits(out.commits);
515
528
  return 0;
@@ -905,6 +918,24 @@ function metaUiView(ws, store, verb, flags, pos) {
905
918
  // that shadows it, which is the same thing saving one in the UI does.
906
919
  let view = {};
907
920
  let id = oneValue(flags, 'id');
921
+ // `module=` on a set is the MOVE, spelled as it is for a collection (`dt set collections/<c>
922
+ // module=<m>`): a value being written, not the `--module` selector `add` takes.
923
+ const moveArg = verb === 'set' ? pos.slice(1).find((p) => p.startsWith('module=')) : undefined;
924
+ if (moveArg) {
925
+ const viewId = id ?? need(pos, 0, 'ui-view id');
926
+ const moveTo = moveArg.slice('module='.length);
927
+ const others = [...pos.slice(1).filter((p) => p !== moveArg && p.includes('=')), ...Object.keys(flags).filter((k) => !VIEW_META_FLAGS.has(k) && k !== 'dry-run')];
928
+ if (others.length) throw new Error(`module= moves the view to another module; the other keys rewrite it. Run them as two commands: dreamteamer set ui-views/${viewId} module=${moveTo}, then dreamteamer set ui-views/${viewId} ${others.join(' ')}`);
929
+ const out = moveUiView(ws, store, viewId, moveTo, { dryRun: !!flags['dry-run'] });
930
+ if (flags.json) { emit(JSON.stringify(out)); return 0; }
931
+ if (out.dryRun) return dryRunPlan(`set ui-views/${viewId} module=${moveTo}`, { descriptors: 1 }, [`view source ${out.from} → ${out.to} (${out.file})`]);
932
+ if (!out.moved) { console.log(`✔ ui-views/${viewId} — already in ${out.to}, nothing to do`); return 0; }
933
+ console.log(`✔ ui-views/${viewId}: ${out.from} → ${out.to} (${out.file})`);
934
+ console.log('✔ compiled — the move is live');
935
+ reportCommits(out.commits);
936
+ return 0;
937
+ }
938
+ if (flags['dry-run']) throw new Error('--dry-run plans a move (module=<m>); a key write has no plan to show — run it without the flag');
908
939
  if (verb === 'set') {
909
940
  id ??= need(pos, 0, 'ui-view id');
910
941
  const { fields } = store.read('ui-views', id);
@@ -1006,7 +1037,7 @@ function relationsRebuild(store, flags, pos) {
1006
1037
  // workspace against a module-owned target) implies no mirror on a target it cannot be committed with
1007
1038
  const perRepo = (r) => {
1008
1039
  const groups = new Map();
1009
- for (const o of parseEach(store, r.owner, (f) => unreadableOwners.push(rel(store.root, f)))) {
1040
+ for (const o of parseEach(store, r.owner, (f) => unreadableOwners.push(rel(store.root, f)), { withStubs: true })) {
1010
1041
  const repo = store.repoOfFile(store.descriptor(r.owner), o.file);
1011
1042
  if (!groups.has(repo)) groups.set(repo, []);
1012
1043
  groups.get(repo).push(o);
@@ -1070,10 +1101,14 @@ function relationsRebuild(store, flags, pos) {
1070
1101
  * mid-walk cannot be resumed past — and rebuild is the one reader that has already written by the
1071
1102
  * time a later record blows up, so an abort leaves a partial sweep behind an error naming no file
1072
1103
  * at all. Here the bad record is handed to `onError` and skipped, and the walk finishes. */
1073
- function* parseEach(store, collection, onError) {
1104
+ function* parseEach(store, collection, onError, { withStubs = false } = {}) {
1074
1105
  const d = store.descriptor(collection);
1075
1106
  const bf = bodyField(d);
1076
- for (const [id, file] of store.ids(collection)) {
1107
+ // `withStubs`: a shadowed stub still OWNS references in its own repo, and the mirrors it justifies
1108
+ // there are not this workspace's to delete
1109
+ const rows = [...store.ids(collection)].map(([id, file]) => ({ id, file }));
1110
+ if (withStubs) rows.push(...store.shadowedStubRecords(collection));
1111
+ for (const { id, file } of rows) {
1077
1112
  let fields;
1078
1113
  try {
1079
1114
  fields = parseRecord(file, d, bf);
@@ -1297,7 +1332,7 @@ export const VERB_FLAGS = {
1297
1332
  // is deliberately UNCHECKED — a skill's frontmatter is an open document (`allowed-tools`, `model`,
1298
1333
  // whatever a harness reads), so there is no closed set to check it against.
1299
1334
  'skills:add': ['json', 'module', 'name', 'description'],
1300
- 'ui-views:add': ['json', 'module', 'id', 'force'], 'ui-views:set': ['json', 'module', 'id', 'force'], 'ui-views:rm': FORCE_RM,
1335
+ 'ui-views:add': ['json', 'module', 'id', 'force'], 'ui-views:set': ['json', 'module', 'id', 'force', 'dry-run'], 'ui-views:rm': FORCE_RM,
1301
1336
  };
1302
1337
 
1303
1338
  /** Edit distance, capped — enough to turn `--fliter` into "did you mean --filter?", and to refuse to
package/src/commit.js CHANGED
@@ -4,7 +4,7 @@
4
4
  import { execFileSync } from 'node:child_process';
5
5
  import fs from 'node:fs';
6
6
  import path from 'node:path';
7
- import { pathToRecord } from './events.js';
7
+ import { pathToRecord, deriveEvents, foldChanges, CHANGE_OF, TYPE_OF } from './events.js';
8
8
  import { parseRecordText } from './records.js';
9
9
  import { relationsOf } from './relations.js';
10
10
  import { splitRef, canonicalCollection } from './ref.js';
@@ -572,3 +572,40 @@ function commitPlan(store, { only = [], message, dryRun = false } = {}) {
572
572
  }
573
573
  return results;
574
574
  }
575
+
576
+ /** The record layer a repo is, by name — what a descriptor's root carries — or null for the workspace
577
+ * and for a module's clone that merely holds its own records. */
578
+ function layerOf(descriptors, repo) {
579
+ for (const d of descriptors.values()) for (const r of storageOf(d).roots) if (r.repo === repo && r.layer) return r.layer;
580
+ return null;
581
+ }
582
+
583
+ /** One sampled repo's rows (the sampler above: `dt commit`, `dt status`) as report changes. A staged
584
+ * rename is two records — the id IS the path — so the old id is read back off the old path. */
585
+ export function rowChanges(descriptors, repo, rows) {
586
+ const prefix = repo === '.' ? '' : `${repo}/`;
587
+ const layer = layerOf(descriptors, repo);
588
+ const of = (rec, rel, change) => ({ collection: rec.collection, id: rec.id, ref: `${rec.collection}/${rec.id}`, path: prefix + rel, repo, layer, change });
589
+ const out = [];
590
+ for (const r of rows) {
591
+ out.push(of(r, r.repoRel, r.verb === 'add' || r.verb === 'rename' ? 'created' : r.verb === 'rm' ? 'deleted' : 'updated'));
592
+ const old = r.verb === 'rename' && r.fromRel ? pathToRecord(descriptors, prefix + r.fromRel) : null;
593
+ if (old) out.push(of(old, r.fromRel, 'deleted'));
594
+ }
595
+ return out;
596
+ }
597
+
598
+ /** `dt changes`: the records changed since `since`, across every repo that holds records. `HEAD` (the
599
+ * default) is the UNCOMMITTED state, each repo against its own HEAD — sampled by the same dry run
600
+ * `dt status` counts with, so the two can never disagree. Any other `since` (a sha or a date) adds
601
+ * the commits since then, read by `deriveEvents`, and folds the two per record. Stateless: no mark
602
+ * file and no cursor, so it is free to run twice and cannot drift from git. */
603
+ export function recordChanges(store, { since = 'HEAD' } = {}) {
604
+ const pending = [];
605
+ for (const r of commitPending(store, { dryRun: true })) if (!r.outside) pending.push(...rowChanges(store.descriptors, r.repo, r.rows));
606
+ const committed = since === 'HEAD' ? [] : deriveEvents(store.root, store.descriptors, since).map((e) => ({
607
+ collection: e.collection, id: e.id, ref: `${e.collection}/${e.id}`, path: e.path, repo: e.repo, layer: layerOf(store.descriptors, e.repo), change: CHANGE_OF[e.type],
608
+ }));
609
+ // `type` is the 0.41.0 spelling of `change`, kept so a reader of the old JSON keeps working
610
+ return foldChanges(committed, pending).map((c) => ({ ...c, type: TYPE_OF[c.change] }));
611
+ }