@rtorcato/repo-tooling 3.45.0 โ†’ 4.0.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/dist/cli/index.js CHANGED
@@ -5,13 +5,6 @@ import { Command } from 'commander';
5
5
  import fs from 'fs-extra';
6
6
  import { doctorCommand } from './commands/doctor.js';
7
7
  import { fixCommand } from './commands/fix.js';
8
- import { loopCleanupCommand } from './commands/loop-cleanup.js';
9
- import { loopEnvCommand } from './commands/loop-env.js';
10
- import { loopGuardCommand } from './commands/loop-guard.js';
11
- import { loopCommentCommand, loopVerdictCommand } from './commands/loop-marker.js';
12
- import { loopReapCommand } from './commands/loop-reap.js';
13
- import { loopTickCommand } from './commands/loop-tick.js';
14
- import { loopWorktreeAddCommand } from './commands/loop-worktree.js';
15
8
  import { setupProject } from './commands/setup.js';
16
9
  import { copyPreset, PRESETS } from './utils/copy-preset.js';
17
10
  import { getToolVersion } from './utils/version.js';
@@ -297,12 +290,6 @@ const TOOL_CATALOG = [
297
290
  exports: [],
298
291
  fixTarget: 'ai',
299
292
  },
300
- {
301
- name: 'Claude skills',
302
- description: 'Install the ai-issue-loop skill into ~/.claude/skills (user-global, opt-in โ€” see --skills-dir)',
303
- exports: [],
304
- fixTarget: 'claude-skills',
305
- },
306
293
  ];
307
294
  program
308
295
  .command('list')
@@ -326,9 +313,6 @@ program
326
313
  .description('๐Ÿฉบ Diagnose project alignment with @rtorcato/repo-tooling presets')
327
314
  .option('-d, --directory <path>', 'Target directory to diagnose', process.cwd())
328
315
  .option('--json', 'Emit machine-readable JSON output')
329
- // The read side of `fix --skills-dir` (#485). No --yes/--json requirement
330
- // here: doctor never writes, so an unresolved directory is just reported.
331
- .option('--skills-dir <path>', 'Where `fix claude-skills` installs user-global agent skills (default: ~/.claude/skills). Pass the same path `fix` was given, or the skill reports as not installed')
332
316
  // Rules are per-repo (#563): this compares them against another repo's, and
333
317
  // only reports. Never drift, never a fixer, never part of the exit code.
334
318
  .option('--rules-from <owner/repo>', "Report how this repo's config and rules differ from that repo's .repo-tooling.json (informational; read via `gh`)")
@@ -343,11 +327,6 @@ program
343
327
  .option('--list', 'List all registered fix targets and exit')
344
328
  .option('--resync', 'Re-scaffold every file recorded in .repo-tooling.json')
345
329
  .option('--diff', 'Show a unified diff of each change before confirming')
346
- .option('--skills-dir <path>', 'Where `fix claude-skills` installs user-global agent skills (default: ~/.claude/skills). Required with --yes/--json when that directory does not exist')
347
- // Deliberately not folded into --yes: unattended runs pass --yes, and this is
348
- // the one overwrite that destroys work living outside the repo (#480).
349
- .option('--force-skills', 'Let `fix claude-skills` overwrite a locally modified skill instead of refusing')
350
- .option('--gh-config-dir <path>', 'gh profile signed in as rules.aiLoop.agentUser, for `fix ai-loop-identity` (default: ~/.config/gh-<agentUser>)')
351
330
  .action((target, options) => fixCommand(target, {
352
331
  directory: options.directory,
353
332
  yes: options.yes,
@@ -356,88 +335,21 @@ program
356
335
  list: options.list,
357
336
  resync: options.resync,
358
337
  diff: options.diff,
359
- skillsDir: options.skillsDir,
360
- forceSkills: options.forceSkills,
361
- ghConfigDir: options.ghConfigDir,
362
338
  }));
363
- // Mechanics the ai-issue-loop skill used to describe in prose-with-shell (#519).
364
- // Deliberately outside the isSelfRepo hook below: the loop runs against this
365
- // repo like any other, and a guard that refuses here would guard nothing.
366
- const loop = program.command('loop').description('๐Ÿ” ai-issue-loop mechanics as tested commands');
367
- loop
368
- .command('guard')
369
- .description('๐Ÿ›ก๏ธ Repair a wrongly-bare main checkout and gate the node_modules rebuild')
370
- .option('--root <path>', 'Main checkout the loop branches worktrees from', process.cwd())
371
- .option('--worktree-root <path>', 'Where ai-* worktrees live (default: <root>-worktrees)')
372
- .option('--removed', 'A worktree was removed this tick โ€” consider rebuilding node_modules')
373
- .option('--json', 'Emit machine-readable JSON output')
374
- .addHelpText('after', '\nExit codes:\n' +
375
- ' 0 root is a usable work tree (healthy, or repaired in place) โ€” continue the tick\n' +
376
- ' 1 repair was attempted and failed; the root is still bare โ€” halt the tick\n' +
377
- ' 2 root is not a repairable main checkout (bare clone, linked worktree, or not a repo) โ€” halt the tick\n')
378
- .action(loopGuardCommand);
379
- loop
380
- .command('env')
381
- .description('๐Ÿงญ Resolve ROOT, WT_ROOT, OWNER_REPO, AGENT_USER, HUMAN_USER and ME once')
382
- .option('-d, --dir <path>', 'Directory to resolve from โ€” main checkout or any worktree', process.cwd())
383
- .option('--json', 'Emit machine-readable JSON output')
384
- .addHelpText('after', "\nWithout --json, prints KEY='value' lines for eval. Empty means none.\n" +
385
- 'Exits 1 when the checkout or its GitHub repo cannot be resolved.\n')
386
- .action(loopEnvCommand);
387
- loop
388
- .command('cleanup')
389
- .description('๐Ÿงน Remove ai-* worktrees whose PR landed on main or was closed')
390
- .option('--root <path>', 'Main checkout the loop branches worktrees from', process.cwd())
391
- .option('--worktree-root <path>', 'Where ai-* worktrees live (default: <root>-worktrees)')
392
- .option('--json', 'Emit machine-readable JSON output')
393
- .addHelpText('after', '\nPass `removed` from --json to `loop guard --removed`.\n' +
394
- 'Exits 1 when a worktree removal failed.\n')
395
- .action(loopCleanupCommand);
396
- loop
397
- .command('worktree')
398
- .description('๐ŸŒณ Loop worktree mechanics')
399
- .command('add <slug>')
400
- .description('๐ŸŒฑ Create ai-<issue>-<slug> off origin/main, link its deps, assert none are missing')
401
- .option('--root <path>', 'Main checkout to branch the worktree from', process.cwd())
402
- .option('--worktree-root <path>', 'Where ai-* worktrees live (default: <root>-worktrees)')
403
- .option('--base <ref>', 'Ref to branch from', 'origin/main')
404
- .option('--json', 'Emit machine-readable JSON output')
405
- .addHelpText('after', '\nExit 1 when the worktree was not created or a symlinkDirectories entry is left\n' +
406
- 'unlinked โ€” do not spawn an implementer. needsInstall means no list was declared.\n')
407
- .action(loopWorktreeAddCommand);
408
- loop
409
- .command('reap')
410
- .description('๐Ÿชฆ Report agents stalled past 45 minutes and what to do about each')
411
- .option('--root <path>', 'Main checkout the loop branches worktrees from', process.cwd())
412
- .option('--worktree-root <path>', 'Where ai-* worktrees live (default: <root>-worktrees)')
413
- .option('--json', 'Emit machine-readable JSON output')
414
- .addHelpText('after', '\nRead-only: prints a verdict per stall (block / drop-label / remove-worktree).\n' +
415
- 'Exits 1 when a gh query failed and the report is incomplete.\n')
416
- .action(loopReapCommand);
417
- loop
418
- .command('comment <pr>')
419
- .description("๐Ÿ’ฌ Upsert the loop's one decision-marker comment on a PR")
420
- .requiredOption('--body-file <path>', 'Comment text, without the marker (- for stdin)')
421
- .option('-d, --dir <path>', 'Directory to resolve the GitHub repo from', process.cwd())
422
- .option('--json', 'Emit machine-readable JSON output')
423
- .action(loopCommentCommand);
424
- loop
425
- .command('verdict <pr>')
426
- .description("โš–๏ธ Read a reviewer arm's verdict marker for the PR's current head")
427
- .requiredOption('--arm <arm>', 'Reviewer arm: code or sec')
428
- .option('-d, --dir <path>', 'Directory to resolve the GitHub repo from', process.cwd())
429
- .option('--json', 'Emit machine-readable JSON output')
430
- .addHelpText('after', '\nPrints PASS, PASS-NOTES, CHANGES, or an empty line when none is posted.\n' +
431
- 'Exits 1 when the PR or its reviews cannot be read.\n')
432
- .action(loopVerdictCommand);
433
- loop
434
- .command('tick')
435
- .description("๐Ÿ“‹ Compute one tick's work list โ€” guard, cleanup, reap, verdicts, pickups")
436
- .option('--root <path>', 'Main checkout, or any worktree of it', process.cwd())
437
- .option('--json', 'Emit machine-readable JSON output')
438
- .addHelpText('after', '\nWrites no GitHub state: the caller applies every label, comment and spawn.\n' +
439
- "Exit 1 or 2 halts the tick (loop guard's codes, or an unresolvable checkout).\n")
440
- .action(loopTickCommand);
339
+ // The ai-issue-loop pipeline moved to @rtorcato/repo-ai (#658). Kept as a
340
+ // pointer so a stale skill calling `repo-tooling loop โ€ฆ` fails loudly with the
341
+ // fix, instead of commander's generic "unknown command".
342
+ program
343
+ .command('loop', { hidden: true })
344
+ .argument('[args...]')
345
+ .allowUnknownOption()
346
+ .helpOption(false)
347
+ .action(() => {
348
+ console.error(chalk.red('`repo-tooling loop` moved to @rtorcato/repo-ai.') +
349
+ '\n Run `npx @rtorcato/repo-ai loop โ€ฆ`, and refresh the skills with' +
350
+ '\n `npx @rtorcato/repo-ai fix claude-skills --force-skills`.');
351
+ process.exitCode = 1;
352
+ });
441
353
  program.hook('preAction', async (_, actionCommand) => {
442
354
  const name = actionCommand.name();
443
355
  if (name === 'setup' || name === 'doctor' || name === 'fix') {
@@ -1,7 +1,6 @@
1
1
  import path from 'node:path';
2
2
  import fs from 'fs-extra';
3
3
  import { CONFIG_SCHEMA, validateProjectConfig } from '../commands/setup-presets.js';
4
- import { SHIPPED_SKILLS } from '../generators/claude-skills.js';
5
4
  import { getToolVersion } from './version.js';
6
5
  export const LOCKFILE_NAME = '.repo-tooling.json';
7
6
  // Package and bin name used before the js-toolingโ†’repo-tooling rename (#272).
@@ -51,9 +50,8 @@ export const DEFAULT_RULES = {
51
50
  * `pnpm schema:generate` and gated by tests/cli/utils/lockfile-schema.test.ts.
52
51
  *
53
52
  * A function, not a const: lockfile.ts sits in an import cycle with
54
- * setup-presets.ts (via the swift scaffolder) and with claude-skills.ts (via
55
- * copy-preset.ts), so CONFIG_SCHEMA and SHIPPED_SKILLS are both in their TDZ
56
- * while this module evaluates. Reading them here, at call time, is safe.
53
+ * setup-presets.ts (via the swift scaffolder), so CONFIG_SCHEMA is in its TDZ
54
+ * while this module evaluates. Reading it here, at call time, is safe.
57
55
  */
58
56
  // ponytail: key sets are compiler-checked against the type; a changed field
59
57
  // *type* (string โ†’ number) still needs both lines edited by hand.
@@ -113,7 +111,7 @@ export function lockfileSchema() {
113
111
  aiLoop: {
114
112
  type: 'object',
115
113
  additionalProperties: false,
116
- description: 'Settings for the ai-issue-loop skills. Repo-scoped on purpose: committed here they travel with the repo and survive a new laptop.',
114
+ description: 'Settings for the ai-issue-loop skills from @rtorcato/repo-ai. Repo-scoped on purpose: committed here they travel with the repo and survive a new laptop.',
117
115
  properties: {
118
116
  agentUser: {
119
117
  type: 'string',
@@ -123,8 +121,8 @@ export function lockfileSchema() {
123
121
  },
124
122
  requiredSkills: {
125
123
  type: 'array',
126
- items: { type: 'string', enum: SHIPPED_SKILLS },
127
- description: 'Agent skills this repo\'s workflows depend on. doctor compares each installed copy\'s stamped hash against the shipped one and reports a missing or stale skill โ€” always as "not configured", never drift, because it probes the machine rather than the repo. It never runs the fixer for you.',
124
+ items: { type: 'string' },
125
+ description: "Agent skills this repo's workflows depend on. Audited by `npx @rtorcato/repo-ai doctor`, which reports a missing or stale installed copy; it never installs one for you.",
128
126
  },
129
127
  mcp: {
130
128
  type: 'object',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rtorcato/repo-tooling",
3
- "version": "3.45.0",
3
+ "version": "4.0.0",
4
4
  "description": "One CLI to scaffold, audit and fix your repo's whole toolchain โ€” linting, tests, commits, releases & CI.",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -1,68 +0,0 @@
1
- import path from 'node:path';
2
- import fs from 'fs-extra';
3
- import { realGhExec } from './github-settings.js';
4
- /**
5
- * `aiLoop.agentUser` assignability (#530). The skills that consume the option
6
- * (`ai-issue-loop`, `ai-workflow`) verify it at runtime and *silently assign
7
- * nothing* on failure โ€” by design, so a deleted bot account or a bot never
8
- * added as a collaborator degrades the loop with no visible symptom. This
9
- * check is where that failure becomes visible.
10
- *
11
- * Read-only, on the same `gh` seam as labels.ts and milestones.ts. Everything
12
- * derives from the consuming repo: the login from its lockfile, the repo from
13
- * its own remote via gh's `{owner}/{repo}` placeholders.
14
- */
15
- const CHECK = 'AI loop agent';
16
- /**
17
- * GitHub login shape: 1โ€“39 chars, alphanumerics and single hyphens, no leading
18
- * or trailing hyphen. The injection boundary โ€” the login is interpolated into
19
- * the API path below.
20
- */
21
- export const LOGIN = /^[a-zA-Z0-9](?:-?[a-zA-Z0-9]){0,38}$/;
22
- const skip = (reason) => ({
23
- check: CHECK,
24
- status: 'ok',
25
- detail: `skipped โ€” ${reason}`,
26
- });
27
- export async function checkAgentUser(dir, agentUser, exec) {
28
- // Absent field โ‡’ not applicable โ€” the single-identity model is the default,
29
- // not a requirement (#521).
30
- if (!agentUser) {
31
- return {
32
- check: CHECK,
33
- status: 'ok',
34
- detail: 'not applicable โ€” no rules.aiLoop.agentUser in .repo-tooling.json',
35
- };
36
- }
37
- if (!LOGIN.test(agentUser)) {
38
- return {
39
- check: CHECK,
40
- status: 'drift',
41
- detail: `rules.aiLoop.agentUser "${agentUser}" is not a valid GitHub login`,
42
- hint: 'Fix or remove rules.aiLoop.agentUser in .repo-tooling.json',
43
- };
44
- }
45
- // Cheap gate first: no .git โ†’ never spawn (keeps tmp-dir doctor runs offline).
46
- if (!(await fs.pathExists(path.join(dir, '.git'))))
47
- return skip('not a git repository');
48
- const gh = exec ?? ((args, stdin) => realGhExec(args, stdin, dir));
49
- // 204 when the login can be assigned issues on this repo, 404 otherwise.
50
- const r = await gh(['api', `repos/{owner}/{repo}/assignees/${agentUser}`]);
51
- if (r.ok) {
52
- return {
53
- check: CHECK,
54
- status: 'ok',
55
- detail: `rules.aiLoop.agentUser "${agentUser}" is an assignable collaborator`,
56
- };
57
- }
58
- if (/HTTP 404/.test(r.stderr)) {
59
- return {
60
- check: CHECK,
61
- status: 'drift',
62
- detail: `rules.aiLoop.agentUser "${agentUser}" is not an assignable collaborator โ€” the loop skills will silently assign nothing`,
63
- hint: `Add the account as a collaborator (\`gh api -X PUT repos/{owner}/{repo}/collaborators/${agentUser}\`) or remove rules.aiLoop.agentUser from .repo-tooling.json`,
64
- };
65
- }
66
- // Offline, unauthenticated, or gh missing โ€” not evidence of drift.
67
- return skip('could not verify assignability');
68
- }
@@ -1,80 +0,0 @@
1
- /**
2
- * `fix ai-loop-identity` (#638): point this checkout's Claude sessions at a gh
3
- * profile signed in as `rules.aiLoop.agentUser`, so `loop guard` stops halting
4
- * on `identity: mismatch`. `.repo-tooling.json` (committed) says *who* the agent
5
- * is; the profile path is machine-specific, so it lands in the gitignored,
6
- * per-checkout `.claude/settings.local.json`.
7
- */
8
- import path from 'node:path';
9
- import fs from 'fs-extra';
10
- import { configuredAgentUser } from '../cli/commands/loop-guard.js';
11
- import { LOGIN } from './agent-user.js';
12
- import { FixerAbort } from './fixers.js';
13
- import { realGhExec } from './github-settings.js';
14
- export const SETTINGS_LOCAL = '.claude/settings.local.json';
15
- /** The profile dir the fixer looks in when `--gh-config-dir` is not given. */
16
- export function defaultGhConfigDir(agentUser, home) {
17
- return path.join(home, '.config', `gh-${agentUser}`);
18
- }
19
- /**
20
- * Returns the files written. Writes nothing โ€” and aborts with the `gh auth
21
- * login` command as the hint โ€” unless the profile really is the agent account.
22
- */
23
- export async function setupAgentIdentity(targetDir, opts) {
24
- const agentUser = await configuredAgentUser(targetDir);
25
- if (!agentUser) {
26
- console.error(' nothing to do โ€” no rules.aiLoop.agentUser in .repo-tooling.json');
27
- return [];
28
- }
29
- // The login comes from a committed file and becomes a path segment below.
30
- if (!LOGIN.test(agentUser)) {
31
- throw new FixerAbort('invalid-agent-user', `rules.aiLoop.agentUser "${agentUser}" is not a valid GitHub login`, 'Fix or remove rules.aiLoop.agentUser in .repo-tooling.json');
32
- }
33
- const dir = path.resolve(opts.ghConfigDir ?? defaultGhConfigDir(agentUser, opts.home));
34
- const gh = opts.gh ?? ((args, env) => realGhExec(args, undefined, targetDir, env));
35
- const login = (await fs.pathExists(dir))
36
- ? await gh(['api', 'user', '--jq', '.login'], { GH_CONFIG_DIR: dir }).then((r) => r.ok ? r.stdout.trim() : '')
37
- : '';
38
- // GitHub logins are case-insensitive, so a case difference is one account.
39
- if (login.toLowerCase() !== agentUser.toLowerCase()) {
40
- throw new FixerAbort('agent-identity-unavailable', `${dir} is ${login ? `signed in as ${login}, not ${agentUser}` : `not signed in to gh as ${agentUser}`} โ€” nothing written`, `Sign in once, in a browser logged in as ${agentUser}, then re-run:\n GH_CONFIG_DIR=${dir} gh auth login --hostname github.com --web --scopes repo`);
41
- }
42
- const written = [];
43
- const settingsPath = path.join(targetDir, SETTINGS_LOCAL);
44
- let settings = {};
45
- if (await fs.pathExists(settingsPath)) {
46
- try {
47
- settings = await fs.readJson(settingsPath);
48
- }
49
- catch {
50
- throw new FixerAbort('settings-local-unparseable', `${SETTINGS_LOCAL} is not valid JSON โ€” not overwriting it`, `Fix the file by hand, or add "env": {"GH_CONFIG_DIR": "${dir}"} to it yourself`);
51
- }
52
- }
53
- const env = (settings.env ?? {});
54
- if (env.GH_CONFIG_DIR !== dir) {
55
- await fs.outputJson(settingsPath, { ...settings, env: { ...env, GH_CONFIG_DIR: dir } }, { spaces: 2 });
56
- written.push(SETTINGS_LOCAL);
57
- }
58
- if (await ensureIgnored(targetDir))
59
- written.push('.gitignore');
60
- return written;
61
- }
62
- // ponytail: exact-line match on the usual spellings; a glob that happens to
63
- // cover the file gets a redundant (harmless) line. `git check-ignore` if that bites.
64
- const IGNORE_LINES = new Set([
65
- SETTINGS_LOCAL,
66
- `/${SETTINGS_LOCAL}`,
67
- '.claude',
68
- '.claude/',
69
- '/.claude',
70
- '/.claude/',
71
- ]);
72
- async function ensureIgnored(targetDir) {
73
- const file = path.join(targetDir, '.gitignore');
74
- const existing = (await fs.pathExists(file)) ? await fs.readFile(file, 'utf-8') : '';
75
- if (existing.split('\n').some((l) => IGNORE_LINES.has(l.trim())))
76
- return false;
77
- const separator = existing === '' || existing.endsWith('\n') ? '' : '\n';
78
- await fs.writeFile(file, `${existing}${separator}${SETTINGS_LOCAL}\n`);
79
- return true;
80
- }
@@ -1,220 +0,0 @@
1
- import path from 'node:path';
2
- import chalk from 'chalk';
3
- import fs from 'fs-extra';
4
- import { realGhExec } from './github-settings.js';
5
- /**
6
- * `ai-issue-loop` label hygiene (#446). Same class of GitHub-side drift as
7
- * github-settings.ts and milestones.ts, on the same `gh` seam.
8
- *
9
- * The bug this exists for: the skill's bootstrap uses `gh label create`, which
10
- * *errors as a no-op* when the label already exists. It can add a missing label
11
- * but can never repair an existing one, so a hand-created `ai-ready` keeps
12
- * whatever colour the web picker gave it forever. Measured across eight repos,
13
- * six had `ai-ready` at `B60205` โ€” byte-identical to `ai-blocked`, so "an agent
14
- * should pick this up" and "an agent gave up" rendered the same. Repair here
15
- * goes through `gh label edit`, which is the whole point of the fixer.
16
- *
17
- * This table is the single source of truth for the label set. The bootstrap
18
- * block in skills/ai-issue-loop/SKILL.md is asserted against it in
19
- * tests/base/labels.test.ts, so the two cannot drift apart.
20
- */
21
- const CHECK = 'AI loop labels';
22
- export const LOOP_LABELS = [
23
- {
24
- name: 'holding',
25
- color: '5319e7',
26
- description: 'Gate/holding issue โ€” human judgement, never auto-picked',
27
- },
28
- { name: 'ai-ready', color: '0e8a16', description: 'Eligible for an AI agent to implement' },
29
- { name: 'ai-wip', color: 'fbca04', description: 'Claimed by an agent; worktree exists' },
30
- { name: 'ai-blocked', color: 'b60205', description: 'Agent gave up; needs a human' },
31
- { name: 'ai-review', color: '1d76db', description: 'PR awaiting agent review' },
32
- { name: 'ai-reviewing-code', color: 'c5def5', description: 'code-reviewer claimed and running' },
33
- { name: 'ai-reviewing-sec', color: 'c5def5', description: 'security-expert claimed and running' },
34
- { name: 'ai-ok-code', color: '0e8a16', description: 'code-reviewer passed' },
35
- { name: 'ai-ok-sec', color: '0e8a16', description: 'security-expert passed' },
36
- { name: 'ai-changes', color: 'd93f0b', description: 'Reviewer requested changes' },
37
- {
38
- name: 'ai-fixing',
39
- color: '006b75',
40
- description: 'Fix-round implementer claimed and running',
41
- },
42
- {
43
- name: 'ai-notes',
44
- color: 'fbca04',
45
- description: 'Passed, but a reviewer left something to read before merging',
46
- },
47
- {
48
- name: 'merge-ready',
49
- color: '8250df',
50
- description: 'Both agent reviews passed and the PR is mergeable โ€” waiting on a human',
51
- },
52
- {
53
- name: 'ai-suggested',
54
- color: 'c2e0c6',
55
- description: 'Follow-up surfaced by an agent review โ€” triage queue, never auto-picked',
56
- },
57
- ];
58
- /**
59
- * How many of the set have to exist before this repo counts as running the
60
- * loop. A repo with none has opted out, not drifted โ€” creating fourteen labels it
61
- * will never use is the nag this threshold exists to prevent. One alone is the
62
- * observed half-state (`cf-common` has only `ai-ready`, applied by hand), which
63
- * is likewise not evidence the pipeline runs there.
64
- */
65
- const IN_USE_THRESHOLD = 2;
66
- const skip = (reason) => ({
67
- check: CHECK,
68
- status: 'ok',
69
- detail: `skipped โ€” ${reason}`,
70
- });
71
- /**
72
- * Case-insensitive, `#`-insensitive. The drift that started this was uppercase
73
- * `B60205` against lowercase `b60205` โ€” GitHub's colour picker writes uppercase,
74
- * `gh` writes lowercase, and the two render identically. Comparing raw would
75
- * report every hand-created label as drift forever and have the fixer PATCH a
76
- * colour that was already correct.
77
- */
78
- const normalizeColor = (c) => c.trim().replace(/^#/, '').toLowerCase();
79
- async function readLabels(gh) {
80
- const r = await gh(['label', 'list', '--json', 'name,color,description', '--limit', '200']);
81
- if (!r.ok)
82
- return null;
83
- try {
84
- const parsed = JSON.parse(r.stdout);
85
- if (!Array.isArray(parsed))
86
- return null;
87
- const byName = new Map();
88
- for (const l of parsed) {
89
- if (typeof l?.name !== 'string')
90
- continue;
91
- byName.set(l.name, {
92
- name: l.name,
93
- color: typeof l.color === 'string' ? l.color : '',
94
- description: typeof l.description === 'string' ? l.description : '',
95
- });
96
- }
97
- return byName;
98
- }
99
- catch {
100
- return null;
101
- }
102
- }
103
- export function classifyLabels(existing) {
104
- const deltas = { present: [], missing: [], wrongColor: [], wrongDescription: [] };
105
- for (const spec of LOOP_LABELS) {
106
- const actual = existing.get(spec.name);
107
- if (!actual) {
108
- deltas.missing.push(spec);
109
- continue;
110
- }
111
- deltas.present.push(spec);
112
- if (normalizeColor(actual.color) !== normalizeColor(spec.color))
113
- deltas.wrongColor.push({ spec, actual: normalizeColor(actual.color) });
114
- if (actual.description.trim() !== spec.description)
115
- deltas.wrongDescription.push(spec);
116
- }
117
- return deltas;
118
- }
119
- const names = (specs) => specs.map((s) => `\`${s.name}\``).join(', ');
120
- export async function checkLoopLabels(dir, exec) {
121
- // Cheap gate first: no .git โ†’ never spawn (keeps tmp-dir doctor runs offline).
122
- if (!(await fs.pathExists(path.join(dir, '.git'))))
123
- return skip('not a git repository');
124
- const gh = exec ?? ((args, stdin) => realGhExec(args, stdin, dir));
125
- const existing = await readLabels(gh);
126
- if (!existing)
127
- return skip('could not read labels');
128
- const { present, missing, wrongColor, wrongDescription } = classifyLabels(existing);
129
- if (present.length < IN_USE_THRESHOLD)
130
- return {
131
- check: CHECK,
132
- status: 'ok',
133
- detail: 'not applicable โ€” repo does not use the ai-issue-loop labels',
134
- };
135
- const deltas = [];
136
- for (const { spec, actual } of wrongColor)
137
- deltas.push(`\`${spec.name}\` is #${actual}, should be #${spec.color}`);
138
- if (wrongDescription.length)
139
- deltas.push(`wrong description: ${names(wrongDescription)}`);
140
- if (missing.length)
141
- deltas.push(`missing: ${names(missing)}`);
142
- if (deltas.length)
143
- return {
144
- check: CHECK,
145
- status: 'drift',
146
- detail: deltas.join('; '),
147
- hint: 'Run `npx @rtorcato/repo-tooling fix labels` to repair them with `gh label edit` โ€” `gh label create` cannot change an existing label, which is how this drifted',
148
- };
149
- return {
150
- check: CHECK,
151
- status: 'ok',
152
- detail: `${present.length} ai-issue-loop label(s) match spec`,
153
- };
154
- }
155
- /**
156
- * Repairs colour and description with `gh label edit`, and creates the labels
157
- * the set is missing. Only on a repo already running the loop (the same
158
- * `IN_USE_THRESHOLD` gate the check uses) โ€” otherwise a plain `fix --yes` would
159
- * push fourteen labels into every repo it touches.
160
- *
161
- * Idempotent: an aligned repo is a no-op, and a label whose only difference is
162
- * the hex case is not touched at all.
163
- *
164
- * Advisories go to `console.error`; stdout carries the `--json` payload (#357).
165
- */
166
- export async function applyLoopLabels(dir, exec) {
167
- if (!(await fs.pathExists(path.join(dir, '.git')))) {
168
- console.error(chalk.gray(' skipped โ€” not a git repository'));
169
- return [];
170
- }
171
- const gh = exec ?? ((args, stdin) => realGhExec(args, stdin, dir));
172
- const existing = await readLabels(gh);
173
- if (!existing) {
174
- console.error(chalk.gray(' skipped โ€” could not read labels'));
175
- return [];
176
- }
177
- const { present, missing, wrongColor, wrongDescription } = classifyLabels(existing);
178
- if (present.length < IN_USE_THRESHOLD) {
179
- console.error(chalk.gray(' skipped โ€” repo does not use the ai-issue-loop labels'));
180
- return [];
181
- }
182
- // One edit per drifted label, whichever field drifted โ€” the API takes both.
183
- const toEdit = new Set([...wrongColor.map((w) => w.spec), ...wrongDescription]);
184
- const applied = [];
185
- for (const spec of toEdit) {
186
- // `edit`, not `create`: create errors as a no-op on an existing label, so a
187
- // fixer built on it would silently repair nothing (#446).
188
- const r = await gh([
189
- 'label',
190
- 'edit',
191
- spec.name,
192
- '--color',
193
- spec.color,
194
- '--description',
195
- spec.description,
196
- ]);
197
- if (r.ok)
198
- applied.push(`repaired label "${spec.name}"`);
199
- else
200
- console.error(chalk.yellow(` could not repair "${spec.name}": ${r.stderr.trim() || 'gh error'}`));
201
- }
202
- for (const spec of missing) {
203
- const r = await gh([
204
- 'label',
205
- 'create',
206
- spec.name,
207
- '--color',
208
- spec.color,
209
- '--description',
210
- spec.description,
211
- ]);
212
- if (r.ok)
213
- applied.push(`created label "${spec.name}"`);
214
- else
215
- console.error(chalk.yellow(` could not create "${spec.name}": ${r.stderr.trim() || 'gh error'}`));
216
- }
217
- if (applied.length === 0)
218
- console.error(chalk.gray(' labels already match spec'));
219
- return applied;
220
- }