@skitterbyte/skitterspec-jira 2.15.0 → 2.16.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/src/init.js CHANGED
@@ -6,7 +6,7 @@ const crypto = require('crypto')
6
6
  const { execFileSync } = require('child_process')
7
7
 
8
8
  const { ensureWorktreeDirTrusted } = require('./env/trust.js')
9
- const { ensureHooks } = require('./env/hooks.js')
9
+ const { ensureHooks, removeHooks } = require('./env/hooks.js')
10
10
  const { repoInfo, expandTokens } = require('./env/resolve.js')
11
11
  const { primaryAnchor } = require('./env/project.js')
12
12
  const { setProjectKeys } = require('./env/projectedit.js')
@@ -202,23 +202,56 @@ function detectRunner(dir, env = process.env) {
202
202
  return { runner: 'npx', rung: 'none' }
203
203
  }
204
204
 
205
- // Fill a command file's `{{exec}}` placeholders. Kept a pure function of
206
- // (content, dir) so `managedTargets` can compare against exactly what
207
- // `installCommands` would write — otherwise every install would hash as
205
+ // The npm package this code was published in, for the cannot-tell rung's
206
+ // `npx -p`. The workspace source (`packages/common`) is private and never
207
+ // published, so it answers with the base distribution — which is what a
208
+ // consumer of the base would fetch anyway.
209
+ function distributionPackage() {
210
+ try {
211
+ const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8'))
212
+ if (!pkg.private && typeof pkg.name === 'string') return pkg.name
213
+ } catch {
214
+ /* no readable package.json — fall through to the base */
215
+ }
216
+ return '@skitterbyte/skitterspec'
217
+ }
218
+
219
+ // Fill `{{exec}} <bin>` placeholders — in command files, which pre-execute the
220
+ // CLI, and in the skills, rules and setup docs that tell Claude to run it. Kept
221
+ // a pure function of (content, dir) so `managedTargets` can compare against
222
+ // exactly what an install would write — otherwise every install would hash as
208
223
  // customized on the next run.
209
224
  //
225
+ // NO RENDERED FORM MAY RESOLVE AN UNSCOPED NAME FROM THE REGISTRY. The bins
226
+ // (`skitterspec`, `skitterspec-<provider>`) are not npm package names: they
227
+ // 404 today, so anyone could publish one. A bare `npx skitterspec` resolves
228
+ // from `node_modules/.bin` while the install is there and FETCHES the stranger's
229
+ // package the moment it is not — a fresh worktree before its install, say. So
230
+ // the local `npx` rung gets `--no-install` (fail rather than fetch), and the
231
+ // cannot-tell rung names the scoped package outright with `-p`.
232
+ //
210
233
  // The token is consumed WITH its trailing space, so an empty runner leaves
211
- // `Bash(skitterspec …)` rather than `Bash( skitterspec …)`. The second pass
212
- // catches a bare `{{exec}}` in case a template ever lands without one.
213
- function renderCommand(content, dir) {
214
- const { runner } = detectRunner(dir)
215
- return content
216
- .split('{{exec}} ')
217
- .join(runner ? `${runner} ` : '')
218
- .split('{{exec}}')
219
- .join(runner)
234
+ // `Bash(skitterspec …)` rather than `Bash( skitterspec …)`.
235
+ const EXEC_RE = /\{\{exec\}\}( ?)([A-Za-z0-9._-]*)/g
236
+
237
+ function renderExec(content, dir, env = process.env) {
238
+ if (!content.includes('{{exec}}')) return content
239
+ const { runner, rung } = detectRunner(dir, env)
240
+ return content.replace(EXEC_RE, (_m, sp, bin) => {
241
+ if (rung === 'none') return bin ? `npx -p ${distributionPackage()} ${bin}` : 'npx'
242
+ const prefix = runner === 'npx' ? 'npx --no-install' : runner
243
+ if (!prefix) return bin
244
+ return `${prefix}${sp}${bin}`
245
+ })
220
246
  }
221
247
 
248
+ // The original name, kept because commands were the first thing rendered.
249
+ const renderCommand = renderExec
250
+
251
+ // Which managed files carry the token: markdown only. Hooks and JSON templates
252
+ // are copied byte for byte.
253
+ const renderable = (assetRel) => assetRel.endsWith('.md')
254
+
222
255
  // --- composed-assets guard -------------------------------------------------
223
256
  //
224
257
  // A source package's `assets/` is PRE-composition: `<!-- seam:NAME -->` is still
@@ -275,9 +308,16 @@ function assertComposedAssets() {
275
308
  const SPEC_MARKER_START = '<!-- skitterspec:start -->'
276
309
  const SPEC_MARKER_END = '<!-- skitterspec:end -->'
277
310
 
311
+ // `team` (the default: everything committed) or `local` (`init --local`: the
312
+ // managed files kept out of git, hooks in settings.local.json, the CLAUDE block
313
+ // in CLAUDE.local.md). Set once per run by `resolveScope`, and recorded in the
314
+ // manifest so a later `update` cannot write team-mode files into a local repo.
315
+ let scope = 'team'
316
+
278
317
  const report = { created: [], updated: [], skipped: [], refused: [], removed: [], customized: [], adopted: [], healed: [], warnings: [], suggestions: [] }
279
318
 
280
319
  function resetReport() {
320
+ scope = 'team'
281
321
  for (const k of Object.keys(report)) report[k].length = 0
282
322
  for (const k of Object.keys(writtenHashes)) delete writtenHashes[k]
283
323
  }
@@ -338,7 +378,7 @@ function sha1(content) {
338
378
  // the bundled content that ships in this distribution's assets.
339
379
  function managedTargets(dir) {
340
380
  const out = []
341
- const add = (assetRel, targetAbs, render = (c) => c) =>
381
+ const add = (assetRel, targetAbs, render = renderable(assetRel) ? renderExec : (c) => c) =>
342
382
  out.push({
343
383
  relPath: rel(dir, targetAbs),
344
384
  abs: targetAbs,
@@ -346,7 +386,7 @@ function managedTargets(dir) {
346
386
  })
347
387
  for (const name of SKILLS) add(path.join('skills', name, 'SKILL.md'), path.join(dir, '.claude', 'skills', name, 'SKILL.md'))
348
388
  for (const name of COMMANDS)
349
- add(path.join('commands', name), path.join(dir, '.claude', 'commands', name), renderCommand)
389
+ add(path.join('commands', name), path.join(dir, '.claude', 'commands', name))
350
390
  for (const name of RULES) add(path.join('rules', name), path.join(dir, '.claude', 'rules', name))
351
391
  for (const name of HOOKS) add(path.join('hooks', name), path.join(dir, '.claude', 'hooks', name))
352
392
  for (const asset of CORE_FILES) add(asset, path.join(dir, 'specs', '.core', path.basename(asset)))
@@ -381,20 +421,24 @@ function readManifest(dir) {
381
421
  version: parsed.version || MANIFEST_VERSION,
382
422
  files,
383
423
  baselined: Object.keys(files).length > 0,
424
+ // Absent means team: every manifest written before `--local` existed
425
+ // reads exactly as it did.
426
+ scope: parsed.scope === 'local' ? 'local' : 'team',
384
427
  }
385
428
  }
386
429
  } catch {
387
430
  /* missing or malformed → empty baseline */
388
431
  }
389
- return { version: MANIFEST_VERSION, files: {}, baselined: false }
432
+ return { version: MANIFEST_VERSION, files: {}, baselined: false, scope: 'team' }
390
433
  }
391
434
 
392
- function writeManifest(dir, files) {
435
+ function writeManifest(dir, files, { local = false } = {}) {
393
436
  const target = path.join(dir, MANIFEST_FILE)
394
437
  ensureDir(path.dirname(target))
395
438
  const sorted = {}
396
439
  for (const k of Object.keys(files).sort()) sorted[k] = files[k]
397
- fs.writeFileSync(target, JSON.stringify({ version: MANIFEST_VERSION, files: sorted }, null, 2) + '\n')
440
+ const body = local ? { version: MANIFEST_VERSION, scope: 'local', files: sorted } : { version: MANIFEST_VERSION, files: sorted }
441
+ fs.writeFileSync(target, JSON.stringify(body, null, 2) + '\n')
398
442
  }
399
443
 
400
444
  // Classify a managed file against the manifest baseline.
@@ -466,7 +510,7 @@ function flushManifest(dir) {
466
510
  for (const relPath of Object.keys(next)) {
467
511
  if (!fs.existsSync(path.join(dir, relPath))) delete next[relPath] // prune gone
468
512
  }
469
- writeManifest(dir, next)
513
+ writeManifest(dir, next, { local: scope === 'local' })
470
514
  }
471
515
 
472
516
  function writeFile(dir, target, content, { force }) {
@@ -526,7 +570,8 @@ function writeFile(dir, target, content, { force }) {
526
570
  }
527
571
 
528
572
  function copyAsset(dir, assetRelPath, targetAbs, opts) {
529
- const content = fs.readFileSync(path.join(ASSETS, assetRelPath), 'utf8')
573
+ const raw = fs.readFileSync(path.join(ASSETS, assetRelPath), 'utf8')
574
+ const content = renderable(assetRelPath) ? renderExec(raw, dir) : raw
530
575
  writeFile(dir, targetAbs, content, opts)
531
576
  }
532
577
 
@@ -543,11 +588,7 @@ function installSkills(dir, opts) {
543
588
 
544
589
  function installCommands(dir, opts) {
545
590
  for (const name of COMMANDS) {
546
- const content = renderCommand(
547
- fs.readFileSync(path.join(ASSETS, 'commands', name), 'utf8'),
548
- dir,
549
- )
550
- writeFile(dir, path.join(dir, '.claude', 'commands', name), content, opts)
591
+ copyAsset(dir, path.join('commands', name), path.join(dir, '.claude', 'commands', name), opts)
551
592
  }
552
593
 
553
594
  // ONLY on the cannot-tell rung, and it warns rather than refusing: `init` has
@@ -557,8 +598,8 @@ function installCommands(dir, opts) {
557
598
  if (COMMANDS.length && detectRunner(dir).rung === 'none') {
558
599
  report.warnings.push(
559
600
  `the skitterspec CLI could not be found here, so the ${COMMANDS.length} slash ` +
560
- 'command(s) were written to call `npx skitterspec`, which will fail — ' +
561
- 'install it (npm i -g @skitterbyte/skitterspec, or add it as a dev ' +
601
+ `command(s) were written to fetch it on every run (\`npx -p ${distributionPackage()}\`) — ` +
602
+ `install it (npm i -g ${distributionPackage()}, or add it as a dev ` +
562
603
  'dependency) and re-run `skitterspec update` to rewrite them',
563
604
  )
564
605
  }
@@ -584,18 +625,17 @@ function registerReviewGateHook(dir) {
584
625
  // "hooks", plural, because two ship now — the review gate and the main guard.
585
626
  // The label names the file and the subject rather than one script, so adding a
586
627
  // third does not leave a report that undercounts what it wrote.
587
- const label = '.claude/settings.json (skitterspec hooks)'
628
+ const file = scope === 'local' ? '.claude/settings.local.json' : '.claude/settings.json'
629
+ const label = `${file} (skitterspec hooks)`
588
630
  let res
589
631
  try {
590
- res = ensureHooks(dir)
632
+ res = ensureHooks(dir, { local: scope === 'local' })
591
633
  } catch {
592
- report.warnings.push('could not write .claude/settings.json — skitterspec hooks not registered')
634
+ report.warnings.push(`could not write ${file} — skitterspec hooks not registered`)
593
635
  return
594
636
  }
595
637
  if (res.reason === 'malformed') {
596
- report.warnings.push(
597
- '.claude/settings.json is not valid JSON — did not register the skitterspec hooks',
598
- )
638
+ report.warnings.push(`${file} is not valid JSON — did not register the skitterspec hooks`)
599
639
  } else if (res.reason === 'created') {
600
640
  report.created.push(label)
601
641
  } else if (res.reason === 'added') {
@@ -605,9 +645,9 @@ function registerReviewGateHook(dir) {
605
645
  // that: rewriting the registered path and then reporting "already
606
646
  // registered" — a run that acts and says it did not, which is the shape of
607
647
  // the bug this whole change exists to fix.
608
- report.updated.push('.claude/settings.json (skitterspec hooks repointed at the renamed script)')
648
+ report.updated.push(`${file} (skitterspec hooks repointed at the renamed script)`)
609
649
  } else {
610
- report.skipped.push('.claude/settings.json (skitterspec hooks already registered)')
650
+ report.skipped.push(`${file} (skitterspec hooks already registered)`)
611
651
  }
612
652
  }
613
653
 
@@ -794,8 +834,16 @@ function trustWorktreeRoot(dir) {
794
834
  // that someone stripped it deliberately (`stripClaudeMdSection` exists and is
795
835
  // reachable from `reset`). Neither is a fault, so both answer `not installed`
796
836
  // and neither is reported as a problem.
837
+ // The file the CLAUDE block lives in: CLAUDE.md, or CLAUDE.local.md for a local
838
+ // install. Read from the manifest when no run has set the scope, so `--check`
839
+ // looks where the block actually is.
840
+ function claudeMdName(dir) {
841
+ const local = scope === 'local' || readManifest(dir).scope === 'local'
842
+ return local ? 'CLAUDE.local.md' : 'CLAUDE.md'
843
+ }
844
+
797
845
  function claudeMdSectionState(dir) {
798
- const target = path.join(dir, 'CLAUDE.md')
846
+ const target = path.join(dir, claudeMdName(dir))
799
847
  if (!fs.existsSync(target)) return 'not installed'
800
848
  const existing = fs.readFileSync(target, 'utf8')
801
849
  if (!existing.includes(SPEC_MARKER_START) || !existing.includes(SPEC_MARKER_END)) {
@@ -832,7 +880,7 @@ function checkSync(dir, { claudeMd = true, log = console.log } = {}) {
832
880
  // report people learn to skim, and then the one line that mattered is missed.
833
881
  if (section === 'differs') {
834
882
  rows.push([
835
- 'CLAUDE.md (spec workflow section)',
883
+ `${claudeMdName(dir)} (spec workflow section)`,
836
884
  'differs from the shipped one — `update` would replace it (it is a copy, so this is either your edit or an out-of-date one)',
837
885
  ])
838
886
  }
@@ -847,11 +895,12 @@ function checkSync(dir, { claudeMd = true, log = console.log } = {}) {
847
895
  function installClaudeMd(dir, { mode }) {
848
896
  const section = fs.readFileSync(path.join(ASSETS, 'claude-md-section.md'), 'utf8').trim()
849
897
  const block = `${SPEC_MARKER_START}\n${section}\n${SPEC_MARKER_END}\n`
850
- const target = path.join(dir, 'CLAUDE.md')
898
+ const name = claudeMdName(dir)
899
+ const target = path.join(dir, name)
851
900
 
852
901
  if (!fs.existsSync(target)) {
853
- fs.writeFileSync(target, `# ${path.basename(dir)}\n\n${block}`)
854
- report.created.push('CLAUDE.md')
902
+ fs.writeFileSync(target, name === 'CLAUDE.md' ? `# ${path.basename(dir)}\n\n${block}` : block)
903
+ report.created.push(name)
855
904
  return
856
905
  }
857
906
 
@@ -859,28 +908,28 @@ function installClaudeMd(dir, { mode }) {
859
908
 
860
909
  if (existing.includes(SPEC_MARKER_START) && existing.includes(SPEC_MARKER_END)) {
861
910
  if (mode !== 'update') {
862
- report.skipped.push('CLAUDE.md (spec workflow already present)')
911
+ report.skipped.push(`${name} (spec workflow already present)`)
863
912
  return
864
913
  }
865
914
  const re = new RegExp(`${SPEC_MARKER_START}[\\s\\S]*?${SPEC_MARKER_END}\\n?`)
866
915
  const next = existing.replace(re, block)
867
916
  if (next === existing) {
868
- report.skipped.push('CLAUDE.md')
917
+ report.skipped.push(`${name}`)
869
918
  } else {
870
919
  fs.writeFileSync(target, next)
871
- report.updated.push('CLAUDE.md (spec workflow section)')
920
+ report.updated.push(`${name} (spec workflow section)`)
872
921
  }
873
922
  return
874
923
  }
875
924
 
876
925
  if (/^##\s+Spec workflow/m.test(existing)) {
877
- report.skipped.push('CLAUDE.md (has a manual "Spec workflow" section — left alone)')
926
+ report.skipped.push(`${name} (has a manual "Spec workflow" section — left alone)`)
878
927
  return
879
928
  }
880
929
 
881
930
  const sep = existing.endsWith('\n') ? '\n' : '\n\n'
882
931
  fs.writeFileSync(target, `${existing}${sep}${block}`)
883
- report.updated.push('CLAUDE.md (appended spec workflow section)')
932
+ report.updated.push(`${name} (appended spec workflow section)`)
884
933
  }
885
934
 
886
935
  // --- detection, resync, reset (safe re-run) ---------------------------------
@@ -895,8 +944,10 @@ function installClaudeMd(dir, { mode }) {
895
944
  function isExistingSetup(dir) {
896
945
  if (managedTargets(dir).some((t) => fs.existsSync(t.abs))) return true
897
946
  if (SPEC_FOLDERS.some((f) => fs.existsSync(path.join(dir, 'specs', f)))) return true
898
- const claude = path.join(dir, 'CLAUDE.md')
899
- return fs.existsSync(claude) && fs.readFileSync(claude, 'utf8').includes(SPEC_MARKER_START)
947
+ return ['CLAUDE.md', 'CLAUDE.local.md'].some((name) => {
948
+ const claude = path.join(dir, name)
949
+ return fs.existsSync(claude) && fs.readFileSync(claude, 'utf8').includes(SPEC_MARKER_START)
950
+ })
900
951
  }
901
952
 
902
953
  // RESYNC: bring managed files to the latest bundled version WITHOUT clobbering
@@ -935,9 +986,11 @@ function resyncManagedFile(dir, target, manifest, force) {
935
986
  write('updated')
936
987
  }
937
988
 
938
- function resync(dir, { force = false, claudeMd = true, diff = false } = {}) {
989
+ function resync(dir, { force = false, claudeMd = true, diff = false, local = false } = {}) {
939
990
  if (!fs.existsSync(dir)) throw new Error(`target dir does not exist: ${dir}`)
940
991
  resetReport()
992
+ resolveScope(dir, local)
993
+ if (scope === 'local') convertCommitted(dir)
941
994
  const manifest = readManifest(dir)
942
995
  for (const t of managedTargets(dir)) resyncManagedFile(dir, t, manifest, force)
943
996
  installFolders(dir)
@@ -955,6 +1008,7 @@ function resync(dir, { force = false, claudeMd = true, diff = false } = {}) {
955
1008
  if (claudeMd) installClaudeMd(dir, { mode: 'update' })
956
1009
  suggestReleaseWith(dir)
957
1010
  flushManifest(dir)
1011
+ if (scope === 'local') writeLocalExcludes(dir)
958
1012
  printReport(dir, 'resync', { diff })
959
1013
  }
960
1014
 
@@ -1145,9 +1199,186 @@ function suggestReleaseWith(dir) {
1145
1199
  )
1146
1200
  }
1147
1201
 
1148
- async function init({ dir, force, claudeMd, mode, isolation, workspaceMode, gating, project }) {
1202
+ // Decide this run's scope. A local manifest stays local whether or not the
1203
+ // flag is passed — a later `update`, or an `init` without it, must not start
1204
+ // writing hooks into the committed settings of a repo set up to keep them out.
1205
+ // Switching a local install back to team is out of scope and says so.
1206
+ function resolveScope(dir, local) {
1207
+ const recorded = readManifest(dir).scope
1208
+ scope = local || recorded === 'local' ? 'local' : 'team'
1209
+ if (!local && recorded === 'local') report.skipped.push('local install (recorded in the manifest) — kept local')
1210
+ if (local && recorded !== 'local') {
1211
+ report.warnings.push(
1212
+ '--local keeps skitterspec on this machine: teammates get none of its skills, rules ' +
1213
+ 'or hooks. Use it where nobody else here uses skitterspec — never for a team that ' +
1214
+ 'shares the hooks and rules as policy',
1215
+ )
1216
+ }
1217
+ }
1218
+
1219
+ // The paths a local install keeps out of git: every managed file, the block's
1220
+ // file, the per-machine settings, the manifest and the review store. Listed per
1221
+ // PATH rather than per directory, so a teammate's own `.claude/skills/foo` is
1222
+ // untouched.
1223
+ //
1224
+ // A skill is listed as its DIRECTORY (no trailing slash), because a worktree
1225
+ // gets it seeded as one symlink — which git sees as a file at that path, and a
1226
+ // `SKILL.md` entry would not match it.
1227
+ function localManagedPaths(dir) {
1228
+ const paths = managedTargets(dir)
1229
+ .map((t) => t.relPath)
1230
+ .filter((p) => !p.startsWith('specs/'))
1231
+ .map((p) => (p.startsWith('.claude/skills/') ? path.posix.dirname(p) : p))
1232
+ return [...new Set(paths)]
1233
+ }
1234
+
1235
+ function localExcludes(dir) {
1236
+ return [
1237
+ ...localManagedPaths(dir),
1238
+ 'CLAUDE.local.md',
1239
+ '.claude/settings.local.json',
1240
+ MANIFEST_FILE.replace(/\\/g, '/'),
1241
+ '.spec-env/',
1242
+ ]
1243
+ }
1244
+
1245
+ // What `spec-env bootstrap` seeds into a local install's worktrees: the managed
1246
+ // paths plus the two per-machine files. A worktree is a fresh checkout, and
1247
+ // git carries none of it there. Empty for a team install, which git carries.
1248
+ function localSeedFiles(dir) {
1249
+ if (readManifest(dir).scope !== 'local') return []
1250
+ return [...localManagedPaths(dir), '.claude/settings.local.json', 'CLAUDE.local.md']
1251
+ }
1252
+
1253
+ const EXCLUDE_START = '# >>> skitterspec (local install)'
1254
+ const EXCLUDE_END = '# <<< skitterspec'
1255
+
1256
+ // Write the managed block into `.git/info/exclude` — never `.gitignore`, which
1257
+ // is itself a committed change. The common dir, so it covers every worktree.
1258
+ // Entries carry the install folder's prefix when it sits below the git root.
1259
+ // Not a git repo, or git unreachable: warn and write nothing.
1260
+ function writeLocalExcludes(dir) {
1261
+ let commonDir, prefix
1262
+ try {
1263
+ const git = (...args) => execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()
1264
+ commonDir = path.resolve(dir, git('rev-parse', '--git-common-dir'))
1265
+ prefix = git('rev-parse', '--show-prefix')
1266
+ } catch {
1267
+ report.warnings.push('not a git repository — nothing excluded; the local install is not hidden from git')
1268
+ return
1269
+ }
1270
+ const file = path.join(commonDir, 'info', 'exclude')
1271
+ const lines = [...new Set(localExcludes(dir))].map((p) => `/${prefix}${p}`)
1272
+ const block = [EXCLUDE_START, ...lines, EXCLUDE_END].join('\n') + '\n'
1273
+ let existing = ''
1274
+ try {
1275
+ existing = fs.readFileSync(file, 'utf8')
1276
+ } catch {
1277
+ /* no exclude file yet */
1278
+ }
1279
+ const start = existing.indexOf(EXCLUDE_START)
1280
+ const end = existing.indexOf(EXCLUDE_END, start)
1281
+ const next =
1282
+ start !== -1 && end !== -1
1283
+ ? existing.slice(0, start) + block + existing.slice(end + EXCLUDE_END.length).replace(/^\n/, '')
1284
+ : existing + (existing && !existing.endsWith('\n') ? '\n' : '') + block
1285
+ if (next === existing) return report.skipped.push('.git/info/exclude (skitterspec block)')
1286
+ ensureDir(path.dirname(file))
1287
+ fs.writeFileSync(file, next)
1288
+ report.updated.push('.git/info/exclude (skitterspec block)')
1289
+ }
1290
+
1291
+ // Convert a COMMITTED (team) install into a local one, in place. Every step
1292
+ // leaves the files on disk and stages or edits only; it never commits — the
1293
+ // operator commits the removal, and teammates who pull it lose the install.
1294
+ //
1295
+ // - managed paths git tracks → `git rm --cached` (staged, file kept)
1296
+ // - our hooks in settings.json → removed per hook; ensureHooks then adds
1297
+ // them to settings.local.json
1298
+ // - the CLAUDE.md section → moved ONLY when it carries the markers. A
1299
+ // markerless "Spec workflow" heading is someone's section, or an older
1300
+ // install's: reported, never bounded by guesswork
1301
+ // - a skitterspec dependency in package.json → reported, never edited
1302
+ //
1303
+ // Quiet on a repo with nothing committed: every step finds nothing.
1304
+ function convertCommitted(dir) {
1305
+ const git = (...args) =>
1306
+ execFileSync('git', ['-C', dir, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })
1307
+ let tracked
1308
+ try {
1309
+ const candidates = [...new Set(localExcludes(dir))].filter((p) => !p.endsWith('/'))
1310
+ tracked = git('ls-files', '--', ...candidates).split('\n').filter(Boolean)
1311
+ } catch {
1312
+ return // not a git repo — writeLocalExcludes says so
1313
+ }
1314
+ let staged = tracked.length > 0
1315
+ if (tracked.length) {
1316
+ git('rm', '--cached', '-q', '--', ...tracked)
1317
+ report.updated.push(`git index (${tracked.length} managed file(s) untracked — kept on disk)`)
1318
+ }
1319
+
1320
+ const hooks = removeHooks(dir)
1321
+ if (hooks.reason === 'malformed') {
1322
+ report.warnings.push('.claude/settings.json is not valid JSON — skitterspec hooks left in it; remove them by hand')
1323
+ } else if (hooks.reason === 'removed') {
1324
+ if (hooks.emptied) {
1325
+ fs.unlinkSync(path.join(dir, '.claude', 'settings.json'))
1326
+ // Stage the deletion too, so the conversion is one thing to commit.
1327
+ try {
1328
+ git('rm', '--cached', '-q', '--ignore-unmatch', '--', '.claude/settings.json')
1329
+ } catch {
1330
+ /* untracked settings — nothing to stage */
1331
+ }
1332
+ report.removed.push('.claude/settings.json (held only skitterspec hooks)')
1333
+ } else report.updated.push(`.claude/settings.json (${hooks.removed} skitterspec hook(s) moved to settings.local.json)`)
1334
+ staged = true
1335
+ }
1336
+
1337
+ const claude = path.join(dir, 'CLAUDE.md')
1338
+ if (fs.existsSync(claude)) {
1339
+ const text = fs.readFileSync(claude, 'utf8')
1340
+ if (text.includes(SPEC_MARKER_START) && text.includes(SPEC_MARKER_END)) {
1341
+ const re = new RegExp(`\\n*${SPEC_MARKER_START}[\\s\\S]*?${SPEC_MARKER_END}\\n?`)
1342
+ fs.writeFileSync(claude, text.replace(re, '\n'))
1343
+ report.updated.push('CLAUDE.md (spec workflow section moved to CLAUDE.local.md)')
1344
+ staged = true
1345
+ } else {
1346
+ const line = text.split('\n').findIndex((l) => /^##\s+Spec workflow/.test(l))
1347
+ if (line !== -1) {
1348
+ report.warnings.push(
1349
+ `CLAUDE.md:${line + 1} has a "Spec workflow" section with no skitterspec markers, so it was ` +
1350
+ 'not moved — move it to CLAUDE.local.md by hand if it is the skitterspec block',
1351
+ )
1352
+ }
1353
+ }
1354
+ }
1355
+
1356
+ try {
1357
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'))
1358
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies }
1359
+ const ours = Object.keys(deps).filter((n) => n.startsWith('@skitterbyte/skitterspec'))
1360
+ for (const name of ours) {
1361
+ report.suggestions.push(
1362
+ `package.json lists ${name} — left as it is. To keep it out of the repo too, ` +
1363
+ `remove it and install it globally (npm i -g ${name}), then re-run \`skitterspec update\``,
1364
+ )
1365
+ }
1366
+ } catch {
1367
+ /* no package.json, or unreadable — nothing to say */
1368
+ }
1369
+
1370
+ if (staged) {
1371
+ report.suggestions.push(
1372
+ 'the conversion is staged, not committed — commit it (/commit) and teammates who pull it lose the install',
1373
+ )
1374
+ }
1375
+ }
1376
+
1377
+ async function init({ dir, force, claudeMd, mode, isolation, workspaceMode, gating, project, local = false }) {
1149
1378
  if (!fs.existsSync(dir)) throw new Error(`target dir does not exist: ${dir}`)
1150
1379
  resetReport()
1380
+ resolveScope(dir, local)
1381
+ if (scope === 'local') convertCommitted(dir)
1151
1382
 
1152
1383
  installSkills(dir, { force })
1153
1384
  installCommands(dir, { force })
@@ -1165,6 +1396,7 @@ async function init({ dir, force, claudeMd, mode, isolation, workspaceMode, gati
1165
1396
  // Record what we wrote (and migrate a pre-manifest repo) so a later resync can
1166
1397
  // tell our files from the user's.
1167
1398
  flushManifest(dir)
1399
+ if (scope === 'local') writeLocalExcludes(dir)
1168
1400
 
1169
1401
  printReport(dir, mode)
1170
1402
  }
@@ -1195,4 +1427,10 @@ module.exports = {
1195
1427
  detectPackageManager,
1196
1428
  detectRunner,
1197
1429
  renderCommand,
1430
+ renderExec,
1431
+ distributionPackage,
1432
+ localExcludes,
1433
+ localSeedFiles,
1434
+ EXCLUDE_START,
1435
+ EXCLUDE_END,
1198
1436
  }
package/src/tada/todo.js CHANGED
@@ -96,7 +96,7 @@ function lastPrompt(g) {
96
96
  * - `gates` `{ [spec]: gateState(...) }`; a missing or `unknown` state is
97
97
  * cannot-tell, and says nothing
98
98
  */
99
- function blockersFrom({ specs, passes = [], gates = {} }) {
99
+ function blockersFrom({ specs, passes = [], gates = {}, parked = {} }) {
100
100
  const want = new Set(specs)
101
101
  const out = []
102
102
  for (const p of passes) {
@@ -106,6 +106,13 @@ function blockersFrom({ specs, passes = [], gates = {} }) {
106
106
  const g = gates[spec]
107
107
  if (g && g.state === 'armed') out.push({ spec, kind: 'gate', phase: g.gate ? g.gate.phase : null })
108
108
  }
109
+ // A spec parked on something outside the repo (feat-spec-resume): the line
110
+ // that holds its next build, from `spec-env resume`'s `blockingNext`. A wait
111
+ // planned for a later phase holds nothing yet and is not listed.
112
+ for (const spec of specs) {
113
+ const b = parked[spec]
114
+ if (b) out.push({ spec, kind: 'parked', where: b.where, text: b.text, until: b.until })
115
+ }
109
116
  return out
110
117
  }
111
118
 
@@ -118,11 +125,11 @@ function blockersFrom({ specs, passes = [], gates = {} }) {
118
125
  * @param {string[]} specs its in-flight spec names
119
126
  * @param {boolean} [required] `review.required`; false opts the gates out
120
127
  */
121
- function readBlockers(reviews, specs, required) {
122
- if (!fs.existsSync(reviews)) return []
128
+ function readBlockers(reviews, specs, required, parked = {}) {
129
+ if (!fs.existsSync(reviews)) return blockersFrom({ specs, parked })
123
130
  const gates = {}
124
131
  for (const spec of specs) gates[spec] = gateState({ ...readGate(path.join(reviews, `${spec}.html`), spec), required })
125
- return blockersFrom({ specs, passes: waitingPasses(reviews).passes, gates })
132
+ return blockersFrom({ specs, passes: waitingPasses(reviews).passes, gates, parked })
126
133
  }
127
134
 
128
135
  /**
@@ -211,6 +218,14 @@ const ageText = (at, now) => {
211
218
  }
212
219
 
213
220
  function blockedText(b, now) {
221
+ if (b.kind === 'parked') {
222
+ const where = b.where === 'spec' ? '' : ` (phase ${b.where})`
223
+ // Compared as local calendar days: a wait "until" a date has run out once
224
+ // that day has begun, not at UTC midnight.
225
+ const due = b.until && b.until <= localDay(now)
226
+ const until = b.until ? (due ? ` · until ${b.until}, now passed — ready to resume` : ` · until ${b.until}`) : ''
227
+ return `${b.spec} — parked${where}: ${b.text}${until} · /spec-resume ${b.spec}`
228
+ }
214
229
  if (b.kind === 'gate') return `${b.spec} — gate armed${b.phase ? `, phase ${b.phase}` : ''}: a verdict is owed`
215
230
  return `${b.spec} — ${b.verdict || 'a'} verdict waiting (${b.code}${b.at ? ageText(b.at, now) : ''})`
216
231
  }
@@ -21,7 +21,10 @@ const {
21
21
  findSpecFolder,
22
22
  resolveSpec,
23
23
  liveWorktreePaths,
24
+ resolveBaseBranch,
24
25
  } = require('../../../env/resolve.js')
26
+ const { specBranchDocs } = require('../../../env/specbranches.js')
27
+ const { frontmatterField } = require('../../../env/resume.js')
25
28
  const { loadEnvConfig } = require('../../../env/config.js')
26
29
  const { primaryAnchor, attachProject, projectIn } = require('../../../env/project.js')
27
30
  const { readSnapshot, parseFrontmatter, lintPhases, fieldsOf, projectionOf, compareStored, comparableDescription } = require('../../sync-core')
@@ -180,6 +183,48 @@ function makeSpecHelpers({ program = 'spec-sync' } = {}) {
180
183
  return [...byName.values()].sort((a, b) => a.spec.localeCompare(b.spec))
181
184
  }
182
185
 
186
+ // `listSpecs`, plus the specs that exist ONLY on their own branch
187
+ // (`source: 'branch'`, with the `ref` they were read from). Under
188
+ // `land.specDocs: "branch"` an in-flight spec has no copy on base and, on a
189
+ // machine that never provisioned it, no worktree either — so a ticket that
190
+ // already has a spec read as unadopted, and `/spec #N` began a second one.
191
+ // Read off local then remote-tracking spec branches, never fetched.
192
+ //
193
+ // WHAT WOULD FOOL THIS: a remote that was never fetched (its specs are absent
194
+ // — the old answer, never a wrong one), and a spec branch renamed away from
195
+ // `branch.pattern` (not found). Anything unreadable adds nothing.
196
+ function listSpecsWithBranches(dir, config) {
197
+ const live = listSpecs(dir, config)
198
+ const git = (args) => {
199
+ try {
200
+ return execFileSync('git', ['-C', dir, ...args], { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()
201
+ } catch {
202
+ return null
203
+ }
204
+ }
205
+ let docs
206
+ try {
207
+ const anchor = primaryAnchor(dir, git)
208
+ const env = loadEnvConfig(anchor.dir || dir)
209
+ if (!env.present) return live
210
+ docs = specBranchDocs(git, env.config, resolveBaseBranch(env.config, git))
211
+ } catch {
212
+ return live
213
+ }
214
+ const field = fieldsOf(config).identifier
215
+ const seen = new Set(live.map((s) => s.spec))
216
+ const extra = docs
217
+ .filter((d) => !seen.has(d.folder))
218
+ .map((d) => ({
219
+ spec: d.folder,
220
+ bucket: d.bucket,
221
+ identifier: frontmatterField(d.overview, field),
222
+ source: 'branch',
223
+ ref: d.ref.replace(/^refs\/(heads|remotes)\//, ''),
224
+ }))
225
+ return [...live, ...extra].sort((a, b) => a.spec.localeCompare(b.spec))
226
+ }
227
+
183
228
  // Resolve a spec argument to its folder, or null with a message on stdout.
184
229
  // EVERY failure path here must print and EVERY caller must return a non-zero
185
230
  // code: a push skill checks $? before it applies a plan, so a resolve failure
@@ -253,7 +298,7 @@ function makeSpecHelpers({ program = 'spec-sync' } = {}) {
253
298
  return lines
254
299
  }
255
300
 
256
- return { resolveSnapshotDir, specIdentifier, linkedIdentifier, listSpecs, listSpecsLive, resolveOrExit, warningLines, warnToErr, verifyLines }
301
+ return { resolveSnapshotDir, specIdentifier, linkedIdentifier, listSpecs, listSpecsLive, listSpecsWithBranches, resolveOrExit, warningLines, warnToErr, verifyLines }
257
302
  }
258
303
 
259
304
  module.exports = { makeSpecHelpers }