dreamteamer 0.40.0 → 0.41.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/bin/dreamteamer.js +67 -12
- package/package.json +1 -1
- package/skills/using-dreamteamer/SKILL.md +4 -3
- package/skills/using-dreamteamer/references/collections.md +34 -12
- package/src/check.js +43 -23
- package/src/cli.js +24 -14
- package/src/collections-cli.js +21 -9
- package/src/compile-collections.js +56 -8
- package/src/compile.js +17 -30
- package/src/extensions.js +2 -1
- package/src/fields.js +8 -2
- package/src/records.js +25 -0
- package/src/schema-ops.js +3 -3
- package/src/store.js +69 -10
- package/src/workspace.js +36 -0
package/bin/dreamteamer.js
CHANGED
|
@@ -13,7 +13,8 @@ const MODULE_SEGMENTS = new Set(['node_modules', 'git_modules', 'modules']);
|
|
|
13
13
|
|
|
14
14
|
const self = fileURLToPath(import.meta.url);
|
|
15
15
|
|
|
16
|
-
// `--
|
|
16
|
+
// `--workspace <name-or-path>` / `-w` — run the verb in ANOTHER workspace without leaving this one
|
|
17
|
+
// (`--vault <path>` is its pre-0.41.0 spelling, kept as a silent alias). Consumed HERE, before
|
|
17
18
|
// anything else resolves, because every verb downstream answers "which workspace am I in" from
|
|
18
19
|
// process.cwd(): changing the directory once IS the whole implementation, and it also points the
|
|
19
20
|
// dev-clone walk below at the TARGET's git_modules rather than the caller's.
|
|
@@ -22,22 +23,46 @@ const self = fileURLToPath(import.meta.url);
|
|
|
22
23
|
// branch re-enters this same file, and a flag left in place would be applied a SECOND time — the
|
|
23
24
|
// path resolving against the already-changed directory, i.e. at the wrong workspace, silently.
|
|
24
25
|
//
|
|
25
|
-
//
|
|
26
|
-
// relative path in the command then resolves against the target — the
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
26
|
+
// A PATH resolves against the INVOKING directory, which is where the caller typed it; every other
|
|
27
|
+
// relative path in the command then resolves against the target — the rule a `cd` would give. A NAME
|
|
28
|
+
// with no such directory is a record layer this workspace DECLARES (`dreamteamer.git_modules`), and
|
|
29
|
+
// resolves to `git_modules/<name>` — the precedent is `npm -w <name-or-path>`. The target is PINNED
|
|
30
|
+
// for this process only: a clone under git_modules/ is otherwise climbed out of by discovery, which
|
|
31
|
+
// would run the verb in the workspace AROUND it — a write landing in the reader and printing ✔.
|
|
32
|
+
// `--workspace=<x>` (npm's spelling too) is the same flag in one argument.
|
|
33
|
+
const flagAt = process.argv.findIndex((a, i) => i >= 2 && /^(--workspace|-w|--vault)(=|$)/.test(a));
|
|
34
|
+
if (flagAt !== -1) {
|
|
35
|
+
const [flagWord, inline] = process.argv[flagAt].split(/=(.*)/s);
|
|
36
|
+
const flag = flagWord === '--vault' ? '--vault' : '--workspace';
|
|
37
|
+
const joined = inline !== undefined;
|
|
38
|
+
const target = joined ? inline : process.argv[flagAt + 1];
|
|
30
39
|
if (!target || target.startsWith('-')) {
|
|
31
|
-
console.error('
|
|
40
|
+
console.error(flag === '--vault'
|
|
41
|
+
? '\u2716 --vault needs a path to a workspace, e.g. `--vault ../another-workspace`'
|
|
42
|
+
: '\u2716 --workspace needs a layer name or a path, e.g. `-w project-alpha` or `-w ../another-workspace`');
|
|
32
43
|
process.exit(1);
|
|
33
44
|
}
|
|
34
|
-
const
|
|
45
|
+
const refuse = (why) => { console.error(`\u2716 ${flag} ${target} \u2014 ${why}`); process.exit(1); };
|
|
46
|
+
let resolved = path.resolve(process.cwd(), target);
|
|
35
47
|
if (!fs.existsSync(resolved)) {
|
|
36
|
-
|
|
37
|
-
process.
|
|
48
|
+
// a NAME: only a record layer this workspace declares — a bundle is modules, not a workspace
|
|
49
|
+
const here = findWorkspaceRoot(process.cwd());
|
|
50
|
+
const layers = here ? declaredLayers(here) : new Map();
|
|
51
|
+
if (/[\\/]/.test(target) || !layers.has(target)) refuse(`no such directory, and no layer of that name is declared here (declared layers: ${[...layers].filter(([, k]) => k === 'layer').map(([n]) => n).join(', ') || 'none'})`);
|
|
52
|
+
resolved = path.join(here, 'git_modules', target);
|
|
53
|
+
if (layers.get(target) === 'bundle') refuse(`git_modules/${target} is a bundle (its package.json names no workspace_module), not a workspace — there is nothing to run a verb in`);
|
|
54
|
+
if (!fs.existsSync(resolved)) refuse(`the layer is declared but not installed (${resolved}); run dreamteamer install`);
|
|
38
55
|
}
|
|
56
|
+
// the TARGET must be a workspace root: a plain folder (one that merely shares a layer's name, say)
|
|
57
|
+
// would be pinned, discovery would climb out of it, and the verb would run in the workspace around it
|
|
58
|
+
if (!isWorkspaceDir(resolved)) refuse(`${resolved} is not a workspace (no package.json with a "dreamteamer" section)`);
|
|
39
59
|
process.chdir(resolved);
|
|
40
|
-
|
|
60
|
+
// PROCESS-LOCAL, never an environment variable: the one reader that needs it is the dev-clone
|
|
61
|
+
// re-exec below, an `import()` into this same process. An env var reached every child — git hooks,
|
|
62
|
+
// an extension spawning dt — and a dt run inside the clone by any of them answered from the layer
|
|
63
|
+
// alone instead of the reader's union.
|
|
64
|
+
globalThis[Symbol.for('dreamteamer.workspace')] = process.cwd(); // the physical path, as discovery will see it
|
|
65
|
+
process.argv.splice(flagAt, joined ? 1 : 2);
|
|
41
66
|
}
|
|
42
67
|
|
|
43
68
|
const devBin = findDevClone(process.cwd());
|
|
@@ -67,7 +92,7 @@ function realpath(p) {
|
|
|
67
92
|
// same workspace rule as src/workspace.js (nearest package.json with a `dreamteamer` key, climbing
|
|
68
93
|
// out only of module nesting), duplicated here because the dev clone must be found BEFORE choosing
|
|
69
94
|
// which src/ to load. Keep the two in step — they must never disagree about which workspace this is.
|
|
70
|
-
function
|
|
95
|
+
function findWorkspaceRoot(start) {
|
|
71
96
|
let dir = path.resolve(start);
|
|
72
97
|
const candidates = []; // nearest → topmost
|
|
73
98
|
while (true) {
|
|
@@ -84,10 +109,40 @@ function findDevClone(start) {
|
|
|
84
109
|
if (!candidates.length) return null;
|
|
85
110
|
let workspace = candidates[0];
|
|
86
111
|
for (const higher of candidates.slice(1)) {
|
|
112
|
+
if (workspace === globalThis[Symbol.for('dreamteamer.workspace')]) break; // an explicitly targeted workspace is never climbed out of
|
|
87
113
|
const viaModule = path.relative(higher, workspace).split(path.sep).some((seg) => MODULE_SEGMENTS.has(seg));
|
|
88
114
|
if (!viaModule) break;
|
|
89
115
|
workspace = higher;
|
|
90
116
|
}
|
|
117
|
+
return workspace;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Does a directory's package.json carry a `dreamteamer` section — is it a workspace (or module) root? */
|
|
121
|
+
function isWorkspaceDir(dir) {
|
|
122
|
+
try { return 'dreamteamer' in JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')); } catch { return false; }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The git_modules entries a workspace declares, name -> 'layer' | 'bundle' — the rule of
|
|
126
|
+
* src/workspace.js layerEntries, restated because this file runs before any src/ is chosen: `records`
|
|
127
|
+
* or `module: true` declares a layer, a clone on disk is a layer when its manifest names
|
|
128
|
+
* `workspace_module`, and one not on disk is a layer not installed. */
|
|
129
|
+
function declaredLayers(root) {
|
|
130
|
+
const out = new Map();
|
|
131
|
+
let entries = {};
|
|
132
|
+
try { entries = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).dreamteamer?.git_modules ?? {}; } catch { /* none */ }
|
|
133
|
+
for (const [name, e] of Object.entries(entries)) {
|
|
134
|
+
const clone = path.join(root, 'git_modules', name);
|
|
135
|
+
let wm = null;
|
|
136
|
+
try { wm = JSON.parse(fs.readFileSync(path.join(clone, 'package.json'), 'utf8')).dreamteamer?.workspace_module ?? null; } catch { /* absent */ }
|
|
137
|
+
const layer = e?.records !== undefined || e?.module === true || !fs.existsSync(clone) || !!wm;
|
|
138
|
+
out.set(name, layer ? 'layer' : 'bundle');
|
|
139
|
+
}
|
|
140
|
+
return out;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function findDevClone(start) {
|
|
144
|
+
const workspace = findWorkspaceRoot(start);
|
|
145
|
+
if (!workspace) return null;
|
|
91
146
|
const bin = path.join(workspace, 'git_modules', 'dreamteamer', 'bin', 'dreamteamer.js');
|
|
92
147
|
return fs.existsSync(bin) ? bin : null;
|
|
93
148
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dreamteamer",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.41.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>",
|
|
@@ -91,9 +91,10 @@ the primary workspace's, whoever shipped the skill you are reading.
|
|
|
91
91
|
|
|
92
92
|
- **start a session in the workspace it is about.** it is the only thing that loads that workspace's
|
|
93
93
|
instructions, and it settles name collisions in its favour.
|
|
94
|
-
- **to touch another workspace from here,
|
|
95
|
-
|
|
96
|
-
|
|
94
|
+
- **to touch another workspace from here, `-w <name|path>` (`--workspace`) — not `cd`.** a record
|
|
95
|
+
layer is named by its git_modules name (`-w project-alpha`), any other workspace by path. the flag
|
|
96
|
+
resolves the target's schema, validates and commits there, and leaves the working directory alone;
|
|
97
|
+
a `cd` outlives the command. (`--vault <path>` is the deprecated spelling.)
|
|
97
98
|
- **every record write prints the workspace it landed in** — `✔ <workspace> · <path>`. a write to
|
|
98
99
|
the wrong workspace passes validation, because the collection usually exists in both, so that line
|
|
99
100
|
is what distinguishes them.
|
|
@@ -262,7 +262,7 @@ Keys are snake_case and closed: compile refuses an unknown one, naming the list.
|
|
|
262
262
|
| `vars` | the `.env` keys records may reference as `${env:KEY}` (`records.md`) |
|
|
263
263
|
| `auto_commit` | whether a record write also commits (default off) |
|
|
264
264
|
| `harnesses` | which coding-agent adapters compile writes |
|
|
265
|
-
| `git_modules` | the lockfile map `dt install` restores into `git_modules/` — `{ url, ref }` per clone;
|
|
265
|
+
| `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 |
|
|
266
266
|
| `disable` | what to drop from the compile: `modules/<id>` (a whole module, its code included) or `<kind>/<id>` (one entity) |
|
|
267
267
|
| `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 |
|
|
268
268
|
|
|
@@ -420,17 +420,25 @@ storage:
|
|
|
420
420
|
|
|
421
421
|
Several workspaces install one module for their shared shapes — an HQ and the projects it oversees
|
|
422
422
|
all take `tasks` from the same package — while each keeps its own task RECORDS in its own repo. The
|
|
423
|
-
HQ reads the projects' records by cloning each project under `git_modules
|
|
424
|
-
entry, which collections that clone contributes:
|
|
423
|
+
HQ reads the projects' records by cloning each project under `git_modules/`:
|
|
425
424
|
|
|
426
425
|
```json
|
|
427
426
|
"git_modules": {
|
|
428
427
|
"org": { "url": "…", "ref": "main" },
|
|
429
|
-
"project-alpha": { "url": "…", "ref": "main", "
|
|
428
|
+
"project-alpha": { "url": "…", "ref": "main", "module": true },
|
|
429
|
+
"project-beta": { "url": "…", "ref": "main", "records": ["tasks", "projects"] }
|
|
430
430
|
}
|
|
431
431
|
```
|
|
432
432
|
|
|
433
|
-
- **
|
|
433
|
+
- **What the CLONE is decides it (0.41.0).** A clone whose own package.json names
|
|
434
|
+
`dreamteamer.workspace_module` is a workspace, so it is a layer: every collection both workspaces
|
|
435
|
+
have reads its data folder. A clone that names none is a bundle, and its `modules/` unpack as
|
|
436
|
+
before. `records:` is optional and NARROWS — only the listed collections are read — and it still
|
|
437
|
+
makes any clone a layer. A collection that cannot layer (below) is skipped with an `ℹ` when the
|
|
438
|
+
clone holds files for it; a data folder no collection here accounts for (a project's own domain
|
|
439
|
+
collections, read without their module) is a compile warning naming the folder and its file
|
|
440
|
+
count, never a failure.
|
|
441
|
+
- **A layer is never a bundle.** Its own `modules/` is not unpacked and it
|
|
434
442
|
is not an extension; the shapes are the modules both workspaces install. Its nested
|
|
435
443
|
`git_modules/` are never read.
|
|
436
444
|
- **`module: true` also compiles the clone's WORKSPACE module** — `modules/<workspace_module>`, as
|
|
@@ -441,14 +449,26 @@ entry, which collections that clone contributes:
|
|
|
441
449
|
extension entry in it is not loaded), and the records half is unchanged. Compile refuses, naming
|
|
442
450
|
the entry: a clone with no `workspace_module`; a module whose id is `default` (the role name every
|
|
443
451
|
workspace's own module carries — name the project's module after the project); an id another
|
|
444
|
-
module here already holds
|
|
445
|
-
|
|
446
|
-
- **Each listed collection gains the clone's data folder as a read root below the workspace's
|
|
452
|
+
module here already holds. `dt status` adds `· module <id>` to the layer's line.
|
|
453
|
+
- **Each layered collection gains the clone's data folder as a read root below the workspace's
|
|
447
454
|
own** — the compiled descriptor states them as `compiled.layers`, and `storageOf(d).roots` is the
|
|
448
455
|
write root first, then each layer. `dt list`, `get`, `check`, the inbound-reference guard of `rm`
|
|
449
456
|
and reference resolution read the union. An id two roots hold is a `check` violation naming both
|
|
450
457
|
files, and a write to it is refused until one is removed; the first root in order answers reads
|
|
451
458
|
meanwhile, never silently.
|
|
459
|
+
- **A record carrying `stub: true` YIELDS (0.41.0).** A stub is a thin placeholder a workspace keeps
|
|
460
|
+
so its own references resolve standalone — a project's copy of a person the HQ holds in full. One
|
|
461
|
+
non-stub plus any stubs of one id: the non-stub answers, in whichever root it sits (either
|
|
462
|
+
direction), and `check` is clean with an `ℹ` counting the shadowed stubs. Two non-stubs are still
|
|
463
|
+
the violation above; stubs only, the first root answers. `stub` is an engine-owned field on every
|
|
464
|
+
collection that can be layered (hidden from lists and forms; a module may not declare one), and a stub still carries
|
|
465
|
+
its collection's required fields. `dt set` writes the answering record in its own repo; `dt add`
|
|
466
|
+
of an id only stubs hold is allowed and prints `shadows N stubs (<layer>…)` — that is how a stub
|
|
467
|
+
is promoted; `dt rm` of the answering record says which stub now shows, and is not refused for
|
|
468
|
+
references the stub keeps resolving. `dt get --json` carries
|
|
469
|
+
`$stub: true` on a stub and `$shadows: [<file>…]` on a record that answers over stubs. A shadowed
|
|
470
|
+
stub is still an owner in its own repo, so the mirrors it justifies there are expected by `check`
|
|
471
|
+
and kept by `relations rebuild`. Only ids more than one root claims have their files read.
|
|
452
472
|
- **A new record goes to the write root** (`storage.path` — this workspace, or the owning module's
|
|
453
473
|
clone for `storage.owner: module`). **An edit or removal of a layer's record lands in place** and
|
|
454
474
|
commits in the layer's repo; `dt commit` samples every layer and publishes one commit per repo.
|
|
@@ -459,12 +479,14 @@ entry, which collections that clone contributes:
|
|
|
459
479
|
- **A mirror is kept only between records of one repo.** A task here naming a project a layer holds
|
|
460
480
|
writes no mirror into the layer, and `check` expects none; the project's own `tasks` mirror on that
|
|
461
481
|
record lists only its own tasks.
|
|
462
|
-
- **What may be
|
|
482
|
+
- **What may be layered:** a collection stored in this workspace. Not a `storage.owner: module`
|
|
463
483
|
collection (one shared list is read from the module's clone already), not a placed one
|
|
464
|
-
(`storage.under`), not a compiled source.
|
|
484
|
+
(`storage.under`), not an env-pointed one, not a compiled source. NAMING one of those in `records:`
|
|
485
|
+
is a compile error, as is a name no collection here answers to.
|
|
465
486
|
- **A layer whose clone is absent** — a fresh checkout before `dreamteamer install` — compiles; `check`
|
|
466
|
-
says its records are unread
|
|
467
|
-
clone
|
|
487
|
+
says its records are unread (only a `records:` or `module: true` entry is known to be a layer before
|
|
488
|
+
its clone exists). `dt status` lists layers after modules with the collections FOUND in each;
|
|
489
|
+
`dt update` pulls them like any clone, and a long-lived store re-indexes when a pull lands files.
|
|
468
490
|
|
|
469
491
|
## mixins — a live shared field set
|
|
470
492
|
|
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
|
|
105
|
-
// the store indexes
|
|
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))
|
|
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
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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) {
|
|
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,7 +14,7 @@ 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';
|
|
@@ -36,9 +36,13 @@ const QUIET = ['ignore', 'pipe', 'ignore'];
|
|
|
36
36
|
|
|
37
37
|
export const USAGE = `usage: dreamteamer <verb> [<target>] [flags]
|
|
38
38
|
|
|
39
|
-
--
|
|
40
|
-
|
|
41
|
-
|
|
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
|
|
@@ -268,10 +272,11 @@ const FIELD_VERBS = ['add-field', 'set-field', 'rm-field', 'rename-field', 'rena
|
|
|
268
272
|
//
|
|
269
273
|
// ⚠ Listing one here EXEMPTS it from the "documented flags are accepted by some verb" guard, which
|
|
270
274
|
// 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: `--
|
|
272
|
-
// test/integration/cross-workspace-targeting.test.js. A global
|
|
273
|
-
// defect that guard was written to catch \u2014 add the coverage,
|
|
274
|
-
|
|
275
|
+
// only safe while the behaviour is pinned somewhere else: `--workspace` / `-w` is covered end-to-end in
|
|
276
|
+
// test/integration/workspace-flag.test.js and `--vault` in cross-workspace-targeting.test.js. A global
|
|
277
|
+
// flag with no such file is the exact defect that guard was written to catch \u2014 add the coverage,
|
|
278
|
+
// not the entry.
|
|
279
|
+
export const GLOBAL_FLAGS = ['workspace', 'vault'];
|
|
275
280
|
|
|
276
281
|
export const WORKSPACE_FLAGS = {
|
|
277
282
|
init: ['name', 'data_path', 'harnesses', 'workspace_module'], update: [],
|
|
@@ -521,15 +526,20 @@ export async function run(argv) {
|
|
|
521
526
|
if (sh) line += ` — shadows ${CHANNEL_LABEL[sh.loser]} copy`;
|
|
522
527
|
console.log(line);
|
|
523
528
|
}
|
|
524
|
-
// record layers: other workspaces cloned here for their records
|
|
525
|
-
|
|
529
|
+
// record layers: other workspaces cloned here for their records. The collections listed are
|
|
530
|
+
// the ones FOUND — compiled with this layer as a root and holding a folder in the clone —
|
|
531
|
+
// never the declared `records:`, which narrows and may name a folder that does not exist.
|
|
532
|
+
const layers = layerEntries(ws.pkg, ws.root);
|
|
526
533
|
if (layers.length) {
|
|
527
534
|
console.log('layers:');
|
|
528
|
-
|
|
529
|
-
|
|
535
|
+
let descriptors = [];
|
|
536
|
+
try { descriptors = [...new Store(ws).descriptors.values()]; } catch { /* no runtime yet */ }
|
|
537
|
+
for (const l of layers) {
|
|
538
|
+
const dir = path.join(ws.root, 'git_modules', l.name);
|
|
530
539
|
const ref = fs.existsSync(dir) ? tryGit(dir, ['rev-parse', '--short', 'HEAD']) : null;
|
|
531
|
-
const mod =
|
|
532
|
-
|
|
540
|
+
const mod = l.module ? modules.find((m) => m.layer === l.name) : null;
|
|
541
|
+
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();
|
|
542
|
+
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
543
|
}
|
|
534
544
|
}
|
|
535
545
|
// env-pointed roots (`storage.path: ${env:NAME}/…`), rendered per machine by compile: the
|
package/src/collections-cli.js
CHANGED
|
@@ -144,7 +144,9 @@ export function collectionCommand(ws, collection, verb, args) {
|
|
|
144
144
|
// descriptor v2: a record older than the `created` stamp still answers it — read, never written
|
|
145
145
|
const created = store.createdOf(collection, id, fields, file);
|
|
146
146
|
if (created !== undefined && fields.created === undefined) fields.created = created;
|
|
147
|
-
|
|
147
|
+
// stubs (0.41.0): `$stub` on a placeholder, `$shadows` on whatever answers over placeholders
|
|
148
|
+
const shadows = store.shadowedStubs(collection, id).map((f) => store.locationOf(d, f).file);
|
|
149
|
+
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
150
|
console.log(dump(fields).trimEnd());
|
|
149
151
|
return 0;
|
|
150
152
|
}
|
|
@@ -170,11 +172,13 @@ export function collectionCommand(ws, collection, verb, args) {
|
|
|
170
172
|
flags[titleField] = pos[0];
|
|
171
173
|
}
|
|
172
174
|
const fields = coerceArrays(d, stripMeta(flags));
|
|
173
|
-
const { id, file, idFallback, deprecated } = store.add(collection, fields, { id: flags.id });
|
|
175
|
+
const { id, file, idFallback, deprecated, shadows } = store.add(collection, fields, { id: flags.id });
|
|
174
176
|
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.`);
|
|
177
|
+
// promoting a stub is a choice the operator should see made: name every placeholder it now covers
|
|
178
|
+
const covers = (shadows ?? []).map((f) => store.layerOfFile(d, f)?.layer ?? 'this workspace');
|
|
175
179
|
flags.json
|
|
176
|
-
? emit(JSON.stringify({ id, path: rel(ws.root, file), ...(idFallback ? { idFallback } : {}) }))
|
|
177
|
-
: console.log(`✔ ${at}${rel(ws.root, file)}`);
|
|
180
|
+
? emit(JSON.stringify({ id, path: rel(ws.root, file), ...(idFallback ? { idFallback } : {}), ...(shadows?.length ? { $shadows: shadows.map((f) => store.locationOf(d, f).file) } : {}) }))
|
|
181
|
+
: console.log(`✔ ${at}${rel(ws.root, file)}${covers.length ? ` — shadows ${covers.length} stub${covers.length === 1 ? '' : 's'} (${covers.join(', ')})` : ''}`);
|
|
178
182
|
// ⚠ SAY IT, EVERY TIME. The id was derived from a hash because the value it is generated
|
|
179
183
|
// from carries no a-z0-9 — the write succeeded and the record is fine, but the id is
|
|
180
184
|
// unreadable and unguessable, and nobody finds that out until they try to type it. By
|
|
@@ -235,8 +239,12 @@ export function collectionCommand(ws, collection, verb, args) {
|
|
|
235
239
|
const id = need(pos, 0, 'id');
|
|
236
240
|
if (flags['dry-run']) return dryRunPlan(`rm ${collection}/${id}`, { records: store.ids(collection).has(id) ? 1 : 0, refs: store.findInboundRefs(`${collection}/${id}`).length });
|
|
237
241
|
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
|
-
|
|
242
|
+
const { inboundIgnored, inboundResolveToStub } = store.rm(collection, id, { force: !!flags.force });
|
|
243
|
+
// the id does not vanish when a stub was shadowed by what was just removed — say which now answers
|
|
244
|
+
const next = store.ids(collection).get(id);
|
|
245
|
+
const showing = next ? store.layerOfFile(d, next) : null;
|
|
246
|
+
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})` : '';
|
|
247
|
+
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
248
|
return 0;
|
|
241
249
|
}
|
|
242
250
|
case 'rename': {
|
|
@@ -1006,7 +1014,7 @@ function relationsRebuild(store, flags, pos) {
|
|
|
1006
1014
|
// workspace against a module-owned target) implies no mirror on a target it cannot be committed with
|
|
1007
1015
|
const perRepo = (r) => {
|
|
1008
1016
|
const groups = new Map();
|
|
1009
|
-
for (const o of parseEach(store, r.owner, (f) => unreadableOwners.push(rel(store.root, f)))) {
|
|
1017
|
+
for (const o of parseEach(store, r.owner, (f) => unreadableOwners.push(rel(store.root, f)), { withStubs: true })) {
|
|
1010
1018
|
const repo = store.repoOfFile(store.descriptor(r.owner), o.file);
|
|
1011
1019
|
if (!groups.has(repo)) groups.set(repo, []);
|
|
1012
1020
|
groups.get(repo).push(o);
|
|
@@ -1070,10 +1078,14 @@ function relationsRebuild(store, flags, pos) {
|
|
|
1070
1078
|
* mid-walk cannot be resumed past — and rebuild is the one reader that has already written by the
|
|
1071
1079
|
* time a later record blows up, so an abort leaves a partial sweep behind an error naming no file
|
|
1072
1080
|
* at all. Here the bad record is handed to `onError` and skipped, and the walk finishes. */
|
|
1073
|
-
function* parseEach(store, collection, onError) {
|
|
1081
|
+
function* parseEach(store, collection, onError, { withStubs = false } = {}) {
|
|
1074
1082
|
const d = store.descriptor(collection);
|
|
1075
1083
|
const bf = bodyField(d);
|
|
1076
|
-
|
|
1084
|
+
// `withStubs`: a shadowed stub still OWNS references in its own repo, and the mirrors it justifies
|
|
1085
|
+
// there are not this workspace's to delete
|
|
1086
|
+
const rows = [...store.ids(collection)].map(([id, file]) => ({ id, file }));
|
|
1087
|
+
if (withStubs) rows.push(...store.shadowedStubRecords(collection));
|
|
1088
|
+
for (const { id, file } of rows) {
|
|
1077
1089
|
let fields;
|
|
1078
1090
|
try {
|
|
1079
1091
|
fields = parseRecord(file, d, bf);
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
//
|
|
11
11
|
// A v1 source — a descriptor without `fields`, or a collection-template — is refused, all of them in
|
|
12
12
|
// one message naming the converter. Nothing here reads the v1 shape.
|
|
13
|
+
import fs from 'node:fs';
|
|
13
14
|
import path from 'node:path';
|
|
14
15
|
import Ajv from 'ajv';
|
|
15
16
|
import addFormats from 'ajv-formats';
|
|
@@ -18,7 +19,7 @@ import { resolveFields, toJsonSchema } from './fields.js';
|
|
|
18
19
|
import { targetsOf } from './descriptor.js';
|
|
19
20
|
import { defaultStoragePath, baseNameOf, singular, inflects, namespaceOf, storageOverlaps } from './namespace.js';
|
|
20
21
|
import { subpathProblem } from './placement.js';
|
|
21
|
-
import { patternRe } from './records.js';
|
|
22
|
+
import { patternRe, walk } from './records.js';
|
|
22
23
|
import { renderTemplate } from './env-vars.js';
|
|
23
24
|
|
|
24
25
|
import { CONVERTER } from './extensions.js';
|
|
@@ -65,7 +66,7 @@ const titleCase = (id) => String(id).split(/[_\-\s/]+/).filter(Boolean).map((w)
|
|
|
65
66
|
* @param {Map<string,{root}>} ctx.dataOwners owns-data modules — every collection defaults to `storage.owner: module`
|
|
66
67
|
* @param {Map<string,{name,root,channel}>} ctx.moduleSources every module source, for a descriptor that names `storage.owner: module`
|
|
67
68
|
* @param {(source: object, rel: Function) => string|null} ctx.unownableBecause why a module's clone cannot hold records, or null
|
|
68
|
-
* @param {{name,root,dataPath,records:string[]}[]} ctx.layers record layers — clones whose
|
|
69
|
+
* @param {{name,root,dataPath,records:string[]|null}[]} ctx.layers record layers — clones whose data is read here; `records` narrows, null reads every collection both have
|
|
69
70
|
* @param {(moduleRoot: string) => string} ctx.repoOf workspace-relative git repo of a module root
|
|
70
71
|
* @param {(p: string) => string} ctx.rel
|
|
71
72
|
* @param {string} ctx.dataPath
|
|
@@ -76,7 +77,7 @@ const titleCase = (id) => String(id).split(/[_\-\s/]+/).filter(Boolean).map((w)
|
|
|
76
77
|
* @returns {{ compiled: Map<string, {doc, sources}>, inert: {path, hash}[], moduleColls: Map<string, Set<string>> }}
|
|
77
78
|
*/
|
|
78
79
|
export function compileCollections(ctx) {
|
|
79
|
-
const { groups, mixins, namespaces, nsOwners, runtimeKinds, core, moduleDeps, modulePeers, channelOf, wsModuleName, engineName, dataOwners, moduleSources, unownableBecause, layers = [], repoOf, dataPath, vars, moduleId, fail, warn } = ctx;
|
|
80
|
+
const { groups, mixins, namespaces, nsOwners, runtimeKinds, core, moduleDeps, modulePeers, channelOf, wsModuleName, engineName, dataOwners, moduleSources, unownableBecause, layers = [], repoOf, dataPath, vars, moduleId, fail, warn, root = vars?.workspaceFolder ?? '.' } = ctx;
|
|
80
81
|
|
|
81
82
|
// ---- v1 is refused, every file at once --------------------------------------------------
|
|
82
83
|
const v1 = [];
|
|
@@ -86,6 +87,7 @@ export function compileCollections(ctx) {
|
|
|
86
87
|
const typeNames = new Set([...groups.keys(), ...core]);
|
|
87
88
|
const allPeers = new Set([...modulePeers.values()].flat());
|
|
88
89
|
const out = new Map();
|
|
90
|
+
const layerClaims = new Map(); // layer name -> clone folders some collection here accounts for
|
|
89
91
|
const inert = [];
|
|
90
92
|
const moduleColls = new Map();
|
|
91
93
|
const owners = new Map(); // collection -> owning module name
|
|
@@ -202,10 +204,21 @@ export function compileCollections(ctx) {
|
|
|
202
204
|
// ---- record layers: the listed clones' data folders, read BELOW the write root ----
|
|
203
205
|
const collLayers = [];
|
|
204
206
|
for (const l of layers) {
|
|
205
|
-
|
|
207
|
+
// where this collection's records would sit in the clone — claimed, so the unread-folder
|
|
208
|
+
// pass below never names a folder some collection here accounts for
|
|
209
|
+
const at = `${l.root}/${a.path && !pointed && !runtime ? a.path : defaultStoragePath(name, namespaces, l.dataPath)}`;
|
|
210
|
+
(layerClaims.get(l.name) ?? layerClaims.set(l.name, new Set()).get(l.name)).add(at);
|
|
211
|
+
if (l.records && !l.records.includes(name)) continue;
|
|
206
212
|
const why = runtime ? 'is a compiled source' : owner === 'module' ? `is \`storage.owner: module\` — one shared list read from the module's clone, which a layer would duplicate` : a.under ? 'is stored under another collection (storage.under) — a placed collection is not layered' : pointed ? 'is env-pointed (its storage.path is a template) — its records are per machine, not a clone\'s' : null;
|
|
207
|
-
if (why) fail(`git_modules.${l.name}.records names "${name}", which ${why}`);
|
|
208
|
-
|
|
213
|
+
if (why && l.records) fail(`git_modules.${l.name}.records names "${name}", which ${why}`);
|
|
214
|
+
if (why) {
|
|
215
|
+
// an INHERENT layer reads every collection both have, so one that cannot layer is skipped —
|
|
216
|
+
// said only when the clone actually holds records there, so a quiet compile stays quiet
|
|
217
|
+
const n = fileCount(path.join(root, at));
|
|
218
|
+
if (n) warn(`ℹ layer ${l.name}: ${name} is not read from the layer — it ${why} (${n} file${n === 1 ? '' : 's'} in ${at}/ unread)`);
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
collLayers.push({ name: l.name, path: at, repo: l.root });
|
|
209
222
|
}
|
|
210
223
|
|
|
211
224
|
// an opaque record's fields are the ones derived from the file itself
|
|
@@ -216,7 +229,7 @@ export function compileCollections(ctx) {
|
|
|
216
229
|
fields.ext ??= { type: 'string', virtual: true, description: "The file's extension, lowercase and without the dot. Read from the file." };
|
|
217
230
|
fields.bytes ??= { type: 'integer', virtual: true, description: "The file's size in bytes. Read from the file." };
|
|
218
231
|
}
|
|
219
|
-
const { fields: resolved, errors, warnings, defaults: fieldDefaults } = resolveFields(fields, { name, collections: typeNames, peers: allPeers, runtime });
|
|
232
|
+
const { fields: resolved, errors, warnings, defaults: fieldDefaults } = resolveFields(fields, { name, collections: typeNames, peers: allPeers, runtime, unlayerable: owner === 'module' || !!a.under || !!pointed });
|
|
220
233
|
if (errors.length) fail(`collection "${name}" (${where}):\n ${errors.join('\n ')}`);
|
|
221
234
|
for (const w of warnings) warn(`⚠ collection ${name}: ${w}`);
|
|
222
235
|
const constraints = authored.constraints ?? [];
|
|
@@ -322,7 +335,13 @@ export function compileCollections(ctx) {
|
|
|
322
335
|
|
|
323
336
|
for (const p of storageOverlaps(storageEntries)) fail(p);
|
|
324
337
|
for (const l of layers) {
|
|
325
|
-
for (const c of l.records) if (!staged.has(c)) fail(`git_modules.${l.name}.records names "${c}", which is not a collection here (have: ${[...staged.keys()].sort().join(', ')})`);
|
|
338
|
+
for (const c of l.records ?? []) if (!staged.has(c)) fail(`git_modules.${l.name}.records names "${c}", which is not a collection here (have: ${[...staged.keys()].sort().join(', ')})`);
|
|
339
|
+
}
|
|
340
|
+
// A layer folder no collection here accounts for — the project's own domain collections, read by a
|
|
341
|
+
// workspace that does not install their module — is WARNED, never failed: reading a project without
|
|
342
|
+
// its domain module is legitimate, but its records silently not appearing is not.
|
|
343
|
+
for (const l of layers) for (const [folder, n] of unreadFolders(root, `${l.root}/${l.dataPath}`, layerClaims.get(l.name) ?? new Set())) {
|
|
344
|
+
warn(`⚠ layer ${l.name}: ${folder}/ holds ${n} file${n === 1 ? '' : 's'} and no collection here reads it — install the module that defines it to read them${l.records ? '' : ', or list the collections to read in git_modules.' + l.name + '.records'}`);
|
|
326
345
|
}
|
|
327
346
|
{
|
|
328
347
|
const words = new Map();
|
|
@@ -408,3 +427,32 @@ function placement(out, fail) {
|
|
|
408
427
|
c.compiled.under_collection = parentName;
|
|
409
428
|
}
|
|
410
429
|
}
|
|
430
|
+
|
|
431
|
+
/** How many files sit under a folder, recursively — 0 when it is absent. */
|
|
432
|
+
function fileCount(dir) {
|
|
433
|
+
if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) return 0;
|
|
434
|
+
let n = 0;
|
|
435
|
+
for (const _ of walk(dir)) n++;
|
|
436
|
+
return n;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/** `[folder, fileCount]` for each folder under a layer's data path that no claimed path accounts for:
|
|
440
|
+
* a claimed folder is skipped, one that is a PREFIX of a claimed path (a namespace folder) is
|
|
441
|
+
* descended into, anything else is unread. Paths are workspace-relative, `/`-joined. */
|
|
442
|
+
function unreadFolders(root, dataDir, claimed) {
|
|
443
|
+
const out = [];
|
|
444
|
+
const visit = (rel) => {
|
|
445
|
+
const abs = path.join(root, rel);
|
|
446
|
+
if (!fs.existsSync(abs)) return;
|
|
447
|
+
for (const e of fs.readdirSync(abs, { withFileTypes: true }).sort((x, y) => x.name.localeCompare(y.name))) {
|
|
448
|
+
if (!e.isDirectory() || e.name.startsWith('.')) continue;
|
|
449
|
+
const p = `${rel}/${e.name}`;
|
|
450
|
+
if (claimed.has(p)) continue;
|
|
451
|
+
if ([...claimed].some((c) => c.startsWith(`${p}/`))) { visit(p); continue; }
|
|
452
|
+
const n = fileCount(path.join(root, p));
|
|
453
|
+
if (n) out.push([p, n]);
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
visit(dataDir);
|
|
457
|
+
return out;
|
|
458
|
+
}
|
package/src/compile.js
CHANGED
|
@@ -16,7 +16,7 @@ import {
|
|
|
16
16
|
// circular on paper in earlier versions — safe: both sides only
|
|
17
17
|
// call at run time, same pattern as store.js ↔ compile.js.
|
|
18
18
|
import { runHarnessAdapters, renderContributions, BEGIN, END, INSTRUCTIONS_BEGIN, INSTRUCTIONS_END } from './harnesses.js';
|
|
19
|
-
import { ensureEditorRecommendation, ensureEnvExample, ensureGitignored } from './workspace.js';
|
|
19
|
+
import { ensureEditorRecommendation, ensureEnvExample, ensureGitignored, layerEntries } from './workspace.js';
|
|
20
20
|
import { satisfies } from './semver.js';
|
|
21
21
|
import { parseEnvValues } from './env-vars.js';
|
|
22
22
|
import { DERIVED_KINDS, readManifest, runtimeDir, engineId, engineVersion, loadDescriptors as loadCompiledDescriptors, STALE_RUNTIME } from './runtime.js';
|
|
@@ -175,10 +175,11 @@ export function discoverModules(root, pkg) {
|
|
|
175
175
|
// caller (compile, status, install) sees the same set.
|
|
176
176
|
const disable = pkg?.dreamteamer?.disable ?? [];
|
|
177
177
|
const disabledHits = new Set();
|
|
178
|
-
// A clone
|
|
179
|
-
//
|
|
180
|
-
// `module: true` its ONE workspace
|
|
181
|
-
|
|
178
|
+
// A clone that is a WORKSPACE (its own manifest names `workspace_module`), or whose entry lists
|
|
179
|
+
// `records`, is a RECORD LAYER — another workspace's data read here — never a bundle: its own
|
|
180
|
+
// modules/ would otherwise unpack and collide with ours. With `module: true` its ONE workspace
|
|
181
|
+
// module is a source too (below).
|
|
182
|
+
const layerList = layerEntries(pkg, root);
|
|
182
183
|
const layers = new Set(layerList.map((l) => l.name));
|
|
183
184
|
// the same rule the extension loader applies (full package name, or its scope-stripped id), so a
|
|
184
185
|
// disabled package loses its content AND its code together
|
|
@@ -293,29 +294,14 @@ function dataOwningModules(sources, fail, rel) {
|
|
|
293
294
|
const toPosix = (p) => p.split(path.sep).join('/');
|
|
294
295
|
|
|
295
296
|
// ---- record layers ----------------------------------------------------------------
|
|
296
|
-
// A `git_modules`
|
|
297
|
-
//
|
|
298
|
-
//
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
export
|
|
304
|
-
const out = [];
|
|
305
|
-
for (const [name, entry] of Object.entries(pkg?.dreamteamer?.git_modules ?? {})) {
|
|
306
|
-
if (entry?.module !== undefined && typeof entry.module !== 'boolean') throw new Error(`git_modules.${name}.module must be true or false (got ${JSON.stringify(entry.module)})`);
|
|
307
|
-
if (entry?.module === true && entry.records === undefined) {
|
|
308
|
-
throw new Error(`git_modules.${name}.module: true without \`records\` — an entry without records is already a bundle: every module under its modules/ compiles. Drop \`module\`, or list the collections it layers.`);
|
|
309
|
-
}
|
|
310
|
-
if (!entry || entry.records === undefined) continue;
|
|
311
|
-
const r = entry.records;
|
|
312
|
-
if (!Array.isArray(r) || !r.length || r.some((c) => typeof c !== 'string' || !c.trim())) {
|
|
313
|
-
throw new Error(`git_modules.${name}.records must be a non-empty list of collection names (got ${JSON.stringify(r)})`);
|
|
314
|
-
}
|
|
315
|
-
out.push({ name, records: r, module: entry.module === true });
|
|
316
|
-
}
|
|
317
|
-
return out;
|
|
318
|
-
}
|
|
297
|
+
// A `git_modules` clone that is itself a WORKSPACE (its manifest names `workspace_module`) — or an
|
|
298
|
+
// entry that lists `records:` — is a record layer: every collection both have reads that clone's data
|
|
299
|
+
// folder as a root below this workspace's own, `records:` narrowing the set when present. The clone
|
|
300
|
+
// contributes no sources — its shapes are the modules both workspaces install.
|
|
301
|
+
|
|
302
|
+
// `layerEntries` lives in workspace.js — compile, status and the extension loader all ask it, and the
|
|
303
|
+
// loader cannot import this file (compile imports the loader). Re-exported under its old address.
|
|
304
|
+
export { layerEntries };
|
|
319
305
|
|
|
320
306
|
/** A layer's data folder, from the clone's own manifest (its `data_path`), default `data`. The clone
|
|
321
307
|
* may be absent — a fresh checkout before `dreamteamer install` — and then the default stands. */
|
|
@@ -626,8 +612,9 @@ export function compile(ws) {
|
|
|
626
612
|
|
|
627
613
|
const dataOwners = dataOwningModules(sources, fail, rel);
|
|
628
614
|
let layers;
|
|
629
|
-
try { layers = layerEntries(pkg).map((l) => ({ ...l, root: path.posix.join('git_modules', l.name), dataPath: layerDataPath(root, l.name) })); }
|
|
615
|
+
try { layers = layerEntries(pkg, root).map((l) => ({ ...l, root: path.posix.join('git_modules', l.name), dataPath: layerDataPath(root, l.name) })); }
|
|
630
616
|
catch (e) { fail(e.message); }
|
|
617
|
+
for (const l of layers) if (!fs.existsSync(path.join(root, l.root))) console.warn(`⚠ layer ${l.name} (${l.root}) is not installed — its records are not read; run dreamteamer install`);
|
|
631
618
|
|
|
632
619
|
const disabled = new Set(config.disable ?? []);
|
|
633
620
|
const disabledHits = new Set(disabledModules); // bare entries were applied at discovery
|
|
@@ -897,7 +884,7 @@ export function compile(ws) {
|
|
|
897
884
|
runtimeKinds: new Set([...kinds, ...DERIVED_KINDS]), core: CORE_COLLECTIONS,
|
|
898
885
|
moduleDeps, modulePeers, channelOf, wsModuleName, engineName, dataOwners,
|
|
899
886
|
moduleSources: new Map(sources.map((s) => [s.name, s])), unownableBecause, layers,
|
|
900
|
-
repoOf: (moduleRoot) => repoRootOf(moduleRoot, root), rel, dataPath: config.data_path ?? 'data', vars: storageVars,
|
|
887
|
+
repoOf: (moduleRoot) => repoRootOf(moduleRoot, root), rel, root, dataPath: config.data_path ?? 'data', vars: storageVars,
|
|
901
888
|
moduleId, fail: collectionsFail, warn: (m) => console.warn(m),
|
|
902
889
|
});
|
|
903
890
|
refusePlacementTransitions(root, compiledColls);
|
package/src/extensions.js
CHANGED
|
@@ -29,6 +29,7 @@ import path from 'node:path';
|
|
|
29
29
|
import { pathToFileURL } from 'node:url';
|
|
30
30
|
import { satisfies } from './semver.js';
|
|
31
31
|
import { engineVersion } from './runtime.js';
|
|
32
|
+
import { layerEntries } from './workspace.js';
|
|
32
33
|
|
|
33
34
|
/** The keys a package.json `dreamteamer` block may carry — the workspace's and a module's alike. */
|
|
34
35
|
export const MANIFEST_KEYS = ['title', 'description', 'workspace_module', 'data_path', 'namespaces', 'vars', 'env', 'auto_commit', 'harnesses', 'git_modules', 'disable', 'local_assets', 'postinstall', 'gitignore_runtime_folder', 'repos_path', 'dependencies', 'peer_collections', 'owns_data', 'engine', 'extension', 'ignore'];
|
|
@@ -80,7 +81,7 @@ export function declaredExtensions(ws) {
|
|
|
80
81
|
try { inline = fs.readdirSync(path.join(ws.root, 'modules')).sort(); } catch { /* no modules/ */ }
|
|
81
82
|
for (const id of inline) consider(path.join(ws.root, 'modules', id), id);
|
|
82
83
|
const listed = (dir) => { try { return fs.readdirSync(dir).sort(); } catch { return []; } };
|
|
83
|
-
const layers = new Set(
|
|
84
|
+
const layers = new Set(layerEntries(ws.pkg, ws.root).map((l) => l.name));
|
|
84
85
|
for (const clone of listed(path.join(ws.root, 'git_modules'))) {
|
|
85
86
|
if (layers.has(clone)) continue; // a record layer: another workspace's data, never its code
|
|
86
87
|
const root = path.join(ws.root, 'git_modules', clone);
|
package/src/fields.js
CHANGED
|
@@ -28,11 +28,14 @@ export const DISPLAY_KEYS = new Set(['editable', 'hidden', 'form_section', 'plac
|
|
|
28
28
|
/** JSON Schema keywords copied onto the emitted property unchanged. */
|
|
29
29
|
const PASS_THROUGH = ['default', 'examples', 'pattern', 'minimum', 'maximum', 'minItems', 'maxItems', 'minLength', 'maxLength', 'const'];
|
|
30
30
|
|
|
31
|
-
/** The
|
|
31
|
+
/** The fields every collection has. `created` is stored (engine-written); `id` and `last_modified` are
|
|
32
|
+
* computed on read; `stub` is stored and written by hand — the engine only READS it, to decide which
|
|
33
|
+
* of several roots answers an id (records.js `resolveClaims`). */
|
|
32
34
|
export const INJECTED_FIELDS = {
|
|
33
35
|
id: { type: 'string', title: 'Id', virtual: true, description: 'The record\'s path inside its collection.' },
|
|
34
36
|
created: { type: 'datetime', title: 'Created', derived: true, description: 'When the record was first written. Stamped by the engine at add; read from the id\'s date or the first commit for a record written before it existed.' },
|
|
35
37
|
last_modified: { type: 'datetime', title: 'Last modified', virtual: true, description: 'When the record was last committed, from git.' },
|
|
38
|
+
stub: { type: 'boolean', title: 'Stub', display: { hidden: ['list', 'form'] }, description: 'A placeholder: it yields to a real record of the same id in any other root (a record layer, or the workspace reading this one), and answers only where none exists.' },
|
|
36
39
|
};
|
|
37
40
|
|
|
38
41
|
/** Is `type` a reference to one or more collections, given the names that exist? */
|
|
@@ -58,9 +61,12 @@ export function resolveFields(authored, ctx) {
|
|
|
58
61
|
const defaults = {};
|
|
59
62
|
const known = new Set(Object.keys(authored ?? {}));
|
|
60
63
|
const fields = {};
|
|
61
|
-
// `created` is STAMPED by the store, which a kind whose records compile writes never goes through
|
|
64
|
+
// `created` is STAMPED by the store, which a kind whose records compile writes never goes through;
|
|
65
|
+
// `stub` exists only where a record can yield — a collection that can never be a layer root (a
|
|
66
|
+
// compiled source, module-owned, placed, env-pointed: ctx.unlayerable) has nothing to yield to
|
|
62
67
|
for (const [k, v] of Object.entries(INJECTED_FIELDS)) {
|
|
63
68
|
if (k === 'created' && ctx.runtime) continue;
|
|
69
|
+
if (k === 'stub' && (ctx.runtime || ctx.unlayerable)) continue;
|
|
64
70
|
if (known.has(k)) errors.push(`field "${k}" is injected by the engine and cannot be authored`);
|
|
65
71
|
fields[k] = { ...v };
|
|
66
72
|
}
|
package/src/records.js
CHANGED
|
@@ -29,6 +29,31 @@ export function parseRecordText(text, d, bodyField) {
|
|
|
29
29
|
return fields;
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
+
// ---- stubs: a record that yields its id (0.41.0) --------------------------------------
|
|
33
|
+
// A record carrying `stub: true` is a placeholder — a thin copy a workspace keeps so its own references
|
|
34
|
+
// resolve standalone — and it YIELDS to any non-stub of the same id in any other root. The store and
|
|
35
|
+
// `check` both decide which file answers an id through `resolveClaims`, so they cannot disagree.
|
|
36
|
+
|
|
37
|
+
/** Does a record file carry `stub: true`? Read only for an id more than one root claims — never for the
|
|
38
|
+
* whole index. A file record (`format: binary`) has no fields and is never a stub; one that will not
|
|
39
|
+
* parse is not a stub either, and `check` reports the parse error on its own. */
|
|
40
|
+
export function isStubRecord(file, d) {
|
|
41
|
+
if (storageOf(d).format === 'binary') return false;
|
|
42
|
+
try { return parseRecordText(fs.readFileSync(file, 'utf8'), d).stub === true; } catch { return false; }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Which of an id's claimants answers, in root order. One non-stub wins wherever it sits and every stub
|
|
46
|
+
* is `shadowed`; two or more non-stubs are `conflicts` (the first answers, exactly as before stubs
|
|
47
|
+
* existed); stubs only — the first root answers and the rest are shadowed. A stub only ever weakens
|
|
48
|
+
* its own claim, so nothing a layer writes can displace a non-stub. */
|
|
49
|
+
export function resolveClaims(claims, isStub) {
|
|
50
|
+
if (claims.length < 2) return { winner: claims[0], conflicts: [], shadowed: [] };
|
|
51
|
+
const stub = claims.map(isStub);
|
|
52
|
+
const real = claims.filter((_, i) => !stub[i]);
|
|
53
|
+
if (!real.length) return { winner: claims[0], conflicts: [], shadowed: claims.slice(1) };
|
|
54
|
+
return { winner: real[0], conflicts: real.length > 1 ? real : [], shadowed: claims.filter((_, i) => stub[i]) };
|
|
55
|
+
}
|
|
56
|
+
|
|
32
57
|
// id patterns may use unicode property escapes — compile with the u flag
|
|
33
58
|
export function patternRe(pattern) {
|
|
34
59
|
try { return new RegExp(pattern, 'u'); } catch { return new RegExp(pattern); }
|
package/src/schema-ops.js
CHANGED
|
@@ -14,7 +14,7 @@ import { v1Refusal } from './compile-collections.js';
|
|
|
14
14
|
import { readManifest, loadDescriptors } from './runtime.js';
|
|
15
15
|
import { normalizeNamespaces, namespaceOf, baseNameOf, qualify, defaultStoragePath, singular } from './namespace.js';
|
|
16
16
|
import { fieldsOf, targetsOf, storageOf, isRuntime, bodyFieldOf, moduleOf } from './descriptor.js';
|
|
17
|
-
import { SCALAR_TYPES, enumValues } from './fields.js';
|
|
17
|
+
import { SCALAR_TYPES, enumValues, INJECTED_FIELDS } from './fields.js';
|
|
18
18
|
import { FIELD_OPTIONS, TEMPLATE_OPTIONS } from './views.js';
|
|
19
19
|
|
|
20
20
|
// Same rule as store.js: a git failure we CATCH must not also print git's own error on top of the
|
|
@@ -2145,8 +2145,8 @@ function pruneEmpty(dir, stopAt) {
|
|
|
2145
2145
|
/** The order a field's keys are written in (§3.4.1): facts about the data, `display`, then what it means. */
|
|
2146
2146
|
const FIELD_KEY_ORDER = ['type', 'title', 'required', 'many', 'default', 'enum', 'unique', 'mirror_of', 'on_delete', 'soft', 'sensitive', 'body', 'derived', 'virtual', 'deprecated', 'passthrough', 'fields', 'values', 'item_title', 'examples', 'pattern', 'minimum', 'maximum', 'minItems', 'maxItems', 'minLength', 'maxLength', 'const', 'display', 'description'];
|
|
2147
2147
|
|
|
2148
|
-
/** The
|
|
2149
|
-
const INJECTED = new Set(
|
|
2148
|
+
/** The fields compile injects into every collection — no source declares one. */
|
|
2149
|
+
const INJECTED = new Set(Object.keys(INJECTED_FIELDS));
|
|
2150
2150
|
|
|
2151
2151
|
/** `--type`: a built-in type, a collection, `a,b` for a union of collections, or `reference`. A
|
|
2152
2152
|
* collection may not be named after a built-in type (compile refuses it), so the two never collide. */
|
package/src/store.js
CHANGED
|
@@ -9,7 +9,7 @@ import Ajv from 'ajv';
|
|
|
9
9
|
import addFormats from 'ajv-formats';
|
|
10
10
|
import { dump, writeSource } from './yaml.js';
|
|
11
11
|
import { generateId } from './template.js';
|
|
12
|
-
import { parseRecord, parseRecordText, patternRe, fmtAjvError, unknownFields, walk, EXT, assertSafeId, idFromRecordPath, MAX_RECORD_BYTES } from './records.js';
|
|
12
|
+
import { parseRecord, parseRecordText, patternRe, fmtAjvError, unknownFields, walk, EXT, assertSafeId, idFromRecordPath, MAX_RECORD_BYTES, isStubRecord, resolveClaims } from './records.js';
|
|
13
13
|
import { normalizeRecord, normalizeTemporal } from './temporal.js';
|
|
14
14
|
import { NO_RUNTIME, sourceHint, loadDescriptors, runtimeDir, namespaces as compiledNamespaces, sourceRoots as compiledSourceRoots } from './runtime.js';
|
|
15
15
|
import { parseRef } from './namespace.js';
|
|
@@ -36,6 +36,8 @@ export class Store {
|
|
|
36
36
|
this.ajv.addFormat('markdown', true);
|
|
37
37
|
this._idsCache = new Map(); // collection -> { key, ids } (see ids())
|
|
38
38
|
this._duplicates = new Map(); // placed collection -> id -> [files], refreshed by every walk (see assertUnambiguous)
|
|
39
|
+
this._stubs = new Map(); // layered collection -> id -> [stub files the answering record shadows]
|
|
40
|
+
this._claimFiles = new Map(); // layered collection -> every file of a contested id at the last walk (see _claimStamps)
|
|
39
41
|
this._head = undefined; // memoized `git rev-parse HEAD` (see gitHead())
|
|
40
42
|
const descriptors = loadDescriptors(root);
|
|
41
43
|
if (!descriptors) throw new Error(NO_RUNTIME);
|
|
@@ -417,10 +419,22 @@ export class Store {
|
|
|
417
419
|
const hit = this._idsCache.get(collection);
|
|
418
420
|
if (hit?.key === key) return hit.ids;
|
|
419
421
|
const ids = this._walkIds(d, dir);
|
|
420
|
-
|
|
422
|
+
// the folder half as measured BEFORE the walk (a change during it invalidates the next read), the
|
|
423
|
+
// claimant half AFTER it — the walk is what decides which files are contested
|
|
424
|
+
this._idsCache.set(collection, { key: key.replace(/\|claims:.*$/, '') + this._claimStamps(d), ids });
|
|
421
425
|
return ids;
|
|
422
426
|
}
|
|
423
427
|
|
|
428
|
+
/** Which file answers a contested id depends on file CONTENT (`stub: true`), which an in-place edit
|
|
429
|
+
* changes without moving any folder or HEAD — so the files of every id more than one root claimed at
|
|
430
|
+
* the last walk are stamped too (mtime and size). Empty for an uncontested collection. */
|
|
431
|
+
_claimStamps(d) {
|
|
432
|
+
const files = this._claimFiles.get(d.name);
|
|
433
|
+
if (!files?.length) return '';
|
|
434
|
+
const st = (f) => { try { const s = fs.statSync(f); return `${s.mtimeMs}:${s.size}`; } catch { return '-'; } };
|
|
435
|
+
return `|claims:${files.map(st).join(',')}`;
|
|
436
|
+
}
|
|
437
|
+
|
|
424
438
|
/** The validity key `ids()` compares against, as its own method because `add` restates it AFTER
|
|
425
439
|
* its write — the only way an index it just extended can still be accepted by the next call.
|
|
426
440
|
* For a placed collection the PARENT root's mtime is in it too: a new parent folder is a new
|
|
@@ -435,7 +449,7 @@ export class Store {
|
|
|
435
449
|
// vanished folder changes the string as surely as a changed one. A LAYER is the same shape:
|
|
436
450
|
// `dt update` pulls files into it without moving this workspace's HEAD or any root's mtime.
|
|
437
451
|
const dirs = this.recordDirs(d);
|
|
438
|
-
return `${this.gitHead()}:${dirs.map(dirTreeStamps).join('|')}`;
|
|
452
|
+
return `${this.gitHead()}:${dirs.map(dirTreeStamps).join('|')}${this._claimStamps(d)}`;
|
|
439
453
|
}
|
|
440
454
|
|
|
441
455
|
/** Refuse a placed write whose path crosses a symlink inside the parent collection's root — a link
|
|
@@ -493,14 +507,29 @@ export class Store {
|
|
|
493
507
|
// Across every root, write root first. FIRST claimant wins and the rest are left for `check`
|
|
494
508
|
// to report — the same rule placement follows, for the same reason: a `get` that answered
|
|
495
509
|
// from whichever layer sorted later would make the answer depend on the clone order.
|
|
496
|
-
|
|
510
|
+
//
|
|
511
|
+
// A STUB yields (records.js resolveClaims): an id two roots claim has its claimants' frontmatter
|
|
512
|
+
// read — only those files, never the whole index — and a non-stub answers wherever it sits.
|
|
513
|
+
// Only two non-stubs are the duplicate that refuses a write.
|
|
514
|
+
const claims = new Map();
|
|
497
515
|
for (const root of this.rootsOf(d)) {
|
|
498
516
|
for (const [id, f] of this._walkRoot(d, root.abs)) {
|
|
499
|
-
|
|
500
|
-
|
|
517
|
+
const c = claims.get(id);
|
|
518
|
+
if (c) c.push(f); else claims.set(id, [f]);
|
|
501
519
|
}
|
|
502
520
|
}
|
|
521
|
+
const dupes = new Map();
|
|
522
|
+
const stubs = new Map();
|
|
523
|
+
for (const [id, files] of claims) {
|
|
524
|
+
if (files.length === 1) { ids.set(id, files[0]); continue; }
|
|
525
|
+
const { winner, conflicts, shadowed } = resolveClaims(files, (f) => isStubRecord(f, d));
|
|
526
|
+
ids.set(id, winner);
|
|
527
|
+
if (conflicts.length) dupes.set(id, conflicts);
|
|
528
|
+
if (shadowed.length) stubs.set(id, shadowed);
|
|
529
|
+
}
|
|
503
530
|
this._duplicates.set(d.name, dupes);
|
|
531
|
+
this._stubs.set(d.name, stubs);
|
|
532
|
+
this._claimFiles.set(d.name, [...claims.values()].filter((f) => f.length > 1).flat());
|
|
504
533
|
return ids;
|
|
505
534
|
}
|
|
506
535
|
if (storageOf(d).shape === 'folder') {
|
|
@@ -970,7 +999,9 @@ export class Store {
|
|
|
970
999
|
// `check` would report, and refusing it here is what keeps the id unique across every root.
|
|
971
1000
|
const file = this.filePath(d, id, undefined, fields);
|
|
972
1001
|
this._assertContained(d, file);
|
|
973
|
-
|
|
1002
|
+
// An id held ONLY by stubs in other roots is free: this write promotes it, and says so (`shadows`).
|
|
1003
|
+
const shadows = this.layered(d) && !fs.existsSync(file) && this.ids(collection).has(id) ? this._stubOnlyClaims(d, id) : [];
|
|
1004
|
+
if (fs.existsSync(file) || ((placementOf(d) || this.layered(d)) && this.ids(collection).has(id) && !shadows.length)) throw new Error(`${collection}/${id} already exists — nothing was written.`);
|
|
974
1005
|
return this.withWriteLock(() => {
|
|
975
1006
|
// captured before the invalidation and handed back, one entry richer, on the success path
|
|
976
1007
|
// below — see _indexAdd for why an add that throws it away is the expensive shape.
|
|
@@ -1008,7 +1039,7 @@ export class Store {
|
|
|
1008
1039
|
}, storageOf(d).repo);
|
|
1009
1040
|
// LAST, after the commit: the key it is re-stated under carries the sha, and `commit` moves it
|
|
1010
1041
|
this._indexAdd(collection, memo, id, file);
|
|
1011
|
-
return { id, file, idFallback, ...(deprecated.length && { deprecated }) };
|
|
1042
|
+
return { id, file, idFallback, ...(deprecated.length && { deprecated }), ...(shadows.length && { shadows }) };
|
|
1012
1043
|
});
|
|
1013
1044
|
}
|
|
1014
1045
|
|
|
@@ -1127,6 +1158,26 @@ export class Store {
|
|
|
1127
1158
|
return null;
|
|
1128
1159
|
}
|
|
1129
1160
|
|
|
1161
|
+
/** Every file claiming `id` when ALL of them are stubs, else `[]` — the case where `add` may promote. */
|
|
1162
|
+
_stubOnlyClaims(d, id) {
|
|
1163
|
+
const files = [this.ids(d.name).get(id), ...this.shadowedStubs(d.name, id)];
|
|
1164
|
+
return files.every((f) => isStubRecord(f, d)) ? files : [];
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
/** The stub files an id's answering record shadows, in root order — `[]` for an id only one root
|
|
1168
|
+
* claims. What `dt get --json` reports as `$shadows`, and what `rm` of the winner leaves showing. */
|
|
1169
|
+
shadowedStubs(collection, id) {
|
|
1170
|
+
this.ids(collection); // ensures the memo is current
|
|
1171
|
+
return this._stubs.get(collection)?.get(id) ?? [];
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
/** Every shadowed stub of a collection, `{ id, file }` — a stub is a real OWNER in its own repo, so
|
|
1175
|
+
* the mirrors it justifies there are still expected (check, relations rebuild). */
|
|
1176
|
+
*shadowedStubRecords(collection) {
|
|
1177
|
+
this.ids(collection);
|
|
1178
|
+
for (const [id, files] of this._stubs.get(collection) ?? []) for (const file of files) yield { id, file };
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1130
1181
|
/** Refuse to WRITE to an id that two files claim. The index keeps the first claimant so reads
|
|
1131
1182
|
* still answer, but a write would land on one copy and leave the other saying something else —
|
|
1132
1183
|
* the exact ambiguity `check` reports, made worse under a verb that printed ✔. */
|
|
@@ -1218,6 +1269,13 @@ export class Store {
|
|
|
1218
1269
|
}
|
|
1219
1270
|
}
|
|
1220
1271
|
|
|
1272
|
+
// ---- an id a STUB keeps answering does not go away -----------------------------------
|
|
1273
|
+
// Removing the record that answers over a stub leaves the id resolving — to the stub. So every
|
|
1274
|
+
// reference to it still resolves: nothing is refused for them, nothing is set to null, and
|
|
1275
|
+
// nothing is reported dangling. (Its own mirror entries are still detached below.)
|
|
1276
|
+
const keepsResolving = this.shadowedStubs(collection, id).length > 0;
|
|
1277
|
+
if (keepsResolving) setNullEdits.length = 0;
|
|
1278
|
+
|
|
1221
1279
|
// ---- what the text scan finds that is NOT the engine's own bookkeeping -------------
|
|
1222
1280
|
// The scan is per FILE, and one file can name this record TWICE — a mirror the engine wrote, and
|
|
1223
1281
|
// a wikilink somebody typed in the same record's body. So excluding a file WHOLESALE is wrong:
|
|
@@ -1262,7 +1320,7 @@ export class Store {
|
|
|
1262
1320
|
// shape, which is what this sentence has always said. What the scan misses (a bare FK, or an
|
|
1263
1321
|
// owner file excluded because it also holds a mirror of ours) is named as record + field.
|
|
1264
1322
|
const extraRestrict = restrictHits.filter((h) => !inbound.includes(h.file));
|
|
1265
|
-
if ((inbound.length || extraRestrict.length) && !force) {
|
|
1323
|
+
if ((inbound.length || extraRestrict.length) && !force && !keepsResolving) {
|
|
1266
1324
|
const all = [...inbound, ...extraRestrict.map((h) => `${h.file} (${h.ref}.${h.field})`)];
|
|
1267
1325
|
throw new Error(`${self} is referenced by:\n${all.map((f) => ` ${f}`).join('\n')}\nfix the references or pass --force. nothing was removed.`);
|
|
1268
1326
|
}
|
|
@@ -1329,7 +1387,8 @@ export class Store {
|
|
|
1329
1387
|
// target is gone but its owners still name it is a history that never held a consistent
|
|
1330
1388
|
// workspace.
|
|
1331
1389
|
this.commit([unit, ...mirrors.files, ...nullFiles], `dreamteamer: ${collection} rm ${id}`, rollback, this.repoOfFile(d, unit));
|
|
1332
|
-
|
|
1390
|
+
const inboundCount = inbound.length + extraRestrict.length;
|
|
1391
|
+
return { id, inboundIgnored: force && !keepsResolving ? inboundCount : 0, ...(keepsResolving ? { inboundResolveToStub: inboundCount } : {}) };
|
|
1333
1392
|
});
|
|
1334
1393
|
}
|
|
1335
1394
|
|
package/src/workspace.js
CHANGED
|
@@ -36,12 +36,48 @@ export function findWorkspace(start = process.cwd()) {
|
|
|
36
36
|
// as something OTHER than a module.
|
|
37
37
|
let found = candidates[0];
|
|
38
38
|
for (const higher of candidates.slice(1)) {
|
|
39
|
+
// a workspace named with `--workspace` (bin/dreamteamer.js pins it, for THIS process only — never
|
|
40
|
+
// in the environment, so no child inherits it) is never climbed out of, even when it is a clone
|
|
41
|
+
// under another workspace's git_modules/ — that is exactly the case it names.
|
|
42
|
+
if (found.root === globalThis[Symbol.for('dreamteamer.workspace')]) break;
|
|
39
43
|
if (!nestedAsModule(higher.root, found.root)) break;
|
|
40
44
|
found = higher;
|
|
41
45
|
}
|
|
42
46
|
return found;
|
|
43
47
|
}
|
|
44
48
|
|
|
49
|
+
/** The declared record layers, validated: `{ name, records, module }` per entry. WHAT THE CLONE IS
|
|
50
|
+
* decides it, not the reader's key (0.41.0): a clone whose own manifest names `workspace_module` is a
|
|
51
|
+
* workspace, so its data is a layer for every collection both have (`records: null`); a clone that
|
|
52
|
+
* names none is a bundle and is not listed here; a clone not on disk is listed (not installed). `records:` still makes an entry a layer and NARROWS
|
|
53
|
+
* it to the listed collections; `module: true` declares one too (and is refused downstream when the
|
|
54
|
+
* clone has no workspace module to contribute). `root` absent reads only the declarations. */
|
|
55
|
+
export function layerEntries(pkg, root = null) {
|
|
56
|
+
const out = [];
|
|
57
|
+
for (const [name, entry] of Object.entries(pkg?.dreamteamer?.git_modules ?? {})) {
|
|
58
|
+
if (entry?.module !== undefined && typeof entry.module !== 'boolean') throw new Error(`git_modules.${name}.module must be true or false (got ${JSON.stringify(entry.module)})`);
|
|
59
|
+
const r = entry?.records;
|
|
60
|
+
if (r !== undefined && (!Array.isArray(r) || !r.length || r.some((c) => typeof c !== 'string' || !c.trim()))) {
|
|
61
|
+
throw new Error(`git_modules.${name}.records must be a non-empty list of collection names (got ${JSON.stringify(r)})`);
|
|
62
|
+
}
|
|
63
|
+
// a clone ON DISK that names no workspace module is a bundle. One NOT on disk cannot say what it is,
|
|
64
|
+
// and is read as a layer that is not installed — announced by compile, check and status — rather
|
|
65
|
+
// than vanishing: reading a project is the default since 0.41.0, and silence is how an absent
|
|
66
|
+
// layer passed for an empty one.
|
|
67
|
+
const clone = root ? path.join(root, 'git_modules', name) : null;
|
|
68
|
+
if (r === undefined && entry?.module !== true && clone && fs.existsSync(clone) && !cloneWorkspaceModule(clone)) continue;
|
|
69
|
+
if (r === undefined && entry?.module !== true && !clone) continue;
|
|
70
|
+
out.push({ name, records: r ?? null, module: entry?.module === true });
|
|
71
|
+
}
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The `workspace_module` a directory's own manifest names, or null — what makes a clone a workspace. */
|
|
76
|
+
export function cloneWorkspaceModule(dir) {
|
|
77
|
+
try { return JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).dreamteamer?.workspace_module || null; }
|
|
78
|
+
catch { return null; }
|
|
79
|
+
}
|
|
80
|
+
|
|
45
81
|
/** Is `inner` reached from `outer` by descending through a module folder? */
|
|
46
82
|
export function nestedAsModule(outer, inner) {
|
|
47
83
|
return path
|