rvlib-shipkit 2.24.0 → 2.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/package.json +2 -2
  3. package/src/agent-time/hooks.ts +329 -0
  4. package/src/agent-time/live.ts +153 -0
  5. package/src/agent-time/render.ts +14 -2
  6. package/src/agent-time/report.ts +56 -4
  7. package/src/agent-time/store.ts +59 -5
  8. package/src/annex/offload.ts +16 -7
  9. package/src/check.ts +3 -1
  10. package/src/checks/SK004-gitignore-policy.check.ts +32 -11
  11. package/src/checks/SK027-agent-wiki-links.check.ts +1 -1
  12. package/src/checks/SK033-global-contribution.check.ts +1 -1
  13. package/src/checks/SK036-draft-media-size.check.ts +1 -1
  14. package/src/checks/SK040-release-words.check.ts +1 -1
  15. package/src/checks/SK042-post-kinds.check.ts +1 -1
  16. package/src/checks/SK045-slow-hooks.check.ts +47 -0
  17. package/src/checks/SK046-hook-records.check.ts +76 -0
  18. package/src/cli/cmd_Annex.ts +12 -7
  19. package/src/cli/cmd_Assets.ts +5 -5
  20. package/src/cli/cmd_Backup.ts +14 -6
  21. package/src/cli/cmd_Capacity.ts +10 -6
  22. package/src/cli/cmd_Checks.ts +12 -1
  23. package/src/cli/cmd_Ci.ts +2 -2
  24. package/src/cli/cmd_Commands.ts +11 -2
  25. package/src/cli/cmd_ConfigKeys.ts +17 -0
  26. package/src/cli/cmd_Home.ts +1 -1
  27. package/src/cli/cmd_Keys.ts +4 -1
  28. package/src/cli/cmd_Lanes.ts +35 -0
  29. package/src/cli/cmd_Mv.ts +6 -7
  30. package/src/cli/cmd_Rec.ts +22 -7
  31. package/src/cli/cmd_Releases.ts +30 -0
  32. package/src/cli/cmd_Review.ts +130 -43
  33. package/src/cli/cmd_Shot.ts +15 -4
  34. package/src/cli/cmd_Status.ts +6 -5
  35. package/src/cli/cmd_Time.ts +18 -6
  36. package/src/cli/cmd_Veille.ts +10 -6
  37. package/src/cli/family-help.ts +136 -0
  38. package/src/cli/family-pages.ts +0 -19
  39. package/src/cli/kit/calls.ts +35 -0
  40. package/src/cli/kit/project-cli.ts +2 -12
  41. package/src/cli/registry.ts +41 -7
  42. package/src/cli.ts +8 -4
  43. package/src/commands/runner.ts +5 -1
  44. package/src/core/capacity.ts +89 -33
  45. package/src/core/check-runner.ts +5 -1
  46. package/src/core/floor-resolve.ts +6 -2
  47. package/src/core/floor.ts +6 -2
  48. package/src/core/history-files.ts +22 -0
  49. package/src/core/jobs.ts +35 -16
  50. package/src/core/layout.ts +2 -2
  51. package/src/core/nearest.ts +16 -0
  52. package/src/core/remove-tree.ts +19 -0
  53. package/src/core/runs.ts +12 -3
  54. package/src/core/signal-name.ts +6 -0
  55. package/src/core/throwaway-worktree.ts +22 -4
  56. package/src/core/trace-audit.ts +22 -4
  57. package/src/core/transient.ts +6 -0
  58. package/src/drill/run.ts +1 -1
  59. package/src/home/daemon-jobs.ts +41 -4
  60. package/src/home/machine-temp.ts +2 -10
  61. package/src/ledger/gate-checks.ts +26 -4
  62. package/src/ledger/git-key.ts +25 -4
  63. package/src/ledger/git-scan.ts +59 -7
  64. package/src/media-store/backup/daemon.ts +103 -20
  65. package/src/media-store/backup/run.ts +21 -15
  66. package/src/media-store/backup/sources.ts +163 -21
  67. package/src/media-store/backup/watch.ts +106 -0
  68. package/src/media-store/daemon.ts +36 -8
  69. package/src/media-store/hand.ts +3 -1
  70. package/src/mv/mv-md.ts +50 -18
  71. package/src/pb/run-pb.ts +2 -10
  72. package/src/plan/repo-source.ts +25 -14
  73. package/src/recordings/model.ts +1 -1
  74. package/src/reflect/transcript.ts +21 -3
  75. package/src/release/run-bump.ts +3 -2
  76. package/src/release/run-release.ts +12 -4
  77. package/src/releases/model.ts +18 -0
  78. package/src/releases/store.ts +13 -1
  79. package/src/repo-config.ts +11 -1
  80. package/src/review/cells.ts +2 -1
  81. package/src/review/format.ts +1 -1
  82. package/src/review/inbox-hook.ts +35 -0
  83. package/src/review/model.ts +26 -7
  84. package/src/review/store.ts +15 -7
  85. package/src/review/trailer-model.ts +2 -2
  86. package/src/shot/client.ts +4 -2
  87. package/src/shot/serve-shot.ts +71 -2
  88. package/src/shot/shooter.ts +65 -11
  89. package/src/shot/shot-ask.ts +32 -9
  90. package/src/suite/judge-suites.ts +77 -10
  91. package/src/suite/select.ts +13 -2
  92. package/src/suite/suite-cli.ts +72 -31
  93. package/src/suite/test-units.ts +31 -12
  94. package/src/trailer/graph.ts +2 -1
  95. package/src/ts/config.ts +12 -35
  96. package/src/ts/rename.ts +31 -17
  97. package/src/ts/workspaces.ts +45 -0
  98. package/src/wiki/run-wiki.ts +8 -2
  99. package/src/wiki/scan-md.ts +42 -1
@@ -13,6 +13,7 @@ import { basename, join, posix } from 'path'
13
13
  import { FULL_TESTS_ENV } from '../ledger/gate-checks.ts'
14
14
  import { CHECK_ID_ENV, recordSuites, type SuitePhase } from '../ledger/suite-log.ts'
15
15
  import { killTree } from '../core/spawn-timeout.ts'
16
+ import { signalName } from '../core/signal-name.ts'
16
17
  import { parallelCap } from '../core/parallel.ts'
17
18
  import { poolDir, SLOT_CORES_ENV, SLOT_HELD_ENV, slotsLine, takeFreeSlots } from '../core/slots.ts'
18
19
  import { keptWorkMs, mostWorkers, workersFor, workersToStart } from './suite-cores.ts'
@@ -23,7 +24,7 @@ import { gitRoot } from '../core/git-root.ts'
23
24
  import { runReaches, type TestRun } from './test-units.ts'
24
25
  import { loadConfig } from '../ts/config.ts'
25
26
  import { conversionRate, machineRate } from './calibrate.ts'
26
- import { aloneRunsNeeded, bunfigTest, coreMs, cpuAllowance, loadShare, type SuiteWork, type BunfigTest, readPhaseCpu, SUITE_CPU_ENV, type AloneRun, type Confirmed, confirmOver, crashedWorkers, interruptedSuites, overWords, ranAs, retryAlone, smallerRun, stallWords, DEFAULT_BUDGET_MS, FULL_CEILING_MS, failedSuites, failLines, judgeSuites, normSuitePath, parseSuiteFlags, planPhases, QUICK_CEILING_MS, redWords } from './judge-suites.ts'
27
+ import { aloneRunsNeeded, bunfigTest, failuresIn, OWN_RATE_MIN_MS, quickTierWords, passedAlone, redRerunCeiling, redRerunsNeeded, rescuedWords, coreMs, cpuAllowance, loadShare, type SuiteWork, type BunfigTest, readPhaseCpu, SUITE_CPU_ENV, type AloneRun, type Confirmed, confirmOver, crashedWorkers, interruptedSuites, overWords, ranAs, retryAlone, smallerRun, stallWords, DEFAULT_BUDGET_MS, FULL_CEILING_MS, failedSuites, failLines, judgeSuites, normSuitePath, parseSuiteFlags, planPhases, QUICK_CEILING_MS, redWords } from './judge-suites.ts'
27
28
 
28
29
  type Phase = { code: number; signal: string | null; stalled: boolean; out: string; timings: Record<string, number>; cpuMs: number | null }
29
30
 
@@ -74,7 +75,7 @@ async function runPhase(args: string[], timingsFile: string | null, ceilingMs: n
74
75
  // bun test's workers and a suite's own subprocesses land
75
76
  const usage = proc.resourceUsage()
76
77
  const cpuMs = usage != null ? Number(usage.cpuTime.user + usage.cpuTime.system) / 1000 : null
77
- return { code, signal: stalled ? null : proc.signalCode ?? null, stalled, out, timings, cpuMs }
78
+ return { code, signal: stalled ? null : signalName(proc.signalCode), stalled, out, timings, cpuMs }
78
79
  }
79
80
 
80
81
  const CPU_PRELOAD = join(import.meta.dir, 'suite-cpu-preload.ts')
@@ -238,39 +239,76 @@ async function runSuites(argv: string[], ctx: SelectCtx): Promise<number> {
238
239
  const p2Ms = p2 == null ? null : Date.now() - p2At
239
240
  const phases = [p1, ...(p2 != null ? [p2] : [])]
240
241
  const ran = phases.reduce((n, p) => n + lastCount(p.out, /Ran (\d+) tests?/g), 0)
241
- const failedTests = phases.reduce((n, p) => n + lastCount(p.out, /^\s*(\d+) fail$/gm), 0)
242
- const errors = phases.reduce((n, p) => n + lastCount(p.out, /^\s*(\d+) errors?$/gm), 0)
243
- const timings = Object.assign({}, ...phases.map((p) => p.timings)) as Record<string, number>
244
242
  const crashed = crashedWorkers(p1.out)
245
- const red = new Set([...phases.flatMap((p) => failedSuites(p.out)), ...crashed.map((c) => c.file)])
246
- const judged = judgeSuites({ timings, tests, tier, red: [...red] })
247
- const slowest = judged.slowest.length > 0 ? ` (slowest: ${judged.slowest.map((t) => `${t.file} ${secs(t.ms)}`).join(', ')})` : ''
248
243
 
249
- // a parallel timing carries every other suite's load, so a suspect
250
- // runs again alone, one process per suspect so its CPU is its own,
251
- // before it can fail the task. One at a time: four alone runs side by
252
- // side each burned about 40% more CPU than one alone (8 cores)
244
+ // a lone run of one suite, in its own process so its CPU is its own. One at a time: four alone runs side
245
+ // by side each burned about 40% more CPU than one alone (8 cores)
253
246
  const aloneRuns: Record<string, AloneRun> = {}
254
- const parallelCpu = phaseCpu.cpu
255
- const parallelCore = Object.fromEntries(judged.over.map((t) => [t.file, toCore(t.file, phaseCpu.work[t.file])]).filter(([, ms]) => ms != null)) as Record<string, number>
256
- const { rerun, cleared: clearedInPhase } = aloneRunsNeeded(judged.over, parallelCpu, budget, load, parallelCore)
257
247
  const aloneAt = Date.now()
258
- const runAlone = async (t: { file: string }, name: string): Promise<AloneRun | null> => {
248
+ const runAlone = async (file: string, name: string, ceiling = ceilingMs): Promise<{ alone: AloneRun | null; phase: Phase }> => {
259
249
  const lines = counted ? join(dir, `${name}.tsv`) : null
260
- const run = await runPhase([...plan.alone, t.file], join(dir, `${name}.json`), ceilingMs, tmp, false, lines, rec)
261
- const wallMs = Object.entries(run.timings).find(([f]) => normSuitePath(f) === t.file)?.[1]
262
- if (wallMs == null) return null
263
- const work = lines != null && existsSync(lines) ? readPhaseCpu(readFileSync(lines, 'utf8'), process.cwd()).work[t.file] : undefined
264
- if (counted && work == null) fallbacks.set(t.file, 'its lone run wrote no counts (a child still alive when it ended, or no line at all)')
265
- const core = toCore(t.file, work)
266
- return { wallMs, cpuMs: run.cpuMs, ...(core != null ? { coreMs: core, childCpuMs: work!.childCpuMs, otherCpuMs: work!.otherCpuMs } : {}) }
250
+ const run = await runPhase([...plan.alone, file], join(dir, `${name}.json`), ceiling, tmp, false, lines, rec)
251
+ const wallMs = Object.entries(run.timings).find(([f]) => normSuitePath(f) === file)?.[1]
252
+ if (wallMs == null) return { alone: null, phase: run }
253
+ const work = lines != null && existsSync(lines) ? readPhaseCpu(readFileSync(lines, 'utf8'), process.cwd()).work[file] : undefined
254
+ if (counted && work == null) fallbacks.set(file, 'its lone run wrote no counts (a child still alive when it ended, or no line at all)')
255
+ const core = toCore(file, work)
256
+ const rate = work != null && work.pCpuMs >= OWN_RATE_MIN_MS ? { rate: work.pInstructions / work.pCpuMs } : {}
257
+ return { alone: { wallMs, cpuMs: run.cpuMs, ...(core != null ? { coreMs: core, childCpuMs: work!.childCpuMs, otherCpuMs: work!.otherCpuMs, ...rate } : {}) }, phase: run }
258
+ }
259
+
260
+ // a suite red in the pooled run of a loaded machine runs again alone, and stays red only when it fails
261
+ // there too: the load read before the run, or after the pool when the machine got busier meanwhile
262
+ const pooledRed = [...new Set([...failedSuites(p1.out), ...crashed.map((c) => c.file)])]
263
+ const during = { load1: Math.max(load.load1, machineLoad().load1), cores: load.cores }
264
+ const asked = redRerunsNeeded({ red: pooledRed, load: during, pooled: parallel && !parallelEmpty, ended: !p1.stalled && p1.signal == null })
265
+ if (asked.note != null) notes.push(asked.note)
266
+ const pooledWhy = failLines(p1.out)
267
+ for (const c of crashed) if (!pooledWhy.has(c.file)) pooledWhy.set(c.file, `its worker crashed: ${c.signal}`)
268
+ const rescued = new Set<string>()
269
+ const rescuedWarns: string[] = []
270
+ for (const [i, file] of asked.rerun.entries()) {
271
+ const ceiling = redRerunCeiling(Object.entries(p1.timings).find(([f]) => normSuitePath(f) === file)?.[1], ceilingMs)
272
+ const { alone, phase } = await runAlone(file, `red-${i}`, ceiling)
273
+ if (!passedAlone(phase)) {
274
+ const again = failLines(phase.out).get(file) ?? (phase.stalled ? `killed at its ${secs(ceiling)} ceiling` : phase.signal != null ? `killed by ${phase.signal}` : `bun exited ${phase.code}`)
275
+ notes.push(`note: ${file} failed in the pooled run and again alone (${again}): its failure stands`)
276
+ continue
277
+ }
278
+ rescued.add(file)
279
+ if (alone != null) aloneRuns[file] = alone
280
+ rescuedWarns.push(rescuedWords(file, pooledWhy.get(file) ?? 'bun named no failure', during))
267
281
  }
282
+ // what the pool counted for the suites that passed alone is not the run's failure
283
+ const off = failuresIn(p1.out, rescued)
284
+ const failedTests = phases.reduce((n, p) => n + lastCount(p.out, /^\s*(\d+) fail$/gm), 0) - off.tests
285
+ const errors = phases.reduce((n, p) => n + lastCount(p.out, /^\s*(\d+) errors?$/gm), 0) - off.errors
286
+ const p1Clean = p1.code === 0 || (rescued.size > 0 && pooledRed.every((f) => rescued.has(f))
287
+ && lastCount(p1.out, /^\s*(\d+) fail$/gm) === off.tests && lastCount(p1.out, /^\s*(\d+) errors?$/gm) === off.errors)
288
+ const timings = Object.assign({}, ...phases.map((p) => p.timings)) as Record<string, number>
289
+ // a crashed worker left no timing: its lone run's stands
290
+ for (const f of rescued) if (!Object.keys(timings).some((k) => normSuitePath(k) === f) && aloneRuns[f] != null) timings[f] = aloneRuns[f]!.wallMs
291
+ const red = new Set([...phases.flatMap((p) => failedSuites(p.out)), ...crashed.map((c) => c.file)].filter((f) => !rescued.has(f)))
292
+ const judged = judgeSuites({ timings, tests, tier, red: [...red] })
293
+ const slowest = judged.slowest.length > 0 ? ` (slowest: ${judged.slowest.map((t) => `${t.file} ${secs(t.ms)}`).join(', ')})` : ''
294
+
295
+ // a parallel timing carries every other suite's load, so a suspect
296
+ // runs again alone before it can fail the task; a suite that already
297
+ // ran alone after a red keeps that run
298
+ // the full tier fails nothing on time, and says what the quick tier's budget would make of this run
299
+ const parallelCpu = phaseCpu.cpu
300
+ const suspects = tier === 'full' ? judgeSuites({ timings, tests, tier: 'quick', red: [...red] }).over : judged.over
301
+ const parallelCore = Object.fromEntries(suspects.map((t) => [t.file, toCore(t.file, phaseCpu.work[t.file])]).filter(([, ms]) => ms != null)) as Record<string, number>
302
+ const need = aloneRunsNeeded(suspects, parallelCpu, budget, load, parallelCore)
303
+ const rerun = tier === 'quick' ? need.rerun : []
304
+ const clearedInPhase = tier === 'quick' ? need.cleared : []
305
+ if (tier === 'full' && cpuFile != null) notes.push(quickTierWords(need.rerun, parallelCpu, parallelCore))
268
306
  for (const [i, t] of rerun.entries()) {
269
- const first = await runAlone(t, `alone-${i}`)
307
+ const first = aloneRuns[t.file] ?? (await runAlone(t.file, `alone-${i}`)).alone
270
308
  if (first == null) continue
271
309
  aloneRuns[t.file] = first
272
310
  if (!retryAlone(t, first, budget, load)) continue
273
- const second = await runAlone(t, `alone-${i}-again`)
311
+ const second = (await runAlone(t.file, `alone-${i}-again`)).alone
274
312
  if (second == null) continue
275
313
  aloneRuns[t.file] = smallerRun(first, second)
276
314
  const charge = (r: AloneRun): string => secs(r.coreMs ?? r.cpuMs ?? r.wallMs)
@@ -290,7 +328,7 @@ async function runSuites(argv: string[], ctx: SelectCtx): Promise<number> {
290
328
  // those are the suites that never finished, not an outside kill
291
329
  const stalledIn = (name: string, p: Phase | null, files: string[]): string | null =>
292
330
  p?.stalled === true ? stallWords(name, ceilingMs, [...new Set([...files, ...interruptedSuites(p.out)])]) : null
293
- const killed = p1.stalled ? [] : crashed.map((c) => `killed by ${c.signal} while running ${c.file} (out of memory, or killed from outside)`)
331
+ const killed = p1.stalled ? [] : crashed.filter((c) => !rescued.has(c.file)).map((c) => `killed by ${c.signal} while running ${c.file} (out of memory, or killed from outside)`)
294
332
  const stalls = [stalledIn('the parallel phase', p1, crashed.map((c) => c.file)), stalledIn('the serial phase', p2, phaseFiles(serialArgs ?? [], rawArgs).filter((a) => p2?.timings[normSuitePath(a)] == null).map(normSuitePath))]
295
333
  for (const line of stalls) if (line != null) killed.unshift(line)
296
334
  if (p1.signal != null) killed.push(`killed by ${p1.signal} during the parallel run (out of memory, or killed from outside)`)
@@ -320,12 +358,14 @@ async function runSuites(argv: string[], ctx: SelectCtx): Promise<number> {
320
358
  const f = normSuitePath(file)
321
359
  return {
322
360
  at, file: f, ms: alone.get(f) ?? ms, status: red.has(f) ? 'fail' as const : 'pass' as const, tier, budgetMs: budget, check, unit,
323
- cpuMs: cpuOf(f), phase: phaseOf(f), phaseMs: ms, failLine: red.has(f) ? why.get(f) ?? '' : '',
361
+ cpuMs: cpuOf(f), phase: phaseOf(f), phaseMs: ms,
362
+ // a pass that failed in the pool keeps that failure: a suite that needs its lone run again and again shows as such
363
+ failLine: red.has(f) ? why.get(f) ?? '' : rescued.has(f) ? `passed alone at load ${during.load1.toFixed(1)} on ${during.cores} cores after failing in the pooled run: ${pooledWhy.get(f) ?? ''}` : '',
324
364
  }
325
365
  }), {
326
366
  at, check, unit, tier, wallMs: Date.now() - t0, setupMs, workers: parallel ? workers ?? 0 : 0, files: Object.keys(timings).length,
327
367
  parallelMs: p1Ms, parallelCpuMs: p1.cpuMs, serialMs: p2Ms, serialCpuMs: p2?.cpuMs ?? null, serialFiles,
328
- aloneMs, aloneFiles: rerun.length, load1: load.load1, cores: load.cores,
368
+ aloneMs, aloneFiles: new Set([...asked.rerun, ...rerun.map((t) => t.file)]).size, load1: load.load1, cores: load.cores,
329
369
  })
330
370
  if (unrecorded != null) notes.push(unrecorded)
331
371
  // never blocking: a suite that got faster must not stop a release
@@ -333,6 +373,7 @@ async function runSuites(argv: string[], ctx: SelectCtx): Promise<number> {
333
373
 
334
374
  for (const n of notes) console.log(n)
335
375
  for (const s of stale) console.log(s)
376
+ for (const w of rescuedWarns) console.log(w)
336
377
  // the root of a repo with units leaves every unit dir to its own check,
337
378
  // so finding no file of its own is a finding, not a failure
338
379
  if (unit === 'root' && ran === 0 && failedTests === 0 && killed.length === 0 && /\b0 test files matching\b|did not match any test files/.test(p1.out)) {
@@ -345,10 +386,10 @@ async function runSuites(argv: string[], ctx: SelectCtx): Promise<number> {
345
386
  const fails: string[] = [
346
387
  ...killed.map((k) => `FAIL: ${k}`),
347
388
  ...(vacuous ? ['FAIL: ran 0 tests: a suite with no test in it proves nothing, write a real one'] : []),
348
- ...(!vacuous && (failedTests > 0 || (phases.some((p) => p.code !== 0 && p.signal == null) && killed.length === 0))
349
- ? [`FAIL: ${redWords({ failedTests, errors, ran, slowest, out: phases.map((p) => p.out).join('\n') })}`] : []),
389
+ ...(!vacuous && (failedTests > 0 || (phases.some((p) => p.code !== 0 && p.signal == null && !(p === p1 && p1Clean)) && killed.length === 0))
390
+ ? [`FAIL: ${redWords({ failedTests, errors, ran, slowest, out: phases.map((p) => p.out).join('\n'), passedAlone: rescued })}`] : []),
350
391
  ...(over.length > 0
351
- ? [`FAIL: ${over.length} suite(s) over the ${budget}ms budget: ${over.map((c) => overWords(c, load, budget)).join(', ')} (run alone, load ${load.load1.toFixed(1)} on ${load.cores} cores before the run). Make each fast, or declare it in ${declaredIn}.slow with what it catches and why it cannot be fast`]
392
+ ? [`FAIL: ${over.length} suite(s) over the ${budget}ms budget: ${over.map((c) => overWords(c, load, budget, instrPerMs)).join(', ')} (run alone, load ${load.load1.toFixed(1)} on ${load.cores} cores before the run). Make each fast, or declare it in ${declaredIn}.slow with what it catches and why it cannot be fast`]
352
393
  : []),
353
394
  ]
354
395
  // the most actionable failure prints LAST, where the gate reads its headline
@@ -100,22 +100,41 @@ export function unitTestBody(pkgText: string | null): { script: string | null; b
100
100
  return { script: null, body: 'bun test' }
101
101
  }
102
102
 
103
- /** the sibling units a unit's tests can read: the ones its package.json names
104
- * in any dependency block, and the ones its tsconfig `paths` point into (a
105
- * bench resolving the libs at their source folders names them nowhere else).
106
- * Their dirs belong to its inputs. Derived, never hand kept, and over
107
- * declaring is safe where under declaring is a stale green */
108
- export function siblingUnits(units: TestUnitDecl[], read: (rel: string) => string | null): Map<string, string[]> {
109
- const pkgs = new Map(units.map((u) => [u.id, parsePkg(read(posix.join(u.rel, 'package.json')))]))
110
- const byName = new Map<string, TestUnitDecl>()
111
- for (const u of units) { const n = pkgs.get(u.id)?.name; if (n != null) byName.set(n, u) }
103
+ /** the package dirs a unit's tests can read, beside its own: every package its
104
+ * package.json names in any dependency block, and every one its tsconfig
105
+ * `paths` point into (a bench resolving the libs at their source folders
106
+ * names them nowhere else), then what those name in turn. A package is a
107
+ * sibling unit or any workspace package, a unit or not: an import reads the
108
+ * folder whatever the release config says of it. Their dirs belong to its
109
+ * inputs. Derived, never hand kept, and over declaring is safe where under
110
+ * declaring is a stale green */
111
+ export function siblingUnits(units: TestUnitDecl[], read: (rel: string) => string | null, workspaces: readonly { name: string; dir: string }[] = []): Map<string, string[]> {
112
+ const manifests = new Map<string, Pkg | null>()
113
+ const manifest = (rel: string): Pkg | null => {
114
+ if (!manifests.has(rel)) manifests.set(rel, parsePkg(read(posix.join(rel, 'package.json'))))
115
+ return manifests.get(rel)!
116
+ }
117
+ const byName = new Map<string, string>(workspaces.map((w) => [w.name, normSuitePath(w.dir).replace(/\/+$/, '')]))
118
+ for (const u of units) { const n = manifest(u.rel)?.name; if (n != null) byName.set(n, u.rel) }
119
+ const dirs = [...new Set([...units.map((u) => u.rel), ...byName.values()])]
120
+ const named = (rel: string): string[] => {
121
+ const p = manifest(rel)
122
+ return [p?.dependencies, p?.devDependencies, p?.peerDependencies, p?.optionalDependencies].flatMap((b) => Object.keys(b ?? {})).flatMap((n) => byName.get(n) ?? [])
123
+ }
112
124
  const out = new Map<string, string[]>()
113
125
  for (const u of units) {
114
- const p = pkgs.get(u.id)
115
- const names = new Set([p?.dependencies, p?.devDependencies, p?.peerDependencies, p?.optionalDependencies].flatMap((b) => Object.keys(b ?? {})))
116
126
  const tsconfig = unitTsconfig(u)
117
127
  const targets = pathTargets(read(tsconfig)).map((t) => posix.normalize(posix.join(posix.dirname(tsconfig), t)))
118
- out.set(u.id, units.filter((s) => s.id !== u.id && ([...names].some((n) => byName.get(n) === s) || targets.some((t) => under(t, s.rel)))).map((s) => s.rel))
128
+ const own = (d: string): boolean => under(d, u.rel)
129
+ // the unit's own dir is in its inputs already, and what it names is followed all the same
130
+ const seen = new Set<string>()
131
+ const queue = [...named(u.rel), ...dirs.filter((d) => targets.some((t) => under(t, d)))]
132
+ for (let d = queue.shift(); d != null; d = queue.shift()) {
133
+ if (seen.has(d)) continue
134
+ seen.add(d)
135
+ queue.push(...named(d))
136
+ }
137
+ out.set(u.id, [...seen].filter((d) => !own(d)).sort())
119
138
  }
120
139
  return out
121
140
  }
@@ -561,7 +561,8 @@ export function nextMixLevel(master: number | null, passes: readonly MixPass[]):
561
561
  const trim = over > 0 ? +(level.trim - over - 0.1).toFixed(2) : level.trim
562
562
  const left = +(gap - (trim - level.trim)).toFixed(2)
563
563
  if (master === null || Math.abs(left) <= MASTER_TOLERANCE) return { gain: level.gain, trim }
564
- const before = passes.findLast((p) => p.level.gain !== level.gain)
564
+ // no findLast: a consumer's own typecheck reads this source, under whatever lib its tsconfig names
565
+ const before = [...passes].reverse().find((p) => p.level.gain !== level.gain)
565
566
  const moved = before ? (m.lufs - level.trim - (before.m.lufs - before.level.trim)) / (level.gain - before.level.gain) : 1
566
567
  const slope = Math.min(1, Math.max(MIN_SLOPE, moved))
567
568
  return { gain: +(level.gain + left / slope).toFixed(2), trim }
package/src/ts/config.ts CHANGED
@@ -17,6 +17,7 @@ import { join } from 'path'
17
17
  import { gitRoot } from '../core/git-root.ts'
18
18
  import { isVendored } from '../core/vendored.ts'
19
19
  import { readVendored } from '../core/vendored-read.ts'
20
+ import { workspacePackagesOf } from './workspaces.ts'
20
21
 
21
22
  export type RvtPackage = {
22
23
  name: string // package.json "name" — the import root for files inside
@@ -120,45 +121,21 @@ function discoverPackages(root: string, roots: string[], skip: string[], vendore
120
121
  // the package.json `workspaces` (an array, or `{ packages }`), each a dir or a glob of dirs, with each one's `exports`:
121
122
  // a workspace outside the roots is still imported by its name, and the test selection's graph follows that edge
122
123
  export function workspacePackages(root: string, vendored: readonly string[] = []): (RvtPackage & { exports?: unknown })[] {
123
- let globs: string[] = []
124
- try {
125
- const w = (JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { workspaces?: string[] | { packages?: string[] } }).workspaces
126
- globs = Array.isArray(w) ? w : w?.packages ?? []
127
- } catch {
128
- return []
129
- }
130
- const dirs = (pattern: string): string[] => {
131
- let at = ['']
132
- for (const seg of pattern.replace(/\/+$/, '').split('/')) {
133
- if (!seg.includes('*')) {
134
- at = at.map((d) => (d === '' ? seg : `${d}/${seg}`))
135
- continue
136
- }
137
- const re = new RegExp(`^${seg.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*')}$`)
138
- at = at.flatMap((d) => {
139
- try {
140
- return readdirSync(join(root, d), { withFileTypes: true }).filter((e) => e.isDirectory() && re.test(e.name)).map((e) => (d === '' ? e.name : `${d}/${e.name}`))
141
- } catch {
142
- return []
143
- }
144
- })
124
+ const read = (rel: string): string | null => {
125
+ try {
126
+ return readFileSync(join(root, rel), 'utf8')
127
+ } catch {
128
+ return null
145
129
  }
146
- return at
147
130
  }
148
- const out: (RvtPackage & { exports?: unknown })[] = []
149
- for (const g of globs) {
150
- if (g.startsWith('!')) continue
151
- for (const dir of dirs(g)) {
152
- if (isVendored(dir, vendored)) continue
153
- try {
154
- const m = JSON.parse(readFileSync(join(root, dir, 'package.json'), 'utf8')) as { name?: string; exports?: unknown }
155
- if (m.name != null && m.name !== '') out.push({ name: m.name, dir, ...(m.exports !== undefined ? { exports: m.exports } : {}) })
156
- } catch {
157
- // no named manifest: not a package
158
- }
131
+ const subdirs = (rel: string): string[] => {
132
+ try {
133
+ return readdirSync(join(root, rel), { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name)
134
+ } catch {
135
+ return []
159
136
  }
160
137
  }
161
- return out
138
+ return workspacePackagesOf(read, subdirs, vendored)
162
139
  }
163
140
 
164
141
  export function loadConfig(cwd: string = process.cwd()): RvtConfig {
package/src/ts/rename.ts CHANGED
@@ -12,13 +12,16 @@
12
12
  // file -> path ending with / same, creates folder if missing
13
13
  // folder -> folder path renames the folder (recursive replacement)
14
14
  import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'fs'
15
+ import { isHistoryFile } from '../core/history-files.ts'
15
16
  import { basename, dirname, extname, join, relative, resolve } from 'path'
16
17
  import { canonicalSpecifier, isSkipped, loadConfig, toPosix, type RvtConfig } from 'rvlib-shipkit/src/ts/config.ts'
17
18
  import { extractSpecs } from 'rvlib-shipkit/src/ts/source-graph.ts'
18
19
  import { gitBin } from '../core/git-bin.ts'
19
- import { retargetRelativeRefs } from '../mv/mv-md.ts'
20
+ import { namesMoved, retargetRelativeRefs } from '../mv/mv-md.ts'
20
21
 
21
22
  const CODE_RE = /\.[cm]?[jt]sx?$/
23
+ /** the overreach warnings a dry run prints: a common stem (`index`) names a thousand files */
24
+ const SHOWN = 12
22
25
 
23
26
  const BINARY_EXTS = new Set([
24
27
  '.png', '.jpg', '.jpeg', '.gif', '.webp', '.ico', '.bmp', '.tiff',
@@ -56,9 +59,11 @@ export type RenameResult = {
56
59
  totalRefs: number
57
60
  suspicious: string[]
58
61
  applied: boolean
62
+ /** plans, changelogs and journals that name the path and stay as written */
63
+ left: number
59
64
  }
60
65
 
61
- export function runRename(srcArg: string, dstArg: string, opts: { apply?: boolean; cfg?: RvtConfig } = {}): RenameResult {
66
+ export function runRename(srcArg: string, dstArg: string, opts: { apply?: boolean; cfg?: RvtConfig; /** rewrite the plans, changelogs and journals too */ history?: boolean } = {}): RenameResult {
62
67
  const cfg = opts.cfg ?? loadConfig()
63
68
  const repoRoot = cfg.root
64
69
 
@@ -113,11 +118,11 @@ export function runRename(srcArg: string, dstArg: string, opts: { apply?: boolea
113
118
  const rewriteFile = (file: string, content: string): { text: string; count: number } => {
114
119
  if (file.endsWith('.md')) {
115
120
  const linked = retargetRelativeRefs(repoRoot, content, dirOf(file), dirOf(movedTo(file) ?? file), mdMoves)
116
- const scanned = scanPairs(linked, pairs)
121
+ const scanned = scanPairs(linked, pairs, { carrierDir: dirOf(file), root: repoRoot })
117
122
  return { text: scanned.text, count: scanned.count + (linked === content ? 0 : 1) }
118
123
  }
119
124
  const rel = CODE_RE.test(file) ? relativeRewrites(file, content, movedTo, isFile) : new Map<string, string>()
120
- if (rel.size === 0) return scanPairs(content, pairs)
125
+ if (rel.size === 0) return scanPairs(content, pairs, { carrierDir: dirOf(file), root: repoRoot })
121
126
  // the relative specifiers this move retargets are set aside while the
122
127
  // path scan runs, so the two rewrites can never compound on one string
123
128
  let masked = content
@@ -132,7 +137,7 @@ export function runRename(srcArg: string, dstArg: string, opts: { apply?: boolea
132
137
  holes.push(`${q}${to}${q}`)
133
138
  }
134
139
  }
135
- const scanned = scanPairs(masked, pairs)
140
+ const scanned = scanPairs(masked, pairs, { carrierDir: dirOf(file), root: repoRoot })
136
141
  let text = scanned.text
137
142
  holes.forEach((h, i) => { text = text.split(`\u0000mv${i}\u0000`).join(h) })
138
143
  return { text, count: scanned.count + relCount }
@@ -140,6 +145,7 @@ export function runRename(srcArg: string, dstArg: string, opts: { apply?: boolea
140
145
 
141
146
  const hits: { file: string; count: number }[] = []
142
147
  let totalRefs = 0
148
+ let left = 0
143
149
  for (const file of allFiles) {
144
150
  if (isSkipped(file, cfg, pkgDirs)) continue
145
151
  if (BINARY_EXTS.has(extname(file).toLowerCase())) continue
@@ -152,6 +158,8 @@ export function runRename(srcArg: string, dstArg: string, opts: { apply?: boolea
152
158
  const nul = content.indexOf('\u0000')
153
159
  if (nul !== -1 && nul < 4096) continue // cheap binary sniff
154
160
  const count = rewriteFile(file, content).count
161
+ // a record of what was true stays as written, unless it is itself what moves
162
+ if (count > 0 && opts.history !== true && isHistoryFile(file) && movedTo(file) == null) { left++; continue }
155
163
  if (count > 0) {
156
164
  hits.push({ file, count })
157
165
  totalRefs += count
@@ -191,10 +199,11 @@ export function runRename(srcArg: string, dstArg: string, opts: { apply?: boolea
191
199
  if (mv.exitCode !== 0) renameSync(srcAbs, dstAbs) // untracked file: plain fs move
192
200
  }
193
201
 
194
- return { srcRel, dstRel, isFolder: srcIsFolder, hits, totalRefs, suspicious, applied: opts.apply === true }
202
+ return { srcRel, dstRel, isFolder: srcIsFolder, hits, totalRefs, suspicious, applied: opts.apply === true, left }
195
203
  }
196
204
 
197
- export function renameCli(argv: string[]): number {
205
+ /** `applyFlag`: the flag the caller's own cli applies with, named by the dry run's last line */
206
+ export function renameCli(argv: string[], applyFlag = '-x or --apply'): number {
198
207
  const apply = argv.includes('-x') || argv.includes('--apply')
199
208
  const paths = argv.filter((a) => !a.startsWith('-'))
200
209
  if (paths.length !== 2) {
@@ -203,7 +212,7 @@ export function renameCli(argv: string[]): number {
203
212
  }
204
213
  let r: RenameResult
205
214
  try {
206
- r = runRename(paths[0]!, paths[1]!, { apply })
215
+ r = runRename(paths[0]!, paths[1]!, { apply, history: argv.includes('--history') })
207
216
  } catch (e) {
208
217
  console.error(String(e instanceof Error ? e.message : e))
209
218
  return 1
@@ -212,11 +221,13 @@ export function renameCli(argv: string[]): number {
212
221
  console.log(`type: ${r.isFolder ? 'folder (recursive)' : 'file'}`)
213
222
  console.log(`refs: ${r.totalRefs} across ${r.hits.length} file(s)`)
214
223
  for (const h of r.hits) console.log(` ${h.count.toString().padStart(4)} ${h.file}`)
224
+ if (r.left > 0) console.log(`left as written: ${r.left} plan, changelog or journal file(s) that name it (--history rewrites them too)`)
215
225
  if (r.suspicious.length > 0) {
216
- console.log('\nwarning: possible substring overreach (inspect before applying):')
217
- for (const s of r.suspicious) console.log(` ${s}`)
226
+ console.log(`\nwarning: ${r.suspicious.length} possible substring overreach (inspect before applying):`)
227
+ for (const s of r.suspicious.slice(0, SHOWN)) console.log(` ${s}`)
228
+ if (r.suspicious.length > SHOWN) console.log(` … ${r.suspicious.length - SHOWN} more of the same kind`)
218
229
  }
219
- if (!r.applied) console.log('\ndry-run. pass -x or --apply to commit.')
230
+ if (!r.applied) console.log(`\ndry run: pass ${applyFlag} to apply.`)
220
231
  else console.log(`\napplied: ${r.srcRel} -> ${r.dstRel} (${r.totalRefs} refs rewritten)`)
221
232
  return 0
222
233
  }
@@ -251,12 +262,15 @@ function relativeRewrites(file: string, content: string, movedTo: (rel: string)
251
262
  return out
252
263
  }
253
264
 
254
- /** the next occurrence of a path that ENDS there: `server/staged` inside
255
- * `server/staged.ts` or `server/staged-x` names another file, never the folder */
256
- function pathAt(text: string, needle: string, from: number): number {
265
+ /** where a path is read: the carrier's folder resolves a relative prefix, the root an absolute one */
266
+ type At = { carrierDir: string; root: string }
267
+
268
+ /** the next occurrence of a path that ENDS there and STARTS there: `server/staged` inside `server/staged.ts` or
269
+ * `server/staged-x`, and `src/a.ts` inside `packages/p/src/a.ts`, name another file */
270
+ function pathAt(text: string, needle: string, from: number, where: At): number {
257
271
  for (let idx = text.indexOf(needle, from); idx !== -1; idx = text.indexOf(needle, idx + 1)) {
258
272
  const next = text.slice(idx + needle.length, idx + needle.length + 2)
259
- if (!/^[\w-]/.test(next) && !/^\.\w/.test(next)) return idx
273
+ if (!/^[\w-]/.test(next) && !/^\.\w/.test(next) && namesMoved(text, idx, needle, needle, where.carrierDir, where.root)) return idx
260
274
  }
261
275
  return -1
262
276
  }
@@ -265,7 +279,7 @@ function pathAt(text: string, needle: string, from: number): number {
265
279
  // tie) and the scan continues PAST the replacement — sequential split/join
266
280
  // would let one pair's output feed the next (the package form is a substring
267
281
  // of the repo form, so that corrupts content)
268
- function scanPairs(text: string, pairs: { from: string; to: string }[]): { text: string; count: number } {
282
+ function scanPairs(text: string, pairs: { from: string; to: string }[], where: At): { text: string; count: number } {
269
283
  let out = ''
270
284
  let i = 0
271
285
  let count = 0
@@ -274,7 +288,7 @@ function scanPairs(text: string, pairs: { from: string; to: string }[]): { text:
274
288
  let hit: { from: string; to: string } | null = null
275
289
  for (const p of pairs) {
276
290
  if (p.from.length === 0) continue
277
- const idx = pathAt(text, p.from, i)
291
+ const idx = pathAt(text, p.from, i, where)
278
292
  if (idx === -1) continue
279
293
  if (at === -1 || idx < at || (idx === at && p.from.length > (hit?.from.length ?? 0))) {
280
294
  at = idx
@@ -0,0 +1,45 @@
1
+ // the package.json `workspaces`, expanded through a reader and never the disk:
2
+ // a check's floor resolution reaches this module, and a check reads only
3
+ // through its context, so nothing here may import fs.
4
+ import { isVendored } from '../core/vendored.ts'
5
+
6
+ export type WorkspacePackage = { name: string; dir: string; exports?: unknown }
7
+
8
+ /** the package.json `workspaces` through a reader: `read` answers a repo-relative file, `subdirs`
9
+ * the dir names directly inside a repo-relative dir ('' is the root). A check
10
+ * hands it its context, so the answer stays keyed on what it read */
11
+ export function workspacePackagesOf(read: (rel: string) => string | null, subdirs: (rel: string) => string[], vendored: readonly string[] = []): WorkspacePackage[] {
12
+ let globs: string[] = []
13
+ try {
14
+ const w = (JSON.parse(read('package.json') ?? '') as { workspaces?: string[] | { packages?: string[] } }).workspaces
15
+ globs = Array.isArray(w) ? w : w?.packages ?? []
16
+ } catch {
17
+ return []
18
+ }
19
+ const dirs = (pattern: string): string[] => {
20
+ let at = ['']
21
+ for (const seg of pattern.replace(/^\.\//, '').replace(/\/+$/, '').split('/')) {
22
+ if (!seg.includes('*')) {
23
+ at = at.map((d) => (d === '' ? seg : `${d}/${seg}`))
24
+ continue
25
+ }
26
+ const re = new RegExp(`^${seg.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*')}$`)
27
+ at = at.flatMap((d) => subdirs(d).filter((n) => re.test(n)).map((n) => (d === '' ? n : `${d}/${n}`)))
28
+ }
29
+ return at
30
+ }
31
+ const out: WorkspacePackage[] = []
32
+ for (const g of globs) {
33
+ if (g.startsWith('!')) continue
34
+ for (const dir of dirs(g)) {
35
+ if (isVendored(dir, vendored)) continue
36
+ try {
37
+ const m = JSON.parse(read(`${dir}/package.json`) ?? '') as { name?: string; exports?: unknown }
38
+ if (m.name != null && m.name !== '') out.push({ name: m.name, dir, ...(m.exports !== undefined ? { exports: m.exports } : {}) })
39
+ } catch {
40
+ // no named manifest: not a package
41
+ }
42
+ }
43
+ }
44
+ return out
45
+ }
@@ -2,6 +2,7 @@
2
2
  // lib; that npm package is frozen). Plain modules behind cmd_Wiki —
3
3
  // clipanion owns the option parsing.
4
4
  import { existsSync } from 'fs'
5
+ import { isHistoryFile, onceAPath } from '../core/history-files.ts'
5
6
  import { basename, join, relative, resolve } from 'path'
6
7
  import { agentDirAt, contributionFileAt } from '../core/agent-dir-at.ts'
7
8
  import { lintMd } from './lint-md.ts'
@@ -68,9 +69,14 @@ export function runWikiLint(o: WikiScanOpts): number {
68
69
  : `FAIL no entrypoint: neither index.md nor README.md in ${cfg.root} — pass --index <entry.md>`)
69
70
  return 1
70
71
  }
72
+ // a changelog or a journal names what was true then: a path that is gone holds when git once had it
73
+ // a heading it names may have been renamed since: the page is judged by its own ref, the anchor is left as written
74
+ const dangling = r.dangling.filter((d) => !(isHistoryFile(d.from) && (d.token.includes('#') || onceAPath(cfg.root, d.token))))
75
+ const held = r.dangling.length - dangling.length
71
76
  for (const f of r.orphans) say(`FAIL orphan: ${f} — unreachable from ${r.index}; link it or delete it`)
72
- for (const d of r.dangling) say(`FAIL dangling: ${d.from} → ${d.token} — target not found`)
73
- if (!r.ok) { say(`FAIL mdwiki lint: ${r.orphans.length} orphan(s), ${r.dangling.length} dangling ref(s) in ${cfg.root}`); return 1 }
77
+ for (const d of dangling) say(`FAIL dangling: ${d.from} → ${d.token} — target not found`)
78
+ if (r.orphans.length > 0 || dangling.length > 0) { say(`FAIL mdwiki lint: ${r.orphans.length} orphan(s), ${dangling.length} dangling ref(s) in ${cfg.root}`); return 1 }
79
+ if (held > 0) say(`ok ${held} ref(s) of a changelog or journal name a path git once held: left as written`)
74
80
  say(`ok mdwiki lint: ${r.files} files, all reachable from ${r.index}, no dangling refs`)
75
81
  return 0
76
82
  }
@@ -32,6 +32,32 @@ export type MdScan = {
32
32
  dangling: MdDanglingRef[]
33
33
  }
34
34
 
35
+ /** the anchor a heading answers to, as the forges write it: lower case, its marks dropped, each space a dash */
36
+ const slugOf = (heading: string): string =>
37
+ heading.trim().toLowerCase().replace(/\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/[^\p{L}\p{N}\p{M}_\- ]/gu, '').replace(/ /g, '-')
38
+
39
+ /** an anchor as a link writes it, read the way a heading's slug is */
40
+ export const anchorSlug = (anchor: string): string => {
41
+ try { return decodeURIComponent(anchor).toLowerCase() } catch { return anchor.toLowerCase() }
42
+ }
43
+
44
+ /** every anchor a page's headings answer to; a heading that repeats takes `-1`, `-2` after its slug. Fenced code holds no heading */
45
+ export function headingSlugs(text: string): Set<string> {
46
+ const out = new Set<string>()
47
+ const seen = new Map<string, number>()
48
+ let fenced = false
49
+ for (const line of text.split('\n')) {
50
+ if (line.startsWith('```')) { fenced = !fenced; continue }
51
+ const m = fenced ? null : /^#{1,6}\s+(.*?)\s*#*\s*$/.exec(line)
52
+ if (m == null) continue
53
+ const s = slugOf(m[1]!)
54
+ const n = seen.get(s) ?? 0
55
+ seen.set(s, n + 1)
56
+ out.add(n === 0 ? s : `${s}-${n}`)
57
+ }
58
+ return out
59
+ }
60
+
35
61
  export function scanMdGraph(cfg: ScanMdConfig): MdGraph {
36
62
  return scanMd(cfg).graph
37
63
  }
@@ -104,6 +130,12 @@ function scanMdNow(cfg: ScanMdConfig): MdScan {
104
130
  if (!inRoot && inBoundary && existsSync(cand)) return { to: [], onDisk: true }
105
131
  return null
106
132
  }
133
+ const headings = new Map<string, Set<string>>()
134
+ const headingsOf = (page: string): Set<string> => {
135
+ let h = headings.get(page)
136
+ if (h == null) { h = headingSlugs(readFileSync(join(cfg.root, page), 'utf8')); headings.set(page, h) }
137
+ return h
138
+ }
107
139
  const edgesOf = (rel: string): MdEdge[] => {
108
140
  const raw = readFileSync(join(cfg.root, rel), 'utf8')
109
141
  const body = raw.startsWith('---\n') ? raw.slice(4).replace(/^[\s\S]*?^---\s*$/m, '') : raw
@@ -122,7 +154,16 @@ function scanMdNow(cfg: ScanMdConfig): MdScan {
122
154
  }
123
155
  for (const m of prose.matchAll(/(?:^|[\s(])@((?:\.{1,2}\/)*[\w][\w./-]*\.md)/gm)) push(m[1]!, true, true, lineOf(m))
124
156
  for (const m of prose.matchAll(/→\s*([\w][\w./-]*\.md)\b/g)) push(m[1]!, false, true, lineOf(m))
125
- for (const m of prose.matchAll(/\]\(([^)\s:]+\.md)\)/g)) push(m[1]!, false, true, lineOf(m))
157
+ // an anchor or a title never changes the page a link reaches; an anchor names a heading of that page, and one
158
+ // the page does not have is a ref of its own that dangles (a heading renamed under its links)
159
+ for (const m of prose.matchAll(/\]\(([^)\s:#]+\.md)?(?:#([^)\s]*))?(?:\s+"[^"]*")?\)/g)) {
160
+ if (m[1] == null && m[2] == null) continue
161
+ if (m[1] != null) push(m[1], false, true, lineOf(m))
162
+ if (m[2] == null || m[2] === '') continue
163
+ const to = m[1] == null ? rel : resolveRef(rel, m[1])?.to
164
+ const page = typeof to === 'string' ? to : to?.length === 1 ? to[0]! : null
165
+ if (page != null && !headingsOf(page).has(anchorSlug(m[2]))) dangling.push({ from: rel, token: `${m[1] ?? ''}#${m[2]}`, line: lineOf(m) })
166
+ }
126
167
  for (const m of prose.matchAll(/\]\(([^)\s:]*\/)\)/g)) push(m[1]!, false, true, lineOf(m))
127
168
  for (const s of spans) for (const m of s.matchAll(/[\w][\w./-]*\.md/g)) push(m[0], false, false)
128
169
  for (const s of spans) for (const m of s.matchAll(/(?:^|\s)([\w.][\w./-]*\/)(?=$|[\s<*])/g)) push(m[1]!, false, false)