dreamteamer 0.49.0 → 0.49.1

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.49.0",
3
+ "version": "0.49.1",
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>",
@@ -212,8 +212,8 @@ hidden: [file-drives] # rows not drawn; a hidden name counts as place
212
212
  module owns refuses the whole call, and the pre-image comes back.
213
213
  - **Old nav settings** (`dreamteamer.navGroups`, `navOrder`, `navHidden` in `.vscode/settings.json`)
214
214
  with no `nav.yaml` make install of a package that ships a fragment, and update of any module, refuse
215
- before npm. Migrate first with `npx -p @dreamteamer/protocol@0.2 dt-nav migrate`, or open the
216
- workspace once in the editor 0.26 or later. `--allow nav-reset` starts from the fragments and leaves
215
+ before npm. Migrate first with `npx -p @dreamteamer/protocol@0.3 dt-nav migrate`, or open the
216
+ workspace once in the editor 0.27 or later. `--allow nav-reset` starts from the fragments and leaves
217
217
  the settings unread. `dt update --engine` is never refused.
218
218
  - **A host writes through the engine**: `readNavDoc`, `validateNavDoc`, `writeNavDoc` and
219
219
  `applyNavFragments` on `import('dreamteamer')`. There is one grammar and one writer.
package/src/compile.js CHANGED
@@ -582,9 +582,22 @@ export function compile(ws) {
582
582
  // points at a file that actually names them; `.vscode/extensions.json` recommends the editor
583
583
  // extension, so the first window offers it. Both are append/merge-only — nothing authored moves.
584
584
  {
585
- const added = ensureEnvExample(root, [...declaredEnv, ...requestedVars].map(([key, mods]) => ({ key, modules: mods, ...(envMeta.get(key) ?? {}) })),
586
- '# secrets for skills and modules go here (copy to .env; .env is never committed).\n# modules declare the env keys they require in their package.json dreamteamer.env list.\n');
587
- if (added.length) console.log(`✔ .env.example now names ${added.join(', ')}`);
585
+ // one entry per key: a key one package declares as env and another requests as a var is one block
586
+ const byKey = new Map();
587
+ for (const [key, mods] of [...declaredEnv, ...requestedVars]) {
588
+ const e = byKey.get(key) ?? byKey.set(key, { key, modules: [], ...(envMeta.get(key) ?? {}) }).get(key);
589
+ for (const m of mods) if (!e.modules.includes(m)) e.modules.push(m);
590
+ }
591
+ // the workspace's own declarations are never dropped; and a declared module not on disk yet (a git
592
+ // module before `dt install`, a dependency before `npm install`) would drop keys it still declares
593
+ const keep = [...declaredVars, ...(config.env ?? []).map((e) => (typeof e === 'string' ? e : e?.name))];
594
+ const complete = !Object.keys(config.git_modules ?? {}).some((n) => !fs.existsSync(path.join(root, 'git_modules', n)))
595
+ && !Object.keys(pkg.dependencies ?? {}).some((n) => !fs.existsSync(path.join(root, 'node_modules', n, 'package.json')));
596
+ const env = ensureEnvExample(root, [...byKey.values()],
597
+ '# secrets for skills and modules go here (copy to .env; .env is never committed).\n# modules declare the env keys they require in their package.json dreamteamer.env list.\n', { keep, complete });
598
+ if (env.added.length) console.log(`✔ .env.example now names ${env.added.join(', ')}`);
599
+ for (const k of env.moved) console.log(`✔ .env.example re-attributes ${k} (now declared by ${byKey.get(k).modules.join(', ')})`);
600
+ for (const k of env.dropped) console.log(`✔ .env.example drops ${k} — no installed package declares it`);
588
601
  ensureEditorRecommendation(root);
589
602
  }
590
603
 
@@ -11,6 +11,7 @@ import fs from 'node:fs';
11
11
  import os from 'node:os';
12
12
  import path from 'node:path';
13
13
  import zlib from 'node:zlib';
14
+ import { fileURLToPath } from 'node:url';
14
15
  import { spawnSync, execFileSync } from 'node:child_process';
15
16
  import { satisfies, EXACT } from './semver.js';
16
17
  import { engineVersion } from './runtime.js';
@@ -207,6 +208,8 @@ const gitIgnored = (root, rel) => gitOk(root, ['check-ignore', '-q', '--', rel])
207
208
  /** `git status --porcelain` of one path: '' when clean (modified AND untracked both count as dirty). */
208
209
  const gitStatus = (root, rel) => { try { return execFileSync('git', ['status', '--porcelain', '--', rel], { cwd: root, encoding: 'utf8' }).trim(); } catch { return ''; } };
209
210
 
211
+ const BIN = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'dreamteamer.js');
212
+
210
213
  // ---- steps 2–4 and 5–6, shared with `dt update` (install one pin later) ----------------------------
211
214
 
212
215
  /**
@@ -215,8 +218,15 @@ const gitStatus = (root, rel) => { try { return execFileSync('git', ['status', '
215
218
  * nav fragments of the listed packages judged and merged (cr-dt-008) — inside the same restore, so a
216
219
  * fragment placing another module's collection, or a nav.yaml that does not read, undoes the call
217
220
  * like a compile refusal. Returns `{ fresh, nav }` (nav: the plan setupAndCommit writes), or `{ code }`.
221
+ *
222
+ * `childCompile` (dt update): this process opened the workspace before npm, and ESM caches an extension's
223
+ * entry and every file it imports by path — so an in-process compile would run the version npm just
224
+ * replaced, blind to a source kind or harness the new one contributes (rnd/issues …dt-update-compiles-with-
225
+ * the-replaced-version-s-extension). The compile then runs in a child, this engine's own `dt compile`; a
226
+ * non-zero exit is a refusal like any other, and `fresh` is only `{ root, pkg }` — the nav plan reads no
227
+ * extension, and activating the cached ones could refuse on a collision the new versions do not have.
218
228
  */
219
- export async function npmAndCompile(ws, list, { npm = resolveNpm(), open, json = false, log = console.log, hooks = {}, what = 'install', ignoreSettings = false } = {}) {
229
+ export async function npmAndCompile(ws, list, { npm = resolveNpm(), open, json = false, log = console.log, hooks = {}, what = 'install', ignoreSettings = false, childCompile = false } = {}) {
220
230
  const names = list.map((e) => e.manifest.name);
221
231
  const pkgFile = path.join(ws.root, 'package.json'), lockFile = path.join(ws.root, 'package-lock.json');
222
232
  const versionOf = (n) => { try { return JSON.parse(fs.readFileSync(path.join(ws.root, 'node_modules', n, 'package.json'), 'utf8')).version ?? null; } catch { return null; } };
@@ -233,10 +243,19 @@ export async function npmAndCompile(ws, list, { npm = resolveNpm(), open, json =
233
243
  // 4. compile — a refusal restores the pre-image and prunes
234
244
  let compiled = false; // a refusal AFTER a compile (the nav fragments) owes the runtime a recompile
235
245
  try {
236
- const fresh = await open(ws.root);
237
- const stdout = console.log;
238
- if (json) console.log = console.error;
239
- try { compile(fresh); compiled = true; } finally { console.log = stdout; }
246
+ let fresh;
247
+ if (childCompile) {
248
+ // --workspace pins the root: a layer under git_modules/ would otherwise be climbed out of to the reader
249
+ const c = spawnSync(process.execPath, [BIN, '--workspace', ws.root, 'compile'], { cwd: ws.root, stdio: json ? ['ignore', 2, 2] : 'inherit', env: childEnv() });
250
+ if (c.status !== 0) throw new Error(`compile exited ${c.status ?? c.error?.message ?? c.signal}`);
251
+ compiled = true;
252
+ fresh = { root: ws.root, pkg: JSON.parse(fs.readFileSync(pkgFile, 'utf8')) };
253
+ } else {
254
+ fresh = await open(ws.root);
255
+ const stdout = console.log;
256
+ if (json) console.log = console.error;
257
+ try { compile(fresh); compiled = true; } finally { console.log = stdout; }
258
+ }
240
259
  const nav = planNavFragments(fresh, { names, ignoreSettings });
241
260
  return { fresh, nav };
242
261
  } catch (e) {
@@ -256,7 +275,8 @@ export async function npmAndCompile(ws, list, { npm = resolveNpm(), open, json =
256
275
  return { code: EXIT.failed };
257
276
  }
258
277
  // compile succeeded before the refusal, so .dreamteamer and the harness folders hold the refused
259
- // packages' sources: compile again over the restored node_modules, so the runtime is the pre-image's
278
+ // packages' sources: compile again over the restored node_modules, so the runtime is the pre-image's.
279
+ // In this process even after a child compile: the versions it cached are the restored ones.
260
280
  if (compiled) {
261
281
  const stdout = console.log;
262
282
  console.log = () => {};
@@ -20,7 +20,7 @@ import { findWorkspace } from './workspace.js';
20
20
  import { parseNavDoc, readNavDoc, writeNavDoc, placedNames, mergeFragment, NavDocError, NAV_FILE } from './nav.js';
21
21
 
22
22
  export const NAV_SETTINGS_LINE = 'nav: settings found, migrated on the next open of the editor or dt web';
23
- export const NAV_GUARD_LINE = 'your nav settings are not saved to nav.yaml yet — run: npx -p @dreamteamer/protocol@0.2 dt-nav migrate (or open this workspace once in the editor 0.26 or later), then run this again; --allow nav-reset skips it';
23
+ export const NAV_GUARD_LINE = 'your nav settings are not saved to nav.yaml yet — run: npx -p @dreamteamer/protocol@0.3 dt-nav migrate (or open this workspace once in the editor 0.27 or later), then run this again; --allow nav-reset skips it';
24
24
  const NAV_KEYS = ['dreamteamer.navGroups', 'dreamteamer.navOrder', 'dreamteamer.navHidden'];
25
25
 
26
26
  export class NavFragmentRefusal extends Error {
package/src/store.js CHANGED
@@ -135,7 +135,8 @@ export class Store {
135
135
  * against — the two read the same relation rows, so they cannot disagree about what a mirror holds.
136
136
  *
137
137
  * Runs INSIDE withWriteLock, after the owner file is on disk. Nothing is validated here: an attach
138
- * was proved to exist by `checkRefs` before the lock, and a detach is removal, which cannot dangle.
138
+ * was proved by `checkRefs` before the lock — to exist, or to be external (vouched for by an exports
139
+ * manifest, no record here to mirror onto) — and a detach is removal, which cannot dangle.
139
140
  *
140
141
  * ⚠ ALL-OR-NOTHING, by its own hand. The one refusal it can raise (a unique owner) is discoverable only
141
142
  * ON a target, i.e. partway through a loop that may already have rewritten other targets — so a
@@ -193,8 +194,10 @@ export class Store {
193
194
  // A DETACH can name a target that is already gone: the owner outlived it (a `--force`
194
195
  // rm), and its FK is the dangling reference `check` reports. There is no mirror left
195
196
  // to edit and `read` would throw, turning someone else's stale data into a refusal of
196
- // this write. An attach never lands here missing — checkRefs proved it before the lock.
197
- if (!this.ids(rel.target).has(parsed.id)) return;
197
+ // this write. An attach lands here missing only when checkRefs accepted it as external
198
+ // (an exports manifest vouches for it): nothing here holds it, so there is no mirror to write.
199
+ // A target whose env-pointed root cannot render here is unread: no mirror either.
200
+ if (storageOf(td).unavailable || !this.ids(rel.target).has(parsed.id)) return;
198
201
  // another repo answers: no mirror there (see above) — mirrors stay per repo
199
202
  const file = this.mirrorFileFor(rel.target, parsed.id, ownerRepo);
200
203
  if (!file) return;
@@ -635,11 +638,21 @@ export class Store {
635
638
  if (!f) throw new Error(`${referrer}: no such record here — a referrer is a record this workspace reads`);
636
639
  repo = this.layerOfFile(rd, f)?.layer ?? null;
637
640
  }
641
+ const v = this.vouched(collection, id, repo);
642
+ if (!v || v.seen) return null;
643
+ return { label: v.label, ...(v.from ? { from: v.from } : {}), manifest: v.manifest };
644
+ }
645
+
646
+ /** The entry the exports manifest of `repo` (a layer name; null: the write root) holds for an id —
647
+ * `{ label, from?, manifest, seen }`, `seen` when its holder is read here (so the entry vouches for
648
+ * nothing: the holder answers, and lacks it) — or null. The one reading `external` and `checkRefs`
649
+ * share, so a write and `check` (src/check.js checkRef) reach one verdict on identical bytes. */
650
+ vouched(collection, id, repo = null) {
638
651
  const facts = exportsFacts(this.root);
639
652
  const ctx = exportsContext({ root: this.root, descriptors: this.descriptors, own: facts.own, layers: facts.layers, dataPath: facts.data });
640
653
  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)) };
654
+ if (!e) return null;
655
+ return { label: e.label, ...(e.from ? { from: e.from } : {}), manifest: path.relative(this.root, path.join(ctx.rootOf(repo), EXPORTS_FILE)), seen: sees(e, collection, ctx) };
643
656
  }
644
657
 
645
658
  read(collection, id) {
@@ -742,7 +755,7 @@ export class Store {
742
755
  // is the whole point of a revert — because `check` re-reads that file and expects a mirror only
743
756
  // for a ref it can parse. Qualifying `after` here would attach a mirror check then calls stale.
744
757
  const restored = { ...tmpFields };
745
- this.validate(d, tmpFields);
758
+ this.validate(d, tmpFields, { repo: this.layerOfFile(d, file)?.layer ?? null });
746
759
  // Restoring an owner field restores its PLACEMENT too — the historical record lived where its
747
760
  // historical owner put it, and writing it into whatever folder the record sits in today would
748
761
  // leave a file `check` reports the moment it lands. Same rule as `set`: only the owner moves it.
@@ -886,7 +899,7 @@ export class Store {
886
899
 
887
900
  // ---- validation (hard) ---------------------------------------------------
888
901
 
889
- validate(d, fields, { skipRefs = false } = {}) {
902
+ validate(d, fields, { skipRefs = false, repo = null } = {}) {
890
903
  // hard at the tools includes UNKNOWN fields: a typo'd key must never land on disk
891
904
  const unknown = unknownFields(d, fields);
892
905
  if (unknown.length) throw new Error(`unknown field(s) for this collection: ${unknown.join(', ')} — nothing was written.`);
@@ -910,7 +923,7 @@ export class Store {
910
923
  const remedy = mirrorRemedy(d, validate.errors.map((e) => e.instancePath.split('/')[1]));
911
924
  throw new Error(`validation failed:\n${msgs.join('\n')}${remedy}\nnothing was written.`);
912
925
  }
913
- if (!skipRefs) this.checkRefs(d, fields);
926
+ if (!skipRefs) this.checkRefs(d, fields, [], repo);
914
927
  return fields;
915
928
  }
916
929
 
@@ -941,7 +954,9 @@ export class Store {
941
954
  }
942
955
  }
943
956
 
944
- checkRefs(d, fields, prefix = []) {
957
+ /** `repo` is the referring record's: the layer that holds it, null for the write root — whose exports
958
+ * manifest may vouch for an id no root here holds, exactly as `check` reads it. */
959
+ checkRefs(d, fields, prefix = [], repo = null) {
945
960
  for (const [key, f] of Object.entries(fieldsOf(d))) {
946
961
  const targets = targetsOf(f);
947
962
  if (!targets) continue;
@@ -975,7 +990,16 @@ export class Store {
975
990
  if (soft) continue;
976
991
  throw new Error(`${key}: reference "${value}" targets unknown collection "${coll}" — nothing was written.`);
977
992
  }
978
- if (!this.ids(coll).has(id) && !soft) throw new Error(`${key}: dangling reference "${value}" — no such record. nothing was written.${mirrorRemedy(d, [key])}`);
993
+ if (soft) continue;
994
+ // a collection whose env-pointed root cannot render here is unread, not empty — `check` passes it
995
+ if (storageOf(this.descriptors.get(coll)).unavailable) continue;
996
+ if (this.ids(coll).has(id)) continue;
997
+ // an id no root here holds, vouched for by the referring repo's exports manifest, is
998
+ // external (cr-dt-004) — accepted, as `check` accepts it. The manifest is read only here,
999
+ // on the way to a refusal, so a write naming a held id never pays for it.
1000
+ const v = this.vouched(coll, id, repo);
1001
+ if (v && !v.seen) continue;
1002
+ throw new Error(`${key}: dangling reference "${value}" — no such record${v ? ` (its holder ${v.from} is read here and does not have it)` : ''}. nothing was written.${mirrorRemedy(d, [key])}`);
979
1003
  }
980
1004
  }
981
1005
  }
@@ -1106,7 +1130,7 @@ export class Store {
1106
1130
  const previous = fs.readFileSync(file, 'utf8');
1107
1131
  const next = { ...fields, ...changes };
1108
1132
  for (const [k, v] of Object.entries(changes)) if (v === null || v === '') delete next[k];
1109
- this.validate(d, next);
1133
+ this.validate(d, next, { repo: this.layerOfFile(d, file)?.layer ?? null });
1110
1134
  this.refuseDuplicateValues(d, collection, id, next, Object.keys(changes));
1111
1135
  // A placed record FOLLOWS ITS OWNER FIELD: changing it moves the file to the new parent's folder
1112
1136
  // (or back to the fallback root) in this same write, id unchanged. Only a change to THAT field
package/src/update.js CHANGED
@@ -94,7 +94,8 @@ export async function updateModules(ws, { name = null, version = null, engine =
94
94
  const extra = names.filter((n) => n !== target && !installed.has(n));
95
95
  const tail = `${moved.length ? ` — members: ${moved.join(', ')}` : ''}${extra.length ? ` — with ${extra.join(', ')}` : ''}`;
96
96
  log(`▶ update: ${target} ${here.version} → ${next}${tail}`);
97
- const step = await npmAndCompile(ws, plan.list, { npm, open, log, what: 'update', ignoreSettings: allow.has('nav-reset') });
97
+ // the compile in a fresh process too: this one cached the versions npm is about to replace
98
+ const step = await npmAndCompile(ws, plan.list, { npm, open, log, what: 'update', ignoreSettings: allow.has('nav-reset'), childCompile: true });
98
99
  if (step.code !== undefined) return step.code;
99
100
  if (step.nav.skipped === 'settings') log(NAV_SETTINGS_LINE);
100
101
  // the setup half in a fresh process: this one imported the version npm just replaced (ESM caches it).
package/src/workspace.js CHANGED
@@ -180,23 +180,62 @@ export function ensureEditorRecommendation(root, warn = console.warn) {
180
180
 
181
181
  /** `.env.example` lists every env key the installed modules declare — the file the missing-key
182
182
  * warning points at, which used to carry two comment lines and none of the keys it was cited for.
183
- * Append-only and idempotent: a key already named in the file (as `KEY=` or `# KEY`) is not added
184
- * again, and nothing an operator wrote is touched. Values never appear here — an example does. */
185
- export function ensureEnvExample(root, entries, header = '') {
186
- if (!entries.length) return [];
183
+ * A key already named in the file (as `KEY=` or `# KEY`) is not added again, and nothing an operator
184
+ * wrote is touched. Values never appear here — an example does.
185
+ *
186
+ * The blocks THIS function wrote follow the declarations (rnd/issues …env-example-keeps-a-key-under-
187
+ * its-old-package…): an engine block is a `KEY=` line directly under `# declared by <packages>` or
188
+ * `# <description> (module <packages>)`. Its comment is rewritten when what declares the key changed
189
+ * (`moved`; the `KEY=` line, whose example may be the operator's, stays), and the block goes when no
190
+ * installed package declares the key (`dropped`) — unless `keep` names it (the workspace's own
191
+ * declaration) or the module set is not `complete` (a declared module not on disk yet: its keys would
192
+ * go and come back). A repeated engine block for one key goes with the first one's rewrite. Every
193
+ * other line is kept byte for byte, its line ending included. Returns `{ added, moved, dropped }`. */
194
+ export function ensureEnvExample(root, entries, header = '', { keep = [], complete = true } = {}) {
187
195
  const file = path.join(root, '.env.example');
188
- const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : header;
189
- const named = new Set([...existing.matchAll(/^\s*#?\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/gm)].map((m) => m[1]));
190
- const added = [];
191
- let out = existing;
196
+ const exists = fs.existsSync(file);
197
+ const result = { added: [], moved: [], dropped: [] };
198
+ if (!entries.length && !exists) return result;
199
+ const existing = exists ? fs.readFileSync(file, 'utf8') : header;
200
+ const declared = new Map(entries.map((e) => [e.key, e]));
201
+ const commentFor = (e) => `# ${e.description ?? `declared by ${e.modules.join(', ')}`}${e.description && e.modules?.length ? ` (module ${e.modules.join(', ')})` : ''}`;
202
+ const lines = existing.split(/(?<=\n)/); // each line keeps its own ending
203
+ const text = (l) => l.replace(/\r?\n$/, '');
204
+ const ENGINE = /^# (?:declared by .+|.* \(module .+\))$/;
205
+ const seen = new Set();
206
+ const out = [];
207
+ for (let i = 0; i < lines.length; i++) {
208
+ const key = /^([A-Za-z_][A-Za-z0-9_]*)=/.exec(text(lines[i]))?.[1];
209
+ const prev = out.length - 1;
210
+ if (!key || prev < 0 || !ENGINE.test(text(out[prev])) || !complete) { out.push(lines[i]); continue; }
211
+ const e = declared.get(key);
212
+ if (e && !seen.has(key)) {
213
+ seen.add(key);
214
+ const want = commentFor(e);
215
+ if (text(out[prev]) !== want) { out[prev] = want + out[prev].slice(text(out[prev]).length); result.moved.push(key); }
216
+ out.push(lines[i]);
217
+ continue;
218
+ }
219
+ if (!e && keep.includes(key)) { out.push(lines[i]); continue; }
220
+ // a key nothing declares, or a second engine block for one: the comment, the key and the blank line before them go
221
+ out.pop();
222
+ if (out.length && text(out[out.length - 1]) === '') out.pop();
223
+ else if (!out.length && i + 1 < lines.length && text(lines[i + 1]) === '') i++; // at the top of the file: the blank line after
224
+ if (!e && !result.dropped.includes(key)) result.dropped.push(key);
225
+ }
226
+ let next = out.join('');
227
+ // what is named after the drops: a dropped key is no longer named, so it is never added back here
228
+ const named = new Set([...next.matchAll(/^\s*#?\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/gm)].map((m) => m[1]));
229
+ const eol = existing.includes('\r\n') ? '\r\n' : '\n';
192
230
  for (const e of entries) {
193
231
  if (named.has(e.key)) continue;
194
- const who = e.modules?.length ? ` (module ${e.modules.join(', ')})` : '';
195
- out = out.trimEnd() + `\n\n# ${e.description ?? `declared by ${e.modules.join(', ')}`}${e.description ? who : ''}\n${e.key}=${e.example ?? ''}\n`;
196
- added.push(e.key);
232
+ next = next.trimEnd() + `${eol}${eol}${commentFor(e)}${eol}${e.key}=${e.example ?? ''}${eol}`;
233
+ named.add(e.key);
234
+ result.added.push(e.key);
197
235
  }
198
- if (added.length) fs.writeFileSync(file, out.replace(/^\n+/, ''));
199
- return added;
236
+ if (result.added.length) next = next.replace(/^(?:\r?\n)+/, '');
237
+ if (next !== existing) fs.writeFileSync(file, next);
238
+ return result;
200
239
  }
201
240
 
202
241
  /**