@futurelastic/colab-handbook 1.12.0-rc.17 → 1.12.0-rc.19

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/package.json CHANGED
@@ -27,5 +27,5 @@
27
27
  "engines": {
28
28
  "node": ">=18"
29
29
  },
30
- "version": "1.12.0-rc.17"
30
+ "version": "1.12.0-rc.19"
31
31
  }
package/tools/colab CHANGED
@@ -6231,9 +6231,15 @@ function cmdDoctor(argv) {
6231
6231
  const entry = { repo: shortRepo(repo), label: v.name, verdict: v.verdict,
6232
6232
  total: v.total, open: v.open, members: v.members, deleted: false, error: null };
6233
6233
  if (opts.prune && v.verdict === 'spent') {
6234
- const del = git.ghLabelDelete(repo, v.name);
6235
- entry.deleted = !!del.ok;
6236
- if (!del.ok) entry.error = del.stderr || 'gh label delete failed';
6234
+ // #448: `spent` came from the search-backed listing; confirm through the issues table.
6235
+ const t = groupLabels.teardownSpentGroupLabel(v.name, {
6236
+ searchOpen: [],
6237
+ confirmOpen: (name) => git.ghOpenIssueNumbersByLabel(repo, name),
6238
+ deleteLabel: (name) => git.ghLabelDelete(repo, name),
6239
+ });
6240
+ entry.deleted = t.deleted;
6241
+ if (t.action === 'keep') entry.error = groupLabels.keptReason(v.name, t);
6242
+ else if (!t.deleted) entry.error = t.error;
6237
6243
  }
6238
6244
  report.spentGroupLabels.push(entry);
6239
6245
  }
@@ -7287,6 +7293,7 @@ const HELP_ADOPT = `colab adopt [--repo <path>] [--json] [--no-verify] [--axis a
7287
7293
  [--writes <free|direct|isolated>] [--channels <c1,c2,...>]
7288
7294
  [--production <url>|none] [--deploy <push-main|tag|manual|none>]
7289
7295
  [--stack "<text>"] [--answered-by <name>] [--reason "<text>"]
7296
+ [--fork | --no-fork]
7290
7297
 
7291
7298
  Detects what a repo already states in .github/project.yml, ASKS a human only what could not be
7292
7299
  detected (flags, or a forced multiple-choice menu at a TTY — every row is a numbered choice,
@@ -7308,6 +7315,14 @@ accepted and reads as free — no adopter's descriptor breaks, and none is re-as
7308
7315
  --answered-by N who is answering, alongside COLAB_HUMAN=1 (see THE HUMAN GATE below)
7309
7316
  --reason "..." required alongside a lowered or evidence-contradicted exposure answer;
7310
7317
  written into the file, next to the key it justifies
7318
+ --fork / --no-fork
7319
+ a repo you own that tracks an upstream you don't (#449) is DETECTED — a
7320
+ remote named \`upstream\` whose URL differs from origin's. Assert it with
7321
+ --fork when the upstream remote is named otherwise; deny it with --no-fork.
7322
+ On a fork, step 5 of the remaining list is the append-only Conventions block
7323
+ (never the thin-shell conversion), the upstream's own agent workflow is
7324
+ named, and a new CLAUDE.md gets no AGENTS.md stub (CONVENTIONS.md §9,
7325
+ "A fork of an upstream")
7311
7326
 
7312
7327
  Any answer flag (--room/--exposure/--writes/--channels/--production/--deploy/--stack) makes the
7313
7328
  whole run NON-INTERACTIVE — it never half-prompts. With no answer flags and no TTY, and something
@@ -7436,7 +7451,7 @@ const ADOPT_ROW_ORDER = ['tier', 'room', 'exposure', 'writes', 'channels'];
7436
7451
  * read from a remote's HEAD, and the report says so (`detected.trunk.source`), never presented
7437
7452
  * as though it were.
7438
7453
  */
7439
- function adoptGitExtras(repoAbs) {
7454
+ function adoptGitExtras(repoAbs, opts = {}) {
7440
7455
  let trunk = git.detectTrunk(repoAbs);
7441
7456
  let trunkSource = trunk ? 'origin-head' : null;
7442
7457
  if (!trunk) {
@@ -7450,7 +7465,26 @@ function adoptGitExtras(repoAbs) {
7450
7465
  const hooksPath = hp.ok && hp.stdout ? hp.stdout : null;
7451
7466
  let hooksDirFiles = [];
7452
7467
  try { hooksDirFiles = fs.readdirSync(path.join(repoAbs, '.githooks')); } catch (_) { /* absent */ }
7453
- return { trunk, trunkSource, hooksPath, hooksDirFiles };
7468
+ // #449: `git ls-files` for the migrations candidate scan (adopt never asks `migrations:`).
7469
+ const ls = git.git(['ls-files'], repoAbs);
7470
+ const trackedFiles = ls.ok ? ls.stdout.split('\n').filter(Boolean) : undefined;
7471
+ return { trunk, trunkSource, hooksPath, hooksDirFiles, trackedFiles, fork: adoptDetectFork(repoAbs, opts) };
7472
+ }
7473
+
7474
+ /**
7475
+ * #449 — is this a repo you own that tracks an upstream you don't? DETECTED, never asked (§9):
7476
+ * a remote named `upstream` whose URL differs from origin's (the conventional name for the repo a
7477
+ * fork tracks). `--fork` asserts it when the upstream remote is named otherwise; `--no-fork`
7478
+ * denies it when a remote named `upstream` means something else. Returns null when not a fork.
7479
+ */
7480
+ function adoptDetectFork(repoAbs, opts = {}) {
7481
+ if (opts.noFork) return null;
7482
+ const up = git.git(['remote', 'get-url', 'upstream'], repoAbs);
7483
+ const origin = git.git(['remote', 'get-url', 'origin'], repoAbs);
7484
+ const upUrl = up.ok && up.stdout ? up.stdout : null;
7485
+ if (upUrl && !(origin.ok && origin.stdout === upUrl)) return { remote: 'upstream', url: upUrl, source: opts.fork ? 'flag' : 'upstream-remote' };
7486
+ if (opts.fork) return { remote: null, url: null, source: 'flag' };
7487
+ return null;
7454
7488
  }
7455
7489
 
7456
7490
  /** The `{ readFile, listDir, tags }` adapter tools/lib/adopt.js asks for — matching the local
@@ -7687,6 +7721,7 @@ function printAdoptReport(report, repoAbs, verify, localFinish) {
7687
7721
  print(`detected trunk: ${t.detected || '(unknown)'}${trunkSourceNote}${t.declared !== null ? ` (declared: ${t.declared}${t.agree === false ? ' ⚠ disagrees with detected' : ''})` : ''}`);
7688
7722
  print(`stack candidates: ${report.detected.stackCandidates.length ? report.detected.stackCandidates.join(', ') : '(none found)'}`);
7689
7723
  print(`declared ports: ${fmtVal(report.detected.ports)}`);
7724
+ if (report.fork) print(`fork of an upstream: yes — ${report.fork.source === 'flag' ? '--fork' : `remote "${report.fork.remote}" ${report.fork.url}`} (step 5 is the append-only block, §9 "A fork of an upstream")`);
7690
7725
  print(`legacy tier letter, derived from (production, deploy): ${report.legacyTierLetter ?? '(undetermined — production is set but deploy matches none of push-main/tag/manual)'}`);
7691
7726
  print('');
7692
7727
  print('Derived consequences:');
@@ -7886,9 +7921,10 @@ async function cmdAdopt(argv) {
7886
7921
  '--deploy': 'deploy', '--stack': 'stack', '--answered-by': 'answeredBy', '--reason': 'reason',
7887
7922
  '--trunk': 'trunk',
7888
7923
  },
7889
- flags: { '--json': 'json', '--no-verify': 'noVerify', '--local': 'local', '--no-labels': 'noLabels', '-h': 'help', '--help': 'help' },
7924
+ flags: { '--json': 'json', '--no-verify': 'noVerify', '--local': 'local', '--no-labels': 'noLabels', '--fork': 'fork', '--no-fork': 'noFork', '-h': 'help', '--help': 'help' },
7890
7925
  });
7891
7926
  if (opts.help) return print(HELP_ADOPT);
7927
+ if (opts.fork && opts.noFork) throw new UserError('--fork and --no-fork contradict each other — pass one');
7892
7928
  if (opts.trunk !== undefined && !opts.local) {
7893
7929
  throw new UserError('--trunk only means something with --local — on an ordinary adoption trunk is DETECTED, never asked (CONVENTIONS.md §9)');
7894
7930
  }
@@ -7904,7 +7940,7 @@ async function cmdAdopt(argv) {
7904
7940
  if (local.exit !== undefined) return local.exit;
7905
7941
  }
7906
7942
  const io = adoptIo(repoAbs);
7907
- const extra = adoptGitExtras(repoAbs);
7943
+ const extra = adoptGitExtras(repoAbs, opts);
7908
7944
  if (local) { extra.trunk = local.trunk; extra.trunkSource = 'local-integration'; }
7909
7945
  const report = adopt.detect(io, extra);
7910
7946
  const cfg = report.cfg;
@@ -8173,7 +8209,7 @@ async function cmdAdopt(argv) {
8173
8209
  fs.mkdirSync(path.dirname(descriptorFile), { recursive: true });
8174
8210
  fs.writeFileSync(descriptorFile, newText);
8175
8211
 
8176
- const afterExtra = adoptGitExtras(repoAbs);
8212
+ const afterExtra = adoptGitExtras(repoAbs, opts);
8177
8213
  if (local) { afterExtra.trunk = local.trunk; afterExtra.trunkSource = 'local-integration'; }
8178
8214
  const after = adopt.detect(adoptIo(repoAbs), afterExtra);
8179
8215
  // #417: a NEW repo (no descriptor before this run, plain adopt) gets the thin-shell CLAUDE.md
@@ -8188,7 +8224,8 @@ async function cmdAdopt(argv) {
8188
8224
  }
8189
8225
  for (const e of entries) print(`✓ wrote ${e.key}: ${fmtVal(e.value)}`);
8190
8226
  if (shell) {
8191
- if (shell.claude === 'written') print('✓ wrote CLAUDE.md — the thin shell: @AGENTS.md + the Conventions block (§9 step 5, #417)');
8227
+ if (shell.claude === 'written' && shell.fork) print('✓ wrote CLAUDE.md — the Conventions block alone: a fork with no upstream AGENTS.md gets no stub (§9 "A fork of an upstream", #449)');
8228
+ else if (shell.claude === 'written') print('✓ wrote CLAUDE.md — the thin shell: @AGENTS.md + the Conventions block (§9 step 5, #417)');
8192
8229
  else if (shell.claude === 'skipped') print(`· CLAUDE.md not written — ${shell.reason}`);
8193
8230
  if (shell.agents === 'written') print('✓ wrote AGENTS.md — a stub; the repo\'s own instructions go here');
8194
8231
  }
@@ -8224,6 +8261,14 @@ function adoptWriteShell(repoAbs, after) {
8224
8261
  const version = handbookVersion(root);
8225
8262
  const atTag = version === 'v0' ? null : stamp.gitIn(root, ['show', `${version}:templates/repo-CLAUDE-block.md`]);
8226
8263
  const blockText = atTag && atTag.ok && atTag.out ? atTag.out : fs.readFileSync(blockFile, 'utf8');
8264
+ // #449: on a fork, every file adopt creates is one the upstream may add later — a merge conflict
8265
+ // forever after. So no AGENTS.md stub there: with the upstream's own AGENTS.md the shell imports
8266
+ // it, without one CLAUDE.md is the block alone.
8267
+ const forkNoAgents = !!(after && after.fork) && !fs.existsSync(agentsAbs);
8268
+ if (forkNoAgents) {
8269
+ fs.writeFileSync(claudeAbs, adopt.renderClaudeShell(blockText, { version, trunk, tier, importAgents: false }));
8270
+ return { claude: 'written', agents: null, fork: true };
8271
+ }
8227
8272
  fs.writeFileSync(claudeAbs, adopt.renderClaudeShell(blockText, { version, trunk, tier }));
8228
8273
  let agents = 'exists';
8229
8274
  if (!fs.existsSync(agentsAbs)) { fs.writeFileSync(agentsAbs, adopt.renderAgentsStub()); agents = 'written'; }
@@ -12412,12 +12457,16 @@ function shipLandedTail({ repoAbs, sess, target, trunk, gh, sha, closeIssues, re
12412
12457
  // its last member.
12413
12458
  if (gh) {
12414
12459
  for (const gl of groupLabelsCarried) {
12415
- const openMembers = git.ghIssueListByLabel(repoAbs, gl, 'open', ['number']);
12416
- if (openMembers === null) { warn(`could not check membership of ${gl} — left in place`); continue; }
12417
- if (openMembers.length > 0) continue; // still binds the remainder — leave it
12418
- const del = git.ghLabelDelete(repoAbs, gl);
12419
- if (del.ok) print(` deleted spent group label ${gl} (every member now closed)`);
12420
- else warn(`could not delete spent group label ${gl}: ${del.stderr || 'gh label delete failed'}`);
12460
+ // #448: search says zero → a non-search read must agree before the repo-wide delete.
12461
+ const t = groupLabels.teardownSpentGroupLabel(gl, {
12462
+ searchOpen: (name) => git.ghIssueListByLabel(repoAbs, name, 'open', ['number']),
12463
+ confirmOpen: (name) => git.ghOpenIssueNumbersByLabel(repoAbs, name),
12464
+ deleteLabel: (name) => git.ghLabelDelete(repoAbs, name),
12465
+ });
12466
+ if (t.reason === 'open') continue; // still binds the remainder — leave it
12467
+ if (t.action === 'keep') { warn(groupLabels.keptReason(gl, t)); continue; }
12468
+ if (t.deleted) print(` deleted spent group label ${gl} (every member now closed)`);
12469
+ else warn(`could not delete spent group label ${gl}: ${t.error}`);
12421
12470
  }
12422
12471
  }
12423
12472
 
@@ -18,7 +18,8 @@
18
18
  * listDir(relPath) -> string[] non-recursive listing, [] if unreadable/absent
19
19
  * tags() -> string[] | null every git tag, or null if undeterminable
20
20
  *
21
- * Git facts that are NOT plain file reads (trunk, `core.hooksPath`) are passed in separately via
21
+ * Git facts that are NOT plain file reads (trunk, `core.hooksPath`, the fork remote and `git ls-files`
22
+ * for #449) are passed in separately via
22
23
  * `extra`, rather than folded into `io` — `detectTrunk()` already lives in `tools/lib/git.js` and
23
24
  * belongs to the CLI layer, not duplicated here.
24
25
  *
@@ -210,22 +211,108 @@ function deriveConsequences({ exposure, writes, room }) {
210
211
 
211
212
  // ---------------------------------------------------------------------- §9 remainder checklist
212
213
 
214
+ const migrationPaths = require('./migration-paths.js');
215
+
213
216
  /**
214
- * §9's steps 3-9, unconditionally — this commit never performs any of them (Boundary, #199's
215
- * plan: "adopt writes the descriptor and nothing else"), so the remainder is the same regardless
216
- * of what the descriptor already states. Handed back as data, not prose, so a caller (a report
217
- * printer, or a future `handbook-sync` call site) does not grow its own paraphrase of these steps.
217
+ * #449 — the agent workflow an upstream ships inside the fork: entries under `.claude/skills/`
218
+ * and `.claude/commands/`, plus a committed `AGENTS.md`. Upstream-owned files compete with the
219
+ * `code-*` skills, and deleting or editing them is a fork patch that conflicts on every upstream
220
+ * merge — so adopt only NAMES them, for the precedence line the appended block carries.
218
221
  */
219
- function remainingSteps() {
220
- return [
221
- { n: 3, text: 'Create the full label set (13 names) — `colab labels --ensure`, CONVENTIONS.md §9 step 3 (#206)' },
222
+ function detectUpstreamAgentFiles(io) {
223
+ const out = [];
224
+ for (const dir of ['.claude/skills', '.claude/commands']) {
225
+ for (const e of io.listDir(dir).slice().sort()) {
226
+ if (e.startsWith('.')) continue;
227
+ out.push(`${dir}/${e}`);
228
+ }
229
+ }
230
+ return out;
231
+ }
232
+
233
+ /**
234
+ * #449 — where this repo's migrations might live, beyond what `migrations:` and the two defaults
235
+ * already cover. Two heuristics over `git ls-files`, both CANDIDATES for a human, never written:
236
+ * a `migrations/` directory nothing covers (the audit's own rule, `undeclaredMigrationDirs`), and
237
+ * a directory holding tracked `*.sql` files nothing covers (a fork whose upstream keeps them in
238
+ * `modules/<name>/sql/` — measured: the no-new-migrations gate was blind there). The `.sql` rule
239
+ * over-reports seeds and fixtures on purpose: a false candidate costs a glance, a missed layout
240
+ * leaves a human-only gate seeing nothing.
241
+ */
242
+ function detectMigrationCandidates(cfg, trackedFiles) {
243
+ const parsed = migrationPaths.parseMigrationPaths(cfg);
244
+ const declared = parsed.paths;
245
+ const files = trackedFiles || [];
246
+ const dirs = new Set(migrationPaths.undeclaredMigrationDirs(files, declared));
247
+ for (const file of files) {
248
+ if (!/\.sql$/i.test(file)) continue;
249
+ const segs = String(file).split('/');
250
+ if (segs.length < 2) continue; // a root-level .sql is not a layout
251
+ if (segs.some((s) => s === 'node_modules' || s === 'vendor')) continue;
252
+ if (migrationPaths.isMigrationPath(file, declared)) continue;
253
+ const dir = `${segs.slice(0, -1).join('/')}/`;
254
+ if ([...dirs].some((d) => dir.startsWith(d))) continue;
255
+ dirs.add(dir);
256
+ }
257
+ return { declared: parsed.declared ? declared : null, candidates: [...dirs].sort() };
258
+ }
259
+
260
+ const MIGRATION_CANDIDATES_SHOWN = 6;
261
+
262
+ /** The step-2 remainder line about `migrations:` — adopt never asks it, so it always reports it. */
263
+ function migrationsStepText(m) {
264
+ const tail = 'project.schema.md `migrations`; `colab adopt` does not ask it, step 2';
265
+ if (m && m.declared && m.declared.length) {
266
+ const extra = m.candidates.length ? ` — still uncovered, check: ${listShort(m.candidates)}` : '';
267
+ return `\`migrations:\` declared (${m.declared.join(', ')})${extra} — ${tail}`;
268
+ }
269
+ if (m && m.candidates.length) {
270
+ return `Declare \`migrations:\` in .github/project.yml — candidate layouts outside database/migrations/ and prisma/migrations/: ${listShort(m.candidates)}. Until declared, the no-new-migrations gate cannot see them — ${tail}`;
271
+ }
272
+ return `Declare \`migrations:\` in .github/project.yml if this repo keeps migrations anywhere but database/migrations/ or prisma/migrations/ (none detected) — ${tail}`;
273
+ }
274
+
275
+ function listShort(items) {
276
+ const shown = items.slice(0, MIGRATION_CANDIDATES_SHOWN).join(', ');
277
+ return items.length > MIGRATION_CANDIDATES_SHOWN ? `${shown} (+${items.length - MIGRATION_CANDIDATES_SHOWN} more)` : shown;
278
+ }
279
+
280
+ /**
281
+ * §9's remainder, as data, not prose, so a caller (a report printer, or a future `handbook-sync`
282
+ * call site) does not grow its own paraphrase of these steps. Adopt writes the descriptor and
283
+ * nothing else (Boundary, #199's plan), so steps 3-9 are always listed.
284
+ *
285
+ * `ctx` (all optional, #449):
286
+ * migrations — `detectMigrationCandidates()`'s result; adds the step-2 `migrations:` line
287
+ * (absent ctx = the pre-#449 list, steps 3-9 only)
288
+ * fork — `{ remote, url, source }` when this repo tracks an upstream it does not own:
289
+ * step 5 becomes the append-only block instead of the thin-shell conversion
290
+ * (CONVENTIONS.md §9, *A fork of an upstream*)
291
+ * upstreamAgentFiles — on a fork, the upstream's own agent workflow, named for the precedence line
292
+ */
293
+ function remainingSteps(ctx = {}) {
294
+ const steps = [];
295
+ if (ctx.migrations) steps.push({ n: 2, text: migrationsStepText(ctx.migrations) });
296
+ steps.push(
297
+ { n: 3, text: 'Create the full label set (21 names) — `colab labels --ensure`, CONVENTIONS.md §9 step 3 (#206)' },
222
298
  { n: 4, text: 'Add the tier topic to the GitHub repo — `gh repo edit --add-topic tier-<b|c|a>`, step 4' },
223
- { n: 5, text: 'Make CLAUDE.md the thin shell — `@AGENTS.md` plus templates/repo-CLAUDE-block.md, repo prose in AGENTS.md (adopt writes both on a new repo, #417), step 5' },
299
+ );
300
+ if (ctx.fork) {
301
+ steps.push({ n: 5, text: `Fork of an upstream (${ctx.fork.source === 'flag' ? '--fork' : `remote "${ctx.fork.remote}"`}): do NOT make CLAUDE.md the thin shell — append templates/repo-CLAUDE-block.md at the END of the upstream's CLAUDE.md (create it only if upstream has none), record that append as a fork patch, leave AGENTS.md and the upstream prose untouched; CONVENTIONS.md §9 "A fork of an upstream", step 5` });
302
+ const agentFiles = ctx.upstreamAgentFiles || [];
303
+ if (agentFiles.length) {
304
+ steps.push({ n: 5, text: `Upstream ships its own agent workflow (${listShort(agentFiles)}): leave it in place, and say in the appended block that fork work runs code-start → code-wrap → code-ship, not that workflow — §9 "A fork of an upstream", step 5` });
305
+ }
306
+ } else {
307
+ steps.push({ n: 5, text: 'Make CLAUDE.md the thin shell — `@AGENTS.md` plus templates/repo-CLAUDE-block.md, repo prose in AGENTS.md (adopt writes both on a new repo, #417), step 5' });
308
+ }
309
+ steps.push(
224
310
  { n: 6, text: "Make sure CI meets §7's outcome — `colab template <name>`, step 6" },
225
311
  { n: 7, text: 'Register the repo — `colab register`, step 7' },
226
312
  { n: 8, text: 'Leave existing branches alone — nothing to do, step 8' },
227
313
  { n: 9, text: 'Do not create `dev` unless genuinely Tier A or Tier C — nothing to do, step 9' },
228
- ];
314
+ );
315
+ return steps;
229
316
  }
230
317
 
231
318
  // ---------------------------------------------------------------------- row state
@@ -321,6 +408,16 @@ function detect(io, extra = {}) {
321
408
  // from a remote's HEAD — tools/colab's adoptGitExtras() is the only place that computes it.
322
409
  const trunkSource = (extra && extra.trunkSource) || null;
323
410
 
411
+ // #449: a repo you own that tracks an upstream you don't. The CLI detects it (a remote named
412
+ // `upstream` whose URL differs from origin's) or takes `--fork`/`--no-fork`; null = not a fork.
413
+ const fork = (extra && extra.fork) || null;
414
+ const upstreamAgentFiles = fork ? detectUpstreamAgentFiles(io) : [];
415
+ // Only when the CLI handed over `git ls-files` — a pure-io caller without it gets no step-2 line
416
+ // rather than a false "none detected".
417
+ const migrations = extra && Array.isArray(extra.trackedFiles)
418
+ ? detectMigrationCandidates(cfg, extra.trackedFiles)
419
+ : null;
420
+
324
421
  return {
325
422
  descriptorExists: io.readFile('.github/project.yml') !== null,
326
423
  cfg,
@@ -335,7 +432,10 @@ function detect(io, extra = {}) {
335
432
  },
336
433
  legacyTierLetter,
337
434
  consequences,
338
- remaining: remainingSteps(),
435
+ fork,
436
+ upstreamAgentFiles,
437
+ migrations,
438
+ remaining: remainingSteps({ migrations, fork, upstreamAgentFiles }),
339
439
  };
340
440
  }
341
441
 
@@ -822,7 +922,7 @@ function renderDescriptor(rawText, entries) {
822
922
  * `tier` may be null (a shape with no legacy letter): the placeholder is then left for a human,
823
923
  * never guessed — the same rule deriveTier itself follows.
824
924
  */
825
- function renderClaudeShell(blockTemplate, { version, trunk, tier }) {
925
+ function renderClaudeShell(blockTemplate, { version, trunk, tier, importAgents = true }) {
826
926
  let block = String(blockTemplate).replace(/^\s*<!--[\s\S]*?-->\s*/, ''); // the paste note
827
927
  block = block.replace('<!-- colab-handbook @ <version> -->', `<!-- colab-handbook @ ${version} -->`);
828
928
  if (trunk) {
@@ -834,7 +934,10 @@ function renderClaudeShell(blockTemplate, { version, trunk, tier }) {
834
934
  // `<A = … · C = … · B = …>` → the one gloss that applies.
835
935
  block = block.replace(/<A = ([^·>]+?) · C = ([^·>]+?) · B = ([^>]+?)>/, (m, a, c, b) => ({ A: a, B: b, C: c })[tier] || m);
836
936
  }
837
- return `@AGENTS.md\n\n${block.replace(/\s*$/, '\n')}`;
937
+ // #449: a fork with no upstream AGENTS.md gets the block alone — no import of a file adopt
938
+ // must not create there.
939
+ const body = block.replace(/\s*$/, '\n');
940
+ return importAgents ? `@AGENTS.md\n\n${body}` : body;
838
941
  }
839
942
 
840
943
  /** The AGENTS.md stub written beside a new shell, only when no AGENTS.md exists. */
@@ -859,6 +962,8 @@ module.exports = {
859
962
  deriveTier,
860
963
  deriveConsequences,
861
964
  remainingSteps,
965
+ detectUpstreamAgentFiles,
966
+ detectMigrationCandidates,
862
967
  detect,
863
968
  // commit 2
864
969
  VALID_ROOM,
package/tools/lib/git.js CHANGED
@@ -695,6 +695,25 @@ function ghIssueListByLabel(repo, label, state, fields) {
695
695
  catch (_) { return null; }
696
696
  }
697
697
 
698
+ /**
699
+ * #448: the open issues carrying `label`, as numbers, read through the REST issues list — NOT
700
+ * search. `gh issue list --label` (ghIssueListByLabel above) is served by GraphQL `search(...)`,
701
+ * whose index can lag a burst of closes and answer "0 open" for a label still on an open issue;
702
+ * this endpoint reads the issues table directly. Pull requests share the endpoint and are dropped.
703
+ * Null on any failure — "could not read", never "none open", same contract as ghIssueListByLabel.
704
+ * Used as the confirming read before a `group:` label is deleted (group-labels.js
705
+ * teardownSpentGroupLabel).
706
+ */
707
+ function ghOpenIssueNumbersByLabel(repo, label) {
708
+ const r = ghApi(repo, [
709
+ '--method', 'GET', '--paginate', 'repos/{owner}/{repo}/issues',
710
+ '-f', `labels=${label}`, '-f', 'state=open', '-f', 'per_page=100',
711
+ '--jq', '.[] | select(.pull_request == null) | .number',
712
+ ]);
713
+ if (!r.ok) return null;
714
+ return String(r.stdout || '').split('\n').map((l) => l.trim()).filter(Boolean).map(Number);
715
+ }
716
+
698
717
  /**
699
718
  * `gh label delete <name> --yes` — returns {ok, stderr}. Deletes the LABEL OBJECT from the
700
719
  * repo's tracker, not one issue's use of it — every issue that carried it loses it. Callers
@@ -1050,7 +1069,7 @@ module.exports = {
1050
1069
  claimRemote, remoteHeads,
1051
1070
  worktreeList, worktreeListDetailed, resolveWorktreePathForBranch, gitFailureLine,
1052
1071
  dirtyTracked, dirtyUntracked, dirtyAny,
1053
- ghAvailable, ghState, ghIssueEdit, ghListLabels, ghAssignedIssues,
1072
+ ghAvailable, ghState, ghIssueEdit, ghListLabels, ghOpenIssueNumbersByLabel, ghAssignedIssues,
1054
1073
  ghCurrentLogin, ghIssueView, ghIssueComment, ghRunForSha, ghRunForCommit, ghRunsForCommit, ghRunsForRef, ghRunsAtCommit, ghRunForCommitAnyRef, commitTimeMs, ghRunsSince, summarizeRunsForCommit,
1055
1074
  ghRunJobCount, ghRunJobs,
1056
1075
  ghIssueListByLabel, ghLabelDelete, ghLabelCreate, ghListLabelsDetailed, ghLabelEditDescription,
@@ -115,6 +115,71 @@ function reportableLabels(verdicts) {
115
115
  return (verdicts || []).filter((v) => v && v.verdict !== 'mid-flight');
116
116
  }
117
117
 
118
+ /**
119
+ * #448: the second read before a destructive delete. Measured in an adopting repo: ship's (i)
120
+ * teardown deleted `group:<key>` while a fourth, deliberately-unshipped member still carried it
121
+ * OPEN — the open-member listing had come back empty 29 s after the squash closed the other three.
122
+ * That listing is `gh issue list --label`, which `gh` serves through GraphQL `search(...)`
123
+ * (verified with GH_DEBUG=api), and the search index lags the issues table: a burst of closes and
124
+ * label writes can leave it answering "0 open" for a label still on an open issue.
125
+ *
126
+ * `gh label delete` is repo-wide and cannot be undone per issue, so "0 open" from search alone is
127
+ * not enough to act on. The confirming read is the REST issues list (`ghOpenIssueNumbersByLabel`),
128
+ * which reads the issues table, not the index. The two failures are asymmetric exactly as
129
+ * isOpenMember's note says — keeping a spent label costs one stale picker entry until the next
130
+ * ship or `doctor --sync --prune`; deleting a live one strips a grouping from work in flight — so
131
+ * every case but "both reads agree on zero" keeps the label.
132
+ *
133
+ * @param {Array|null} searchOpen open members per the search-backed listing; null = could not read
134
+ * @param {Array|null} confirmOpen open member NUMBERS per the non-search read; null = could not read
135
+ * @returns {{action:'delete'|'keep', reason:string, open:number[]}}
136
+ * reason ∈ unread · open · unconfirmed · disagree · spent
137
+ */
138
+ function spentLabelDecision(searchOpen, confirmOpen) {
139
+ if (searchOpen === null || searchOpen === undefined) return { action: 'keep', reason: 'unread', open: [] };
140
+ if (Array.isArray(searchOpen) && searchOpen.length > 0) return { action: 'keep', reason: 'open', open: [] };
141
+ if (confirmOpen === null || confirmOpen === undefined || !Array.isArray(confirmOpen)) {
142
+ return { action: 'keep', reason: 'unconfirmed', open: [] };
143
+ }
144
+ if (confirmOpen.length > 0) {
145
+ const nums = confirmOpen.map((m) => (m && typeof m === 'object' ? m.number : m))
146
+ .filter((n) => n !== undefined && n !== null);
147
+ return { action: 'keep', reason: 'disagree', open: nums };
148
+ }
149
+ return { action: 'delete', reason: 'spent', open: [] };
150
+ }
151
+
152
+ /**
153
+ * The I/O shell around spentLabelDecision, with every call injected so the delete path is pinned by
154
+ * a test with no network (#448). `searchOpen` may be passed pre-read (doctor already has the
155
+ * membership from its classify pass) or as a function; `confirmOpen` and `deleteLabel` are always
156
+ * functions and are only CALLED when needed — the confirm read only when search said zero, the
157
+ * delete only when both reads agree.
158
+ *
159
+ * @returns {{action:'delete'|'keep', reason:string, open:number[], deleted:boolean, error:string|null}}
160
+ */
161
+ function teardownSpentGroupLabel(name, { searchOpen, confirmOpen, deleteLabel }) {
162
+ if (!isGroupLabel(name)) return { action: 'keep', reason: 'unread', open: [], deleted: false, error: null };
163
+ const s = typeof searchOpen === 'function' ? searchOpen(name) : searchOpen;
164
+ const needConfirm = Array.isArray(s) && s.length === 0;
165
+ const c = needConfirm ? confirmOpen(name) : null;
166
+ const d = spentLabelDecision(s, needConfirm ? c : null);
167
+ if (d.action !== 'delete') return { ...d, deleted: false, error: null };
168
+ const r = deleteLabel(name) || {};
169
+ return { ...d, deleted: !!r.ok, error: r.ok ? null : (r.stderr || 'gh label delete failed') };
170
+ }
171
+
172
+ /** One human line for a kept label — the CLI and its test read the same words. */
173
+ function keptReason(name, d) {
174
+ switch (d.reason) {
175
+ case 'unread': return `could not check membership of ${name} — left in place`;
176
+ case 'unconfirmed': return `${name} reads 0 open members by search but the confirming (non-search) read failed — left in place`;
177
+ case 'disagree': return `${name} reads 0 open members by search, but #${d.open.join(', #')} still carr${d.open.length === 1 ? 'ies' : 'y'} it open (non-search read) — left in place; the search index is lagging (#448)`;
178
+ default: return '';
179
+ }
180
+ }
181
+
118
182
  module.exports = {
119
183
  isOpenMember, classifyGroupLabel, classifyGroupLabels, deletableLabels, reportableLabels,
184
+ spentLabelDecision, teardownSpentGroupLabel, keptReason,
120
185
  };