@bugb-technologies/bravos 1.18.0 → 1.22.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.
Files changed (45) hide show
  1. package/dist/account.js +19 -2
  2. package/dist/cli.js +133 -15
  3. package/dist/context.js +126 -3
  4. package/dist/cursor.js +4 -2
  5. package/dist/dashboard.js +9 -0
  6. package/dist/device.js +3 -1
  7. package/dist/doctor.js +4 -0
  8. package/dist/guide.js +7 -3
  9. package/dist/help.js +15 -8
  10. package/dist/instruction-blocks.js +257 -0
  11. package/dist/principles.js +279 -0
  12. package/dist/review-server.js +19 -4
  13. package/dist/review-wait.js +11 -0
  14. package/dist/review.js +342 -41
  15. package/dist/rules.js +82 -6
  16. package/dist/uninstall.js +9 -2
  17. package/docs/GUIDE.md +18 -2
  18. package/docs/UPGRADING.md +63 -0
  19. package/hooks/autopilot.mjs +2 -1
  20. package/hooks/cards.mjs +23 -5
  21. package/hooks/coach.mjs +3 -0
  22. package/hooks/invite.mjs +10 -0
  23. package/hooks/lib/audience.mjs +83 -0
  24. package/hooks/lib/briefing.mjs +83 -2
  25. package/hooks/lib/context.mjs +57 -1
  26. package/hooks/lib/display.mjs +11 -0
  27. package/hooks/lib/licence.mjs +2 -1
  28. package/hooks/lib/machine.mjs +77 -0
  29. package/hooks/lib/pre-pr.mjs +82 -1
  30. package/hooks/lib/principles.mjs +513 -0
  31. package/hooks/lib/refresh.mjs +11 -1
  32. package/hooks/lib/replay.mjs +218 -100
  33. package/hooks/pre-pr.mjs +3 -0
  34. package/hooks/session-start.mjs +35 -7
  35. package/package.json +1 -1
  36. package/skills/bravos/SKILL.md +1 -0
  37. package/skills/bravos-context/SKILL.md +4 -4
  38. package/skills/bravos-principles/SKILL.md +52 -0
  39. package/templates/dashboard/dashboard.html +75 -1
  40. package/templates/omp/bravos.js +10 -1
  41. package/templates/opencode/bravos.js +11 -2
  42. package/templates/review/review.html +140 -11
  43. package/templates/workflows/bravos-nightly-claude.yml +1 -1
  44. package/templates/workflows/bravos-nightly-codex.yml +1 -1
  45. package/templates/workflows/bravos-pr-gate.yml +1 -1
@@ -0,0 +1,279 @@
1
+ // @comment -- "bravos principles, the CLI side: writes .guardlink/principles.md from the confirmed adoptions, adds and clears exceptions, copies a principles set from another repository, checks it, and verifies where each candidate on the review page came from. The format, fingerprints and the check itself are in hooks/lib/principles.mjs, shared with the hooks and CI."
2
+ import { execFileSync } from 'node:child_process';
3
+ import { randomBytes } from 'node:crypto';
4
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
6
+ import { pathToFileURL } from 'node:url';
7
+ import { hooksDir } from './paths.js';
8
+ import { parseIntentRules } from './rules.js';
9
+ import { BravosError } from './types.js';
10
+ let cached = null;
11
+ export const principlesLib = () => (cached ??= import(pathToFileURL(join(hooksDir(), 'lib', 'principles.mjs')).href));
12
+ const today = (now) => now.toISOString().slice(0, 10);
13
+ // @comment -- "Writes one file inside the repository: every folder on the way must be a real folder (no link), and the file is replaced atomically through a temporary name, so a planted link cannot redirect the write."
14
+ function writeInRepo(root, rel, data) {
15
+ let dir = realpathSync(root);
16
+ for (const part of dirname(rel).split(/[\\/]/).filter((p) => p && p !== '.')) {
17
+ dir = join(dir, part);
18
+ try {
19
+ mkdirSync(dir);
20
+ }
21
+ catch (e) {
22
+ if (e.code !== 'EEXIST')
23
+ throw e;
24
+ }
25
+ if (!lstatSync(dir).isDirectory() || realpathSync(dir) !== dir)
26
+ throw new BravosError(`refusing to write through a link in ${rel}`);
27
+ }
28
+ const temp = join(dir, `.bravos-${randomBytes(12).toString('hex')}.tmp`);
29
+ try {
30
+ writeFileSync(temp, data, { flag: 'wx', mode: 0o644 });
31
+ renameSync(temp, join(dir, basename(rel)));
32
+ }
33
+ finally {
34
+ rmSync(temp, { force: true });
35
+ }
36
+ }
37
+ function readSource(root, L) {
38
+ const text = L.treeReader(root).read(L.SOURCE_FILE);
39
+ if (text === null)
40
+ return null;
41
+ try {
42
+ const j = JSON.parse(text);
43
+ return j && j.schema === L.SOURCE_SCHEMA && typeof j.repo === 'string' && typeof j.from === 'string' && typeof j.commit === 'string' && typeof j.hash === 'string' ? j : null;
44
+ }
45
+ catch {
46
+ return null;
47
+ }
48
+ }
49
+ // @comment -- "Rewrites .guardlink/principles.md from the confirmed adoptions and the approved exceptions. A principle that was adopted before and no longer is moves to Retired with the reason, so nothing disappears without a word. Returns what changed, as lines."
50
+ // @mitigates #principles against #forged-principle using #adoption-fingerprint -- "principles.md is generated only from adoptions the review server recorded with their fingerprints; nothing an agent writes in chat or in the draft reaches the Adopted section"
51
+ export async function writePrinciples(root, _now = new Date()) {
52
+ const L = await principlesLib();
53
+ const reader = L.treeReader(root);
54
+ const { files } = L.readAdoptionFiles(reader);
55
+ const states = L.principleStates(files);
56
+ const adopted = states.filter((s) => s.state === 'adopted');
57
+ const { exceptions } = L.readExceptions(reader);
58
+ const before = L.parsePrinciples(reader.read(L.PRINCIPLES_FILE) ?? '');
59
+ const reason = (s) => {
60
+ if (!s)
61
+ return 'its adoption was removed';
62
+ if (s.state === 'declined' || s.state === 'disputed')
63
+ return `declined by ${s.decliners.map((d) => `${d.by} (${d.date})`).join(', ')}`;
64
+ if (s.state === 'disagreed')
65
+ return 'people adopted different wordings; settle on one in bravos review principles';
66
+ return 'its adoption no longer matches its fingerprint';
67
+ };
68
+ const retired = new Map(before.retired.map((r) => [r.id, r]));
69
+ for (const p of before.adopted)
70
+ if (!adopted.some((s) => s.id === p.id))
71
+ retired.set(p.id, { id: p.id, statement: p.statement, why: reason(states.find((s) => s.id === p.id)) });
72
+ for (const s of adopted)
73
+ retired.delete(s.id);
74
+ const source = readSource(root, L);
75
+ const text = L.renderPrinciples({ adopted, exceptions, retired: [...retired.values()].sort((a, b) => Number(a.id.slice(4)) - Number(b.id.slice(4))), source });
76
+ const old = reader.read(L.PRINCIPLES_FILE);
77
+ if (old === text)
78
+ return [`${L.PRINCIPLES_FILE}: unchanged (${adopted.length} adopted)`];
79
+ if (!adopted.length && !exceptions.length && !retired.size && old === null)
80
+ return ['principles: nothing adopted yet, so no principles.md was written'];
81
+ writeInRepo(root, L.PRINCIPLES_FILE, text);
82
+ const lines = [`${L.PRINCIPLES_FILE}: ${adopted.length} adopted (${adopted.filter((s) => s.principle?.kind === 'enforced').length} enforced)${exceptions.length ? `, ${exceptions.length} exception${exceptions.length === 1 ? '' : 's'}` : ''}${retired.size ? `, ${retired.size} retired` : ''}`];
83
+ for (const s of states.filter((x) => x.state === 'disagreed' || x.state === 'disputed'))
84
+ lines.push(` ${s.id} is not adopted: ${reason(s)}`);
85
+ lines.push(`Commit it with the adoptions: git add ${L.PRINCIPLES_FILE} ${L.ANSWERS_DIR}/`);
86
+ return lines;
87
+ }
88
+ /** bravos principles check on the working tree. */
89
+ export async function checkPrinciplesAt(root, now = new Date()) {
90
+ const L = await principlesLib();
91
+ const result = L.checkPrinciples(L.treeReader(root), now);
92
+ const lines = L.formatCheck(result);
93
+ const drift = await sourceDrift(root);
94
+ if (drift)
95
+ lines.push(` · ${drift}`);
96
+ return { result, lines };
97
+ }
98
+ // @comment -- "Records an exception a person approved: the principle must be adopted, the area a repository glob, the reason and the approver's name given, and the end day after today and within a year. The CLI calls this only from an interactive terminal after the approver typed their name and the principle id; it never extends an exception that exists (a new one is a new decision)."
99
+ // @mitigates #principles against #forged-principle using #person-only-exception -- "An exception records the approver's typed name, the reason and an end date at most a year away, carries its own fingerprint, and is checked for expiry by every principles check, so it cannot be added quietly or run forever"
100
+ export async function addException(root, input, now = new Date()) {
101
+ const L = await principlesLib();
102
+ const reader = L.treeReader(root);
103
+ const adopted = L.principleStates(L.readAdoptionFiles(reader).files).filter((s) => s.state === 'adopted');
104
+ if (!L.ID.test(input.principle))
105
+ throw new BravosError(`'${input.principle}' is not a principle id: they look like SDP-1`);
106
+ if (!adopted.some((s) => s.id === input.principle))
107
+ throw new BravosError(`${input.principle} is not adopted here, so it has no exceptions to make`);
108
+ if (!L.validGlob(input.where))
109
+ throw new BravosError('--where takes a repository path or glob such as src/legacy/** (no leading slash, no ..)');
110
+ const reason = L.oneLine(input.reason, 400);
111
+ const by = L.oneLine(input.by, 80);
112
+ if (!reason)
113
+ throw new BravosError('an exception needs --reason: why this code may break the principle for now');
114
+ if (!by)
115
+ throw new BravosError('an exception needs the name of the person approving it');
116
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(input.until) || Number.isNaN(Date.parse(`${input.until}T00:00:00Z`)))
117
+ throw new BravosError('--until takes the last day the exception holds, as YYYY-MM-DD');
118
+ const approved = today(now);
119
+ const days = (Date.parse(`${input.until}T00:00:00Z`) - Date.parse(`${approved}T00:00:00Z`)) / 86400000;
120
+ if (days < 1)
121
+ throw new BravosError('--until must be after today');
122
+ if (days > L.MAX_EXCEPTION_DAYS)
123
+ throw new BravosError(`an exception ends within ${L.MAX_EXCEPTION_DAYS} days; approve a new one when it ends`);
124
+ const { exceptions, problems } = L.readExceptions(reader);
125
+ if (problems.length)
126
+ throw new BravosError(`${L.EXCEPTIONS_FILE} needs fixing first: ${problems.join('; ')}`);
127
+ const e = { principle: input.principle, where: input.where, reason, by, approved, until: input.until, hash: '' };
128
+ e.hash = L.exceptionFingerprint(e);
129
+ if (exceptions.some((x) => x.principle === e.principle && x.where === e.where && L.live(x, now)))
130
+ throw new BravosError(`${e.principle} already has a live exception for ${e.where}; it is not extended, it ends on its day`);
131
+ writeInRepo(root, L.EXCEPTIONS_FILE, JSON.stringify({ schema: L.EXCEPTIONS_SCHEMA, exceptions: [...exceptions, e] }, null, 2) + '\n');
132
+ return [`Exception recorded: ${e.principle} in ${e.where} until ${e.until}, approved by ${e.by}.`, ...(await writePrinciples(root, now))];
133
+ }
134
+ // @comment -- "Removes exceptions whose end day has passed. Removing one only tightens the rules, so it needs no approver; the gate already treats an expired exception as absent."
135
+ export async function clearExpired(root, now = new Date()) {
136
+ const L = await principlesLib();
137
+ const { exceptions, problems } = L.readExceptions(L.treeReader(root));
138
+ if (problems.some((p) => !/ended on|runs \d+ days/.test(p)) && problems.length)
139
+ throw new BravosError(`${L.EXCEPTIONS_FILE} needs fixing first: ${problems.join('; ')}`);
140
+ const keep = exceptions.filter((e) => L.live(e, now));
141
+ const gone = exceptions.length - keep.length;
142
+ if (!gone)
143
+ return ['principles: no exception has ended'];
144
+ writeInRepo(root, L.EXCEPTIONS_FILE, JSON.stringify({ schema: L.EXCEPTIONS_SCHEMA, exceptions: keep }, null, 2) + '\n');
145
+ return [`Removed ${gone} ended exception${gone === 1 ? '' : 's'}.`, ...(await writePrinciples(root, now))];
146
+ }
147
+ const gitOut = (cwd, args, env) => {
148
+ try {
149
+ return execFileSync('git', args, { cwd, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 10000 }).trim();
150
+ }
151
+ catch {
152
+ return null;
153
+ }
154
+ };
155
+ /** owner/repo from a GitHub origin, else the folder's name: never a local path or a URL with credentials. */
156
+ function repoLabel(dir, env) {
157
+ const origin = gitOut(dir, ['config', '--get', 'remote.origin.url'], env) ?? '';
158
+ const m = /github\.com[:/]([A-Za-z0-9-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/.exec(origin);
159
+ return m ? `${m[1]}/${m[2]}` : basename(dir);
160
+ }
161
+ // @comment -- "bravos principles copy --from <repository>: the same principles in another repository. The source must pass its own check; its adoption records are copied (they are the evidence behind each line), this repository's exceptions are kept, and a record names the source repository, its commit and its principles.md hash, so bravos principles check here says when the source has moved on. Refuses to overwrite adoptions made here unless --replace."
162
+ export async function copyPrinciples(root, from, opts, env, now = new Date()) {
163
+ const L = await principlesLib();
164
+ const src = resolve(root, from);
165
+ if (!existsSync(join(src, L.PRINCIPLES_FILE)))
166
+ throw new BravosError(`${from} has no ${L.PRINCIPLES_FILE}`);
167
+ if (realpathSync(src) === realpathSync(root))
168
+ throw new BravosError('--from names this repository');
169
+ const sourceCheck = L.checkPrinciples(L.treeReader(src), now);
170
+ if (!sourceCheck.ok)
171
+ throw new BravosError(`${from}'s principles do not pass their own check, so they are not copied:\n${L.formatCheck(sourceCheck).slice(1).join('\n')}`);
172
+ const here = L.treeReader(root);
173
+ const localAnswers = here.list(L.ANSWERS_DIR).filter((n) => n.endsWith('.json'));
174
+ if (localAnswers.length && !readSource(root, L) && !opts.replace)
175
+ throw new BravosError(`this repository already has its own adoptions in ${L.ANSWERS_DIR}/ (${localAnswers.join(', ')}); copying would replace them. Run again with --replace if the team means that.`);
176
+ const srcReader = L.treeReader(src);
177
+ const names = srcReader.list(L.ANSWERS_DIR).filter((n) => n.endsWith('.json'));
178
+ for (const n of localAnswers)
179
+ rmSync(join(root, L.ANSWERS_DIR, n), { force: true });
180
+ for (const n of names) {
181
+ const text = srcReader.read(`${L.ANSWERS_DIR}/${n}`);
182
+ if (text !== null)
183
+ writeInRepo(root, `${L.ANSWERS_DIR}/${n}`, text);
184
+ }
185
+ const rel = relative(realpathSync(root), realpathSync(src)).split(sep).join('/');
186
+ const record = {
187
+ schema: L.SOURCE_SCHEMA,
188
+ repo: repoLabel(src, env),
189
+ from: isAbsolute(rel) ? basename(src) : rel,
190
+ commit: gitOut(src, ['rev-parse', 'HEAD'], env) ?? 'unknown',
191
+ hash: L.sha(srcReader.read(L.PRINCIPLES_FILE) ?? ''),
192
+ copiedAt: now.toISOString(),
193
+ };
194
+ writeInRepo(root, L.SOURCE_FILE, JSON.stringify(record, null, 2) + '\n');
195
+ return [`Copied ${sourceCheck.adopted.length} principle${sourceCheck.adopted.length === 1 ? '' : 's'} from ${record.repo} at ${record.commit.slice(0, 9)}.`, ...(await writePrinciples(root, now)), `Commit them: git add ${L.PRINCIPLES_FILE} ${L.ANSWERS_DIR}/ ${L.SOURCE_FILE}`];
196
+ }
197
+ // @comment -- "For a copied principles set: whether the source repository, where it was copied from and when it is still at that relative path on this machine, now holds a different principles.md. Null when this set is not a copy; a sentence otherwise."
198
+ export async function sourceDrift(root) {
199
+ const L = await principlesLib();
200
+ const s = readSource(root, L);
201
+ if (!s)
202
+ return null;
203
+ const src = resolve(root, s.from);
204
+ const text = existsSync(join(src, L.PRINCIPLES_FILE)) ? L.treeReader(src).read(L.PRINCIPLES_FILE) : null;
205
+ if (text === null)
206
+ return `copied from ${s.repo} at ${s.commit.slice(0, 9)}; that repository is not at ${s.from} on this machine, so whether it changed is not known`;
207
+ if (L.sha(text) === s.hash)
208
+ return `copied from ${s.repo} at ${s.commit.slice(0, 9)}, and still the same as its source`;
209
+ return `copied from ${s.repo} at ${s.commit.slice(0, 9)}, but its source has changed since: bravos principles copy --from ${s.from}`;
210
+ }
211
+ // @comment -- "Whether a candidate on the review page may be proposed, for the two origins that need files beyond the draft: a confirmed INV rule in an intent.md (this repository's, or another one's named as <relative path>:INV-n), or a starter-list entry quoted word for word. Returns the problem as a sentence, or null. A document citation is checked where the review is prepared, against the stored document's text."
212
+ // @mitigates #principles against #principle-origin-invented using #verified-principle-origin -- "A principle candidate is refused unless its intent rule exists and a named person confirmed it, or it is a starter entry unchanged; the agent cannot present its own assumption as something the team already said"
213
+ export async function principleOriginProblem(root, q) {
214
+ const p = q.principle;
215
+ if (!p)
216
+ return `${q.id}: a principle candidate needs its principle details`;
217
+ const L = await principlesLib();
218
+ if (p.origin === 'starter') {
219
+ const s = L.STARTER.find((x) => x.id === p.starter);
220
+ if (!s)
221
+ return `${q.id}: '${p.starter}' is not on bravos's starter list (${L.STARTER.map((x) => x.id).join(', ')})`;
222
+ if (L.oneLine(q.text) !== s.statement)
223
+ return `${q.id}: a starter principle is offered in the starter list's own words ("${s.statement}"); people change the wording on the page`;
224
+ return null;
225
+ }
226
+ if (p.origin === 'intent') {
227
+ for (const ref of p.from ?? []) {
228
+ const m = /^(?:(.+):)?(INV-\d+)$/.exec(ref);
229
+ if (!m)
230
+ return `${q.id}: '${ref}' is not an intent rule reference (INV-3, or ../other-repo:INV-3)`;
231
+ const dir = m[1] ? resolve(root, m[1]) : root;
232
+ if (m[1] && isAbsolute(m[1]))
233
+ return `${q.id}: '${ref}' names another repository by an absolute path; use a path relative to this one`;
234
+ let text;
235
+ try {
236
+ text = readFileSync(join(dir, '.guardlink', 'intent.md'), 'utf8');
237
+ }
238
+ catch {
239
+ return `${q.id}: ${m[1] ? `${m[1]} has` : 'this repository has'} no .guardlink/intent.md to take ${m[2]} from`;
240
+ }
241
+ const rule = parseIntentRules(text).find((r) => r.id === m[2]);
242
+ if (!rule)
243
+ return `${q.id}: ${m[2]} is not in ${m[1] ? `${m[1]}'s` : 'this repository\'s'} intent.md`;
244
+ if (rule.decided !== 'confirmed' || !rule.decidedBy)
245
+ return `${q.id}: ${ref} is still a draft nobody confirmed, so it cannot become a principle yet`;
246
+ }
247
+ return (p.from ?? []).length ? null : `${q.id}: an intent principle names the INV rules it comes from`;
248
+ }
249
+ return null;
250
+ }
251
+ // @comment -- "At Confirm, for kind principles: records on each adopting answer the exact principle adopted (the wording the person kept or wrote, the kind, scope, why and paths from the draft) and its fingerprint; a decline or any other answer carries none. Anything a page sent under `adopted` is replaced, so the record is the server's, not the browser's."
252
+ export async function withAdoptions(draft, a) {
253
+ const L = await principlesLib();
254
+ const answers = Object.create(null);
255
+ for (const [id, ans] of Object.entries(a.answers)) {
256
+ const { adopted: _drop, ...rest } = ans;
257
+ const q = draft.questions.find((x) => x.id === id);
258
+ if (!q?.principle || rest.verdict === 'no' || !['chosen', 'agree', 'edited', 'accepted'].includes(rest.verdict)) {
259
+ answers[id] = rest;
260
+ continue;
261
+ }
262
+ const own = typeof rest.value === 'string' && rest.value !== 'agree' && rest.value !== 'no' ? rest.value : undefined;
263
+ const statement = L.oneLine(own ?? q.text, 600);
264
+ if (!statement)
265
+ throw new BravosError(`${id}: the principle's wording is empty`);
266
+ const fields = L.principleFields({ id, kind: q.principle.kind, statement, scope: q.principle.scope, why: q.principle.why, paths: q.principle.paths });
267
+ answers[id] = { ...rest, adopted: { ...fields, hash: L.fingerprint(fields) } };
268
+ }
269
+ return { ...a, answers };
270
+ }
271
+ /** Lists the principles answers folder, for doctor and the dashboard: how many people have answered. */
272
+ export function adoptionFileCount(root) {
273
+ try {
274
+ return readdirSync(join(root, '.guardlink', 'principles-answers')).filter((n) => n.endsWith('.json')).length;
275
+ }
276
+ catch {
277
+ return 0;
278
+ }
279
+ }
@@ -1,7 +1,22 @@
1
- // @comment -- "Detached child that serves one review: argv root, kind, token, port. Started by bravos review so the command can return at once in any harness; it exits on Done or after 30 minutes idle."
1
+ // @comment -- "Detached child that serves one review: argv root, kind, token, port. Started by bravos review so the command can return at once in any harness. It re-reads the draft on each load (one page stays open across a rewritten draft), stores documents added on the page through the same checks as bravos context add, rewrites principles.md from the adoptions after each Confirm of the principles review, and exits on Done or after 30 minutes idle."
2
+ import { addPageDocument } from './context.js';
2
3
  import { prepareReview, readDraft, renderReview, startReviewServer } from './review.js';
3
4
  const [root, kind, token, port] = process.argv.slice(2);
4
- const review = await prepareReview(root, readDraft(root, kind));
5
- const page = await renderReview(review, { kind: 'serve', token });
6
- const { server } = await startReviewServer(root, review.draft, page, token, Number(port));
5
+ const load = async () => {
6
+ const review = await prepareReview(root, readDraft(root, kind));
7
+ return { draft: review.draft, page: await renderReview(review, { kind: 'serve', token }) };
8
+ };
9
+ const first = await load();
10
+ const { server } = await startReviewServer(root, first.draft, first.page, token, Number(port), {
11
+ reload: load,
12
+ addDocument: async (doc) => {
13
+ try {
14
+ return { ok: true, lines: await addPageDocument(root, doc, process.env) };
15
+ }
16
+ catch (e) {
17
+ return { ok: false, reason: e instanceof Error ? e.message : String(e) };
18
+ }
19
+ },
20
+ afterConfirm: async (k) => (k === 'principles' ? (await import('./principles.js')).writePrinciples(root) : []),
21
+ });
7
22
  server.on('close', () => process.exit(0));
@@ -74,3 +74,14 @@ export async function waitGone(pid, ms, everyMs = 300) {
74
74
  await new Promise((r) => setTimeout(r, Math.min(everyMs, Math.max(1, until - Date.now()))));
75
75
  }
76
76
  }
77
+ /** Resolves true as soon as `done()` holds, false when `ms` passed first. Reads files and the process table only, so the page's idle clock is never reset by the waiting. */
78
+ export async function waitUntil(done, ms, everyMs = 300) {
79
+ const until = Date.now() + ms;
80
+ for (;;) {
81
+ if (done())
82
+ return true;
83
+ if (Date.now() >= until)
84
+ return false;
85
+ await new Promise((r) => setTimeout(r, Math.min(everyMs, Math.max(1, until - Date.now()))));
86
+ }
87
+ }