@bluenyang/reins 0.3.3 → 0.3.4-rc.2

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.
@@ -9,6 +9,7 @@ import { repoRoot } from '../lib/git.js';
9
9
  import { BACK, EXIT } from '../lib/prompter.js';
10
10
  import { harnessVersion, packageHarness, packageVersion } from '../lib/upstream.js';
11
11
  import { RUNS_REINS, runInstall } from './install.js';
12
+ import { FORCE_WITH_LEASE_QUESTION, recordedForceWithLease, } from '../lib/local-settings.js';
12
13
  /** Numeric dotted-version compare; pre-release suffixes are ignored. */
13
14
  /** A 0.3 harness from before the AGENTS.md guide (0.3.0, 0.3.1 and their rcs); 0.x installs are reconciled instead. */
14
15
  export function beforeGuide(version) {
@@ -25,18 +26,29 @@ export function newer(a, b) {
25
26
  }
26
27
  return false;
27
28
  }
28
- /** Changelog entries for versions in (from, to]. */
29
- export function changesBetween(changelog, from, to) {
29
+ /**
30
+ * Changelog entries for versions in (from, to], grouped under their version in the changelog's order
31
+ * (newest first); a version without entries is left out (024 S-1).
32
+ */
33
+ export function changesByVersion(changelog, from, to) {
30
34
  const out = [];
31
- let take = false;
35
+ let cur = null;
32
36
  for (const line of changelog.split(/\r?\n/)) {
33
37
  const h = /^## (\S+)/.exec(line);
34
- if (h)
35
- take = newer(h[1] ?? '0', from) && !newer(h[1] ?? '0', to);
36
- else if (take && line.startsWith('- '))
37
- out.push(line.slice(2));
38
+ if (h) {
39
+ const v = h[1] ?? '0';
40
+ cur = newer(v, from) && !newer(v, to) ? { version: v, items: [] } : null;
41
+ if (cur)
42
+ out.push(cur);
43
+ }
44
+ else if (cur && line.startsWith('- '))
45
+ cur.items.push(line.slice(2));
38
46
  }
39
- return out;
47
+ return out.filter((g) => g.items.length > 0);
48
+ }
49
+ /** Changelog entries for versions in (from, to], as one flat list. */
50
+ export function changesBetween(changelog, from, to) {
51
+ return changesByVersion(changelog, from, to).flatMap((g) => g.items);
40
52
  }
41
53
  /** 0.x working files and folders under `.loctx/` that 0.3 no longer makes (design §7). */
42
54
  const LEGACY_LOCTX = [
@@ -161,8 +173,20 @@ export async function runUpdate(o) {
161
173
  plan.cleanup.length === 0 &&
162
174
  plan.handEdited.length === 0 &&
163
175
  (!a || a.created.length + a.changed.length + a.removed.length === 0);
164
- if (nothing)
176
+ // the force-with-lease question is asked once per machine, even when nothing else changes (024 S-26a)
177
+ const unanswered = !o.forceWithLease && !recordedForceWithLease(repoRoot(o.cwd ?? process.cwd()));
178
+ if (nothing && !unanswered)
165
179
  return plan;
180
+ if (nothing) {
181
+ const deny = await o.prompter.confirm({ message: FORCE_WITH_LEASE_QUESTION, initial: true });
182
+ if (deny === EXIT)
183
+ return { ...plan, declined: true };
184
+ return runUpdate({
185
+ ...o,
186
+ prompter: undefined,
187
+ forceWithLease: deny === false ? 'allow' : 'deny',
188
+ });
189
+ }
166
190
  o.show?.(plan);
167
191
  const ok = await o.prompter.confirm({ message: 'Apply this update?', initial: true });
168
192
  if (ok === BACK || ok === EXIT || !ok)
@@ -177,7 +201,15 @@ export async function runUpdate(o) {
177
201
  return { ...plan, declined: true };
178
202
  force = over === true;
179
203
  }
180
- return runUpdate({ ...o, prompter: undefined, yes: true, force });
204
+ // asked once per machine, before the run that writes (024 S-26a)
205
+ let forceWithLease = o.forceWithLease ?? recordedForceWithLease(repoRoot(o.cwd ?? process.cwd()));
206
+ if (!forceWithLease) {
207
+ const deny = await o.prompter.confirm({ message: FORCE_WITH_LEASE_QUESTION, initial: true });
208
+ if (deny === EXIT)
209
+ return { ...plan, declined: true };
210
+ forceWithLease = deny === false ? 'allow' : 'deny';
211
+ }
212
+ return runUpdate({ ...o, prompter: undefined, yes: true, force, forceWithLease });
181
213
  }
182
214
  return updateNow(o);
183
215
  }
@@ -186,6 +218,7 @@ async function updateNow(o) {
186
218
  const res = {
187
219
  root,
188
220
  changes: [],
221
+ changesByVersion: [],
189
222
  overrides: [],
190
223
  removed: [],
191
224
  cleanup: [],
@@ -204,8 +237,10 @@ async function updateNow(o) {
204
237
  res.cliFrom = pin.cli ? String(pin.cli) : 'none';
205
238
  res.cliTo = packageVersion();
206
239
  const cl = join(up, 'CHANGELOG.md');
207
- if (existsSync(cl) && newer(res.to, res.from))
208
- res.changes = changesBetween(readFileSync(cl, 'utf8'), res.from, res.to);
240
+ if (existsSync(cl) && newer(res.to, res.from)) {
241
+ res.changesByVersion = changesByVersion(readFileSync(cl, 'utf8'), res.from, res.to);
242
+ res.changes = res.changesByVersion.flatMap((g) => g.items);
243
+ }
209
244
  const agents = join(root, 'AGENTS.md');
210
245
  if (existsSync(agents))
211
246
  res.overrides = [...overrides(readFileSync(agents, 'utf8'))];
@@ -252,6 +287,7 @@ async function updateNow(o) {
252
287
  }
253
288
  }
254
289
  res.install = await runInstall({
290
+ forceWithLease: o.forceWithLease,
255
291
  mode: pin.mode ?? 'auto',
256
292
  asker: defaultsAsker,
257
293
  cwd: root,
@@ -279,15 +315,21 @@ export function updateNotes(r) {
279
315
  return (r.install?.notes ?? []).filter((n) => n.startsWith('.husky/') ||
280
316
  n.startsWith('hook proposal') ||
281
317
  n.startsWith('no hook tool found') ||
282
- (n.startsWith('left alone ') && !n.includes(': edited by hand')));
318
+ (n.startsWith('left alone ') && !n.includes(': edited by hand')) ||
319
+ // the personal force-with-lease line and its migration from the team file (024 S-26a, review 6)
320
+ n.startsWith('force push with lease') ||
321
+ n.startsWith('.claude/settings.local.json'));
283
322
  }
284
323
  /** The report `reins update` prints; with `dry` it is the plan shown before the confirmation. */
285
324
  export function formatUpdate(r, dry) {
286
325
  const out = [];
287
326
  const a = r.install?.applied;
288
327
  out.push(`reins update — cli ${r.cliFrom === 'none' ? 'none' : `v${r.cliFrom}`} → v${r.cliTo}, harness v${r.from} → v${r.to}${dry ? ' (dry run)' : ''}`);
289
- for (const c of r.changes)
290
- out.push(` · ${c}`);
328
+ for (const g of r.changesByVersion) {
329
+ out.push(` ${g.version}`);
330
+ for (const c of g.items)
331
+ out.push(` · ${c}`);
332
+ }
291
333
  if (r.converted) {
292
334
  out.push(`bindings: ${dry ? 'would convert' : 'converted'} version 1 → 2`);
293
335
  for (const n of r.converted)
@@ -58,7 +58,7 @@ function fallbackHow(doc, r) {
58
58
  export function renderDelegation(doc, local) {
59
59
  const lines = ['## Delegation', ''];
60
60
  if (!local)
61
- lines.push(`If \`${LOCAL_DELEGATION}\` exists, follow it instead of this section (your personal settings; \`reins config --local\` writes it).`, '');
61
+ lines.push(`If \`${LOCAL_DELEGATION}\` exists, follow it instead of this section (your personal settings; \`reins config --local\` writes it): open it before anything else and use its table.`, '');
62
62
  if (doc.mode !== 'multi') {
63
63
  lines.push(`Mode: **single** — you are the PM — the model in this conversation — and do every role yourself, stage by stage. You may use subagents of your own model for read-heavy work (research, large log summaries, review, audit) and, when urgent, for parallel work on independent units; keep connected work (plan and implementation of one feature) in one run. Switching to multi is the user's choice.`);
64
64
  }
@@ -0,0 +1,74 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { parse } from 'yaml';
4
+ const INSTALL = /^(?:(?:pnpm|yarn|bun|npm) (?:install|i|ci)\b|corepack enable\b|go mod download\b)/;
5
+ const onPullRequest = (on) => on === 'pull_request' ||
6
+ (Array.isArray(on) && on.includes('pull_request')) ||
7
+ (!!on && typeof on === 'object' && !Array.isArray(on) && 'pull_request' in on);
8
+ /** `cmd` run in `dir`, from the root, for the tools that take a directory option; null otherwise. */
9
+ export function fromDir(cmd, dir) {
10
+ if (!dir || dir === '.')
11
+ return cmd;
12
+ const [tool, ...rest] = cmd.split(' ');
13
+ const r = rest.join(' ');
14
+ switch (tool) {
15
+ case 'pnpm':
16
+ return `pnpm --dir ${dir} ${r}`;
17
+ case 'yarn':
18
+ return `yarn --cwd ${dir} ${r}`;
19
+ case 'npm':
20
+ return `npm --prefix ${dir} ${r}`;
21
+ case 'go':
22
+ return `go -C ${dir} ${r}`;
23
+ case 'make':
24
+ return `make -C ${dir} ${r}`;
25
+ default:
26
+ return null;
27
+ }
28
+ }
29
+ /**
30
+ * The one-line `run:` commands of the workflows that run on `pull_request` (024 S-8): no `${{`, one
31
+ * command (`compound` false), not an install step and not `skip(cmd)`; a multi-line `run: |` is unclear
32
+ * and left out, and so is a `working-directory` step whose tool takes no directory option.
33
+ */
34
+ export function ciRuns(root, compound, skip) {
35
+ const dir = join(root, '.github/workflows');
36
+ if (!existsSync(dir))
37
+ return [];
38
+ const out = [];
39
+ for (const f of readdirSync(dir).toSorted()) {
40
+ if (!/\.ya?ml$/.test(f))
41
+ continue;
42
+ let doc;
43
+ try {
44
+ doc = parse(readFileSync(join(dir, f), 'utf8'));
45
+ }
46
+ catch {
47
+ continue;
48
+ }
49
+ if (!doc || !onPullRequest(doc.on))
50
+ continue;
51
+ for (const job of Object.values(doc.jobs ?? {}))
52
+ for (const step of job?.steps ?? []) {
53
+ const s = step;
54
+ if (typeof s?.run !== 'string')
55
+ continue;
56
+ const raw = s.run.trim().replace(/\s+/g, ' ');
57
+ // a block scalar (`run: |`) keeps its newline even with one line in it
58
+ if (s.run.includes('\n') || raw.includes('${{') || compound(raw))
59
+ continue;
60
+ if (INSTALL.test(raw) || skip(raw))
61
+ continue;
62
+ const wd = typeof s['working-directory'] === 'string'
63
+ ? s['working-directory'].replace(/^\.\//, '').replace(/\/$/, '')
64
+ : '';
65
+ // a directory with a space, an expression or other characters would not read back as one word
66
+ if (wd && !/^[\w@.+/-]+$/.test(wd))
67
+ continue;
68
+ const cmd = fromDir(raw, wd);
69
+ if (cmd)
70
+ out.push({ file: `.github/workflows/${f}`, cmd, dir: wd === '.' ? '' : wd, raw });
71
+ }
72
+ }
73
+ return out;
74
+ }
@@ -0,0 +1,266 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { parse } from 'yaml';
4
+ const LOCKS = ['pnpm-lock.yaml', 'yarn.lock', 'package-lock.json', 'bun.lockb', 'bun.lock'];
5
+ const SKIP = new Set(['node_modules', '.git', 'dist', 'build', 'vendor', '.loctx', '.agents']);
6
+ const readJson = (p) => {
7
+ try {
8
+ return JSON.parse(readFileSync(p, 'utf8'));
9
+ }
10
+ catch {
11
+ return null;
12
+ }
13
+ };
14
+ /** A file that makes `dir` a project of its own, outside the root workspace (croffle `apps/server/web`). */
15
+ export function ownProjectFile(root, dir) {
16
+ if (!dir)
17
+ return null;
18
+ for (const f of [...LOCKS, 'pnpm-workspace.yaml'])
19
+ if (existsSync(join(root, dir, f)))
20
+ return `${dir}/${f}`;
21
+ return null;
22
+ }
23
+ /** The workspace globs of the root: `pnpm-workspace.yaml` `packages`, else package.json `workspaces`. */
24
+ export function workspaceGlobs(root) {
25
+ const pnpm = join(root, 'pnpm-workspace.yaml');
26
+ if (existsSync(pnpm)) {
27
+ try {
28
+ const doc = parse(readFileSync(pnpm, 'utf8'));
29
+ if (Array.isArray(doc?.packages))
30
+ return { globs: doc.packages.map(String), file: 'pnpm-workspace.yaml' };
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ const pkg = readJson(join(root, 'package.json'));
37
+ const ws = pkg?.['workspaces'];
38
+ const list = Array.isArray(ws)
39
+ ? ws
40
+ : ws && typeof ws === 'object' && Array.isArray(ws.packages)
41
+ ? ws.packages
42
+ : null;
43
+ return list ? { globs: list.map(String), file: 'package.json' } : null;
44
+ }
45
+ /** One path segment of a glob as a regular expression: `*` is any run of characters but `/`. */
46
+ const segment = (s) => new RegExp(`^${s.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '[^/]*')}$`);
47
+ /** Directories (with a package.json) a workspace glob names: literal, `a/*`, `a/*-x`, `a/**`. */
48
+ function expand(root, glob) {
49
+ const parts = glob.replace(/^\.\//, '').replace(/\/$/, '').split('/');
50
+ const out = [];
51
+ const walk = (dir, i, depth) => {
52
+ if (i === parts.length) {
53
+ if (existsSync(join(root, dir, 'package.json')))
54
+ out.push(dir);
55
+ return;
56
+ }
57
+ const p = parts[i];
58
+ if (p === '**') {
59
+ walk(dir, i + 1, depth); // zero directories
60
+ if (depth > 4)
61
+ return;
62
+ for (const e of children(root, dir))
63
+ walk(dir ? `${dir}/${e}` : e, i, depth + 1);
64
+ return;
65
+ }
66
+ if (!p.includes('*')) {
67
+ walk(dir ? `${dir}/${p}` : p, i + 1, depth);
68
+ return;
69
+ }
70
+ const re = segment(p);
71
+ for (const e of children(root, dir))
72
+ if (re.test(e))
73
+ walk(dir ? `${dir}/${e}` : e, i + 1, depth);
74
+ };
75
+ walk('', 0, 0);
76
+ return out;
77
+ }
78
+ function children(root, dir) {
79
+ try {
80
+ return readdirSync(join(root, dir), { withFileTypes: true })
81
+ .filter((e) => e.isDirectory() && !SKIP.has(e.name))
82
+ .map((e) => e.name)
83
+ .toSorted();
84
+ }
85
+ catch {
86
+ return [];
87
+ }
88
+ }
89
+ /**
90
+ * The packages of the root workspace (024 S-7): the globs expanded to directories with a package.json,
91
+ * `!` globs taken out, and a directory with a lock or workspace file of its own left out.
92
+ */
93
+ export function workspacePackages(root) {
94
+ const ws = workspaceGlobs(root);
95
+ if (!ws)
96
+ return [];
97
+ const take = new Set();
98
+ for (const g of ws.globs.filter((x) => !x.startsWith('!')))
99
+ for (const d of expand(root, g))
100
+ take.add(d);
101
+ for (const g of ws.globs.filter((x) => x.startsWith('!')))
102
+ for (const d of expand(root, g.slice(1)))
103
+ take.delete(d);
104
+ return [...take]
105
+ .filter((d) => d !== '' && !ownProjectFile(root, d))
106
+ .toSorted()
107
+ .map((dir) => {
108
+ const name = readJson(join(root, dir, 'package.json'))?.['name'];
109
+ return typeof name === 'string' ? { dir, name } : { dir };
110
+ });
111
+ }
112
+ const nameGlob = (p) => new RegExp(`^${p.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*')}$`);
113
+ /** The packages a pnpm `--filter`/npm `-w` value selects: a name as written, or `./dir`/`dir`. */
114
+ function select(pkgs, v) {
115
+ if (/[*{}[\]^!]|\.\.\./.test(v))
116
+ return null;
117
+ const path = v.replace(/^\.\//, '').replace(/\/$/, '');
118
+ const byName = pkgs.filter((p) => p.name === v);
119
+ if (byName.length)
120
+ return byName;
121
+ const byDir = pkgs.filter((p) => p.dir === path);
122
+ return byDir.length ? byDir : [];
123
+ }
124
+ /** The script after an optional `run`, with nothing after it; null when that is not the shape. */
125
+ function scriptAt(rest) {
126
+ const r = rest[0] === 'run' ? rest.slice(1) : rest;
127
+ return r.length === 1 && /^[\w:.-]+$/.test(r[0]) ? r[0] : null;
128
+ }
129
+ const HARMLESS = new Set(['--parallel', '--stream', '--if-present']);
130
+ /**
131
+ * Whether one command (already split into words) runs a script in workspace packages, in one of the
132
+ * forms of 024 S-7. A form with any other flag is unclear, so nothing is filtered by it.
133
+ */
134
+ export function forwards(words, pkgs) {
135
+ const [tool, ...a] = words;
136
+ if (tool === 'pnpm') {
137
+ let all = false;
138
+ let picked = null;
139
+ const rest = [];
140
+ for (let i = 0; i < a.length; i++) {
141
+ const w = a[i];
142
+ if (w === '-r' || w === '--recursive')
143
+ all = true;
144
+ else if (w === '--filter' || w === '-F' || w.startsWith('--filter=') || /^-F./.test(w)) {
145
+ const v = w.includes('=')
146
+ ? w.slice(w.indexOf('=') + 1)
147
+ : w.length > 2 && w.startsWith('-F')
148
+ ? w.slice(2)
149
+ : a[++i];
150
+ const s = v === undefined ? null : select(pkgs, v);
151
+ if (s === null)
152
+ return { unclear: `pnpm filter ${v ?? ''}` };
153
+ picked = [...(picked ?? []), ...s];
154
+ }
155
+ else if (HARMLESS.has(w))
156
+ continue;
157
+ else if (w.startsWith('-'))
158
+ return all || picked ? { unclear: `pnpm ${w}` } : null;
159
+ else
160
+ rest.push(w);
161
+ }
162
+ if (!all && !picked)
163
+ return null;
164
+ const s = scriptAt(rest);
165
+ if (!s)
166
+ return { unclear: 'pnpm: not one script' };
167
+ // a filter narrows -r: pnpm runs the filtered packages only (review 1)
168
+ return { scripts: [s], pkgs: picked ?? pkgs };
169
+ }
170
+ if (tool === 'npm') {
171
+ let all = false;
172
+ let picked = null;
173
+ const rest = [];
174
+ for (let i = 0; i < a.length; i++) {
175
+ const w = a[i];
176
+ if (w === '--workspaces' || w === '-ws')
177
+ all = true;
178
+ else if (w === '-w' || w === '--workspace' || w.startsWith('--workspace=')) {
179
+ const v = w.includes('=') ? w.slice(w.indexOf('=') + 1) : a[++i];
180
+ const s = v === undefined ? null : select(pkgs, v);
181
+ if (s === null)
182
+ return { unclear: `npm workspace ${v ?? ''}` };
183
+ picked = [...(picked ?? []), ...s];
184
+ }
185
+ else if (HARMLESS.has(w))
186
+ continue;
187
+ else if (w.startsWith('-'))
188
+ return all || picked ? { unclear: `npm ${w}` } : null;
189
+ else
190
+ rest.push(w);
191
+ }
192
+ if (!all && !picked)
193
+ return null;
194
+ if (rest[0] !== 'run' && rest[0] !== 'run-script')
195
+ return { unclear: 'npm: not run' };
196
+ const s = scriptAt(rest.slice(1));
197
+ if (!s)
198
+ return { unclear: 'npm: not one script' };
199
+ return { scripts: [s], pkgs: picked ?? pkgs };
200
+ }
201
+ if (tool === 'yarn') {
202
+ if (a[0] === 'workspaces' && a[1] === 'run') {
203
+ const s = scriptAt(a.slice(2));
204
+ return s ? { scripts: [s], pkgs } : { unclear: 'yarn workspaces run' };
205
+ }
206
+ if (a[0] === 'workspace' && a[1]) {
207
+ const s = scriptAt(a.slice(2));
208
+ const p = select(pkgs, a[1]);
209
+ return s && p ? { scripts: [s], pkgs: p } : { unclear: 'yarn workspace' };
210
+ }
211
+ if (a[0] === 'workspaces' && a[1] === 'foreach') {
212
+ const ok = new Set([
213
+ '-A',
214
+ '--all',
215
+ '-p',
216
+ '--parallel',
217
+ '-v',
218
+ '--verbose',
219
+ '-i',
220
+ '--interlaced',
221
+ '-t',
222
+ '--topological',
223
+ '-R',
224
+ '--recursive',
225
+ ]);
226
+ const rest = a.slice(2);
227
+ const i = rest.indexOf('run');
228
+ if (i < 0 || rest.slice(0, i).some((w) => !ok.has(w)))
229
+ return { unclear: 'yarn workspaces foreach' };
230
+ const s = scriptAt(rest.slice(i));
231
+ return s ? { scripts: [s], pkgs } : { unclear: 'yarn workspaces foreach' };
232
+ }
233
+ return null;
234
+ }
235
+ if (tool === 'bun') {
236
+ if (a[0] !== '--filter' || a[1] === undefined)
237
+ return null;
238
+ if (/[^\w@/.*-]/.test(a[1]))
239
+ return { unclear: `bun filter ${a[1]}` };
240
+ const re = nameGlob(a[1]);
241
+ const s = scriptAt(a.slice(2));
242
+ return s
243
+ ? { scripts: [s], pkgs: pkgs.filter((p) => p.name !== undefined && re.test(p.name)) }
244
+ : { unclear: 'bun --filter' };
245
+ }
246
+ if (tool === 'turbo' || tool === 'lerna') {
247
+ if (a[0] !== 'run')
248
+ return null;
249
+ const s = a.slice(1);
250
+ if (s.length === 0 || s.some((w) => !/^[\w:.-]+$/.test(w)))
251
+ return { unclear: `${tool} run` };
252
+ return { scripts: tool === 'lerna' ? s.slice(0, 1) : s, pkgs };
253
+ }
254
+ if (tool === 'nx') {
255
+ if (a[0] !== 'run-many')
256
+ return null;
257
+ const s = a.slice(1);
258
+ if ((s[0] !== '-t' && s[0] !== '--target' && s[0] !== '--targets') || s.length < 2)
259
+ return { unclear: 'nx run-many' };
260
+ const names = s.slice(1);
261
+ if (names.some((w) => !/^[\w:.-]+$/.test(w)))
262
+ return { unclear: 'nx run-many' };
263
+ return { scripts: names, pkgs };
264
+ }
265
+ return null;
266
+ }