context.ts
This file
Path
packages/drafting/src/context.ts
324 lines · 9.1 KiB · TypeScript
Last changed by
Close the code browser and drafting wave: its decisions in two ADRs, every rule it added held, and its leftovers folded inoscabrielbefore adoption009640c
History of this fileTake it
Merge branch 'build/908-drafter-workers-ai'oscabrielbefore adoption004e40e
lines 1–2why, one step back1/**2 * What the drafter reads: files picked from the project's canonical tree atClose the code browser and drafting wave: its decisions in two ADRs, every rule it added held, and its leftovers folded inoscabrielbefore adoption009640c
line 3why, one step back3 * the landed commit, deterministically, within a byte budget (ADR 0018).Merge branch 'build/908-drafter-workers-ai'oscabrielbefore adoption004e40e
lines 4–324why, one step back4 * The caller hands the tree and a reader over the canonical repo only, so5 * no layer's repo can be read here; a path that looks like a layer's or a6 * held-back check's is refused anyway, as is an env file.7 *8 * The order is the priority: an existing ask with its test as a style9 * example (first, so no long README can spend the budget it needs), the10 * root READMEs, the root manifest, the project module, then the11 * territory's files (or, with none given, the source files whose path12 * shares the most words with the want, at most 12), each source with its13 * sibling tests, and last every other README. Each file is cut at 40 KB,14 * and the rest of the budget cuts the next one, both with a marker.15 */16import { Brand } from "@repo/brand";17import type { ConfigFile } from "@repo/protocol/domain/common";18import { RepoPath } from "@repo/protocol/ids";19import { Array, Effect, Option, Order, Schema, pipe } from "effect";2021/** The bytes the model reads in all, about 50k tokens. */22const defaultBudget = 200 * 1024;2324/** The most of one file the model reads. */25const perFile = 40 * 1024;2627/** Room kept for a cut file's marker. */28const markerRoom = 64;2930/** Source files ranked by the want, when no territory is given. */31const rankedFiles = 12;3233const manifests = new Set([34 "Cargo.toml",35 "go.mod",36 "package.json",37 "pyproject.toml",38]);3940const sourceExtensions = new Set([41 "c",42 "cc",43 "cjs",44 "cpp",45 "cs",46 "ex",47 "exs",48 "go",49 "h",50 "hpp",51 "hs",52 "java",53 "js",54 "jsx",55 "kt",56 "lua",57 "mjs",58 "ml",59 "mts",60 "php",61 "py",62 "rb",63 "rs",64 "scala",65 "sh",66 "swift",67 "ts",68 "tsx",69 "zig",70]);7172const testFolders = new Set(["__tests__", "spec", "test", "tests"]);7374const vendored = new Set(["dist", "node_modules", "target", "vendor"]);7576const stopWords = new Set([77 "and",78 "are",79 "but",80 "for",81 "from",82 "has",83 "its",84 "not",85 "the",86 "that",87 "this",88 "when",89 "with",90]);9192const askFolder = `${Brand.configDir}/asks/`;9394const askSuffix = ".ask.ts";9596const segmentsOf = (path: string) => path.split("/");9798const baseName = (path: string) => segmentsOf(path).at(-1) ?? path;99100const folderOf = (path: string) =>101 path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";102103const extensionOf = (path: string) => {104 const name = baseName(path);105106 return name.includes(".") ? name.slice(name.lastIndexOf(".") + 1) : "";107};108109/** A layer's file, a held-back check, or an env file: never read. */110const isWithheld = (path: string) =>111 path.startsWith(`${Brand.configDir}/layers/`) ||112 segmentsOf(path).some(113 (segment) =>114 segment === "held-back" ||115 (segment.startsWith(".env") && segment !== ".env.schema")116 );117118const isReadme = (path: string) => /^readme(?:\.|$)/iu.test(baseName(path));119120const isTest = (path: string) =>121 segmentsOf(path).some((segment) => testFolders.has(segment)) ||122 /[._-](?:test|spec)\.[^.]+$/u.test(baseName(path)) ||123 baseName(path).startsWith("test_");124125const isSource = (path: string) =>126 sourceExtensions.has(extensionOf(path)) &&127 !isTest(path) &&128 !path.startsWith(`${Brand.configDir}/`) &&129 !segmentsOf(path).some((segment) => vendored.has(segment));130131const isAskFile = (path: string) =>132 path.startsWith(askFolder) &&133 path.endsWith(askSuffix) &&134 !path.slice(askFolder.length).includes("/");135136/** A file's name without its extensions: `add.test.ts` is `add`. */137const stemOf = (path: string) => baseName(path).split(".")[0] ?? "";138139/** A word and its camel-case parts, lower-cased: `addMonths` → addmonths, add, months. */140const wordsOf = (text: string): readonly string[] =>141 text142 .split(/[^A-Za-z0-9]+/u)143 .flatMap((word) =>144 word.length === 0145 ? []146 : [147 word.toLowerCase(),148 ...(word.match(/[A-Z]?[a-z0-9]+|[A-Z]+(?![a-z])/gu) ?? []).map(149 (part) => part.toLowerCase()150 ),151 ]152 )153 .filter((word) => word.length >= 3 && !stopWords.has(word));154155/** How many of the want's words a path shares, its extension left out. */156const overlap = (want: ReadonlySet<string>, path: string) =>157 Array.dedupe(158 wordsOf(path.slice(0, path.length - extensionOf(path).length))159 ).filter((word) => want.has(word)).length;160161interface Ranked {162 readonly path: string;163 readonly score: number;164}165166/** Most shared words first, then by path. */167const byScore = Order.combine(168 Order.mapInput(Order.flip(Order.Number), ({ score }: Ranked) => score),169 Order.mapInput(Order.String, ({ path }: Ranked) => path)170);171172/** The source files whose path shares a word with the want, most first, at most `rankedFiles`. */173const ranked = (paths: readonly string[], want: ReadonlySet<string>) =>174 paths175 .flatMap((path): Ranked[] => {176 const score = isSource(path) ? overlap(want, path) : 0;177178 return score > 0 ? [{ path, score }] : [];179 })180 .toSorted(byScore)181 .slice(0, rankedFiles)182 .map(({ path }) => path);183184/** The tests beside a source file: the same stem with a test suffix, anywhere. */185const siblingTests = (tree: readonly string[], source: string) => {186 const stem = stemOf(source);187188 return tree.filter(189 (path) =>190 isTest(path) &&191 path !== source &&192 (stemOf(path) === stem || baseName(path).startsWith(`test_${stem}.`))193 );194};195196const decodeLiteral = Schema.decodeOption(Schema.fromJsonString(Schema.String));197198/** The test file an ask file names in its `path`, when it names one. */199const askTestPath = (source: string): Option.Option<string> =>200 pipe(201 Option.fromNullishOr(202 /\bpath:\s*(?<literal>"(?:[^"\\\n]|\\.)*")/u.exec(source)?.groups?.literal203 ),204 Option.flatMap(decodeLiteral)205 );206207/** The folder the picked style example's test sits in: the project's ask-test folder. */208export const askTestFolderOf = (209 files: readonly ConfigFile[]210): Option.Option<string> =>211 pipe(212 Array.findFirst(files, ({ path }) => isAskFile(path)),213 Option.flatMap(({ content }) => askTestPath(content)),214 Option.map(folderOf)215 );216217const encoder = new TextEncoder();218219const decoder = new TextDecoder();220221/** `content` cut to at most `room` bytes and its marker, or none when nothing fits. */222const cut = (content: string, room: number): Option.Option<string> => {223 const bytes = encoder.encode(content);224225 if (bytes.length <= Math.min(room, perFile)) {226 return Option.some(content);227 }228229 const shown = Math.min(perFile, room - markerRoom);230231 return shown <= 0232 ? Option.none()233 : Option.some(234 `${decoder.decode(bytes.slice(0, shown)).replace(/�$/u, "")}\n[cut: the first ${shown} of ${bytes.length} bytes]\n`235 );236};237238/**239 * The files the model reads for a want, in the order above, each read once240 * through `read` and the whole within `budget` bytes. The same tree, in any241 * order, and the same want give the same files.242 */243export const pickFiles = (244 tree: readonly RepoPath[],245 input: { readonly want: string; readonly territory?: readonly RepoPath[] },246 read: (path: RepoPath) => Effect.Effect<string>,247 budget: number = defaultBudget248): Effect.Effect<readonly ConfigFile[]> =>249 Effect.gen(function* () {250 const paths: readonly string[] = Array.dedupe(251 tree.filter((path) => !isWithheld(path)).toSorted(Order.String)252 );253254 const rootReadmes = paths.filter(255 (path) => !path.includes("/") && isReadme(path)256 );257258 const settings = [259 ...paths.filter((path) => manifests.has(path)),260 ...paths.filter((path) => path === `${Brand.configDir}/project.ts`),261 ];262263 const example = Array.last(paths.filter(isAskFile));264265 const exampleSource = yield* Option.match(example, {266 onNone: () => Effect.succeed(Option.none<string>()),267 onSome: (path) => Effect.asSome(read(RepoPath.make(path))),268 });269270 const exampleTest = pipe(271 exampleSource,272 Option.flatMap(askTestPath),273 Option.filter((path) => paths.includes(path))274 );275276 const want = new Set(wordsOf(input.want));277278 const chosen =279 input.territory === undefined || input.territory.length === 0280 ? ranked(paths, want)281 : paths.filter((path) =>282 (input.territory ?? []).some(283 (territory) =>284 path === territory || path.startsWith(`${territory}/`)285 )286 );287288 const withTests = chosen.flatMap((path) => [289 path,290 ...(isTest(path) ? [] : siblingTests(paths, path)),291 ]);292293 const otherReadmes = paths.filter(294 (path) => path.includes("/") && isReadme(path)295 );296297 const order = Array.dedupe([298 ...Option.toArray(example),299 ...Option.toArray(exampleTest),300 ...rootReadmes,301 ...settings,302 ...withTests,303 ...otherReadmes,304 ]);305306 const picked: ConfigFile[] = [];307 let left = budget;308309 for (const path of order) {310 const content =311 path === Option.getOrUndefined(example)312 ? Option.getOrElse(exampleSource, () => "")313 : yield* read(RepoPath.make(path));314315 const shown = cut(content, left);316317 if (Option.isSome(shown)) {318 picked.push({ content: shown.value, path: RepoPath.make(path) });319 left -= encoder.encode(shown.value).length;320 }321 }322323 return picked;324 });