Skip to content
Myr

context.ts

This file

Path

packages/drafting/src/context.ts

301 lines · 7.6 KiB · TypeScript

Last changed by

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

History of this file

Take it

Merge branch 'build/908-drafter-workers-ai'oscabrielbefore adoption004e40e

line 1why, one step back
1/**

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

lines 2–3why, one step back
2 * A path that looks like a layer's or a held-back check's is refused even
3 * though the caller hands a reader over the canonical repo only.

Merge branch 'build/908-drafter-workers-ai'oscabrielbefore adoption004e40e

lines 4–7why, one step back
4 *
5 * The order is the priority: an existing ask with its test as a style6 * example (first, so no long README can spend the budget it needs), the7 * root READMEs, the root manifest, the project module, then the

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

lines 8–10why, one step back
8 * territory's files (or the source files whose path shares the most words
9 * with the want), each source with its sibling tests, and last every other10 * README.

Merge branch 'build/908-drafter-workers-ai'oscabrielbefore adoption004e40e

lines 11–301why, one step back
11 */
12import { Brand } from "@repo/brand";13import type { ConfigFile } from "@repo/protocol/domain/common";14import { RepoPath } from "@repo/protocol/ids";15import { Array, Effect, Option, Order, Schema, pipe } from "effect";1617const defaultBudget = 200 * 1024;1819const perFile = 40 * 1024;2021const markerRoom = 64;2223const rankedFiles = 12;2425const manifests = new Set([26 "Cargo.toml",27 "go.mod",28 "package.json",29 "pyproject.toml",30]);3132const sourceExtensions = new Set([33 "c",34 "cc",35 "cjs",36 "cpp",37 "cs",38 "ex",39 "exs",40 "go",41 "h",42 "hpp",43 "hs",44 "java",45 "js",46 "jsx",47 "kt",48 "lua",49 "mjs",50 "ml",51 "mts",52 "php",53 "py",54 "rb",55 "rs",56 "scala",57 "sh",58 "swift",59 "ts",60 "tsx",61 "zig",62]);6364const testFolders = new Set(["__tests__", "spec", "test", "tests"]);6566const vendored = new Set(["dist", "node_modules", "target", "vendor"]);6768const stopWords = new Set([69 "and",70 "are",71 "but",72 "for",73 "from",74 "has",75 "its",76 "not",77 "the",78 "that",79 "this",80 "when",81 "with",82]);8384const askFolder = `${Brand.configDir}/asks/`;8586const askSuffix = ".ask.ts";8788const segmentsOf = (path: string) => path.split("/");8990const baseName = (path: string) => segmentsOf(path).at(-1) ?? path;9192const folderOf = (path: string) =>93 path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";9495const extensionOf = (path: string) => {96 const name = baseName(path);9798 return name.includes(".") ? name.slice(name.lastIndexOf(".") + 1) : "";99};100101const isWithheld = (path: string) =>102 path.startsWith(`${Brand.configDir}/layers/`) ||103 segmentsOf(path).some(104 (segment) =>105 segment === "held-back" ||106 (segment.startsWith(".env") && segment !== ".env.schema")107 );108109const isReadme = (path: string) => /^readme(?:\.|$)/iu.test(baseName(path));110111const isTest = (path: string) =>112 segmentsOf(path).some((segment) => testFolders.has(segment)) ||113 /[._-](?:test|spec)\.[^.]+$/u.test(baseName(path)) ||114 baseName(path).startsWith("test_");115116const isSource = (path: string) =>117 sourceExtensions.has(extensionOf(path)) &&118 !isTest(path) &&119 !path.startsWith(`${Brand.configDir}/`) &&120 !segmentsOf(path).some((segment) => vendored.has(segment));121122const isAskFile = (path: string) =>123 path.startsWith(askFolder) &&124 path.endsWith(askSuffix) &&125 !path.slice(askFolder.length).includes("/");126127const stemOf = (path: string) => baseName(path).split(".")[0] ?? "";128129const wordsOf = (text: string): readonly string[] =>130 text131 .split(/[^A-Za-z0-9]+/u)132 .flatMap((word) =>133 word.length === 0134 ? []135 : [136 word.toLowerCase(),137 ...(word.match(/[A-Z]?[a-z0-9]+|[A-Z]+(?![a-z])/gu) ?? []).map(138 (part) => part.toLowerCase()139 ),140 ]141 )142 .filter((word) => word.length >= 3 && !stopWords.has(word));143144const overlap = (want: ReadonlySet<string>, path: string) =>145 Array.dedupe(146 wordsOf(path.slice(0, path.length - extensionOf(path).length))147 ).filter((word) => want.has(word)).length;148149interface Ranked {150 readonly path: string;151 readonly score: number;152}153154const byScore = Order.combine(155 Order.mapInput(Order.flip(Order.Number), ({ score }: Ranked) => score),156 Order.mapInput(Order.String, ({ path }: Ranked) => path)157);158159const ranked = (paths: readonly string[], want: ReadonlySet<string>) =>160 paths161 .flatMap((path): Ranked[] => {162 const score = isSource(path) ? overlap(want, path) : 0;163164 return score > 0 ? [{ path, score }] : [];165 })166 .toSorted(byScore)167 .slice(0, rankedFiles)168 .map(({ path }) => path);169170const siblingTests = (tree: readonly string[], source: string) => {171 const stem = stemOf(source);172173 return tree.filter(174 (path) =>175 isTest(path) &&176 path !== source &&177 (stemOf(path) === stem || baseName(path).startsWith(`test_${stem}.`))178 );179};180181const decodeLiteral = Schema.decodeOption(Schema.fromJsonString(Schema.String));182183const askTestPath = (source: string): Option.Option<string> =>184 pipe(185 Option.fromNullishOr(186 /\bpath:\s*(?<literal>"(?:[^"\\\n]|\\.)*")/u.exec(source)?.groups?.literal187 ),188 Option.flatMap(decodeLiteral)189 );190191export const askTestFolderOf = (192 files: readonly ConfigFile[]193): Option.Option<string> =>194 pipe(195 Array.findFirst(files, ({ path }) => isAskFile(path)),196 Option.flatMap(({ content }) => askTestPath(content)),197 Option.map(folderOf)198 );199200const encoder = new TextEncoder();201202const decoder = new TextDecoder();203204const cut = (content: string, room: number): Option.Option<string> => {205 const bytes = encoder.encode(content);206207 if (bytes.length <= Math.min(room, perFile)) {208 return Option.some(content);209 }210211 const shown = Math.min(perFile, room - markerRoom);212213 return shown <= 0214 ? Option.none()215 : Option.some(216 `${decoder.decode(bytes.slice(0, shown)).replace(/�$/u, "")}\n[cut: the first ${shown} of ${bytes.length} bytes]\n`217 );218};219220export const pickFiles = (221 tree: readonly RepoPath[],222 input: { readonly want: string; readonly territory?: readonly RepoPath[] },223 read: (path: RepoPath) => Effect.Effect<string>,224 budget: number = defaultBudget225): Effect.Effect<readonly ConfigFile[]> =>226 Effect.gen(function* () {227 const paths: readonly string[] = Array.dedupe(228 tree.filter((path) => !isWithheld(path)).toSorted(Order.String)229 );230231 const rootReadmes = paths.filter(232 (path) => !path.includes("/") && isReadme(path)233 );234235 const settings = [236 ...paths.filter((path) => manifests.has(path)),237 ...paths.filter((path) => path === `${Brand.configDir}/project.ts`),238 ];239240 const example = Array.last(paths.filter(isAskFile));241242 const exampleSource = yield* Option.match(example, {243 onNone: () => Effect.succeed(Option.none<string>()),244 onSome: (path) => Effect.asSome(read(RepoPath.make(path))),245 });246247 const exampleTest = pipe(248 exampleSource,249 Option.flatMap(askTestPath),250 Option.filter((path) => paths.includes(path))251 );252253 const want = new Set(wordsOf(input.want));254255 const chosen =256 input.territory === undefined || input.territory.length === 0257 ? ranked(paths, want)258 : paths.filter((path) =>259 (input.territory ?? []).some(260 (territory) =>261 path === territory || path.startsWith(`${territory}/`)262 )263 );264265 const withTests = chosen.flatMap((path) => [266 path,267 ...(isTest(path) ? [] : siblingTests(paths, path)),268 ]);269270 const otherReadmes = paths.filter(271 (path) => path.includes("/") && isReadme(path)272 );273274 const order = Array.dedupe([275 ...Option.toArray(example),276 ...Option.toArray(exampleTest),277 ...rootReadmes,278 ...settings,279 ...withTests,280 ...otherReadmes,281 ]);282283 const picked: ConfigFile[] = [];284 let left = budget;285286 for (const path of order) {287 const content =288 path === Option.getOrUndefined(example)289 ? Option.getOrElse(exampleSource, () => "")290 : yield* read(RepoPath.make(path));291292 const shown = cut(content, left);293294 if (Option.isSome(shown)) {295 picked.push({ content: shown.value, path: RepoPath.make(path) });296 left -= encoder.encode(shown.value).length;297 }298 }299300 return picked;301 });