dreamteamer 0.46.1 → 0.48.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 +71 -6
- package/package.json +8 -3
- package/skills/using-dreamteamer/SKILL.md +7 -4
- package/skills/using-dreamteamer/references/extensions.md +41 -0
- package/skills/using-dreamteamer/references/getting-started.md +8 -8
- package/skills/using-dreamteamer/references/setup.md +122 -0
- package/skills/using-dreamteamer/references/writing-a-module.md +132 -0
- package/src/api.js +14 -2
- package/src/check-alone.js +121 -0
- package/src/checkout.js +253 -1
- package/src/cli.js +110 -24
- package/src/collections-cli.js +4 -2
- package/src/compile.js +1 -1
- package/src/doctor.js +10 -0
- package/src/env-write.js +162 -0
- package/src/extensions.js +36 -6
- package/src/init.js +30 -12
- package/src/install-modules.js +383 -0
- package/src/scaffold-templates.js +85 -0
- package/src/schema-ops.js +27 -4
- package/src/setup-contract.js +101 -0
- package/src/setup.js +506 -0
- package/src/testing.d.ts +29 -0
- package/src/testing.js +86 -0
- package/src/update.js +89 -0
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// The `setup` contribution — extension API 1, setup version 1.
|
|
2
|
+
//
|
|
3
|
+
// A module that needs something from the person (a folder, a token, a download, a sign-in) declares
|
|
4
|
+
// HOW through a list of units, and the engine drives every unit the same way: `dt install` fills the
|
|
5
|
+
// unit's inputs and applies its safe actions, `dt setup` resumes and verifies, `dt status` folds its
|
|
6
|
+
// checks into one line. The engine never learns a module's name — a unit is addressed by its `id`,
|
|
7
|
+
// identical whether its module is installed alone or composed into a bigger package.
|
|
8
|
+
//
|
|
9
|
+
// setup: [{
|
|
10
|
+
// id: 'meetings', version: 1,
|
|
11
|
+
// inputs: [{ id, title?, env?, kind: 'string'|'path'|'rows'|'secret-path', required?, default?, prompt?, rows?: { columns } }],
|
|
12
|
+
// inspect(ctx) → { checks: [{ id, status, title, detail?, fix?, evidence? }] }
|
|
13
|
+
// plan(ctx, inputs) → { checks, actions: [{ id, title, effects: [{ kind, detail }], preview?, expect?, runBy?, kind? }], needs: [inputId] }
|
|
14
|
+
// apply(ctx, action, inputs) → { ok, changed: [paths], message? }
|
|
15
|
+
// }]
|
|
16
|
+
//
|
|
17
|
+
// This file is the validator and nothing else: pure, no fs, so the contract is testable without a
|
|
18
|
+
// workspace. `src/setup.js` runs the units.
|
|
19
|
+
export const SETUP_VERSION = 1;
|
|
20
|
+
export const INPUT_KINDS = ['string', 'path', 'rows', 'secret-path'];
|
|
21
|
+
export const CHECK_STATUSES = ['ready', 'configured', 'unverified', 'missing', 'blocked'];
|
|
22
|
+
export const EFFECT_KINDS = ['workspace-files', 'download', 'network', 'machine', 'account'];
|
|
23
|
+
|
|
24
|
+
const UNIT_ID = /^[a-z][a-z0-9-]*$/;
|
|
25
|
+
const INPUT_ID = /^[a-z][a-z0-9_]*$/;
|
|
26
|
+
const ENV_KEY = /^[A-Z][A-Z0-9_]*$/;
|
|
27
|
+
|
|
28
|
+
const kindOf = (v) => (Array.isArray(v) ? 'a list' : v === null ? 'null' : typeof v === 'object' ? 'an object' : typeof v);
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Validate one package's `setup` contribution. Returns the units with their defaults filled and the
|
|
32
|
+
* package name stamped as `module`, or the refusals — every one naming the unit and the field, so a
|
|
33
|
+
* module author reads the message and fixes the one line.
|
|
34
|
+
* `declared` is the package's `dreamteamer.env` and `dreamteamer.vars`: an input that names an env
|
|
35
|
+
* key must also be declared there, so a variable is declared in exactly one place.
|
|
36
|
+
*/
|
|
37
|
+
export function validateSetup(name, value, { env = [], vars = [] } = {}) {
|
|
38
|
+
if (value === undefined || value === null) return { units: [], errors: [] };
|
|
39
|
+
if (!Array.isArray(value)) return { units: [], errors: [`extension ${name}: setup must be a list of units (got ${kindOf(value)})`] };
|
|
40
|
+
const declared = new Set([...(env ?? []), ...(vars ?? [])]);
|
|
41
|
+
const errors = [];
|
|
42
|
+
const units = [];
|
|
43
|
+
const seen = new Set();
|
|
44
|
+
for (const u of value) {
|
|
45
|
+
if (!u || typeof u !== 'object' || Array.isArray(u)) { errors.push(`extension ${name}: a setup unit must be an object (got ${kindOf(u)})`); continue; }
|
|
46
|
+
if (typeof u.id !== 'string' || !UNIT_ID.test(u.id)) { errors.push(`extension ${name}: a setup unit id is a lowercase slug (got ${JSON.stringify(u.id)})`); continue; }
|
|
47
|
+
if (seen.has(u.id)) { errors.push(`extension ${name}: setup unit "${u.id}" is declared twice`); continue; }
|
|
48
|
+
seen.add(u.id);
|
|
49
|
+
if (u.version !== SETUP_VERSION) { errors.push(`unit ${u.id} declares setup version ${u.version}; this engine understands ${SETUP_VERSION} — update the engine or the module`); continue; }
|
|
50
|
+
let bad = false;
|
|
51
|
+
for (const f of ['inspect', 'plan']) if (typeof u[f] !== 'function') { errors.push(`unit ${u.id}: ${f} must be a function`); bad = true; }
|
|
52
|
+
// apply is optional since 0.48.0: a unit whose every action carries `env` needs none (the engine
|
|
53
|
+
// performs those); a non-env action from an apply-less unit fails at run time, named (src/setup.js)
|
|
54
|
+
if (u.apply !== undefined && typeof u.apply !== 'function') { errors.push(`unit ${u.id}: apply must be a function when present`); bad = true; }
|
|
55
|
+
// `dt status` and `dt doctor` call inspect without awaiting, so an async one would read as "no
|
|
56
|
+
// evidence — never ready" with no error anywhere; refused here by name instead (review finding 5)
|
|
57
|
+
if (typeof u.inspect === 'function' && u.inspect.constructor?.name === 'AsyncFunction') { errors.push(`unit ${u.id}: inspect must be synchronous — dt status reads it without awaiting`); bad = true; }
|
|
58
|
+
const inputs = [];
|
|
59
|
+
const rawInputs = u.inputs ?? [];
|
|
60
|
+
if (!Array.isArray(rawInputs)) { errors.push(`unit ${u.id}: inputs must be a list`); bad = true; }
|
|
61
|
+
else {
|
|
62
|
+
for (const i of rawInputs) {
|
|
63
|
+
if (!i || typeof i !== 'object') { errors.push(`unit ${u.id}: an input must be an object (got ${kindOf(i)})`); bad = true; continue; }
|
|
64
|
+
if (typeof i.id !== 'string' || !INPUT_ID.test(i.id)) { errors.push(`unit ${u.id}: an input id is a lowercase identifier (got ${JSON.stringify(i.id)})`); bad = true; continue; }
|
|
65
|
+
if (!INPUT_KINDS.includes(i.kind)) { errors.push(`unit ${u.id}: input ${i.id} has kind ${JSON.stringify(i.kind)} — one of ${INPUT_KINDS.join(', ')}`); bad = true; continue; }
|
|
66
|
+
if (i.env !== undefined) {
|
|
67
|
+
if (typeof i.env !== 'string' || !ENV_KEY.test(i.env)) { errors.push(`unit ${u.id}: input ${i.id} names env ${JSON.stringify(i.env)}, which is not an environment key`); bad = true; continue; }
|
|
68
|
+
if (!declared.has(i.env)) { errors.push(`unit ${u.id}: input ${i.id} names env ${i.env}, which the package does not declare in dreamteamer.env or vars`); bad = true; continue; }
|
|
69
|
+
}
|
|
70
|
+
if (i.kind === 'rows' && !(Array.isArray(i.rows?.columns) && i.rows.columns.length && i.rows.columns.every((c) => typeof c === 'string'))) { errors.push(`unit ${u.id}: input ${i.id} is rows and must declare rows.columns`); bad = true; continue; }
|
|
71
|
+
inputs.push({ id: i.id, kind: i.kind, env: i.env, required: i.required === true, title: i.title ?? i.id, default: i.default, prompt: i.prompt, rows: i.rows });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (bad) continue;
|
|
75
|
+
units.push({ id: u.id, version: SETUP_VERSION, module: name, inputs, inspect: u.inspect, plan: u.plan, apply: u.apply });
|
|
76
|
+
}
|
|
77
|
+
return { units, errors };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Does this action ask the engine to write `.env`? (`env: { KEY: value, … }` on the action — D61.) */
|
|
81
|
+
export const isEnvAction = (action) => !!action && typeof action === 'object' && action.env !== undefined;
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Judge an env action's shape when a plan is read. `declared` is the Set of env keys the package
|
|
85
|
+
* declares (`dreamteamer.env` ∪ `vars`). `{ ok: true }`, or `{ ok: false, state, reason }` where
|
|
86
|
+
* `state` is what the driver writes on the action: `needs-input` for a value not yet known
|
|
87
|
+
* (`undefined`/`null` — the shape a unit's plan has before its input arrives), `blocked` for anything
|
|
88
|
+
* the unit got wrong. Pure; the file-level refusals (git exposure, a key assigned twice, a quote in
|
|
89
|
+
* the value) are `src/env-write.js`'s, judged by the driver with the file in hand.
|
|
90
|
+
*/
|
|
91
|
+
export function validateEnvAction(action, declared) {
|
|
92
|
+
const env = action?.env;
|
|
93
|
+
if (!env || typeof env !== 'object' || Array.isArray(env)) return { ok: false, state: 'blocked', reason: 'env must be an object of KEY → value' };
|
|
94
|
+
for (const [key, value] of Object.entries(env)) {
|
|
95
|
+
if (!ENV_KEY.test(key)) return { ok: false, state: 'blocked', reason: `${key} is not an environment key` };
|
|
96
|
+
if (!declared.has(key)) return { ok: false, state: 'blocked', reason: `${key} is not declared by the package (dreamteamer.env or vars)` };
|
|
97
|
+
if (value === undefined || value === null) return { ok: false, state: 'needs-input', reason: `${key} has no value yet` };
|
|
98
|
+
if (typeof value !== 'string') return { ok: false, state: 'blocked', reason: `${key}: a value that is not a string` };
|
|
99
|
+
}
|
|
100
|
+
return { ok: true };
|
|
101
|
+
}
|
package/src/setup.js
ADDED
|
@@ -0,0 +1,506 @@
|
|
|
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, isEnvAction, validateEnvAction } from './setup-contract.js';
|
|
20
|
+
import { setEnvValues, fingerprint, leftoverTemps, gitExposure, writeEnvAtomic, EnvRefusal } from './env-write.js';
|
|
21
|
+
import { parseEnvValues } from './env-vars.js';
|
|
22
|
+
import { RUNTIME_DIR } from './runtime.js';
|
|
23
|
+
import { discoverModules } from './compile.js';
|
|
24
|
+
|
|
25
|
+
export const EFFECTS_ALLOWED = ['download', 'network', 'machine'];
|
|
26
|
+
export const EXIT = { done: 0, failed: 1, usage: 2, needsInput: 3 };
|
|
27
|
+
|
|
28
|
+
// ---- pure ---------------------------------------------------------------------------------------
|
|
29
|
+
|
|
30
|
+
/** `--input id=value` and `--input unit.id=value`, repeated; the value may itself hold `=`. */
|
|
31
|
+
export function parseInputFlags(argv) {
|
|
32
|
+
const out = [];
|
|
33
|
+
for (let i = 0; i < argv.length; i++) {
|
|
34
|
+
if (argv[i] !== '--input') continue;
|
|
35
|
+
const raw = argv[++i];
|
|
36
|
+
const eq = raw?.indexOf('=') ?? -1;
|
|
37
|
+
if (eq < 1) throw usage('--input takes id=value (or unit.id=value)');
|
|
38
|
+
const key = raw.slice(0, eq), value = raw.slice(eq + 1);
|
|
39
|
+
const dot = key.indexOf('.');
|
|
40
|
+
out.push(dot > 0 ? { unit: key.slice(0, dot), id: key.slice(dot + 1), value } : { unit: null, id: key, value });
|
|
41
|
+
}
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** `--allow <kind>`, repeated; an unknown kind is a usage error naming the vocabulary. */
|
|
46
|
+
export function parseAllow(argv) {
|
|
47
|
+
const allow = new Set();
|
|
48
|
+
for (let i = 0; i < argv.length; i++) {
|
|
49
|
+
if (argv[i] !== '--allow') continue;
|
|
50
|
+
const kind = argv[++i];
|
|
51
|
+
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\``);
|
|
52
|
+
allow.add(kind);
|
|
53
|
+
}
|
|
54
|
+
return allow;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export class SetupUsage extends Error { constructor(m) { super(m); this.code = EXIT.usage; } }
|
|
58
|
+
const usage = (m) => new SetupUsage(m);
|
|
59
|
+
|
|
60
|
+
const expandHome = (p, home) => (typeof p === 'string' && (p === '~' || p.startsWith('~/')) ? path.join(home, p.slice(1)) : p);
|
|
61
|
+
|
|
62
|
+
/** 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. */
|
|
63
|
+
function secretPathProblem(value) {
|
|
64
|
+
let st;
|
|
65
|
+
try { st = fs.statSync(value); } catch { return `${value}: no such file`; }
|
|
66
|
+
if (!st.isFile()) return `${value}: not a file`;
|
|
67
|
+
if (process.platform !== 'win32' && (st.mode & 0o077)) return `${value} is readable by other users — chmod 600 ${value}`;
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
const flagText = (f) => `--input ${f.unit ? `${f.unit}.` : ''}${f.id}=`;
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Fill every unit's inputs. Returns `inputs` (unit id → { inputId: value }), `missing` (required
|
|
74
|
+
* inputs with no value from any source), `ignored` and `problems`. `prompt(input, default)` is called
|
|
75
|
+
* only in a TTY, only for what is still missing, and only when `noInput` is false. Strict (the default)
|
|
76
|
+
* throws a usage error for a flag naming no input, two values for one shared key, or a secret-path
|
|
77
|
+
* that does not exist or is not owner-only — nothing has run yet. `lenient` (install, where npm has
|
|
78
|
+
* already written) keeps going: the unknown flag is listed in `ignored`, the bad value in `problems`
|
|
79
|
+
* with the input left unfilled, so the install still commits and the line says what is still needed.
|
|
80
|
+
*/
|
|
81
|
+
export async function fillInputs(units, { flags = [], env = {}, tty = false, noInput = false, prompt = null, home = os.homedir(), lenient = false } = {}) {
|
|
82
|
+
const inputs = new Map(units.map((u) => [u.id, {}]));
|
|
83
|
+
const missing = [], ignored = [], problems = [];
|
|
84
|
+
const refuse = (text, problem = null) => { if (!lenient) throw usage(text); if (problem) problems.push(problem); else ignored.push(text); };
|
|
85
|
+
// a bare --input id= is unambiguous when every unit declaring that id names the same env key
|
|
86
|
+
const byId = new Map();
|
|
87
|
+
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 });
|
|
88
|
+
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))));
|
|
89
|
+
const live = [];
|
|
90
|
+
for (const f of flags) {
|
|
91
|
+
const owners = byId.get(f.id) ?? [];
|
|
92
|
+
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; }
|
|
93
|
+
if (!f.unit && !owners.length) { refuse(`${flagText(f)} names no input of ${units.map((u) => u.id).join(', ') || 'any unit'}`); continue; }
|
|
94
|
+
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; }
|
|
95
|
+
live.push(f);
|
|
96
|
+
}
|
|
97
|
+
// an env key shared by several inputs is one input: a flag for any of them fills all of them, and two
|
|
98
|
+
// different values for it in one call are a refusal naming both (D39)
|
|
99
|
+
const envValues = new Map(), envFlag = new Map(), conflicted = new Set();
|
|
100
|
+
for (const u of units) for (const i of u.inputs) for (const f of live) {
|
|
101
|
+
if (!i.env || i.kind === 'rows' || !valueOf(u, i, f)) continue; // a rows input is repeatable: every flag is one more row
|
|
102
|
+
if (envValues.has(i.env) && envValues.get(i.env) !== f.value && envFlag.get(i.env) !== f) {
|
|
103
|
+
const first = envFlag.get(i.env);
|
|
104
|
+
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 });
|
|
105
|
+
conflicted.add(i.env);
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
if (!envValues.has(i.env)) { envValues.set(i.env, f.value); envFlag.set(i.env, f); }
|
|
109
|
+
}
|
|
110
|
+
// a default declared by any input sharing the key is the key's default, and required is the OR of
|
|
111
|
+
// every declaration sharing it (D39: one key, one input)
|
|
112
|
+
const envDefaults = new Map(), envRequired = new Set();
|
|
113
|
+
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); }
|
|
114
|
+
const isRequired = (i) => !!i.required || (!!i.env && envRequired.has(i.env));
|
|
115
|
+
for (const u of units) {
|
|
116
|
+
for (const i of u.inputs) {
|
|
117
|
+
if (i.env && conflicted.has(i.env)) continue;
|
|
118
|
+
let value;
|
|
119
|
+
const given = live.filter((f) => valueOf(u, i, f)).map((f) => f.value);
|
|
120
|
+
if (i.kind === 'rows') {
|
|
121
|
+
if (given.length) value = given;
|
|
122
|
+
} else if (given.length) value = given.at(-1);
|
|
123
|
+
else if (i.env && envValues.has(i.env)) value = envValues.get(i.env);
|
|
124
|
+
else if (i.env && env[i.env] !== undefined && String(env[i.env]).trim() !== '') value = String(env[i.env]);
|
|
125
|
+
else if (i.default !== undefined) value = i.default;
|
|
126
|
+
else if (i.env && envDefaults.has(i.env)) value = envDefaults.get(i.env);
|
|
127
|
+
if (value === undefined && tty && !noInput && prompt) {
|
|
128
|
+
const answer = await prompt(i, i.default);
|
|
129
|
+
if (answer !== undefined && answer !== null && String(answer).trim() !== '') value = i.kind === 'rows' ? [String(answer)] : String(answer);
|
|
130
|
+
}
|
|
131
|
+
if (value === undefined) { if (isRequired(i)) missing.push({ unit: u.id, id: i.id }); continue; }
|
|
132
|
+
if (i.kind === 'path' || i.kind === 'secret-path') value = expandHome(value, home);
|
|
133
|
+
if (i.kind === 'secret-path') {
|
|
134
|
+
// a flag's bad value is the caller's to fix (usage, strict); one the environment or a default holds
|
|
135
|
+
// is reported on the unit's line and left unfilled, whoever runs
|
|
136
|
+
const problem = secretPathProblem(value);
|
|
137
|
+
if (problem && given.length) { refuse(`--input ${i.id}=${problem}`, { unit: u.id, id: i.id, reason: problem, required: true, env: i.env ?? null }); continue; }
|
|
138
|
+
if (problem) { problems.push({ unit: u.id, id: i.id, reason: problem, required: isRequired(i), env: i.env ?? null }); continue; }
|
|
139
|
+
}
|
|
140
|
+
inputs.get(u.id)[i.id] = value;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return { inputs, missing, ignored, problems };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** The env keys a unit must not see: those whose value the engine refused for it. */
|
|
147
|
+
export const droppedKeys = (problems, unitId) => [...new Set(problems.filter((p) => p.unit === unitId && p.env).map((p) => p.env))];
|
|
148
|
+
|
|
149
|
+
/** May this action run now? `ask(action)` is the y/n in a TTY; `allow` the --allow kinds. */
|
|
150
|
+
export async function consent(action, { allow = new Set(), tty = false, ask = null, authorize = false } = {}) {
|
|
151
|
+
const kinds = [...new Set((action.effects ?? []).map((e) => e.kind))];
|
|
152
|
+
if (kinds.includes('account')) return authorize && tty;
|
|
153
|
+
const asked = kinds.filter((k) => k !== 'workspace-files');
|
|
154
|
+
if (!asked.length) return true;
|
|
155
|
+
if (asked.every((k) => allow.has(k))) return true;
|
|
156
|
+
if (tty && ask) return !!(await ask(action, asked));
|
|
157
|
+
return false;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** One line from a unit's checks — the design's status table, in its order. */
|
|
161
|
+
export function fold(checks, { skipped = false } = {}) {
|
|
162
|
+
if (skipped) return { state: 'skipped', detail: 'dt setup <unit> to resume', verified: null };
|
|
163
|
+
if (!checks.length) return { state: 'no-evidence', detail: 'inspect returned no checks — never ready', verified: null };
|
|
164
|
+
const unknown = checks.filter((c) => !CHECK_STATUSES.includes(c.status));
|
|
165
|
+
if (unknown.length) return { state: 'blocked', detail: unknown.map((c) => `${c.title ?? c.id}: unknown status ${JSON.stringify(c.status)}`).join(' · '), verified: null };
|
|
166
|
+
const blocked = checks.filter((c) => c.status === 'blocked');
|
|
167
|
+
if (blocked.length) return { state: 'blocked', detail: blocked.map((c) => `${c.title ?? c.id}${c.detail ? ` — ${c.detail}` : ''}`).join(' · '), verified: null };
|
|
168
|
+
const open = checks.filter((c) => c.status === 'missing' || c.status === 'unverified');
|
|
169
|
+
if (open.length) return { state: 'configured', detail: open.map((c) => `${c.title ?? c.id} ${c.status}`).join(' · '), verified: null };
|
|
170
|
+
const dates = checks.map((c) => c.evidence?.at).filter((d) => typeof d === 'string').sort();
|
|
171
|
+
return { state: 'ready', detail: '', verified: dates.at(-1) ?? null };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** A provider's FAILURE text, with anything that looks like a value gone: a `key=value` (a `<placeholder>`
|
|
175
|
+
* is not a value), a bearer token, an e-mail address, a home folder, a 32+-character token. Key names
|
|
176
|
+
* and shapes stay. Applied to what a unit throws, a failed apply's message and an action's reason —
|
|
177
|
+
* never to a check's fix or title, an action's title or a next-command line (D67). */
|
|
178
|
+
export function redact(text) {
|
|
179
|
+
return String(text ?? '')
|
|
180
|
+
// a key=value whose key is a secret word, alone or as the last part of a prefixed name (ACME_TOKEN=…);
|
|
181
|
+
// a bare `key=` counts, a prefixed `primary_key=` does not; a <placeholder> is not a value
|
|
182
|
+
.replace(/\b((?:[A-Za-z0-9]+[_-])*(?:token|secret|password|passwd|api[_-]?key|client[_-]?secret|credential))=(?!<)\S+/gi, '$1=[redacted]')
|
|
183
|
+
.replace(/(^|[^A-Za-z0-9_-])(key)=(?!<)\S+/gi, '$1$2=[redacted]')
|
|
184
|
+
.replace(/\bBearer\s+\S+/g, 'Bearer [redacted]')
|
|
185
|
+
// an e-mail address — but not the `git@host` of an ssh remote
|
|
186
|
+
.replace(/[^\s@"'<>():,`]+@[^\s@"'<>():,`/]+\.[A-Za-z]{2,}/g, (m) => (m.startsWith('git@') ? m : '<email>'))
|
|
187
|
+
// a home folder where a path starts (a file URL, quotes, backticks, a comma list included) — not a
|
|
188
|
+
// /home/ segment inside an http URL, not the shared folder
|
|
189
|
+
.replace(/(?<=^|[\s"'=(:`,]|file:\/\/)\/(?:Users|home)\/(?!Shared\b)[^\s/"'`,]+/g, '~')
|
|
190
|
+
.replace(/(?<=^|[\s"'=(:`,])[A-Za-z]:\\Users\\[^\s\\"'`,]+/g, '~')
|
|
191
|
+
// a long token: 32+ characters of [A-Za-z0-9_-] — except an env key name (capitals in `_`-joined parts),
|
|
192
|
+
// a dated id (a `--`) or a kebab id (three or more lower-case `-`-joined words, none over 16); a base32
|
|
193
|
+
// seed, a one-case run or a prefixed token (xoxb-…) is a token
|
|
194
|
+
.replace(/\b[A-Za-z0-9_-]{32,}\b/g, (m) => (/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/.test(m) || m.includes('--') || (/^[a-z0-9]+(?:-[a-z0-9]+){2,}$/.test(m) && m.split('-').every((p) => p.length <= 16)) ? m : '[redacted]'));
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Judge an env action when a plan is read — the driver's own verdict, from what it can see without
|
|
199
|
+
* writing (D61). Pure: handed the `.env` text, the leftover temps beside it, the git exposure verdict
|
|
200
|
+
* and the plan-time fingerprint (`expect`). Returns the action as the driver will treat it: `done`
|
|
201
|
+
* when every key already holds its value; `needs-input` for a value not yet known; `blocked` with the
|
|
202
|
+
* reason for anything the write would refuse; else the unit's own state (`ready` by default) with
|
|
203
|
+
* `expect` stamped and `effects` defaulted to the one workspace-files entry. A plain action is
|
|
204
|
+
* returned as is.
|
|
205
|
+
*/
|
|
206
|
+
export function judgeEnvAction(action, { declared, text, temps = [], exposure = { safe: true }, expect, written = new Map(), unit = null }) {
|
|
207
|
+
if (!isEnvAction(action)) return action;
|
|
208
|
+
const keys = Object.keys(action.env ?? {});
|
|
209
|
+
const effects = (action.effects ?? []).length ? action.effects : [{ kind: 'workspace-files', detail: `.env: ${keys.join(', ')}` }];
|
|
210
|
+
const out = { ...action, effects, runBy: action.runBy ?? 'engine' };
|
|
211
|
+
const v = validateEnvAction(action, declared);
|
|
212
|
+
if (!v.ok) return { ...out, state: v.state, reason: v.reason };
|
|
213
|
+
let changed;
|
|
214
|
+
try { ({ changed } = setEnvValues(text, action.env)); } catch (e) { return { ...out, state: 'blocked', reason: e instanceof EnvRefusal ? e.message : redact(e.message) }; }
|
|
215
|
+
if (!changed.length) return { ...out, state: 'done', reason: `${keys.join(', ')} already hold${keys.length === 1 ? 's' : ''} this value` };
|
|
216
|
+
// two units sharing a key is allowed (one input, D39); two units writing DIFFERENT values to it in one run
|
|
217
|
+
// is not — the last write would win silently and the first unit would read a value it never wrote (he3)
|
|
218
|
+
const clash = changed.find((k) => written.has(k) && written.get(k).unit !== unit && written.get(k).value !== action.env[k]);
|
|
219
|
+
if (clash) return { ...out, state: 'blocked', reason: `${clash} was written by unit ${written.get(clash).unit} in this run with another value — two units disagree on it; set it by hand` };
|
|
220
|
+
if (temps.length) return { ...out, state: 'blocked', reason: `temporary files from an interrupted write sit beside .env (${temps.join(', ')}) — review and delete them first` };
|
|
221
|
+
if (!exposure.safe) return { ...out, state: 'blocked', reason: exposure.reason };
|
|
222
|
+
if (action.state && action.state !== 'ready' && action.state !== 'done') return { ...out, expect };
|
|
223
|
+
return { ...out, state: 'ready', expect };
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
// ---- the workspace side -----------------------------------------------------------------------
|
|
227
|
+
|
|
228
|
+
/** Every setup unit the loaded extensions contribute, with its package. */
|
|
229
|
+
export const units = (ws) => (ws.extensions ?? []).flatMap((e) => (e.setup ?? []).map((u) => ({ ...u, module: e.name, dir: e.dir, declared: new Set([...(e.env ?? []), ...(e.vars ?? [])]) })));
|
|
230
|
+
export const skippedUnits = (ws) => ws.pkg?.dreamteamer?.setup?.skipped ?? [];
|
|
231
|
+
export const receiptDir = (ws, unitId) => path.join(ws.root, RUNTIME_DIR, 'setup', unitId);
|
|
232
|
+
|
|
233
|
+
/** The environment a unit sees: the process's, with the workspace `.env` filling what it lacks. */
|
|
234
|
+
export function unitEnv(ws, processEnv = process.env) {
|
|
235
|
+
const file = path.join(ws.root, '.env');
|
|
236
|
+
// a leading byte-order mark would hide the first key from the reader (`^KEY=`) and let a key inside
|
|
237
|
+
// another key's quoted value read as an assignment (held-out he1) — skipped here, the workspace side
|
|
238
|
+
const dotenv = fs.existsSync(file) ? parseEnvValues(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, '')) : new Map();
|
|
239
|
+
return { ...Object.fromEntries(dotenv), ...processEnv };
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Run one unit: inspect → plan(inputs) → apply what is consented → inspect. Never throws for a
|
|
243
|
+
* provider's fault: a throwing apply is one failed action, redacted, and the unit reads blocked. */
|
|
244
|
+
export async function runUnit(ws, unit, { inputs = {}, allow = new Set(), tty = false, ask = null, authorize = false, verify = false, processEnv = process.env, api = null, drop = [], written = new Map() } = {}) {
|
|
245
|
+
// the env is re-read after every applied action: a safe action's whole point is often to write the
|
|
246
|
+
// key the next inspect reads (`PROBE_HOME=` into .env), and a stale copy would report it missing.
|
|
247
|
+
// `drop` names the keys whose value the engine refused (a secret-path that is missing or not
|
|
248
|
+
// owner-only): the unit never sees them, so it can neither trust nor record them
|
|
249
|
+
const envFor = () => { const e = unitEnv(ws, processEnv); for (const k of drop) delete e[k]; return e; };
|
|
250
|
+
const ctx = { root: ws.root, ws, dt: api, env: envFor(), tty, receiptDir: receiptDir(ws, unit.id) };
|
|
251
|
+
const applied = [], failed = [];
|
|
252
|
+
let pending = [], needs = [];
|
|
253
|
+
const done = new Set(), refused = new Set();
|
|
254
|
+
// an env action is the engine's to perform (D61): judged when the plan is read against the file as
|
|
255
|
+
// it was when the plan ran (the fingerprint taken before `plan`, so a plan that touches .env itself
|
|
256
|
+
// makes the write refuse), then written by rename instead of handed to apply
|
|
257
|
+
const envFile = path.join(ws.root, '.env');
|
|
258
|
+
const envText = () => { try { return fs.readFileSync(envFile, 'utf8'); } catch { return ''; } };
|
|
259
|
+
const snapshot = () => { try { return fingerprint(envFile); } catch (e) { return e; } };
|
|
260
|
+
const judge = (actions, expect) => actions.map((a) => {
|
|
261
|
+
if (!isEnvAction(a)) return a;
|
|
262
|
+
if (expect instanceof Error) return judgeEnvAction({ ...a, state: 'blocked', reason: expect.message }, { declared: unit.declared ?? new Set(), text: '', expect: null });
|
|
263
|
+
return judgeEnvAction(a, { declared: unit.declared ?? new Set(), text: envText(), temps: leftoverTemps(envFile), exposure: gitExposure(ws.root, '.env'), expect, written, unit: unit.id });
|
|
264
|
+
});
|
|
265
|
+
// what is listed as pending is printed (and under --json, whole): an env action is listed by the KEYS it
|
|
266
|
+
// would write, never its values; a reason is failure text, redacted (D67)
|
|
267
|
+
const withReason = (a, extra) => ({ ...a, ...extra, ...(isEnvAction(a) ? { env: Object.keys(a.env ?? {}) } : {}), ...(a.reason !== undefined ? { reason: redact(a.reason) } : {}) });
|
|
268
|
+
// the plan is asked again after every applied action: an action's preconditions are often what the
|
|
269
|
+
// previous one made (a venv before the download, a key in .env before the check that reads it), so
|
|
270
|
+
// one pass would leave them pending for a second call that a person should not have to make
|
|
271
|
+
for (let round = 0; round < 50; round++) {
|
|
272
|
+
let planned;
|
|
273
|
+
const expect = snapshot();
|
|
274
|
+
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 }; }
|
|
275
|
+
needs = planned.needs ?? [];
|
|
276
|
+
pending = [];
|
|
277
|
+
let next = null;
|
|
278
|
+
for (const action of judge(planned.actions ?? [], expect)) {
|
|
279
|
+
if (done.has(action.id)) continue;
|
|
280
|
+
if (action.state && action.state !== 'ready') { if (action.state !== 'done') pending.push(withReason(action, { why: action.state === 'needs-input' ? 'needs input' : action.state })); else done.add(action.id); continue; }
|
|
281
|
+
if (refused.has(action.id)) { pending.push(withReason(action, { why: refused.get?.(action.id) ?? 'declined' })); continue; }
|
|
282
|
+
const isVerify = action.kind === 'verify';
|
|
283
|
+
if (isVerify && !verify) { pending.push(withReason(action, { why: 'run with --verify' })); continue; }
|
|
284
|
+
if ((action.runBy === 'owner' || (action.effects ?? []).some((e) => e.kind === 'account')) && !(authorize && tty)) { pending.push(withReason(action, { why: 'the owner\'s step: dt setup <unit> --authorize' })); continue; }
|
|
285
|
+
if (!next) next = action; else pending.push(withReason(action, { why: 'after the step before it' }));
|
|
286
|
+
}
|
|
287
|
+
if (!next) break;
|
|
288
|
+
if (!(await consent(next, { allow, tty, ask, authorize }))) {
|
|
289
|
+
refused.add(next.id);
|
|
290
|
+
pending.push(withReason(next, { why: `needs --allow ${[...new Set((next.effects ?? []).map((e) => e.kind).filter((k) => k !== 'workspace-files'))].join(' --allow ')}` }));
|
|
291
|
+
// the actions queued behind it stay listed as they are; nothing else can run this round
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
done.add(next.id);
|
|
295
|
+
if (isEnvAction(next)) {
|
|
296
|
+
// the engine's own write: refused only when the file moved since the plan (or cannot be written)
|
|
297
|
+
try {
|
|
298
|
+
const { text, changed } = setEnvValues(envText(), next.env);
|
|
299
|
+
writeEnvAtomic(ws.root, text, next.expect);
|
|
300
|
+
for (const k of changed) written.set(k, { unit: unit.id, value: next.env[k] });
|
|
301
|
+
// a ready env action's reason is the unit's note on what it wrote or left out (a malformed row it
|
|
302
|
+
// skipped); printed after the write, redacted like every reason (D67)
|
|
303
|
+
applied.push({ id: next.id, changed: ['.env'], message: `wrote .env (${changed.join(', ')})${next.reason ? ` — ${redact(next.reason)}` : ''}` });
|
|
304
|
+
ctx.env = envFor();
|
|
305
|
+
} catch (e) { failed.push({ id: next.id, message: e instanceof EnvRefusal ? e.message : redact(e.message) }); }
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
if (typeof unit.apply !== 'function') { failed.push({ id: next.id, message: `unit ${unit.id}: action ${next.id} carries no env and the unit declares no apply` }); continue; }
|
|
309
|
+
try {
|
|
310
|
+
const r = (await unit.apply(ctx, next, inputs)) ?? { ok: false, message: 'apply returned nothing' };
|
|
311
|
+
if (r.ok) { applied.push({ id: next.id, changed: r.changed ?? [], message: r.message }); ctx.env = envFor(); }
|
|
312
|
+
else failed.push({ id: next.id, message: redact(r.message ?? 'apply refused') });
|
|
313
|
+
} catch (e) { failed.push({ id: next.id, message: redact(e.message) }); }
|
|
314
|
+
}
|
|
315
|
+
// the final word on what is still open comes from one more plan, so a declined action and the ones
|
|
316
|
+
// behind it read with their own states, never as "after the step before it"
|
|
317
|
+
try {
|
|
318
|
+
const expect = snapshot();
|
|
319
|
+
const last = (await unit.plan(ctx, inputs)) ?? {};
|
|
320
|
+
needs = last.needs ?? needs;
|
|
321
|
+
pending = judge(last.actions ?? [], expect).filter((a) => !done.has(a.id) && a.state !== 'done').map((a) => {
|
|
322
|
+
if (a.state && a.state !== 'ready') return withReason(a, { why: a.state === 'needs-input' ? 'needs input' : a.state });
|
|
323
|
+
if (a.kind === 'verify' && !verify) return withReason(a, { why: 'run with --verify' });
|
|
324
|
+
if (a.runBy === 'owner' || (a.effects ?? []).some((e) => e.kind === 'account')) return withReason(a, { why: 'the owner\'s step: dt setup <unit> --authorize' });
|
|
325
|
+
return withReason(a, { why: `needs --allow ${[...new Set((a.effects ?? []).map((e) => e.kind).filter((k) => k !== 'workspace-files'))].join(' --allow ')}` });
|
|
326
|
+
});
|
|
327
|
+
} catch { /* the loop's own view stands */ }
|
|
328
|
+
return { checks: safeInspect(unit, ctx), applied, pending, failed, needs };
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** A unit's checks, never a throw: a thrown error is one blocked row, redacted; an inspect that hands back a
|
|
332
|
+
* Promise (a plain function wrapping an async body — the load-time rule only sees an AsyncFunction) is a
|
|
333
|
+
* blocked row naming the fix, never "no evidence". `dt doctor` reads through it too. */
|
|
334
|
+
export function safeInspect(unit, ctx) {
|
|
335
|
+
try {
|
|
336
|
+
const r = unit.inspect(ctx);
|
|
337
|
+
if (typeof r?.then === 'function') { r.then(null, () => {}); return [{ id: `${unit.id}.inspect`, status: 'blocked', title: 'inspect', detail: 'inspect returned a Promise — dt status reads it without awaiting; make it synchronous' }]; }
|
|
338
|
+
return Array.isArray(r?.checks) ? r.checks : [];
|
|
339
|
+
} catch (e) { return [{ id: `${unit.id}.inspect`, status: 'blocked', title: 'inspect', detail: redact(e.message) }]; }
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** The setup section of `dt status`: one entry per unit, then one per package with no unit. */
|
|
343
|
+
export function statusLines(ws, { processEnv = process.env } = {}) {
|
|
344
|
+
const env = unitEnv(ws, processEnv);
|
|
345
|
+
const lines = [];
|
|
346
|
+
const skipped = new Set(skippedUnits(ws));
|
|
347
|
+
const byModule = new Map();
|
|
348
|
+
for (const u of units(ws)) (byModule.get(u.module) ?? byModule.set(u.module, []).get(u.module)).push(u);
|
|
349
|
+
for (const [module, us] of byModule) {
|
|
350
|
+
for (const u of us) {
|
|
351
|
+
// the same rule as setup: a secret-path the environment holds that is missing or not owner-only is
|
|
352
|
+
// never handed to the unit — status shows it as its own missing row, with the fix
|
|
353
|
+
const unitEnvHere = { ...env };
|
|
354
|
+
const refused = [];
|
|
355
|
+
for (const i of u.inputs ?? []) {
|
|
356
|
+
if (i.kind !== 'secret-path' || !i.env || unitEnvHere[i.env] === undefined || String(unitEnvHere[i.env]).trim() === '') continue;
|
|
357
|
+
const problem = secretPathProblem(expandHome(String(unitEnvHere[i.env]), os.homedir()));
|
|
358
|
+
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>` }); }
|
|
359
|
+
}
|
|
360
|
+
const ctx = { root: ws.root, ws, dt: null, env: unitEnvHere, tty: false, receiptDir: receiptDir(ws, u.id) };
|
|
361
|
+
const checks = [...refused, ...safeInspect(u, ctx)];
|
|
362
|
+
const f = fold(checks, { skipped: skipped.has(u.id) });
|
|
363
|
+
lines.push({ package: module, unit: u.id, grouped: us.length > 1, ...f, checks, next: nextCommand(u.id, f, checks) });
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
// a skip entry no installed package provides is not silent: one line names it and how to clear it
|
|
367
|
+
const provided = new Set([...byModule.values()].flat().map((u) => u.id));
|
|
368
|
+
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` });
|
|
369
|
+
// every other installed module — an extension without a unit, or a plain module with no code at all —
|
|
370
|
+
// reads `no setup`, naming the declared env keys and vars nobody set; the engine and the workspace's own
|
|
371
|
+
// module are not modules anybody installs
|
|
372
|
+
const own = ws.pkg?.dreamteamer?.workspace_module ?? 'default';
|
|
373
|
+
for (const m of discoverModules(ws.root, ws.pkg).modules) {
|
|
374
|
+
let manifest = {};
|
|
375
|
+
try { manifest = JSON.parse(fs.readFileSync(path.join(m.root, 'package.json'), 'utf8')); } catch { /* no manifest */ }
|
|
376
|
+
const name = manifest.name ?? m.name;
|
|
377
|
+
if (name === 'dreamteamer' || m.name === own || byModule.has(name)) continue;
|
|
378
|
+
const dt = manifest.dreamteamer ?? {};
|
|
379
|
+
const needs = [...(dt.env ?? []), ...(dt.vars ?? [])].filter((k) => env[k] === undefined || String(env[k]).trim() === '');
|
|
380
|
+
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` : '' });
|
|
381
|
+
}
|
|
382
|
+
return lines;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function nextCommand(unitId, f, checks) {
|
|
386
|
+
if (f.state === 'skipped') return `dt setup ${unitId}`;
|
|
387
|
+
if (f.state === 'ready') return '';
|
|
388
|
+
const fix = checks.find((c) => c.status !== 'ready' && c.status !== 'configured' && c.fix)?.fix;
|
|
389
|
+
return fix ?? `dt setup ${unitId}`;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
export function renderStatusLines(lines) {
|
|
393
|
+
if (!lines.length) return [];
|
|
394
|
+
const out = ['setup:'];
|
|
395
|
+
const label = (l) => (l.unit ? (l.grouped ? `${moduleId(l.package)} › ${l.unit}` : l.unit) : moduleId(l.package));
|
|
396
|
+
const width = Math.max(...lines.map((l) => label(l).length));
|
|
397
|
+
for (const l of lines) {
|
|
398
|
+
const state = l.state === 'no-setup' ? 'no setup' : l.state === 'no-evidence' ? 'no evidence' : l.state;
|
|
399
|
+
const verified = l.verified ? ` · verified ${l.verified}` : '';
|
|
400
|
+
out.push(` ${label(l).padEnd(width)} ${state}${verified}${l.detail ? ` ${l.detail}` : ''}${l.next ? ` → ${l.next}` : ''}`);
|
|
401
|
+
}
|
|
402
|
+
return out;
|
|
403
|
+
}
|
|
404
|
+
const moduleId = (name) => String(name).replace(/^@[^/]+\//, '');
|
|
405
|
+
|
|
406
|
+
/** Record a skip (or clear one) in package.json → dreamteamer.setup.skipped, keeping the file's own indentation. */
|
|
407
|
+
export function setSkipped(ws, unitId, on) {
|
|
408
|
+
const file = path.join(ws.root, 'package.json');
|
|
409
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
410
|
+
const indent = /^\t/m.test(text) ? '\t' : (/^( +)"/m.exec(text)?.[1] ?? ' ');
|
|
411
|
+
const pkg = JSON.parse(text);
|
|
412
|
+
const block = (pkg.dreamteamer ??= {});
|
|
413
|
+
const list = new Set(block.setup?.skipped ?? []);
|
|
414
|
+
if (on) list.add(unitId); else list.delete(unitId);
|
|
415
|
+
if (list.size) (block.setup ??= {}).skipped = [...list].sort();
|
|
416
|
+
else if (block.setup) { delete block.setup.skipped; if (!Object.keys(block.setup).length) delete block.setup; }
|
|
417
|
+
fs.writeFileSync(file, JSON.stringify(pkg, null, indent) + '\n');
|
|
418
|
+
ws.pkg = pkg;
|
|
419
|
+
try {
|
|
420
|
+
execFileSync('git', ['add', '--', 'package.json'], { cwd: ws.root, stdio: 'ignore' });
|
|
421
|
+
execFileSync('git', ['commit', '--quiet', '-m', `dreamteamer: ${on ? 'skip' : 'resume'} setup of ${unitId}`, '--', 'package.json'], { cwd: ws.root, stdio: 'ignore' });
|
|
422
|
+
} catch { /* no repo, or nothing to commit — the file is written either way */ }
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// ---- the verb -----------------------------------------------------------------------------------
|
|
426
|
+
|
|
427
|
+
/** The terminal's prompt and y/n, on one readline — `dt setup` and `dt install` share it. */
|
|
428
|
+
export function ttyIO() {
|
|
429
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
430
|
+
return { prompt: ttyPrompt(rl), ask: ttyAsk(rl), close: () => rl.close() };
|
|
431
|
+
}
|
|
432
|
+
// an EOF (Ctrl-D) at a prompt is no answer — the input stays missing (exit 3), the action declined — never a crash
|
|
433
|
+
const question = async (rl, text) => { try { return (await rl.question(text)).trim(); } catch { return ''; } };
|
|
434
|
+
const ttyPrompt = (rl) => async (input, def) => {
|
|
435
|
+
const hint = def !== undefined ? ` [${def}]` : input.required ? ' (required)' : ' (enter to skip)';
|
|
436
|
+
const answer = await question(rl, `${input.prompt ?? input.title ?? input.id}${hint}: `);
|
|
437
|
+
return answer === '' ? def : answer;
|
|
438
|
+
};
|
|
439
|
+
const ttyAsk = (rl) => async (action, kinds) => {
|
|
440
|
+
const effects = (action.effects ?? []).map((e) => `${e.kind}: ${e.detail}`).join('\n ');
|
|
441
|
+
const answer = (await question(rl, `${action.title} — ${kinds.join(', ')}\n ${effects}\n run it? [y/N] `)).toLowerCase();
|
|
442
|
+
return answer === 'y' || answer === 'yes';
|
|
443
|
+
};
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* `dt setup [<unit>] [--input k=v]… [--allow <kind>]… [--authorize] [--verify] [--skip] [--no-input] [--json]`
|
|
447
|
+
* 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.
|
|
448
|
+
*/
|
|
449
|
+
export async function setupCommand(ws, argv, { processEnv = process.env, tty = !!(process.stdin.isTTY && process.stdout.isTTY), log = console.log, api = null, io = null } = {}) {
|
|
450
|
+
const env = unitEnv(ws, processEnv);
|
|
451
|
+
const json = argv.includes('--json');
|
|
452
|
+
const noInput = json || argv.includes('--no-input');
|
|
453
|
+
const flags = { authorize: argv.includes('--authorize'), verify: argv.includes('--verify'), skip: argv.includes('--skip') };
|
|
454
|
+
let allow, inputFlags;
|
|
455
|
+
try { allow = parseAllow(argv); inputFlags = parseInputFlags(argv); } catch (e) { if (e instanceof SetupUsage) { console.error(`✖ ${e.message}`); return EXIT.usage; } throw e; }
|
|
456
|
+
const target = argv.find((a, i) => !a.startsWith('--') && argv[i - 1] !== '--input' && argv[i - 1] !== '--allow');
|
|
457
|
+
const all = units(ws);
|
|
458
|
+
const chosen = target ? all.filter((u) => u.id === target) : all;
|
|
459
|
+
if (target && !chosen.length) { console.error(`✖ no setup unit "${target}" — installed units: ${all.map((u) => u.id).join(', ') || '(none)'}`); return EXIT.usage; }
|
|
460
|
+
if (!all.length) { log('— no installed module declares setup — `dt status` lists what is installed, `dt install <package>` adds a module'); return EXIT.done; }
|
|
461
|
+
if (flags.authorize && !target) { console.error('✖ --authorize takes one unit: dt setup <unit> --authorize'); return EXIT.usage; }
|
|
462
|
+
if (flags.authorize && !tty) { console.error('✖ --authorize needs a terminal: the owner signs in; a script cannot'); return EXIT.usage; }
|
|
463
|
+
if (flags.skip) {
|
|
464
|
+
if (!target) { console.error('✖ --skip takes one unit: dt setup <unit> --skip'); return EXIT.usage; }
|
|
465
|
+
setSkipped(ws, target, true);
|
|
466
|
+
log(`— ${target}: skipped (dt setup ${target} to resume)`);
|
|
467
|
+
return EXIT.done;
|
|
468
|
+
}
|
|
469
|
+
if (target && skippedUnits(ws).includes(target)) { setSkipped(ws, target, false); log(`✔ ${target}: no longer skipped`); }
|
|
470
|
+
const skipped = new Set(skippedUnits(ws));
|
|
471
|
+
const run = chosen.filter((u) => !skipped.has(u.id));
|
|
472
|
+
const term = tty && !noInput && !io ? ttyIO() : null;
|
|
473
|
+
const prompt = io?.prompt ?? term?.prompt ?? null;
|
|
474
|
+
const ask = io?.ask ?? term?.ask ?? null;
|
|
475
|
+
let code = EXIT.done;
|
|
476
|
+
const results = [];
|
|
477
|
+
try {
|
|
478
|
+
const filled = await fillInputs(run, { flags: inputFlags, env, tty, noInput, prompt });
|
|
479
|
+
const written = new Map(); // the keys this run's env actions wrote, by unit — one run never lets two units disagree on a key
|
|
480
|
+
for (const u of run) {
|
|
481
|
+
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), written });
|
|
482
|
+
const problems = filled.problems.filter((m) => m.unit === u.id);
|
|
483
|
+
const missing = [...filled.missing.filter((m) => m.unit === u.id).map((m) => m.id), ...problems.filter((m) => m.required).map((m) => m.id)];
|
|
484
|
+
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, {});
|
|
485
|
+
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])] });
|
|
486
|
+
if (missing.length) code = Math.max(code, EXIT.needsInput);
|
|
487
|
+
else if (r.failed.length && code === EXIT.done) code = EXIT.failed; // D57: an apply that failed is a failure, never a 0
|
|
488
|
+
}
|
|
489
|
+
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: [] });
|
|
490
|
+
} catch (e) {
|
|
491
|
+
if (e instanceof SetupUsage) { console.error(`✖ ${e.message}`); return EXIT.usage; }
|
|
492
|
+
throw e;
|
|
493
|
+
} finally { term?.close(); }
|
|
494
|
+
if (json) { log(JSON.stringify({ workspace: { root: ws.root, name: ws.pkg?.name ?? null }, units: results }, null, 2)); return code; }
|
|
495
|
+
for (const r of results) {
|
|
496
|
+
const verified = r.verified ? ` · verified ${r.verified}` : '';
|
|
497
|
+
log(`${r.state === 'ready' ? '✔' : r.state === 'blocked' ? '✖' : '—'} ${r.id}: ${r.state}${verified}${r.detail ? ` — ${r.detail}` : ''}`);
|
|
498
|
+
for (const a of r.applied) log(` ✔ ${a.id}${a.message ? ` — ${a.message}` : ''}`);
|
|
499
|
+
for (const f of r.failed) log(` ✖ ${f.id} — ${f.message}`);
|
|
500
|
+
for (const p of r.problems ?? []) log(` ✖ ${p.id} — ${p.reason}`);
|
|
501
|
+
for (const p of r.pending) log(` … ${p.id} (${p.why})${p.reason ? ` — ${p.reason}` : ''}`);
|
|
502
|
+
if (r.needs.length) log(` needs input: ${r.needs.join(', ')} — --input ${r.needs[0]}=<value>`);
|
|
503
|
+
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`);
|
|
504
|
+
}
|
|
505
|
+
return code;
|
|
506
|
+
}
|
package/src/testing.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// The typed contract of `import … from 'dreamteamer/testing'` (src/testing.js): a module's own test
|
|
2
|
+
// suite on the real engine. Synchronous throughout. Policy (D64): on 0.x a breaking change to this
|
|
3
|
+
// export lands in a minor, announced one release ahead in UPDATING.md.
|
|
4
|
+
|
|
5
|
+
/** One engine run: its exit status (null when it was ended on `timeoutMs`), stdout and stderr. */
|
|
6
|
+
export interface Result { status: number | null; stdout: string; stderr: string }
|
|
7
|
+
export interface RunOptions {
|
|
8
|
+
/** Laid over the process environment (and the synthetic git identity) for this run. */
|
|
9
|
+
env?: Record<string, string>;
|
|
10
|
+
/** Ends the run by SIGKILL after this many milliseconds; `status` is then null. Default 60 000. */
|
|
11
|
+
timeoutMs?: number;
|
|
12
|
+
/** Text handed to the run's stdin (a hook payload, a prompt's answer). */
|
|
13
|
+
input?: string;
|
|
14
|
+
}
|
|
15
|
+
/** A workspace `createWorkspace` made: its root, the engine it runs on, and `run` bound to it. */
|
|
16
|
+
export interface Workspace { root: string; engine: string; dt(args: string[], opts?: RunOptions): Result }
|
|
17
|
+
|
|
18
|
+
/** The package root of the engine running this file — never one found on PATH. */
|
|
19
|
+
export const ENGINE: string;
|
|
20
|
+
/** `dt init` in a fresh temp folder on `engine`, else `DT_ENGINE_DIR`, else `ENGINE`. Throws if init fails. */
|
|
21
|
+
export function createWorkspace(opts?: { engine?: string }): Workspace;
|
|
22
|
+
/** `npm pack` of a module folder; the tarball's path. */
|
|
23
|
+
export function pack(moduleDir: string): string;
|
|
24
|
+
/** `dt install` of a name, a tarball path or a module folder (packed first). Exit 3 is a result. */
|
|
25
|
+
export function install(ws: Workspace, spec: string, opts?: RunOptions): Result;
|
|
26
|
+
/** The CLI of the workspace's engine, run in the workspace. */
|
|
27
|
+
export function run(ws: Workspace, args: string[], opts?: RunOptions): Result;
|
|
28
|
+
/** Does the running engine (or `DT_ENGINE_DIR`'s) satisfy the semver range? */
|
|
29
|
+
export function engineMeets(range: string): boolean;
|