dreamteamer 0.47.0 → 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 +8 -0
- package/package.json +5 -1
- package/skills/using-dreamteamer/SKILL.md +1 -0
- package/skills/using-dreamteamer/references/extensions.md +33 -0
- package/skills/using-dreamteamer/references/setup.md +6 -4
- 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 +2 -1
- package/src/cli.js +21 -7
- package/src/collections-cli.js +4 -2
- package/src/compile.js +1 -1
- package/src/doctor.js +2 -2
- package/src/env-write.js +162 -0
- package/src/extensions.js +11 -0
- package/src/install-modules.js +2 -1
- package/src/scaffold-templates.js +85 -0
- package/src/schema-ops.js +27 -4
- package/src/setup-contract.js +30 -1
- package/src/setup.js +108 -22
- package/src/testing.d.ts +29 -0
- package/src/testing.js +86 -0
package/src/env-write.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// The `.env` writer behind a unit's env action (cr-dt-007, D61): the engine performs the one write
|
|
2
|
+
// every module's setup used to carry its own copy of — a key's value span replaced in place or
|
|
3
|
+
// appended, every other byte kept, the file replaced whole by rename, and only while it still has
|
|
4
|
+
// the fingerprint the plan saw. What is written reads back through `parseEnvValues` identically:
|
|
5
|
+
// `envSpans` follows that reader's grammar (an unquoted value runs to end of line; a quoted one may
|
|
6
|
+
// span lines), so this file is the writer half of one grammar, not a second grammar.
|
|
7
|
+
//
|
|
8
|
+
// Refusals are `EnvRefusal` with a `code`, so the driver (src/setup.js) can turn the ones it can see
|
|
9
|
+
// before writing into a plan-time `blocked` and keep only `changed` (the file moved after the plan)
|
|
10
|
+
// and an I/O error as a write-time failure. Nothing here reads a value back to the caller.
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
14
|
+
import { spawnSync } from 'node:child_process';
|
|
15
|
+
|
|
16
|
+
export class EnvRefusal extends Error {
|
|
17
|
+
constructor(code, message) { super(message); this.code = code; }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const ENV_KEY = /^[A-Z][A-Z0-9_]*$/;
|
|
21
|
+
// the reader's assignment, with the value token captured: KEY=value · KEY="…" (spans lines) · KEY='…'
|
|
22
|
+
const ASSIGNMENT = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)=("(?:[^"\\]|\\.)*"|'[^']*'|[^\n]*)$/gm;
|
|
23
|
+
|
|
24
|
+
/** Every assignment in `.env` text, in file order: `{ key, start, end, raw, value, quoted }` where
|
|
25
|
+
* `[start, end)` is the value token's span (an unquoted value without its trailing whitespace, so a
|
|
26
|
+
* CRLF file keeps its `\r`), `raw` the text there, `value` what parseEnvValues reads, `quoted` the
|
|
27
|
+
* quote character or false. */
|
|
28
|
+
export function envSpans(text) {
|
|
29
|
+
const out = [];
|
|
30
|
+
// a leading byte-order mark is not part of the first key: scanned as if absent, offsets kept (it is one
|
|
31
|
+
// UTF-16 unit, replaced by one newline so `^` still matches the first line)
|
|
32
|
+
const body = String(text).replace(/^\uFEFF/, '\n');
|
|
33
|
+
for (const m of body.matchAll(ASSIGNMENT)) {
|
|
34
|
+
let raw = m[2];
|
|
35
|
+
const quoted = raw.startsWith('"') && raw.endsWith('"') && raw.length >= 2 ? '"' : raw.startsWith("'") && raw.endsWith("'") && raw.length >= 2 ? "'" : false;
|
|
36
|
+
if (!quoted) raw = raw.replace(/\s+$/, '');
|
|
37
|
+
const start = m.index + m[0].length - m[2].length;
|
|
38
|
+
out.push({ key: m[1], start, end: start + raw.length, raw, value: quoted ? raw.slice(1, -1) : raw.trim(), quoted });
|
|
39
|
+
}
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The token written for `value`: plain when nothing in it needs quoting (a backslash reads back as
|
|
44
|
+
* itself unquoted — a Windows path), else double-quoted. Inside double quotes the reader treats `\x` as
|
|
45
|
+
* one unit, so a backslash there could swallow the closing quote: refused. */
|
|
46
|
+
function token(key, value, preferQuoted) {
|
|
47
|
+
const plain = /^[^\s#"']*$/.test(value) && value === value.trim() && !(preferQuoted && !value.includes('\\'));
|
|
48
|
+
if (plain) return value;
|
|
49
|
+
if (value.includes('\\')) throw new EnvRefusal('value', `${key}: a value with characters this action does not write — set it by hand`);
|
|
50
|
+
return `"${value}"`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* `.env` text with every key of `values` set, every other byte kept: a present key's value span is
|
|
55
|
+
* replaced in place (its quoting kept when it was double-quoted); an absent key is appended as its
|
|
56
|
+
* own line. `changed` lists the keys whose value differs from what the file held.
|
|
57
|
+
* Refuses, by code: `twice` (a key assigned more than once — which assignment wins is the reader's
|
|
58
|
+
* accident, so neither is rewritten) and `value` (a value holding `"` or NUL — the reader does not
|
|
59
|
+
* unescape, so such a value cannot read back as written).
|
|
60
|
+
*/
|
|
61
|
+
export function setEnvValues(text, values) {
|
|
62
|
+
let out = String(text);
|
|
63
|
+
// a byte-order mark stays where it is; envSpans scans past it (the engine's reader of the unit's
|
|
64
|
+
// environment, unitEnv, skips it too — held-out he1)
|
|
65
|
+
const changed = [];
|
|
66
|
+
for (const [key, value] of Object.entries(values)) {
|
|
67
|
+
if (!ENV_KEY.test(key)) throw new EnvRefusal('key', `${key} is not an environment key`);
|
|
68
|
+
if (typeof value !== 'string') throw new EnvRefusal('value', `${key}: a value that is not a string`);
|
|
69
|
+
const found = envSpans(out).filter((s) => s.key === key);
|
|
70
|
+
if (found.length > 1) throw new EnvRefusal('twice', `${key} is assigned more than once in .env — resolve that by hand first`);
|
|
71
|
+
// a value the file already holds is done, whatever it holds: one a person set by hand after a refusal
|
|
72
|
+
// is never refused again
|
|
73
|
+
if (found.length === 1 && found[0].value === value) continue;
|
|
74
|
+
// a `"` the reader does not unescape; `$`, a backtick or a carriage return a shell that sources .env
|
|
75
|
+
// would expand or split; NUL — refused, so what is written reads back as written everywhere
|
|
76
|
+
if (/["$`\r\0]/.test(value)) throw new EnvRefusal('value', `${key}: a value with characters this action does not write — set it by hand`);
|
|
77
|
+
if (found.length === 1) {
|
|
78
|
+
const s = found[0];
|
|
79
|
+
out = out.slice(0, s.start) + token(key, value, s.quoted === '"') + out.slice(s.end);
|
|
80
|
+
} else {
|
|
81
|
+
const nl = out.includes('\r\n') ? '\r\n' : '\n';
|
|
82
|
+
out = `${out}${out && !out.endsWith('\n') ? nl : ''}${key}=${token(key, value, false)}${nl}`;
|
|
83
|
+
}
|
|
84
|
+
changed.push(key);
|
|
85
|
+
}
|
|
86
|
+
return { text: out, changed };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** `sha256:<hex>` of a regular file, `absent` when there is none; a symlink or a non-file is refused. */
|
|
90
|
+
export function fingerprint(file) {
|
|
91
|
+
let st;
|
|
92
|
+
try { st = fs.lstatSync(file); } catch (error) { if (error.code === 'ENOENT') return 'absent'; throw error; }
|
|
93
|
+
if (st.isSymbolicLink()) throw new EnvRefusal('symlink', `${path.basename(file)} is a symlink — a symlinked file is never written; replace the link with a regular file first`);
|
|
94
|
+
if (!st.isFile()) throw new EnvRefusal('not-file', `${path.basename(file)} is not a regular file`);
|
|
95
|
+
return `sha256:${createHash('sha256').update(fs.readFileSync(file)).digest('hex')}`;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const tempPrefix = (target) => `${path.basename(target)}.setup-`;
|
|
99
|
+
/** Temporary files an interrupted write of `target` left beside it — a reason to stop and name them. */
|
|
100
|
+
export function leftoverTemps(target) {
|
|
101
|
+
try { return fs.readdirSync(path.dirname(target)).filter((f) => f.startsWith(tempPrefix(target)) && f.endsWith('.tmp')).sort(); }
|
|
102
|
+
catch { return []; }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// read-only git, scoped to the root: no optional locks, no fsmonitor, no GIT_* from the environment
|
|
106
|
+
const GIT_ENV_KEYS = ['PATH', 'HOME', 'USERPROFILE', 'SystemRoot', 'SYSTEMROOT', 'TMPDIR', 'TEMP', 'TMP', 'LANG', 'LC_ALL', 'XDG_CONFIG_HOME'];
|
|
107
|
+
function git(root, args) {
|
|
108
|
+
const env = { GIT_TERMINAL_PROMPT: '0' };
|
|
109
|
+
for (const k of GIT_ENV_KEYS) if (process.env[k] !== undefined) env[k] = process.env[k];
|
|
110
|
+
const r = spawnSync('git', ['--no-optional-locks', '-c', 'core.fsmonitor=false', '-C', root, ...args], { env, encoding: 'utf8', timeout: 10_000, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
111
|
+
return { status: r.error ? null : r.status, stderr: r.stderr ?? '' };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Could workspace-relative `rel` end up in a commit? `{ safe }` or `{ safe: false, reason }`: in a
|
|
115
|
+
* repository git decides (not tracked, and ignored); outside any repository nothing can be committed. */
|
|
116
|
+
export function gitExposure(root, rel) {
|
|
117
|
+
const top = git(root, ['rev-parse', '--show-toplevel']);
|
|
118
|
+
if (top.status !== 0) {
|
|
119
|
+
if (top.status === 128 && /not a git repository/i.test(top.stderr)) return { safe: true };
|
|
120
|
+
if (top.status === null) return { safe: true }; // no git on this machine: nothing commits
|
|
121
|
+
return { safe: false, reason: `git could not inspect this workspace — nothing was written` };
|
|
122
|
+
}
|
|
123
|
+
if (git(root, ['ls-files', '--error-unmatch', '--', rel]).status === 0) return { safe: false, reason: `${rel} is tracked by git, so its contents would be committed — untrack it (git rm --cached ${rel}) and ignore it first` };
|
|
124
|
+
if (git(root, ['check-ignore', '-q', '--', rel]).status === 0) return { safe: true };
|
|
125
|
+
return { safe: false, reason: `git would commit ${rel} — add it to .gitignore first` };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Is any component of `.env` under `root` a symlink, or does the path leave the root? */
|
|
129
|
+
function confinedEnv(root) {
|
|
130
|
+
const real = fs.realpathSync(root);
|
|
131
|
+
const target = path.join(real, '.env');
|
|
132
|
+
let st = null;
|
|
133
|
+
try { st = fs.lstatSync(target); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
134
|
+
if (st?.isSymbolicLink()) throw new EnvRefusal('symlink', '.env is a symlink — a symlinked file is never written; replace the link with a regular file first');
|
|
135
|
+
return target;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Replace `<root>/.env` with `content` by rename, only while it still has fingerprint `expect`
|
|
140
|
+
* (`absent` for a file that did not exist). The temporary file is removed on every failure this
|
|
141
|
+
* process survives; an existing file keeps its mode, a new one is created owner-only. The last check
|
|
142
|
+
* and the rename are two calls, not a compare-and-swap — optimistic, kept as short as it can be.
|
|
143
|
+
*/
|
|
144
|
+
export function writeEnvAtomic(root, content, expect) {
|
|
145
|
+
const target = confinedEnv(root);
|
|
146
|
+
const stale = () => new EnvRefusal('changed', '.env changed after the preview — nothing was written; plan again');
|
|
147
|
+
if (fingerprint(target) !== expect) throw stale();
|
|
148
|
+
let mode = 0o600;
|
|
149
|
+
try { mode = fs.statSync(target).mode & 0o777; } catch { /* a new file */ }
|
|
150
|
+
const temp = path.join(path.dirname(target), `${tempPrefix(target)}${process.pid}.${randomBytes(6).toString('hex')}.tmp`);
|
|
151
|
+
const fd = fs.openSync(temp, 'wx', mode);
|
|
152
|
+
try {
|
|
153
|
+
try { fs.writeFileSync(fd, content); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
|
|
154
|
+
confinedEnv(root);
|
|
155
|
+
if (fingerprint(target) !== expect) throw stale();
|
|
156
|
+
fs.renameSync(temp, target);
|
|
157
|
+
} catch (error) {
|
|
158
|
+
fs.rmSync(temp, { force: true });
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
161
|
+
return fingerprint(target);
|
|
162
|
+
}
|
package/src/extensions.js
CHANGED
|
@@ -57,6 +57,17 @@ export function v1ManifestRefusal(block, where) {
|
|
|
57
57
|
|
|
58
58
|
export const EXTENSION_API = 1;
|
|
59
59
|
|
|
60
|
+
/** What `dt check` holds every discovered package's manifest to, beyond the `dreamteamer` block: the
|
|
61
|
+
* engine never under `dependencies` — npm nests a second engine there whenever the pin differs from the
|
|
62
|
+
* workspace's, and a module reaching that copy disagrees with the engine the operator ran (D66).
|
|
63
|
+
* `devDependencies` (a module's own tests) and `peerDependencies` are the two places it belongs. */
|
|
64
|
+
export function manifestViolations(pkg, file) {
|
|
65
|
+
if (pkg?.dependencies && typeof pkg.dependencies === 'object' && 'dreamteamer' in pkg.dependencies) {
|
|
66
|
+
return [{ file, message: `${pkg.name ?? file} lists dreamteamer under dependencies — a second engine would be installed beside this one; move it to devDependencies or peerDependencies` }];
|
|
67
|
+
}
|
|
68
|
+
return [];
|
|
69
|
+
}
|
|
70
|
+
|
|
60
71
|
const CONTRIBUTION_KEYS = new Set(['commands', 'sourceKinds', 'analyze', 'harnesses', 'orientation', 'hooks', 'check', 'doctor', 'next', 'setup']);
|
|
61
72
|
|
|
62
73
|
/** The modules that declare an extension entry: the workspace's own `modules/<id>/` first, then each
|
package/src/install-modules.js
CHANGED
|
@@ -266,8 +266,9 @@ export async function setupAndCommit(ws, fresh, names, { subject, inputFlags = [
|
|
|
266
266
|
try {
|
|
267
267
|
const filled = await fillInputs(fresh_units, { flags: inputFlags, env: { ...dotenv(fresh), ...processEnv }, tty, noInput, prompt: io?.prompt ?? term?.prompt ?? null, lenient: true });
|
|
268
268
|
ignored = filled.ignored;
|
|
269
|
+
const written = new Map(); // one run never lets two units disagree on a key (he3)
|
|
269
270
|
for (const u of fresh_units) {
|
|
270
|
-
const res = await runUnit(fresh, u, { inputs: filled.inputs.get(u.id) ?? {}, allow, tty, ask: io?.ask ?? term?.ask ?? null, authorize: false, verify: false, processEnv, drop: droppedKeys(filled.problems, u.id) });
|
|
271
|
+
const res = await runUnit(fresh, u, { inputs: filled.inputs.get(u.id) ?? {}, allow, tty, ask: io?.ask ?? term?.ask ?? null, authorize: false, verify: false, processEnv, drop: droppedKeys(filled.problems, u.id), written });
|
|
271
272
|
const problems = filled.problems.filter((m) => m.unit === u.id);
|
|
272
273
|
const missing = [...filled.missing.filter((m) => m.unit === u.id).map((m) => m.id), ...problems.filter((m) => m.required).map((m) => m.id)];
|
|
273
274
|
const f = fold(res.failed.length ? [...res.checks, ...res.failed.map((x) => ({ id: x.id, status: 'blocked', title: x.id, detail: x.message }))] : res.checks, {});
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
// The text `dt add modules` writes beside a new module's package.json (cr-dt-007, G4): a README with the
|
|
2
|
+
// install line, and — under `--extension` — an extension entry whose one setup unit asks for one token and
|
|
3
|
+
// lets the engine write it into .env (the env action, D61). Pure: strings in, strings out.
|
|
4
|
+
|
|
5
|
+
/** `acme-crm` → `ACME_CRM_TOKEN`: the one env key the scaffolded unit declares. */
|
|
6
|
+
export const scaffoldKey = (id) => `${id.toUpperCase().replace(/-/g, '_')}_TOKEN`;
|
|
7
|
+
|
|
8
|
+
export function readmeText({ id, pkgName, description, extension }) {
|
|
9
|
+
const key = scaffoldKey(id);
|
|
10
|
+
return [
|
|
11
|
+
`# ${pkgName}`,
|
|
12
|
+
'',
|
|
13
|
+
description || 'A dreamteamer module.',
|
|
14
|
+
'',
|
|
15
|
+
'```bash',
|
|
16
|
+
`dt install ${pkgName}`,
|
|
17
|
+
...(extension ? [`dt setup ${id} --input token=<token> # writes ${key} into .env`] : []),
|
|
18
|
+
'```',
|
|
19
|
+
'',
|
|
20
|
+
'## Developing it',
|
|
21
|
+
'',
|
|
22
|
+
'```bash',
|
|
23
|
+
'dt compile && dt status # the inline module is live in this workspace',
|
|
24
|
+
'npm test # node --test on dreamteamer/testing',
|
|
25
|
+
`dt check modules/${id} --alone # exit 0: publishable`,
|
|
26
|
+
'```',
|
|
27
|
+
'',
|
|
28
|
+
'Writing a module: the `using-dreamteamer` skill, references/writing-a-module.md.',
|
|
29
|
+
'',
|
|
30
|
+
].join('\n');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function extensionText({ id }) {
|
|
34
|
+
const key = scaffoldKey(id);
|
|
35
|
+
return `// ${id} — the extension entry. \`activate(dt)\` receives the running engine's API; it returns what this
|
|
36
|
+
// module contributes. The one setup unit asks for a token and names the .env write; the engine performs
|
|
37
|
+
// it (confined, fingerprint-checked, never printed). Add commands, check, doctor or next as you need them.
|
|
38
|
+
const KEY = '${key}';
|
|
39
|
+
|
|
40
|
+
/** Read-only and synchronous: what is set up, from the environment the engine hands over. */
|
|
41
|
+
function inspect(ctx) {
|
|
42
|
+
return { checks: [{ id: '${id}.token', status: ctx.env[KEY] ? 'configured' : 'missing', title: KEY, fix: 'dt setup ${id} --input token=<token>' }] };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** What would run: one env action, ready once the token is known. */
|
|
46
|
+
function plan(ctx, inputs) {
|
|
47
|
+
const token = inputs.token ?? ctx.env[KEY];
|
|
48
|
+
return {
|
|
49
|
+
checks: inspect({ ...ctx, env: { ...ctx.env, ...(token ? { [KEY]: token } : {}) } }).checks,
|
|
50
|
+
actions: [{ id: 'set-token', title: \`write \${KEY} into .env\`, env: { [KEY]: token }, state: token ? 'ready' : 'needs-input' }],
|
|
51
|
+
needs: token ? [] : ['token'],
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export const apiVersion = 1;
|
|
56
|
+
|
|
57
|
+
export default function activate(dt) {
|
|
58
|
+
return {
|
|
59
|
+
setup: [{
|
|
60
|
+
id: '${id}', version: 1,
|
|
61
|
+
inputs: [{ id: 'token', kind: 'string', env: KEY, required: true, title: '${id} token', prompt: 'The token for ${id}' }],
|
|
62
|
+
inspect, plan,
|
|
63
|
+
}],
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The one test a new module starts with: installed the way a stranger installs it, on the engine that
|
|
70
|
+
* runs the test, and checked. `npm test` runs it (`node --test`). */
|
|
71
|
+
export function testText({ id }) {
|
|
72
|
+
return `// ${id} — installed into a fresh workspace on the engine running this test, the way a stranger installs it.
|
|
73
|
+
import { test } from 'node:test';
|
|
74
|
+
import assert from 'node:assert/strict';
|
|
75
|
+
import { fileURLToPath } from 'node:url';
|
|
76
|
+
import { createWorkspace, install, run } from 'dreamteamer/testing';
|
|
77
|
+
|
|
78
|
+
test('${id} installs into a fresh workspace and checks clean', () => {
|
|
79
|
+
const ws = createWorkspace();
|
|
80
|
+
const r = install(ws, fileURLToPath(new URL('..', import.meta.url))); // packed with npm pack, then dt install
|
|
81
|
+
assert.ok([0, 3].includes(r.status), r.stdout + r.stderr); // 3: an input is still to be given
|
|
82
|
+
assert.equal(run(ws, ['check']).status, 0);
|
|
83
|
+
});
|
|
84
|
+
`;
|
|
85
|
+
}
|
package/src/schema-ops.js
CHANGED
|
@@ -22,6 +22,7 @@ import { FIELD_OPTIONS, TEMPLATE_OPTIONS, viewOverlayOf } from './views.js';
|
|
|
22
22
|
const GIT_QUIET = ['ignore', 'pipe', 'ignore'];
|
|
23
23
|
import { walk, idFromRecordPath, parseRecord, EXT } from './records.js';
|
|
24
24
|
import { Store, serialize, atomicWrite } from './store.js';
|
|
25
|
+
import { readmeText, extensionText, testText, scaffoldKey } from './scaffold-templates.js';
|
|
25
26
|
|
|
26
27
|
// ---- the gate -------------------------------------------------------------------
|
|
27
28
|
|
|
@@ -297,8 +298,18 @@ function editWorkspacePkg(ws, mutate) {
|
|
|
297
298
|
return file;
|
|
298
299
|
}
|
|
299
300
|
|
|
300
|
-
|
|
301
|
+
const NPM_NAME = /^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/;
|
|
302
|
+
const ENGINE_VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
303
|
+
|
|
304
|
+
export function createModule(ws, store, { name, description, namespace, extension = false, pkg: pkgName = null }) {
|
|
301
305
|
if (!name || name === true) throw new Error('missing module name — dreamteamer add modules --name <id>');
|
|
306
|
+
if (pkgName === true) throw new Error('--package takes the npm name: dreamteamer add modules --name <id> --package @scope/<id>');
|
|
307
|
+
if (pkgName && (pkgName.length > 214 || !NPM_NAME.test(pkgName))) throw new Error(`"${pkgName}" is not an npm package name — lowercase, URL-safe, optionally @scope/name`);
|
|
308
|
+
if (extension && !/^[a-z]/.test(name)) throw new Error(`--extension needs a module id that starts with a letter — "${name}" becomes the setup unit's id and its env key (${scaffoldKey(name)}), and both must start with one`);
|
|
309
|
+
if (pkgName) {
|
|
310
|
+
const holder = discoverModules(ws.root, ws.pkg).modules.find((m) => { try { return JSON.parse(fs.readFileSync(path.join(m.root, 'package.json'), 'utf8')).name === pkgName; } catch { return false; } });
|
|
311
|
+
if (holder) throw new Error(`${pkgName} is already the package name of ${path.relative(ws.root, holder.root) || holder.root} — two modules under one name would shadow each other; pick another --package`);
|
|
312
|
+
}
|
|
302
313
|
if (!MODULE_ID.test(name)) {
|
|
303
314
|
throw new Error(`invalid module id "${name}" — lowercase alphanumeric with single hyphens. It becomes a folder name, a package name and a record id at once, so there is only one spelling.`);
|
|
304
315
|
}
|
|
@@ -329,12 +340,23 @@ export function createModule(ws, store, { name, description, namespace }) {
|
|
|
329
340
|
}
|
|
330
341
|
// `files` is the npm publish surface: every kind a module CAN ship, so a kind added to the engine
|
|
331
342
|
// does not silently stop being packaged.
|
|
332
|
-
|
|
343
|
+
// `engine` is the floor the module is written against: the engine that scaffolded it (cr-dt-007)
|
|
344
|
+
dt.engine = `>=${ENGINE_VERSION}`;
|
|
345
|
+
if (extension) { dt.extension = './src/extension.js'; dt.env = [scaffoldKey(name)]; }
|
|
346
|
+
const files = [...KINDS, ...(extension ? ['src'] : []), 'README.md'];
|
|
347
|
+
// `--package` makes it publishable: its npm name (the module id stays the folder), a first version,
|
|
348
|
+
// and the engine as a devDependency for its own tests — never `dependencies`, which would nest a second engine (D66)
|
|
349
|
+
const mpkg = pkgName
|
|
350
|
+
? { name: pkgName, version: '0.1.0', type: 'module', files, scripts: { test: 'node --test' }, devDependencies: { dreamteamer: ENGINE_VERSION }, dreamteamer: dt }
|
|
351
|
+
: { name, private: true, version: '0.0.1', type: 'module', files, scripts: { test: 'node --test' }, dreamteamer: dt };
|
|
333
352
|
const pkgFile = path.join(root, 'package.json');
|
|
353
|
+
const written = { 'README.md': readmeText({ id: name, pkgName: mpkg.name, description, extension }), 'test/module.test.mjs': testText({ id: name }), ...(extension ? { 'src/extension.js': extensionText({ id: name }) } : {}) };
|
|
334
354
|
|
|
335
355
|
const out = gatedTreeOp(ws, store, {
|
|
336
356
|
subject: `dreamteamer: modules add ${name}`,
|
|
337
|
-
|
|
357
|
+
// compile regenerates .env.example from the declared keys, so a module that declares one (--extension)
|
|
358
|
+
// changes it — it rides in the same commit rather than being left modified outside it
|
|
359
|
+
paths: [path.relative(ws.root, pkgFile), ...Object.keys(written).map((f) => path.relative(ws.root, path.join(root, f))), ...(extension && fs.existsSync(path.join(ws.root, '.env.example')) ? ['.env.example'] : [])],
|
|
338
360
|
mutate: () => {
|
|
339
361
|
// ⚠ SCAFFOLD EVERY KIND FOLDER. Not decoration: it is what makes the module's shape
|
|
340
362
|
// self-documenting the moment it exists, and compile's "contributed no recognised sources"
|
|
@@ -343,10 +365,11 @@ export function createModule(ws, store, { name, description, namespace }) {
|
|
|
343
365
|
// git cannot track an empty directory, so only package.json is in the pathspec.
|
|
344
366
|
for (const kind of KINDS) fs.mkdirSync(path.join(root, kind), { recursive: true });
|
|
345
367
|
fs.writeFileSync(pkgFile, JSON.stringify(mpkg, null, '\t') + '\n');
|
|
368
|
+
for (const [f, text] of Object.entries(written)) { fs.mkdirSync(path.dirname(path.join(root, f)), { recursive: true }); fs.writeFileSync(path.join(root, f), text); }
|
|
346
369
|
},
|
|
347
370
|
undo: () => fs.rmSync(root, { recursive: true, force: true }),
|
|
348
371
|
});
|
|
349
|
-
return { id: name, root: path.relative(ws.root, root), file: pkgFile, namespace: ns || null, commits: out.commits };
|
|
372
|
+
return { id: name, root: path.relative(ws.root, root), file: pkgFile, files: ['package.json', ...Object.keys(written)], namespace: ns || null, commits: out.commits };
|
|
350
373
|
}
|
|
351
374
|
|
|
352
375
|
/** The settable fields of a `modules` record, and how each translates from the record-shaped value
|
package/src/setup-contract.js
CHANGED
|
@@ -48,7 +48,13 @@ export function validateSetup(name, value, { env = [], vars = [] } = {}) {
|
|
|
48
48
|
seen.add(u.id);
|
|
49
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
50
|
let bad = false;
|
|
51
|
-
for (const f of ['inspect', 'plan'
|
|
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; }
|
|
52
58
|
const inputs = [];
|
|
53
59
|
const rawInputs = u.inputs ?? [];
|
|
54
60
|
if (!Array.isArray(rawInputs)) { errors.push(`unit ${u.id}: inputs must be a list`); bad = true; }
|
|
@@ -70,3 +76,26 @@ export function validateSetup(name, value, { env = [], vars = [] } = {}) {
|
|
|
70
76
|
}
|
|
71
77
|
return { units, errors };
|
|
72
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
CHANGED
|
@@ -16,7 +16,8 @@ import os from 'node:os';
|
|
|
16
16
|
import path from 'node:path';
|
|
17
17
|
import readline from 'node:readline/promises';
|
|
18
18
|
import { execFileSync } from 'node:child_process';
|
|
19
|
-
import { CHECK_STATUSES } from './setup-contract.js';
|
|
19
|
+
import { CHECK_STATUSES, isEnvAction, validateEnvAction } from './setup-contract.js';
|
|
20
|
+
import { setEnvValues, fingerprint, leftoverTemps, gitExposure, writeEnvAtomic, EnvRefusal } from './env-write.js';
|
|
20
21
|
import { parseEnvValues } from './env-vars.js';
|
|
21
22
|
import { RUNTIME_DIR } from './runtime.js';
|
|
22
23
|
import { discoverModules } from './compile.js';
|
|
@@ -170,30 +171,77 @@ export function fold(checks, { skipped = false } = {}) {
|
|
|
170
171
|
return { state: 'ready', detail: '', verified: dates.at(-1) ?? null };
|
|
171
172
|
}
|
|
172
173
|
|
|
173
|
-
/** A provider's
|
|
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). */
|
|
174
178
|
export function redact(text) {
|
|
175
179
|
return String(text ?? '')
|
|
176
|
-
|
|
177
|
-
|
|
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 };
|
|
178
224
|
}
|
|
179
225
|
|
|
180
226
|
// ---- the workspace side -----------------------------------------------------------------------
|
|
181
227
|
|
|
182
228
|
/** 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 })));
|
|
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 ?? [])]) })));
|
|
184
230
|
export const skippedUnits = (ws) => ws.pkg?.dreamteamer?.setup?.skipped ?? [];
|
|
185
231
|
export const receiptDir = (ws, unitId) => path.join(ws.root, RUNTIME_DIR, 'setup', unitId);
|
|
186
232
|
|
|
187
233
|
/** The environment a unit sees: the process's, with the workspace `.env` filling what it lacks. */
|
|
188
234
|
export function unitEnv(ws, processEnv = process.env) {
|
|
189
235
|
const file = path.join(ws.root, '.env');
|
|
190
|
-
|
|
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();
|
|
191
239
|
return { ...Object.fromEntries(dotenv), ...processEnv };
|
|
192
240
|
}
|
|
193
241
|
|
|
194
242
|
/** Run one unit: inspect → plan(inputs) → apply what is consented → inspect. Never throws for a
|
|
195
243
|
* 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 = [] } = {}) {
|
|
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() } = {}) {
|
|
197
245
|
// the env is re-read after every applied action: a safe action's whole point is often to write the
|
|
198
246
|
// key the next inspect reads (`PROBE_HOME=` into .env), and a stale copy would report it missing.
|
|
199
247
|
// `drop` names the keys whose value the engine refused (a secret-path that is missing or not
|
|
@@ -203,32 +251,61 @@ export async function runUnit(ws, unit, { inputs = {}, allow = new Set(), tty =
|
|
|
203
251
|
const applied = [], failed = [];
|
|
204
252
|
let pending = [], needs = [];
|
|
205
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) } : {}) });
|
|
206
268
|
// the plan is asked again after every applied action: an action's preconditions are often what the
|
|
207
269
|
// previous one made (a venv before the download, a key in .env before the check that reads it), so
|
|
208
270
|
// one pass would leave them pending for a second call that a person should not have to make
|
|
209
271
|
for (let round = 0; round < 50; round++) {
|
|
210
272
|
let planned;
|
|
273
|
+
const expect = snapshot();
|
|
211
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 }; }
|
|
212
275
|
needs = planned.needs ?? [];
|
|
213
276
|
pending = [];
|
|
214
277
|
let next = null;
|
|
215
|
-
for (const action of planned.actions ?? []) {
|
|
278
|
+
for (const action of judge(planned.actions ?? [], expect)) {
|
|
216
279
|
if (done.has(action.id)) continue;
|
|
217
|
-
if (action.state && action.state !== 'ready') { if (action.state !== 'done') pending.push(
|
|
218
|
-
if (refused.has(action.id)) { pending.push(
|
|
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; }
|
|
219
282
|
const isVerify = action.kind === 'verify';
|
|
220
|
-
if (isVerify && !verify) { pending.push(
|
|
221
|
-
if ((action.runBy === 'owner' || (action.effects ?? []).some((e) => e.kind === 'account')) && !(authorize && tty)) { pending.push(
|
|
222
|
-
if (!next) next = action; else pending.push(
|
|
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' }));
|
|
223
286
|
}
|
|
224
287
|
if (!next) break;
|
|
225
288
|
if (!(await consent(next, { allow, tty, ask, authorize }))) {
|
|
226
289
|
refused.add(next.id);
|
|
227
|
-
pending.push(
|
|
290
|
+
pending.push(withReason(next, { why: `needs --allow ${[...new Set((next.effects ?? []).map((e) => e.kind).filter((k) => k !== 'workspace-files'))].join(' --allow ')}` }));
|
|
228
291
|
// the actions queued behind it stay listed as they are; nothing else can run this round
|
|
229
292
|
continue;
|
|
230
293
|
}
|
|
231
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; }
|
|
232
309
|
try {
|
|
233
310
|
const r = (await unit.apply(ctx, next, inputs)) ?? { ok: false, message: 'apply returned nothing' };
|
|
234
311
|
if (r.ok) { applied.push({ id: next.id, changed: r.changed ?? [], message: r.message }); ctx.env = envFor(); }
|
|
@@ -238,20 +315,28 @@ export async function runUnit(ws, unit, { inputs = {}, allow = new Set(), tty =
|
|
|
238
315
|
// the final word on what is still open comes from one more plan, so a declined action and the ones
|
|
239
316
|
// behind it read with their own states, never as "after the step before it"
|
|
240
317
|
try {
|
|
318
|
+
const expect = snapshot();
|
|
241
319
|
const last = (await unit.plan(ctx, inputs)) ?? {};
|
|
242
320
|
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
|
|
245
|
-
if (a.kind === 'verify' && !verify) return
|
|
246
|
-
if (a.runBy === 'owner' || (a.effects ?? []).some((e) => e.kind === 'account')) return
|
|
247
|
-
return
|
|
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 ')}` });
|
|
248
326
|
});
|
|
249
327
|
} catch { /* the loop's own view stands */ }
|
|
250
328
|
return { checks: safeInspect(unit, ctx), applied, pending, failed, needs };
|
|
251
329
|
}
|
|
252
330
|
|
|
253
|
-
|
|
254
|
-
|
|
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) }]; }
|
|
255
340
|
}
|
|
256
341
|
|
|
257
342
|
/** The setup section of `dt status`: one entry per unit, then one per package with no unit. */
|
|
@@ -391,8 +476,9 @@ export async function setupCommand(ws, argv, { processEnv = process.env, tty = !
|
|
|
391
476
|
const results = [];
|
|
392
477
|
try {
|
|
393
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
|
|
394
480
|
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) });
|
|
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 });
|
|
396
482
|
const problems = filled.problems.filter((m) => m.unit === u.id);
|
|
397
483
|
const missing = [...filled.missing.filter((m) => m.unit === u.id).map((m) => m.id), ...problems.filter((m) => m.required).map((m) => m.id)];
|
|
398
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, {});
|