dreamteamer 0.46.0 → 0.47.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/README.md +63 -6
- package/package.json +4 -3
- package/skills/using-dreamteamer/SKILL.md +6 -4
- package/skills/using-dreamteamer/references/extensions.md +8 -0
- package/skills/using-dreamteamer/references/getting-started.md +8 -8
- package/skills/using-dreamteamer/references/setup.md +120 -0
- package/src/checkout.js +260 -4
- package/src/cli.js +90 -18
- package/src/doctor.js +10 -0
- package/src/extensions.js +25 -6
- package/src/init.js +39 -14
- package/src/install-modules.js +382 -0
- package/src/setup-contract.js +72 -0
- package/src/setup.js +420 -0
- package/src/update.js +89 -0
package/src/setup.js
ADDED
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
// `dt setup` — and the setup half of `dt install` and `dt status`: the engine's generic driver for
|
|
2
|
+
// the units modules declare (src/setup-contract.js). Nothing here knows a module: it fills inputs,
|
|
3
|
+
// asks consent per effect, runs inspect → plan → apply → inspect, folds the checks into one line and
|
|
4
|
+
// keeps a unit's receipts. The vocabulary is the design's (rnd/design-docs/2026-11-12--cli-first-module-lifecycle):
|
|
5
|
+
//
|
|
6
|
+
// inputs --input id=value (or unit.id=value) → the environment → the declared default → a TTY
|
|
7
|
+
// prompt for what is still missing → `needs`. Two inputs naming one env key are ONE input.
|
|
8
|
+
// consent workspace-files never asks; download / network / machine ask y/n in a TTY or run under
|
|
9
|
+
// --allow <kind>; account runs only under `setup <unit> --authorize`, in a TTY.
|
|
10
|
+
// status skipped · no-evidence · blocked · configured · ready [· verified <date>]
|
|
11
|
+
// receipts .dreamteamer/setup/<unit>/ — per machine, gitignored with the runtime, never committed
|
|
12
|
+
//
|
|
13
|
+
// Pure functions first (tested without a workspace), then the runner and the verb.
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import os from 'node:os';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import readline from 'node:readline/promises';
|
|
18
|
+
import { execFileSync } from 'node:child_process';
|
|
19
|
+
import { CHECK_STATUSES } from './setup-contract.js';
|
|
20
|
+
import { parseEnvValues } from './env-vars.js';
|
|
21
|
+
import { RUNTIME_DIR } from './runtime.js';
|
|
22
|
+
import { discoverModules } from './compile.js';
|
|
23
|
+
|
|
24
|
+
export const EFFECTS_ALLOWED = ['download', 'network', 'machine'];
|
|
25
|
+
export const EXIT = { done: 0, failed: 1, usage: 2, needsInput: 3 };
|
|
26
|
+
|
|
27
|
+
// ---- pure ---------------------------------------------------------------------------------------
|
|
28
|
+
|
|
29
|
+
/** `--input id=value` and `--input unit.id=value`, repeated; the value may itself hold `=`. */
|
|
30
|
+
export function parseInputFlags(argv) {
|
|
31
|
+
const out = [];
|
|
32
|
+
for (let i = 0; i < argv.length; i++) {
|
|
33
|
+
if (argv[i] !== '--input') continue;
|
|
34
|
+
const raw = argv[++i];
|
|
35
|
+
const eq = raw?.indexOf('=') ?? -1;
|
|
36
|
+
if (eq < 1) throw usage('--input takes id=value (or unit.id=value)');
|
|
37
|
+
const key = raw.slice(0, eq), value = raw.slice(eq + 1);
|
|
38
|
+
const dot = key.indexOf('.');
|
|
39
|
+
out.push(dot > 0 ? { unit: key.slice(0, dot), id: key.slice(dot + 1), value } : { unit: null, id: key, value });
|
|
40
|
+
}
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** `--allow <kind>`, repeated; an unknown kind is a usage error naming the vocabulary. */
|
|
45
|
+
export function parseAllow(argv) {
|
|
46
|
+
const allow = new Set();
|
|
47
|
+
for (let i = 0; i < argv.length; i++) {
|
|
48
|
+
if (argv[i] !== '--allow') continue;
|
|
49
|
+
const kind = argv[++i];
|
|
50
|
+
if (!EFFECTS_ALLOWED.includes(kind)) throw usage(`--allow takes one of ${EFFECTS_ALLOWED.join(', ')} (got ${JSON.stringify(kind)}); an account step is \`dt setup <unit> --authorize\``);
|
|
51
|
+
allow.add(kind);
|
|
52
|
+
}
|
|
53
|
+
return allow;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export class SetupUsage extends Error { constructor(m) { super(m); this.code = EXIT.usage; } }
|
|
57
|
+
const usage = (m) => new SetupUsage(m);
|
|
58
|
+
|
|
59
|
+
const expandHome = (p, home) => (typeof p === 'string' && (p === '~' || p.startsWith('~/')) ? path.join(home, p.slice(1)) : p);
|
|
60
|
+
|
|
61
|
+
/** A secret-path input's file: it must exist, be a file, and (posix) be readable by its owner only. The engine never reads it. */
|
|
62
|
+
function secretPathProblem(value) {
|
|
63
|
+
let st;
|
|
64
|
+
try { st = fs.statSync(value); } catch { return `${value}: no such file`; }
|
|
65
|
+
if (!st.isFile()) return `${value}: not a file`;
|
|
66
|
+
if (process.platform !== 'win32' && (st.mode & 0o077)) return `${value} is readable by other users — chmod 600 ${value}`;
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
const flagText = (f) => `--input ${f.unit ? `${f.unit}.` : ''}${f.id}=`;
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Fill every unit's inputs. Returns `inputs` (unit id → { inputId: value }), `missing` (required
|
|
73
|
+
* inputs with no value from any source), `ignored` and `problems`. `prompt(input, default)` is called
|
|
74
|
+
* only in a TTY, only for what is still missing, and only when `noInput` is false. Strict (the default)
|
|
75
|
+
* throws a usage error for a flag naming no input, two values for one shared key, or a secret-path
|
|
76
|
+
* that does not exist or is not owner-only — nothing has run yet. `lenient` (install, where npm has
|
|
77
|
+
* already written) keeps going: the unknown flag is listed in `ignored`, the bad value in `problems`
|
|
78
|
+
* with the input left unfilled, so the install still commits and the line says what is still needed.
|
|
79
|
+
*/
|
|
80
|
+
export async function fillInputs(units, { flags = [], env = {}, tty = false, noInput = false, prompt = null, home = os.homedir(), lenient = false } = {}) {
|
|
81
|
+
const inputs = new Map(units.map((u) => [u.id, {}]));
|
|
82
|
+
const missing = [], ignored = [], problems = [];
|
|
83
|
+
const refuse = (text, problem = null) => { if (!lenient) throw usage(text); if (problem) problems.push(problem); else ignored.push(text); };
|
|
84
|
+
// a bare --input id= is unambiguous when every unit declaring that id names the same env key
|
|
85
|
+
const byId = new Map();
|
|
86
|
+
for (const u of units) for (const i of u.inputs) (byId.get(i.id) ?? byId.set(i.id, []).get(i.id)).push({ unit: u.id, env: i.env ?? null });
|
|
87
|
+
const valueOf = (u, i, f) => (f.unit ? f.unit === u.id && f.id === i.id : f.id === i.id && (byId.get(i.id).every((d) => d.env === (i.env ?? null) && (d.env !== null || d.unit === u.id))));
|
|
88
|
+
const live = [];
|
|
89
|
+
for (const f of flags) {
|
|
90
|
+
const owners = byId.get(f.id) ?? [];
|
|
91
|
+
if (f.unit && !units.some((u) => u.id === f.unit && u.inputs.some((i) => i.id === f.id))) { refuse(`${flagText(f)} names no input of ${f.unit}`); continue; }
|
|
92
|
+
if (!f.unit && !owners.length) { refuse(`${flagText(f)} names no input of ${units.map((u) => u.id).join(', ') || 'any unit'}`); continue; }
|
|
93
|
+
if (!f.unit && owners.length > 1 && !(owners.every((o) => o.env !== null && o.env === owners[0].env))) { refuse(`${flagText(f)} is ambiguous: ${owners.map((o) => `${o.unit}.${f.id}`).join(', ')} — say which with unit.id=`); continue; }
|
|
94
|
+
live.push(f);
|
|
95
|
+
}
|
|
96
|
+
// an env key shared by several inputs is one input: a flag for any of them fills all of them, and two
|
|
97
|
+
// different values for it in one call are a refusal naming both (D39)
|
|
98
|
+
const envValues = new Map(), envFlag = new Map(), conflicted = new Set();
|
|
99
|
+
for (const u of units) for (const i of u.inputs) for (const f of live) {
|
|
100
|
+
if (!i.env || i.kind === 'rows' || !valueOf(u, i, f)) continue; // a rows input is repeatable: every flag is one more row
|
|
101
|
+
if (envValues.has(i.env) && envValues.get(i.env) !== f.value && envFlag.get(i.env) !== f) {
|
|
102
|
+
const first = envFlag.get(i.env);
|
|
103
|
+
refuse(`${flagText(first)} and ${flagText(f)} name one key, ${i.env}, with different values — give one`, { unit: u.id, id: i.id, reason: `${flagText(first)} and ${flagText(f)} name one key, ${i.env}, with different values — give one`, required: false, env: i.env });
|
|
104
|
+
conflicted.add(i.env);
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
if (!envValues.has(i.env)) { envValues.set(i.env, f.value); envFlag.set(i.env, f); }
|
|
108
|
+
}
|
|
109
|
+
// a default declared by any input sharing the key is the key's default, and required is the OR of
|
|
110
|
+
// every declaration sharing it (D39: one key, one input)
|
|
111
|
+
const envDefaults = new Map(), envRequired = new Set();
|
|
112
|
+
for (const u of units) for (const i of u.inputs) if (i.env) { if (i.default !== undefined && !envDefaults.has(i.env)) envDefaults.set(i.env, i.default); if (i.required) envRequired.add(i.env); }
|
|
113
|
+
const isRequired = (i) => !!i.required || (!!i.env && envRequired.has(i.env));
|
|
114
|
+
for (const u of units) {
|
|
115
|
+
for (const i of u.inputs) {
|
|
116
|
+
if (i.env && conflicted.has(i.env)) continue;
|
|
117
|
+
let value;
|
|
118
|
+
const given = live.filter((f) => valueOf(u, i, f)).map((f) => f.value);
|
|
119
|
+
if (i.kind === 'rows') {
|
|
120
|
+
if (given.length) value = given;
|
|
121
|
+
} else if (given.length) value = given.at(-1);
|
|
122
|
+
else if (i.env && envValues.has(i.env)) value = envValues.get(i.env);
|
|
123
|
+
else if (i.env && env[i.env] !== undefined && String(env[i.env]).trim() !== '') value = String(env[i.env]);
|
|
124
|
+
else if (i.default !== undefined) value = i.default;
|
|
125
|
+
else if (i.env && envDefaults.has(i.env)) value = envDefaults.get(i.env);
|
|
126
|
+
if (value === undefined && tty && !noInput && prompt) {
|
|
127
|
+
const answer = await prompt(i, i.default);
|
|
128
|
+
if (answer !== undefined && answer !== null && String(answer).trim() !== '') value = i.kind === 'rows' ? [String(answer)] : String(answer);
|
|
129
|
+
}
|
|
130
|
+
if (value === undefined) { if (isRequired(i)) missing.push({ unit: u.id, id: i.id }); continue; }
|
|
131
|
+
if (i.kind === 'path' || i.kind === 'secret-path') value = expandHome(value, home);
|
|
132
|
+
if (i.kind === 'secret-path') {
|
|
133
|
+
// a flag's bad value is the caller's to fix (usage, strict); one the environment or a default holds
|
|
134
|
+
// is reported on the unit's line and left unfilled, whoever runs
|
|
135
|
+
const problem = secretPathProblem(value);
|
|
136
|
+
if (problem && given.length) { refuse(`--input ${i.id}=${problem}`, { unit: u.id, id: i.id, reason: problem, required: true, env: i.env ?? null }); continue; }
|
|
137
|
+
if (problem) { problems.push({ unit: u.id, id: i.id, reason: problem, required: isRequired(i), env: i.env ?? null }); continue; }
|
|
138
|
+
}
|
|
139
|
+
inputs.get(u.id)[i.id] = value;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return { inputs, missing, ignored, problems };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** The env keys a unit must not see: those whose value the engine refused for it. */
|
|
146
|
+
export const droppedKeys = (problems, unitId) => [...new Set(problems.filter((p) => p.unit === unitId && p.env).map((p) => p.env))];
|
|
147
|
+
|
|
148
|
+
/** May this action run now? `ask(action)` is the y/n in a TTY; `allow` the --allow kinds. */
|
|
149
|
+
export async function consent(action, { allow = new Set(), tty = false, ask = null, authorize = false } = {}) {
|
|
150
|
+
const kinds = [...new Set((action.effects ?? []).map((e) => e.kind))];
|
|
151
|
+
if (kinds.includes('account')) return authorize && tty;
|
|
152
|
+
const asked = kinds.filter((k) => k !== 'workspace-files');
|
|
153
|
+
if (!asked.length) return true;
|
|
154
|
+
if (asked.every((k) => allow.has(k))) return true;
|
|
155
|
+
if (tty && ask) return !!(await ask(action, asked));
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** One line from a unit's checks — the design's status table, in its order. */
|
|
160
|
+
export function fold(checks, { skipped = false } = {}) {
|
|
161
|
+
if (skipped) return { state: 'skipped', detail: 'dt setup <unit> to resume', verified: null };
|
|
162
|
+
if (!checks.length) return { state: 'no-evidence', detail: 'inspect returned no checks — never ready', verified: null };
|
|
163
|
+
const unknown = checks.filter((c) => !CHECK_STATUSES.includes(c.status));
|
|
164
|
+
if (unknown.length) return { state: 'blocked', detail: unknown.map((c) => `${c.title ?? c.id}: unknown status ${JSON.stringify(c.status)}`).join(' · '), verified: null };
|
|
165
|
+
const blocked = checks.filter((c) => c.status === 'blocked');
|
|
166
|
+
if (blocked.length) return { state: 'blocked', detail: blocked.map((c) => `${c.title ?? c.id}${c.detail ? ` — ${c.detail}` : ''}`).join(' · '), verified: null };
|
|
167
|
+
const open = checks.filter((c) => c.status === 'missing' || c.status === 'unverified');
|
|
168
|
+
if (open.length) return { state: 'configured', detail: open.map((c) => `${c.title ?? c.id} ${c.status}`).join(' · '), verified: null };
|
|
169
|
+
const dates = checks.map((c) => c.evidence?.at).filter((d) => typeof d === 'string').sort();
|
|
170
|
+
return { state: 'ready', detail: '', verified: dates.at(-1) ?? null };
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** A provider's error, with anything that looks like a value gone. Key names and shapes stay. */
|
|
174
|
+
export function redact(text) {
|
|
175
|
+
return String(text ?? '')
|
|
176
|
+
.replace(/\b(token|secret|password|passwd|api[_-]?key|key|client[_-]?secret|credential)=\S+/gi, '$1=[redacted]')
|
|
177
|
+
.replace(/\bBearer\s+\S+/g, 'Bearer [redacted]');
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// ---- the workspace side -----------------------------------------------------------------------
|
|
181
|
+
|
|
182
|
+
/** Every setup unit the loaded extensions contribute, with its package. */
|
|
183
|
+
export const units = (ws) => (ws.extensions ?? []).flatMap((e) => (e.setup ?? []).map((u) => ({ ...u, module: e.name, dir: e.dir })));
|
|
184
|
+
export const skippedUnits = (ws) => ws.pkg?.dreamteamer?.setup?.skipped ?? [];
|
|
185
|
+
export const receiptDir = (ws, unitId) => path.join(ws.root, RUNTIME_DIR, 'setup', unitId);
|
|
186
|
+
|
|
187
|
+
/** The environment a unit sees: the process's, with the workspace `.env` filling what it lacks. */
|
|
188
|
+
export function unitEnv(ws, processEnv = process.env) {
|
|
189
|
+
const file = path.join(ws.root, '.env');
|
|
190
|
+
const dotenv = fs.existsSync(file) ? parseEnvValues(fs.readFileSync(file, 'utf8')) : new Map();
|
|
191
|
+
return { ...Object.fromEntries(dotenv), ...processEnv };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Run one unit: inspect → plan(inputs) → apply what is consented → inspect. Never throws for a
|
|
195
|
+
* provider's fault: a throwing apply is one failed action, redacted, and the unit reads blocked. */
|
|
196
|
+
export async function runUnit(ws, unit, { inputs = {}, allow = new Set(), tty = false, ask = null, authorize = false, verify = false, processEnv = process.env, api = null, drop = [] } = {}) {
|
|
197
|
+
// the env is re-read after every applied action: a safe action's whole point is often to write the
|
|
198
|
+
// key the next inspect reads (`PROBE_HOME=` into .env), and a stale copy would report it missing.
|
|
199
|
+
// `drop` names the keys whose value the engine refused (a secret-path that is missing or not
|
|
200
|
+
// owner-only): the unit never sees them, so it can neither trust nor record them
|
|
201
|
+
const envFor = () => { const e = unitEnv(ws, processEnv); for (const k of drop) delete e[k]; return e; };
|
|
202
|
+
const ctx = { root: ws.root, ws, dt: api, env: envFor(), tty, receiptDir: receiptDir(ws, unit.id) };
|
|
203
|
+
const applied = [], failed = [];
|
|
204
|
+
let pending = [], needs = [];
|
|
205
|
+
const done = new Set(), refused = new Set();
|
|
206
|
+
// the plan is asked again after every applied action: an action's preconditions are often what the
|
|
207
|
+
// previous one made (a venv before the download, a key in .env before the check that reads it), so
|
|
208
|
+
// one pass would leave them pending for a second call that a person should not have to make
|
|
209
|
+
for (let round = 0; round < 50; round++) {
|
|
210
|
+
let planned;
|
|
211
|
+
try { planned = (await unit.plan(ctx, inputs)) ?? {}; } catch (e) { return { checks: safeInspect(unit, ctx), applied, pending, failed: [...failed, { id: 'plan', message: redact(e.message) }], needs }; }
|
|
212
|
+
needs = planned.needs ?? [];
|
|
213
|
+
pending = [];
|
|
214
|
+
let next = null;
|
|
215
|
+
for (const action of planned.actions ?? []) {
|
|
216
|
+
if (done.has(action.id)) continue;
|
|
217
|
+
if (action.state && action.state !== 'ready') { if (action.state !== 'done') pending.push({ ...action, why: action.state === 'needs-input' ? 'needs input' : action.state }); else done.add(action.id); continue; }
|
|
218
|
+
if (refused.has(action.id)) { pending.push({ ...action, why: refused.get?.(action.id) ?? 'declined' }); continue; }
|
|
219
|
+
const isVerify = action.kind === 'verify';
|
|
220
|
+
if (isVerify && !verify) { pending.push({ ...action, why: 'run with --verify' }); continue; }
|
|
221
|
+
if ((action.runBy === 'owner' || (action.effects ?? []).some((e) => e.kind === 'account')) && !(authorize && tty)) { pending.push({ ...action, why: 'the owner\'s step: dt setup <unit> --authorize' }); continue; }
|
|
222
|
+
if (!next) next = action; else pending.push({ ...action, why: 'after the step before it' });
|
|
223
|
+
}
|
|
224
|
+
if (!next) break;
|
|
225
|
+
if (!(await consent(next, { allow, tty, ask, authorize }))) {
|
|
226
|
+
refused.add(next.id);
|
|
227
|
+
pending.push({ ...next, why: `needs --allow ${[...new Set((next.effects ?? []).map((e) => e.kind).filter((k) => k !== 'workspace-files'))].join(' --allow ')}` });
|
|
228
|
+
// the actions queued behind it stay listed as they are; nothing else can run this round
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
done.add(next.id);
|
|
232
|
+
try {
|
|
233
|
+
const r = (await unit.apply(ctx, next, inputs)) ?? { ok: false, message: 'apply returned nothing' };
|
|
234
|
+
if (r.ok) { applied.push({ id: next.id, changed: r.changed ?? [], message: r.message }); ctx.env = envFor(); }
|
|
235
|
+
else failed.push({ id: next.id, message: redact(r.message ?? 'apply refused') });
|
|
236
|
+
} catch (e) { failed.push({ id: next.id, message: redact(e.message) }); }
|
|
237
|
+
}
|
|
238
|
+
// the final word on what is still open comes from one more plan, so a declined action and the ones
|
|
239
|
+
// behind it read with their own states, never as "after the step before it"
|
|
240
|
+
try {
|
|
241
|
+
const last = (await unit.plan(ctx, inputs)) ?? {};
|
|
242
|
+
needs = last.needs ?? needs;
|
|
243
|
+
pending = (last.actions ?? []).filter((a) => !done.has(a.id) && a.state !== 'done').map((a) => {
|
|
244
|
+
if (a.state && a.state !== 'ready') return { ...a, why: a.state === 'needs-input' ? 'needs input' : a.state };
|
|
245
|
+
if (a.kind === 'verify' && !verify) return { ...a, why: 'run with --verify' };
|
|
246
|
+
if (a.runBy === 'owner' || (a.effects ?? []).some((e) => e.kind === 'account')) return { ...a, why: 'the owner\'s step: dt setup <unit> --authorize' };
|
|
247
|
+
return { ...a, why: `needs --allow ${[...new Set((a.effects ?? []).map((e) => e.kind).filter((k) => k !== 'workspace-files'))].join(' --allow ')}` };
|
|
248
|
+
});
|
|
249
|
+
} catch { /* the loop's own view stands */ }
|
|
250
|
+
return { checks: safeInspect(unit, ctx), applied, pending, failed, needs };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function safeInspect(unit, ctx) {
|
|
254
|
+
try { const r = unit.inspect(ctx); return Array.isArray(r?.checks) ? r.checks : []; } catch (e) { return [{ id: `${unit.id}.inspect`, status: 'blocked', title: 'inspect', detail: redact(e.message) }]; }
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** The setup section of `dt status`: one entry per unit, then one per package with no unit. */
|
|
258
|
+
export function statusLines(ws, { processEnv = process.env } = {}) {
|
|
259
|
+
const env = unitEnv(ws, processEnv);
|
|
260
|
+
const lines = [];
|
|
261
|
+
const skipped = new Set(skippedUnits(ws));
|
|
262
|
+
const byModule = new Map();
|
|
263
|
+
for (const u of units(ws)) (byModule.get(u.module) ?? byModule.set(u.module, []).get(u.module)).push(u);
|
|
264
|
+
for (const [module, us] of byModule) {
|
|
265
|
+
for (const u of us) {
|
|
266
|
+
// the same rule as setup: a secret-path the environment holds that is missing or not owner-only is
|
|
267
|
+
// never handed to the unit — status shows it as its own missing row, with the fix
|
|
268
|
+
const unitEnvHere = { ...env };
|
|
269
|
+
const refused = [];
|
|
270
|
+
for (const i of u.inputs ?? []) {
|
|
271
|
+
if (i.kind !== 'secret-path' || !i.env || unitEnvHere[i.env] === undefined || String(unitEnvHere[i.env]).trim() === '') continue;
|
|
272
|
+
const problem = secretPathProblem(expandHome(String(unitEnvHere[i.env]), os.homedir()));
|
|
273
|
+
if (problem) { delete unitEnvHere[i.env]; refused.push({ id: `${u.id}.${i.id}`, status: 'missing', title: i.title ?? i.id, detail: problem, fix: `dt setup ${u.id} --input ${i.id}=<path>` }); }
|
|
274
|
+
}
|
|
275
|
+
const ctx = { root: ws.root, ws, dt: null, env: unitEnvHere, tty: false, receiptDir: receiptDir(ws, u.id) };
|
|
276
|
+
const checks = [...refused, ...safeInspect(u, ctx)];
|
|
277
|
+
const f = fold(checks, { skipped: skipped.has(u.id) });
|
|
278
|
+
lines.push({ package: module, unit: u.id, grouped: us.length > 1, ...f, checks, next: nextCommand(u.id, f, checks) });
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
// a skip entry no installed package provides is not silent: one line names it and how to clear it
|
|
282
|
+
const provided = new Set([...byModule.values()].flat().map((u) => u.id));
|
|
283
|
+
for (const id of skipped) if (!provided.has(id)) lines.push({ package: null, unit: id, grouped: false, state: 'skipped', detail: 'no installed package provides it', verified: null, checks: [], next: `remove "${id}" from dreamteamer.setup.skipped in package.json` });
|
|
284
|
+
// every other installed module — an extension without a unit, or a plain module with no code at all —
|
|
285
|
+
// reads `no setup`, naming the declared env keys and vars nobody set; the engine and the workspace's own
|
|
286
|
+
// module are not modules anybody installs
|
|
287
|
+
const own = ws.pkg?.dreamteamer?.workspace_module ?? 'default';
|
|
288
|
+
for (const m of discoverModules(ws.root, ws.pkg).modules) {
|
|
289
|
+
let manifest = {};
|
|
290
|
+
try { manifest = JSON.parse(fs.readFileSync(path.join(m.root, 'package.json'), 'utf8')); } catch { /* no manifest */ }
|
|
291
|
+
const name = manifest.name ?? m.name;
|
|
292
|
+
if (name === 'dreamteamer' || m.name === own || byModule.has(name)) continue;
|
|
293
|
+
const dt = manifest.dreamteamer ?? {};
|
|
294
|
+
const needs = [...(dt.env ?? []), ...(dt.vars ?? [])].filter((k) => env[k] === undefined || String(env[k]).trim() === '');
|
|
295
|
+
lines.push({ package: name, unit: null, state: 'no-setup', detail: needs.length ? `needs: ${needs.join(', ')}` : '', verified: null, checks: [], next: needs.length ? `set ${needs.join(', ')} in .env` : '' });
|
|
296
|
+
}
|
|
297
|
+
return lines;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function nextCommand(unitId, f, checks) {
|
|
301
|
+
if (f.state === 'skipped') return `dt setup ${unitId}`;
|
|
302
|
+
if (f.state === 'ready') return '';
|
|
303
|
+
const fix = checks.find((c) => c.status !== 'ready' && c.status !== 'configured' && c.fix)?.fix;
|
|
304
|
+
return fix ?? `dt setup ${unitId}`;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export function renderStatusLines(lines) {
|
|
308
|
+
if (!lines.length) return [];
|
|
309
|
+
const out = ['setup:'];
|
|
310
|
+
const label = (l) => (l.unit ? (l.grouped ? `${moduleId(l.package)} › ${l.unit}` : l.unit) : moduleId(l.package));
|
|
311
|
+
const width = Math.max(...lines.map((l) => label(l).length));
|
|
312
|
+
for (const l of lines) {
|
|
313
|
+
const state = l.state === 'no-setup' ? 'no setup' : l.state === 'no-evidence' ? 'no evidence' : l.state;
|
|
314
|
+
const verified = l.verified ? ` · verified ${l.verified}` : '';
|
|
315
|
+
out.push(` ${label(l).padEnd(width)} ${state}${verified}${l.detail ? ` ${l.detail}` : ''}${l.next ? ` → ${l.next}` : ''}`);
|
|
316
|
+
}
|
|
317
|
+
return out;
|
|
318
|
+
}
|
|
319
|
+
const moduleId = (name) => String(name).replace(/^@[^/]+\//, '');
|
|
320
|
+
|
|
321
|
+
/** Record a skip (or clear one) in package.json → dreamteamer.setup.skipped, keeping the file's own indentation. */
|
|
322
|
+
export function setSkipped(ws, unitId, on) {
|
|
323
|
+
const file = path.join(ws.root, 'package.json');
|
|
324
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
325
|
+
const indent = /^\t/m.test(text) ? '\t' : (/^( +)"/m.exec(text)?.[1] ?? ' ');
|
|
326
|
+
const pkg = JSON.parse(text);
|
|
327
|
+
const block = (pkg.dreamteamer ??= {});
|
|
328
|
+
const list = new Set(block.setup?.skipped ?? []);
|
|
329
|
+
if (on) list.add(unitId); else list.delete(unitId);
|
|
330
|
+
if (list.size) (block.setup ??= {}).skipped = [...list].sort();
|
|
331
|
+
else if (block.setup) { delete block.setup.skipped; if (!Object.keys(block.setup).length) delete block.setup; }
|
|
332
|
+
fs.writeFileSync(file, JSON.stringify(pkg, null, indent) + '\n');
|
|
333
|
+
ws.pkg = pkg;
|
|
334
|
+
try {
|
|
335
|
+
execFileSync('git', ['add', '--', 'package.json'], { cwd: ws.root, stdio: 'ignore' });
|
|
336
|
+
execFileSync('git', ['commit', '--quiet', '-m', `dreamteamer: ${on ? 'skip' : 'resume'} setup of ${unitId}`, '--', 'package.json'], { cwd: ws.root, stdio: 'ignore' });
|
|
337
|
+
} catch { /* no repo, or nothing to commit — the file is written either way */ }
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// ---- the verb -----------------------------------------------------------------------------------
|
|
341
|
+
|
|
342
|
+
/** The terminal's prompt and y/n, on one readline — `dt setup` and `dt install` share it. */
|
|
343
|
+
export function ttyIO() {
|
|
344
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
345
|
+
return { prompt: ttyPrompt(rl), ask: ttyAsk(rl), close: () => rl.close() };
|
|
346
|
+
}
|
|
347
|
+
// an EOF (Ctrl-D) at a prompt is no answer — the input stays missing (exit 3), the action declined — never a crash
|
|
348
|
+
const question = async (rl, text) => { try { return (await rl.question(text)).trim(); } catch { return ''; } };
|
|
349
|
+
const ttyPrompt = (rl) => async (input, def) => {
|
|
350
|
+
const hint = def !== undefined ? ` [${def}]` : input.required ? ' (required)' : ' (enter to skip)';
|
|
351
|
+
const answer = await question(rl, `${input.prompt ?? input.title ?? input.id}${hint}: `);
|
|
352
|
+
return answer === '' ? def : answer;
|
|
353
|
+
};
|
|
354
|
+
const ttyAsk = (rl) => async (action, kinds) => {
|
|
355
|
+
const effects = (action.effects ?? []).map((e) => `${e.kind}: ${e.detail}`).join('\n ');
|
|
356
|
+
const answer = (await question(rl, `${action.title} — ${kinds.join(', ')}\n ${effects}\n run it? [y/N] `)).toLowerCase();
|
|
357
|
+
return answer === 'y' || answer === 'yes';
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* `dt setup [<unit>] [--input k=v]… [--allow <kind>]… [--authorize] [--verify] [--skip] [--no-input] [--json]`
|
|
362
|
+
* Exit: 0 done (pending and blocked steps printed), 1 a unit's apply failed (its blocked line names it — never a crash; D57), 2 usage, 3 a required input missing.
|
|
363
|
+
*/
|
|
364
|
+
export async function setupCommand(ws, argv, { processEnv = process.env, tty = !!(process.stdin.isTTY && process.stdout.isTTY), log = console.log, api = null, io = null } = {}) {
|
|
365
|
+
const env = unitEnv(ws, processEnv);
|
|
366
|
+
const json = argv.includes('--json');
|
|
367
|
+
const noInput = json || argv.includes('--no-input');
|
|
368
|
+
const flags = { authorize: argv.includes('--authorize'), verify: argv.includes('--verify'), skip: argv.includes('--skip') };
|
|
369
|
+
let allow, inputFlags;
|
|
370
|
+
try { allow = parseAllow(argv); inputFlags = parseInputFlags(argv); } catch (e) { if (e instanceof SetupUsage) { console.error(`✖ ${e.message}`); return EXIT.usage; } throw e; }
|
|
371
|
+
const target = argv.find((a, i) => !a.startsWith('--') && argv[i - 1] !== '--input' && argv[i - 1] !== '--allow');
|
|
372
|
+
const all = units(ws);
|
|
373
|
+
const chosen = target ? all.filter((u) => u.id === target) : all;
|
|
374
|
+
if (target && !chosen.length) { console.error(`✖ no setup unit "${target}" — installed units: ${all.map((u) => u.id).join(', ') || '(none)'}`); return EXIT.usage; }
|
|
375
|
+
if (!all.length) { log('— no installed module declares setup — `dt status` lists what is installed, `dt install <package>` adds a module'); return EXIT.done; }
|
|
376
|
+
if (flags.authorize && !target) { console.error('✖ --authorize takes one unit: dt setup <unit> --authorize'); return EXIT.usage; }
|
|
377
|
+
if (flags.authorize && !tty) { console.error('✖ --authorize needs a terminal: the owner signs in; a script cannot'); return EXIT.usage; }
|
|
378
|
+
if (flags.skip) {
|
|
379
|
+
if (!target) { console.error('✖ --skip takes one unit: dt setup <unit> --skip'); return EXIT.usage; }
|
|
380
|
+
setSkipped(ws, target, true);
|
|
381
|
+
log(`— ${target}: skipped (dt setup ${target} to resume)`);
|
|
382
|
+
return EXIT.done;
|
|
383
|
+
}
|
|
384
|
+
if (target && skippedUnits(ws).includes(target)) { setSkipped(ws, target, false); log(`✔ ${target}: no longer skipped`); }
|
|
385
|
+
const skipped = new Set(skippedUnits(ws));
|
|
386
|
+
const run = chosen.filter((u) => !skipped.has(u.id));
|
|
387
|
+
const term = tty && !noInput && !io ? ttyIO() : null;
|
|
388
|
+
const prompt = io?.prompt ?? term?.prompt ?? null;
|
|
389
|
+
const ask = io?.ask ?? term?.ask ?? null;
|
|
390
|
+
let code = EXIT.done;
|
|
391
|
+
const results = [];
|
|
392
|
+
try {
|
|
393
|
+
const filled = await fillInputs(run, { flags: inputFlags, env, tty, noInput, prompt });
|
|
394
|
+
for (const u of run) {
|
|
395
|
+
const r = await runUnit(ws, u, { inputs: filled.inputs.get(u.id) ?? {}, allow, tty, ask, authorize: flags.authorize, verify: flags.verify, processEnv, api, drop: droppedKeys(filled.problems, u.id) });
|
|
396
|
+
const problems = filled.problems.filter((m) => m.unit === u.id);
|
|
397
|
+
const missing = [...filled.missing.filter((m) => m.unit === u.id).map((m) => m.id), ...problems.filter((m) => m.required).map((m) => m.id)];
|
|
398
|
+
const f = fold(r.failed.length ? [...r.checks, ...r.failed.map((x) => ({ id: x.id, status: 'blocked', title: x.id, detail: x.message }))] : r.checks, {});
|
|
399
|
+
results.push({ id: u.id, module: u.module, ...f, checks: r.checks, applied: r.applied, pending: r.pending, failed: r.failed, problems, needs: [...new Set([...missing, ...r.needs])] });
|
|
400
|
+
if (missing.length) code = Math.max(code, EXIT.needsInput);
|
|
401
|
+
else if (r.failed.length && code === EXIT.done) code = EXIT.failed; // D57: an apply that failed is a failure, never a 0
|
|
402
|
+
}
|
|
403
|
+
for (const u of chosen.filter((x) => skipped.has(x.id))) results.push({ id: u.id, module: u.module, ...fold([], { skipped: true }), checks: [], applied: [], pending: [], failed: [], needs: [] });
|
|
404
|
+
} catch (e) {
|
|
405
|
+
if (e instanceof SetupUsage) { console.error(`✖ ${e.message}`); return EXIT.usage; }
|
|
406
|
+
throw e;
|
|
407
|
+
} finally { term?.close(); }
|
|
408
|
+
if (json) { log(JSON.stringify({ workspace: { root: ws.root, name: ws.pkg?.name ?? null }, units: results }, null, 2)); return code; }
|
|
409
|
+
for (const r of results) {
|
|
410
|
+
const verified = r.verified ? ` · verified ${r.verified}` : '';
|
|
411
|
+
log(`${r.state === 'ready' ? '✔' : r.state === 'blocked' ? '✖' : '—'} ${r.id}: ${r.state}${verified}${r.detail ? ` — ${r.detail}` : ''}`);
|
|
412
|
+
for (const a of r.applied) log(` ✔ ${a.id}${a.message ? ` — ${a.message}` : ''}`);
|
|
413
|
+
for (const f of r.failed) log(` ✖ ${f.id} — ${f.message}`);
|
|
414
|
+
for (const p of r.problems ?? []) log(` ✖ ${p.id} — ${p.reason}`);
|
|
415
|
+
for (const p of r.pending) log(` … ${p.id} (${p.why})${p.reason ? ` — ${p.reason}` : ''}`);
|
|
416
|
+
if (r.needs.length) log(` needs input: ${r.needs.join(', ')} — --input ${r.needs[0]}=<value>`);
|
|
417
|
+
if (!flags.authorize && (r.pending ?? []).some((p) => p.runBy === 'owner' || (p.effects ?? []).some((e) => e.kind === 'account'))) log(` the owner's step (opens a browser): dt setup ${r.id}${r.needs.map((n) => ` --input ${n}=<value>`).join('')} --authorize`);
|
|
418
|
+
}
|
|
419
|
+
return code;
|
|
420
|
+
}
|
package/src/update.js
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// `dt update <name>[@<version>] | --engine` — move ONE pin forward on purpose: an npm module to the
|
|
2
|
+
// latest release within its ranges (or to the named version), or the engine itself. Re-pinned
|
|
3
|
+
// exactly, closure-checked exactly as `dt install` checks it, compiled, committed with install's
|
|
4
|
+
// pathspec. A downgrade needs `--allow downgrade`; a development link is skipped and named. Nothing
|
|
5
|
+
// here runs on its own, and `dt update` with no target keeps its meaning: git modules fast-forward.
|
|
6
|
+
// A module update is install's steps 2–6 on the whole resolved closure, so a version that adds a
|
|
7
|
+
// dependency brings it in and a version that adds a setup unit runs its safe part.
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { spawnSync, execFileSync } from 'node:child_process';
|
|
11
|
+
import { resolveNpm, childEnv } from './checkout.js';
|
|
12
|
+
import { readSpecManifest, resolveClosure, installedModules, compareVersions, InstallRefusal, npmFloor, npmAndCompile, setupAndCommit, printUnitResults } from './install-modules.js';
|
|
13
|
+
import { EXIT } from './setup.js';
|
|
14
|
+
|
|
15
|
+
const gitOk = (root, args) => { try { execFileSync('git', args, { cwd: root, stdio: 'ignore' }); return true; } catch { return false; } };
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* `updateModules(ws, { name, version, engine, allow, from }, { open, npm, log })` → exit code.
|
|
19
|
+
* `name` is a package name (with `version` the exact version asked for, or null for latest);
|
|
20
|
+
* `engine: true` targets `dreamteamer` itself.
|
|
21
|
+
*/
|
|
22
|
+
export async function updateModules(ws, { name = null, version = null, engine = false, allow = new Set(), from = null, noCommit = false } = {}, { open, npm = resolveNpm(), log = console.log, processEnv = process.env } = {}) {
|
|
23
|
+
if (typeof open !== 'function') throw new Error('updateModules: opts.open is required');
|
|
24
|
+
const floor = npmFloor(npm);
|
|
25
|
+
if (floor) { console.error(`✖ ${floor}`); return EXIT.failed; }
|
|
26
|
+
const target = engine ? 'dreamteamer' : name;
|
|
27
|
+
const installed = installedModules(ws);
|
|
28
|
+
const here = engine
|
|
29
|
+
? (() => { try { return { name: 'dreamteamer', version: JSON.parse(fs.readFileSync(path.join(ws.root, 'node_modules', 'dreamteamer', 'package.json'), 'utf8')).version, linked: fs.lstatSync(path.join(ws.root, 'node_modules', 'dreamteamer')).isSymbolicLink() }; } catch { return null; } })()
|
|
30
|
+
: installed.get(target);
|
|
31
|
+
if (!here) { console.error(`✖ ${target} is not installed — dt install ${target}`); return EXIT.failed; }
|
|
32
|
+
if (here.linked) { log(`— ${target}: a development link — skipped (not pinned; remove the link to pin a version)`); return EXIT.done; }
|
|
33
|
+
let entry;
|
|
34
|
+
try { entry = readSpecManifest(version ? `${target}@${version}` : target, { from, npm, cwd: ws.root }); } catch (e) { if (e instanceof InstallRefusal) { console.error(`✖ ${e.message}`); return EXIT.failed; } throw e; }
|
|
35
|
+
const next = entry.manifest.version;
|
|
36
|
+
if (next === here.version) { log(`✔ ${target} is already ${next} — nothing to do`); return EXIT.done; }
|
|
37
|
+
if (compareVersions(next, here.version) < 0 && !allow.has('downgrade')) { console.error(`✖ ${target} ${here.version} → ${next} is a downgrade — say so: dt update ${target}@${next} --allow downgrade`); return EXIT.failed; }
|
|
38
|
+
const subject = `dreamteamer: update ${target} ${here.version} → ${next}`;
|
|
39
|
+
if (engine) {
|
|
40
|
+
// the engine itself: npm, then compile with the NEW engine — this process is the old one
|
|
41
|
+
log(`▶ update: ${target} ${here.version} → ${next}`);
|
|
42
|
+
const r = spawnSync(npm, ['install', '--save-exact', '--no-audit', '--no-fund', entry.spec], { cwd: ws.root, stdio: 'inherit', env: childEnv(), timeout: 600_000 });
|
|
43
|
+
if (r.status !== 0) { console.error(`✖ npm exited ${r.status ?? r.error?.message} — run the same command again to resume`); return EXIT.failed; }
|
|
44
|
+
let got = null;
|
|
45
|
+
try { got = JSON.parse(fs.readFileSync(path.join(ws.root, 'node_modules', 'dreamteamer', 'package.json'), 'utf8')).version; } catch { /* missing */ }
|
|
46
|
+
if (got !== next) { console.error(`✖ npm exited 0, but node_modules/dreamteamer is ${got ?? 'missing'}, not ${next}`); return EXIT.failed; }
|
|
47
|
+
const c = spawnSync(process.execPath, [path.join(ws.root, 'node_modules', 'dreamteamer', 'bin', 'dreamteamer.js'), 'compile'], { cwd: ws.root, stdio: 'inherit', env: childEnv(), timeout: 600_000 });
|
|
48
|
+
if (c.status !== 0) { console.error(`✖ compile with dreamteamer ${next} exited ${c.status} — the pin moved; fix what it reports, then dt compile`); return EXIT.failed; }
|
|
49
|
+
let committed = null;
|
|
50
|
+
if (!noCommit && gitOk(ws.root, ['rev-parse', '--git-dir'])) {
|
|
51
|
+
const paths = ['package.json', 'package-lock.json', '.env.example'].filter((rel) => fs.existsSync(path.join(ws.root, rel)));
|
|
52
|
+
if (gitOk(ws.root, ['add', '--', ...paths]) && gitOk(ws.root, ['commit', '--quiet', '-m', subject, '--', ...paths])) committed = paths;
|
|
53
|
+
}
|
|
54
|
+
log(`✔ ${target} ${here.version} → ${next} — compiled${committed ? `, committed (${committed.join(', ')})` : ', not committed'}`);
|
|
55
|
+
return EXIT.done;
|
|
56
|
+
}
|
|
57
|
+
// a module: install one pin later — the closure check exactly as install step 1 (with the target
|
|
58
|
+
// itself out of the installed map, so "installed at another version" does not refuse the very move
|
|
59
|
+
// being asked for), then install's steps 2–6 on the WHOLE resolved list: a version that adds a
|
|
60
|
+
// dreamteamer.dependencies entry brings the dependency in, compiled and committed with it, and a
|
|
61
|
+
// version that adds a setup unit runs its safe part
|
|
62
|
+
const others = new Map([...installed].filter(([n]) => n !== target));
|
|
63
|
+
let plan;
|
|
64
|
+
try { plan = resolveClosure([entry.spec], { installed: others, from, npm, cwd: ws.root }); } catch (e) { if (e instanceof InstallRefusal) { console.error(`✖ ${e.message}`); return EXIT.failed; } throw e; }
|
|
65
|
+
const names = plan.list.map((e) => e.manifest.name);
|
|
66
|
+
const extra = names.filter((n) => n !== target);
|
|
67
|
+
log(`▶ update: ${target} ${here.version} → ${next}${extra.length ? ` — with ${extra.join(', ')}` : ''}`);
|
|
68
|
+
const step = await npmAndCompile(ws, plan.list, { npm, open, log, what: 'update' });
|
|
69
|
+
if (step.code !== undefined) return step.code;
|
|
70
|
+
const out = await setupAndCommit(ws, step.fresh, names, { subject, processEnv, noCommit });
|
|
71
|
+
log(`✔ ${target} ${here.version} → ${next}${extra.length ? ` (with ${extra.join(', ')})` : ''} — compiled${out.committed ? `, committed (${out.committed.join(', ')})` : ', not committed'}`);
|
|
72
|
+
printUnitResults(out.results, out.ignored, log);
|
|
73
|
+
return out.code;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** The `dt update` argv: a target (`name`, `name@version`), `--engine`, `--allow downgrade`, `--from <dir>`, `--no-commit`. */
|
|
77
|
+
export function parseUpdateArgs(argv) {
|
|
78
|
+
const out = { name: null, version: null, engine: argv.includes('--engine'), allow: new Set(), from: null, noCommit: argv.includes('--no-commit') };
|
|
79
|
+
for (let i = 0; i < argv.length; i++) {
|
|
80
|
+
const a = argv[i];
|
|
81
|
+
if (a === '--allow') { const k = argv[++i]; if (k !== 'downgrade') throw new Error(`dt update --allow takes downgrade (got ${JSON.stringify(k)})`); out.allow.add(k); }
|
|
82
|
+
else if (a === '--from') out.from = argv[++i] ?? null;
|
|
83
|
+
else if (!a.startsWith('--') && !['--allow', '--from'].includes(argv[i - 1])) {
|
|
84
|
+
const at = a.startsWith('@') ? a.indexOf('@', 1) : a.indexOf('@');
|
|
85
|
+
if (at > 0) { out.name = a.slice(0, at); out.version = a.slice(at + 1); } else out.name = a;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return out;
|
|
89
|
+
}
|