@turri-dev/cli 0.4.2-next.a6867e8 → 0.4.3-next.3fc888b

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 (128) hide show
  1. package/README.md +1 -0
  2. package/dist/background-skills.d.ts +4 -1
  3. package/dist/background-skills.js +9 -1
  4. package/dist/capture/agents.d.ts +391 -0
  5. package/dist/capture/agents.js +338 -0
  6. package/dist/capture/area.d.ts +58 -0
  7. package/dist/capture/area.js +197 -0
  8. package/dist/capture/assemble.d.ts +122 -0
  9. package/dist/capture/assemble.js +452 -0
  10. package/dist/capture/capture.d.ts +116 -0
  11. package/dist/capture/capture.js +1281 -0
  12. package/dist/capture/chat.d.ts +29 -0
  13. package/dist/capture/chat.js +94 -0
  14. package/dist/capture/checks.d.ts +142 -0
  15. package/dist/capture/checks.js +643 -0
  16. package/dist/capture/config.d.ts +13 -0
  17. package/dist/capture/config.js +60 -0
  18. package/dist/capture/interface.d.ts +71 -0
  19. package/dist/capture/interface.js +199 -0
  20. package/dist/capture/map.d.ts +58 -0
  21. package/dist/capture/map.js +530 -0
  22. package/dist/capture/plan.d.ts +8 -0
  23. package/dist/capture/plan.js +13 -0
  24. package/dist/capture/progress.d.ts +109 -0
  25. package/dist/capture/progress.js +240 -0
  26. package/dist/capture/report.d.ts +75 -0
  27. package/dist/capture/report.js +268 -0
  28. package/dist/capture/scripts.d.ts +26 -0
  29. package/dist/capture/scripts.js +33 -0
  30. package/dist/capture/state.d.ts +299 -0
  31. package/dist/capture/state.js +43 -0
  32. package/dist/capture/trial.d.ts +34 -0
  33. package/dist/capture/trial.js +89 -0
  34. package/dist/capture-cli.d.ts +1 -0
  35. package/dist/capture-cli.js +77 -0
  36. package/dist/chat-commands.d.ts +2 -10
  37. package/dist/chat-commands.js +3 -57
  38. package/dist/chat-tab-header.d.ts +15 -0
  39. package/dist/chat-tab-header.js +78 -0
  40. package/dist/chat-tabs.d.ts +26 -0
  41. package/dist/chat-tabs.js +100 -0
  42. package/dist/chat-terminal.js +57 -8
  43. package/dist/chat-waiting.d.ts +4 -1
  44. package/dist/chat-waiting.js +7 -4
  45. package/dist/chats.d.ts +12 -7
  46. package/dist/chats.js +35 -21
  47. package/dist/cli.js +32 -14
  48. package/dist/config-edit.js +4 -2
  49. package/dist/config.d.ts +15 -2
  50. package/dist/config.js +62 -4
  51. package/dist/extension.d.ts +1 -0
  52. package/dist/extension.js +262 -136
  53. package/dist/identity.js +3 -2
  54. package/dist/init-config.js +2 -0
  55. package/dist/loop-cli.js +5 -1
  56. package/dist/loop-tools.d.ts +2 -3
  57. package/dist/loop-tools.js +12 -13
  58. package/dist/new-project.d.ts +5 -0
  59. package/dist/new-project.js +11 -0
  60. package/dist/pi-launch.js +2 -0
  61. package/dist/pi-themes.d.ts +3 -0
  62. package/dist/pi-themes.js +21 -0
  63. package/dist/pi.js +2 -2
  64. package/dist/plain-code-blocks.d.ts +14 -0
  65. package/dist/plain-code-blocks.js +56 -0
  66. package/dist/pointer-hover.d.ts +12 -0
  67. package/dist/pointer-hover.js +48 -0
  68. package/dist/question-dialog.d.ts +5 -0
  69. package/dist/question-dialog.js +20 -1
  70. package/dist/regenerate/chunk-plan.d.ts +2 -11
  71. package/dist/regenerate/chunk-plan.js +9 -20
  72. package/dist/regenerate/command-check.d.ts +9 -0
  73. package/dist/regenerate/command-check.js +163 -14
  74. package/dist/regenerate/job-panel.d.ts +5 -107
  75. package/dist/regenerate/job-panel.js +4 -289
  76. package/dist/regenerate/jobs-tree.d.ts +1 -0
  77. package/dist/regenerate/jobs-tree.js +5 -1
  78. package/dist/regenerate/loop.d.ts +6 -14
  79. package/dist/regenerate/loop.js +51 -35
  80. package/dist/regenerate/side-panel.d.ts +6 -1
  81. package/dist/regenerate/side-panel.js +158 -22
  82. package/dist/regenerate/spec-map-view.d.ts +11 -3
  83. package/dist/regenerate/spec-map-view.js +22 -2
  84. package/dist/regenerate/test-scripts.d.ts +8 -0
  85. package/dist/regenerate/test-scripts.js +20 -5
  86. package/dist/reopen.d.ts +29 -0
  87. package/dist/reopen.js +47 -0
  88. package/dist/resume-line.d.ts +4 -1
  89. package/dist/resume-line.js +5 -2
  90. package/dist/sentinel-chat.js +7 -2
  91. package/dist/sentinel.d.ts +1 -1
  92. package/dist/sentinel.js +4 -2
  93. package/dist/setup.js +9 -1
  94. package/dist/terminal-notifications.d.ts +31 -0
  95. package/dist/terminal-notifications.js +134 -0
  96. package/docs/README.md +2 -0
  97. package/docs/capture.md +207 -0
  98. package/docs/chats.md +8 -7
  99. package/docs/config.md +18 -3
  100. package/docs/development.md +4 -1
  101. package/docs/hosting.md +2 -2
  102. package/docs/launch.md +2 -2
  103. package/docs/regenerating.md +9 -8
  104. package/docs/sandbox.md +3 -1
  105. package/docs/sentinel.md +11 -11
  106. package/docs/skills-and-gates.md +1 -1
  107. package/docs/theming.md +3 -3
  108. package/docs/using.md +12 -5
  109. package/genome/capture/capture.md +26 -0
  110. package/genome/capture/check-conventions.md +5 -0
  111. package/genome/capture/check-reference.md +11 -0
  112. package/genome/capture/compact.md +7 -0
  113. package/genome/capture/concepts.md +3 -0
  114. package/genome/capture/divide.md +9 -0
  115. package/genome/capture/feature.md +45 -0
  116. package/genome/capture/interface.md +9 -0
  117. package/genome/capture/modules.md +23 -0
  118. package/genome/capture/outline.md +11 -0
  119. package/genome/capture/readability.md +12 -0
  120. package/genome/capture/reference.md +10 -0
  121. package/genome/capture/split.md +9 -0
  122. package/genome/capture/survey.md +37 -0
  123. package/genome/capture/trial.md +18 -0
  124. package/genome/capture/verify.md +7 -0
  125. package/genome/rules/turri-regeneration.md +2 -2
  126. package/package.json +3 -3
  127. package/dist/regenerate/steer.d.ts +0 -34
  128. package/dist/regenerate/steer.js +0 -91
@@ -0,0 +1,530 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { closeSync, existsSync, openSync, readdirSync, readFileSync, readSync, statSync } from "node:fs";
3
+ import { join, relative, resolve } from "node:path";
4
+ import { posix } from "node:path";
5
+ import { isWithin, slashed } from "../regenerate/paths.js";
6
+ /**
7
+ * The surfaces that are the software's interface - what a user, a client or a script calls by name: its routes, commands,
8
+ * options, screens and the environment variables it reads. Capture names every one in its ***plain, or says why not.
9
+ */
10
+ export const INTERFACE_KINDS = new Set(["route", "command", "option", "screen", "env"]);
11
+ /** Folders never part of what is captured: dependencies, caches, histories, build output, turri's own. */
12
+ const SKIPPED_DIRS = new Set([
13
+ ".git",
14
+ ".hg",
15
+ ".svn",
16
+ "node_modules",
17
+ ".venv",
18
+ "venv",
19
+ "__pycache__",
20
+ ".mypy_cache",
21
+ ".pytest_cache",
22
+ ".ruff_cache",
23
+ ".tox",
24
+ ".nox",
25
+ ".next",
26
+ ".nuxt",
27
+ ".svelte-kit",
28
+ ".turri",
29
+ ".plaingit",
30
+ "plain_modules",
31
+ ".gradle",
32
+ ".idea",
33
+ ".vscode",
34
+ "target",
35
+ "coverage",
36
+ ]);
37
+ /** Lock files: the versions the dependencies are pinned to, which say nothing about what the software does. */
38
+ export const LOCK_FILES = new Set([
39
+ "package-lock.json",
40
+ "yarn.lock",
41
+ "pnpm-lock.yaml",
42
+ "bun.lockb",
43
+ "poetry.lock",
44
+ "uv.lock",
45
+ "Pipfile.lock",
46
+ "go.sum",
47
+ "Cargo.lock",
48
+ "composer.lock",
49
+ "Gemfile.lock",
50
+ ]);
51
+ /** Files that say nothing about what the software does: lock files and the like. */
52
+ const SKIPPED_FILES = new Set([...LOCK_FILES, ".DS_Store"]);
53
+ const SOURCE_EXTENSIONS = new Set([
54
+ "py", "js", "jsx", "ts", "tsx", "mjs", "cjs", "mts", "cts", "go", "rs", "java", "kt", "kts", "scala", "rb", "php", "cs", "fs",
55
+ "swift", "c", "h", "cc", "cpp", "hpp", "m", "mm", "ex", "exs", "erl", "clj", "cljs", "dart", "lua", "vue", "svelte", "astro",
56
+ "html", "htm", "jinja", "jinja2", "j2", "hbs", "handlebars", "ejs", "erb", "twig", "css", "scss", "sass", "less", "sql", "sh",
57
+ "bash", "zsh", "ps1", "r", "jl", "elm", "hs", "ml", "zig", "nim",
58
+ ]);
59
+ const DOC_EXTENSIONS = new Set(["md", "mdx", "rst", "adoc", "txt"]);
60
+ const ASSET_EXTENSIONS = new Set([
61
+ "png", "jpg", "jpeg", "gif", "svg", "webp", "ico", "bmp", "avif", "tif", "tiff", "woff", "woff2", "ttf", "otf", "eot", "mp3",
62
+ "wav", "ogg", "flac", "m4a", "mp4", "webm", "mov", "avi",
63
+ ]);
64
+ const MANIFEST_FILES = new Set([
65
+ "package.json", "pyproject.toml", "setup.py", "setup.cfg", "Pipfile", "go.mod", "Cargo.toml", "pom.xml", "build.gradle",
66
+ "build.gradle.kts", "settings.gradle", "settings.gradle.kts", "Gemfile", "composer.json", "mix.exs", "deno.json", "Dockerfile",
67
+ "docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml", "Makefile", "tsconfig.json", "vite.config.ts",
68
+ "vite.config.js", "next.config.js", "next.config.mjs", "angular.json", "manage.py",
69
+ ]);
70
+ /** The folders tests live in, by name. */
71
+ const TEST_DIRS = new Set(["test", "tests", "__tests__", "spec", "specs", "e2e", "cypress", "playwright", "integration_tests"]);
72
+ const TEST_FILE = /(^test_.*\.py$)|(_test\.(py|go)$)|(\.(test|spec)\.[cm]?[jt]sx?$)|(Tests?\.(java|kt|cs)$)|(_spec\.rb$)|(^conftest\.py$)/;
73
+ /** A file larger than this has its lines counted, and no surfaces looked for: generated, minified or data. */
74
+ const MAX_SCANNED_BYTES = 512 * 1024;
75
+ /**
76
+ * How many tests, exports or tables a file keeps: enough to show what it does, never a generated file's thousands. Its
77
+ * interface is kept whole - a file defining seventy options has seventy - since capture checks every one.
78
+ */
79
+ const MAX_SURFACES_PER_KIND = 60;
80
+ function extensionOf(name) {
81
+ const dot = name.lastIndexOf(".");
82
+ return dot <= 0 ? "" : name.slice(dot + 1).toLowerCase();
83
+ }
84
+ /** What kind of file a path is, by its name and folders alone. */
85
+ export function kindOf(path) {
86
+ const parts = path.split("/");
87
+ const name = parts.at(-1);
88
+ const extension = extensionOf(name);
89
+ if (MANIFEST_FILES.has(name) || /^requirements.*\.txt$/.test(name) || /\.(csproj|sln|cabal|gemspec)$/.test(name))
90
+ return "manifest";
91
+ if (ASSET_EXTENSIONS.has(extension))
92
+ return "asset";
93
+ if (isContract(path, name, extension))
94
+ return "contract";
95
+ if (TEST_FILE.test(name) || parts.slice(0, -1).some((part) => TEST_DIRS.has(part)))
96
+ return SOURCE_EXTENSIONS.has(extension) ? "test" : "other";
97
+ if (SOURCE_EXTENSIONS.has(extension))
98
+ return "source";
99
+ if (DOC_EXTENSIONS.has(extension))
100
+ return "doc";
101
+ return "other";
102
+ }
103
+ function isContract(path, name, extension) {
104
+ if (/^(openapi|swagger)[^/]*\.(ya?ml|json)$/i.test(name))
105
+ return true;
106
+ if (["graphql", "gql", "proto", "avsc", "prisma"].includes(extension))
107
+ return true;
108
+ if (/\.schema\.json$/i.test(name))
109
+ return true;
110
+ if (extension === "sql" && path.split("/").some((part) => /^(migrations?|schema|db)$/i.test(part)))
111
+ return true;
112
+ if (/^schema\.sql$/i.test(name))
113
+ return true;
114
+ return false;
115
+ }
116
+ /** The files of a codebase: what git sees - tracked, and untracked but not ignored - in a repo; every file but the skipped ones elsewhere. */
117
+ export function listFiles(root, exclude = []) {
118
+ const excluded = exclude.map((path) => resolve(path));
119
+ const kept = (path) => {
120
+ const parts = path.split("/");
121
+ if (parts.slice(0, -1).some((part) => SKIPPED_DIRS.has(part)) || SKIPPED_FILES.has(parts.at(-1)))
122
+ return false;
123
+ const absolute = join(root, ...parts);
124
+ return !excluded.some((dir) => isWithin(absolute, dir));
125
+ };
126
+ const fromGit = spawnSync("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], { cwd: root, encoding: "utf8", maxBuffer: 256 * 1024 * 1024 });
127
+ if (fromGit.status === 0) {
128
+ return [...new Set(fromGit.stdout.split("\0").filter((path) => path !== ""))]
129
+ .filter(kept)
130
+ .filter((path) => {
131
+ try {
132
+ return statSync(join(root, ...path.split("/"))).isFile();
133
+ }
134
+ catch {
135
+ // Deleted, and not yet committed as deleted.
136
+ return false;
137
+ }
138
+ })
139
+ .sort();
140
+ }
141
+ const found = [];
142
+ const walk = (dir) => {
143
+ let entries;
144
+ try {
145
+ entries = readdirSync(dir, { withFileTypes: true });
146
+ }
147
+ catch {
148
+ return;
149
+ }
150
+ for (const entry of entries) {
151
+ const path = join(dir, entry.name);
152
+ if (entry.isDirectory()) {
153
+ if (!SKIPPED_DIRS.has(entry.name) && !excluded.some((skip) => isWithin(path, skip)))
154
+ walk(path);
155
+ }
156
+ else if (entry.isFile()) {
157
+ found.push(slashed(relative(root, path)));
158
+ }
159
+ }
160
+ };
161
+ walk(root);
162
+ return found.filter(kept).sort();
163
+ }
164
+ /** Whether a file's start holds a NUL byte - binary, however it is named. */
165
+ function looksBinary(path) {
166
+ let fd;
167
+ try {
168
+ fd = openSync(path, "r");
169
+ const buffer = Buffer.alloc(8000);
170
+ const read = readSync(fd, buffer, 0, buffer.length, 0);
171
+ return buffer.subarray(0, read).includes(0);
172
+ }
173
+ catch {
174
+ return true;
175
+ }
176
+ finally {
177
+ if (fd !== undefined)
178
+ closeSync(fd);
179
+ }
180
+ }
181
+ function countLines(text) {
182
+ if (text === "")
183
+ return 0;
184
+ let lines = 1;
185
+ for (let at = text.indexOf("\n"); at !== -1; at = text.indexOf("\n", at + 1))
186
+ lines += 1;
187
+ return text.endsWith("\n") ? lines - 1 : lines;
188
+ }
189
+ /** Build the map of the codebase at `root`, leaving out what `exclude` names - capture's own output above all. */
190
+ export function buildMap(root, options = {}) {
191
+ const absoluteRoot = resolve(root);
192
+ const paths = withoutPlainProjects(listFiles(absoluteRoot, options.exclude ?? []));
193
+ const texts = new Map();
194
+ const files = paths.map((path) => {
195
+ const kind = kindOf(path);
196
+ const disk = join(absoluteRoot, ...path.split("/"));
197
+ if (kind === "asset")
198
+ return { path, kind, lines: 0, surfaces: [], imports: [] };
199
+ let size = 0;
200
+ try {
201
+ size = statSync(disk).size;
202
+ }
203
+ catch {
204
+ return { path, kind, lines: 0, surfaces: [], imports: [] };
205
+ }
206
+ if (looksBinary(disk))
207
+ return { path, kind: "other", lines: 0, surfaces: [], imports: [] };
208
+ let text = "";
209
+ try {
210
+ text = readFileSync(disk, "utf8");
211
+ }
212
+ catch {
213
+ return { path, kind, lines: 0, surfaces: [], imports: [] };
214
+ }
215
+ const lines = countLines(text);
216
+ if (size <= MAX_SCANNED_BYTES && (kind === "source" || kind === "test" || kind === "contract"))
217
+ texts.set(path, text);
218
+ return { path, kind, lines, bytes: size, surfaces: [], imports: [] };
219
+ });
220
+ const resolver = importResolver(absoluteRoot, paths);
221
+ for (const file of files) {
222
+ const text = texts.get(file.path);
223
+ if (text === undefined)
224
+ continue;
225
+ file.surfaces = surfacesOf(file.path, text, file.kind);
226
+ file.imports = resolver(file.path, text).filter((target) => target !== file.path);
227
+ }
228
+ // File-routed frameworks: the route is the file's own path.
229
+ for (const file of files) {
230
+ const route = fileRoute(file.path);
231
+ if (route !== undefined && !file.surfaces.some((surface) => surface.kind === "screen" && surface.name === route))
232
+ file.surfaces.unshift({ kind: "screen", name: route });
233
+ }
234
+ return { root: absoluteRoot, files };
235
+ }
236
+ /**
237
+ * The files outside the turri projects in the codebase - a folder with a `config.turri.yaml` or a module's own file,
238
+ * an earlier capture's: its ***plain is not the code, and capture never reads what it wrote itself.
239
+ */
240
+ export function withoutPlainProjects(paths) {
241
+ const projects = paths.filter((path) => /^config\.turri(\.[^/]+)?\.yaml$/.test(posix.basename(path)) && path.includes("/")).map((path) => posix.dirname(path));
242
+ return paths.filter((path) => !projects.some((project) => path.startsWith(`${project}/`)));
243
+ }
244
+ /** A page of Next.js, Nuxt, SvelteKit or Astro, whose route is where the file is. */
245
+ export function fileRoute(path) {
246
+ const pages = /(?:^|\/)(?:src\/)?pages\/(.+)\.(?:tsx|jsx|ts|js|vue|astro|md|mdx)$/.exec(path);
247
+ if (pages !== null) {
248
+ const route = pages[1].replace(/(^|\/)index$/, "");
249
+ // The app's frame and its API routes are not pages anyone visits.
250
+ if (/(^|\/)_(app|document|error)$/.test(route) || pages[1].startsWith("api/"))
251
+ return undefined;
252
+ return `/${route}`;
253
+ }
254
+ const app = /(?:^|\/)(?:src\/)?app\/(?:(.+)\/)?page\.(?:tsx|jsx|ts|js|mdx)$/.exec(path);
255
+ if (app !== null)
256
+ return `/${(app[1] ?? "").split("/").filter((part) => !/^\(.*\)$/.test(part)).join("/")}`;
257
+ const svelte = /(?:^|\/)src\/routes\/(?:(.+)\/)?\+page\.svelte$/.exec(path);
258
+ if (svelte !== null)
259
+ return `/${(svelte[1] ?? "").split("/").filter((part) => !/^\(.*\)$/.test(part)).join("/")}`;
260
+ return undefined;
261
+ }
262
+ const PY = ["py"];
263
+ const JS = ["js", "jsx", "ts", "tsx", "mjs", "cjs", "mts", "cts", "vue", "svelte"];
264
+ const HTTP_METHODS = "get|post|put|patch|delete|head|options|all";
265
+ const upper = (text) => (text ?? "").toUpperCase();
266
+ /** An option's names as its definition lists them, quotes gone: `"-v", "--verbose"` is `-v, --verbose`. */
267
+ const optionNames = (list) => (list ?? "").split(",").map((name) => name.trim().replace(/^["']|["']$/g, "")).join(", ");
268
+ const PATTERNS = [
269
+ // Flask, FastAPI, Starlette, Sanic, aiohttp - a decorator with the path.
270
+ {
271
+ kind: "route",
272
+ regex: /@[\w.]+\.(route|get|post|put|patch|delete|head|options|websocket|api_route)\(\s*f?["']([^"']*)["']([^\n]*)/g,
273
+ extensions: PY,
274
+ name: (m) => {
275
+ const methods = /methods\s*=\s*[[(]([^\])]*)[\])]/.exec(m[3] ?? "")?.[1];
276
+ const method = m[1] === "route" || m[1] === "api_route" ? (methods !== undefined ? methods.replace(/["'\s]/g, "").toUpperCase() : "GET") : upper(m[1]);
277
+ return `${method} ${m[2]}`;
278
+ },
279
+ },
280
+ // Django.
281
+ { kind: "route", regex: /\b(?:re_)?path\(\s*r?["']([^"']*)["']/g, extensions: PY, name: (m) => `/${m[1].replace(/^\^|\$$/g, "")}` },
282
+ // Express, Fastify, Koa, Hono.
283
+ {
284
+ kind: "route",
285
+ regex: new RegExp(`\\b(?:app|router|server|api|fastify|routes|r)\\.(${HTTP_METHODS})\\(\\s*["'\`]([^"'\`]+)["'\`]`, "g"),
286
+ extensions: JS,
287
+ name: (m) => `${upper(m[1])} ${m[2]}`,
288
+ },
289
+ // NestJS.
290
+ { kind: "route", regex: /@(Get|Post|Put|Patch|Delete|All)\(\s*(?:["'`]([^"'`]*)["'`])?\s*\)/g, extensions: ["ts", "js"], name: (m) => `${upper(m[1])} ${m[2] ?? ""}`.trim() },
291
+ // Spring.
292
+ {
293
+ kind: "route",
294
+ regex: /@(Get|Post|Put|Patch|Delete|Request)Mapping\(\s*(?:value\s*=\s*|path\s*=\s*)?\{?\s*"([^"]*)"/g,
295
+ extensions: ["java", "kt"],
296
+ name: (m) => `${m[1] === "Request" ? "ANY" : upper(m[1])} ${m[2]}`,
297
+ },
298
+ // Go: net/http, gin, echo, chi, fiber.
299
+ { kind: "route", regex: /\.(?:HandleFunc|Handle)\(\s*"([^"]+)"/g, extensions: ["go"], name: (m) => m[1] },
300
+ { kind: "route", regex: /\.(GET|POST|PUT|PATCH|DELETE|Get|Post|Put|Patch|Delete)\(\s*"([^"]+)"/g, extensions: ["go"], name: (m) => `${upper(m[1])} ${m[2]}` },
301
+ // Rails.
302
+ { kind: "route", regex: /^\s*(get|post|put|patch|delete)\s+["']([^"']+)["']/gm, extensions: ["rb"], name: (m) => `${upper(m[1])} ${m[2]}` },
303
+ { kind: "route", regex: /^\s*resources?\s+:(\w+)/gm, extensions: ["rb"], name: (m) => `resources ${m[1]}` },
304
+ // axum, actix.
305
+ { kind: "route", regex: /\.route\(\s*"([^"]+)"\s*,\s*(get|post|put|patch|delete)/g, extensions: ["rs"], name: (m) => `${upper(m[2])} ${m[1]}` },
306
+ { kind: "route", regex: /#\[(get|post|put|patch|delete)\(\s*"([^"]+)"/g, extensions: ["rs"], name: (m) => `${upper(m[1])} ${m[2]}` },
307
+ // Commands: click, typer, argparse, cobra, commander, yargs, picocli, clap.
308
+ {
309
+ kind: "command",
310
+ regex: /@[\w.]*command\(\s*(?:name\s*=\s*)?(?:["']([^"']+)["'])?[^\n]*\n(?:\s*@[^\n]*\n)*\s*(?:async\s+)?def\s+(\w+)/g,
311
+ extensions: PY,
312
+ name: (m) => m[1] ?? m[2].replace(/_/g, "-"),
313
+ },
314
+ { kind: "command", regex: /add_parser\(\s*["']([^"']+)["']/g, extensions: PY, name: (m) => m[1] },
315
+ // An option with every name it has: `add_argument("-v", "--verbose", ...)` is `-v, --verbose`.
316
+ { kind: "option", regex: /add_argument\(\s*((?:["']--?[\w-]+["']\s*,\s*)*["']--?[\w-]+["'])/g, extensions: PY, name: (m) => optionNames(m[1]) },
317
+ { kind: "option", regex: /@click\.option\(\s*((?:["']--?[\w-]+["']\s*,\s*)*["']--?[\w-]+["'])/g, extensions: PY, name: (m) => optionNames(m[1]) },
318
+ { kind: "command", regex: /\bUse:\s*"([^"\s]+)/g, extensions: ["go"], name: (m) => m[1] },
319
+ { kind: "command", regex: /\.command\(\s*["'`]([^"'`\s<[]+)/g, extensions: JS, name: (m) => m[1] },
320
+ { kind: "option", regex: /\.(?:option|requiredOption)\(\s*["'`]((?:-\w,\s*)?--?[\w-]+)/g, extensions: JS, name: (m) => m[1] },
321
+ { kind: "command", regex: /@Command\(\s*name\s*=\s*"([^"]+)"/g, extensions: ["java", "kt"], name: (m) => m[1] },
322
+ { kind: "command", regex: /(?:Command::new|SubCommand::with_name)\(\s*"([^"]+)"/g, extensions: ["rs"], name: (m) => m[1] },
323
+ // Environment variables read, by name in capitals.
324
+ { kind: "env", regex: /\b(?:os\.)?(?:environ\.get|getenv|environ\.setdefault)\(\s*["']([A-Z][A-Z0-9_]*)["']/g, extensions: PY, kinds: ["source"], name: (m) => m[1] },
325
+ { kind: "env", regex: /\b(?:os\.)?environ\[\s*["']([A-Z][A-Z0-9_]*)["']\s*\]/g, extensions: PY, kinds: ["source"], name: (m) => m[1] },
326
+ { kind: "env", regex: /\bprocess\.env(?:\.([A-Z][A-Z0-9_]*)\b|\[\s*["'`]([A-Z][A-Z0-9_]*)["'`]\s*\])/g, extensions: JS, kinds: ["source"], name: (m) => m[1] ?? m[2] },
327
+ { kind: "env", regex: /\bos\.(?:Getenv|LookupEnv)\(\s*"([A-Z][A-Z0-9_]*)"/g, extensions: ["go"], kinds: ["source"], name: (m) => m[1] },
328
+ { kind: "env", regex: /\benv::var(?:_os)?\(\s*"([A-Z][A-Z0-9_]*)"/g, extensions: ["rs"], kinds: ["source"], name: (m) => m[1] },
329
+ { kind: "env", regex: /\bSystem\.getenv\(\s*"([A-Z][A-Z0-9_]*)"/g, extensions: ["java", "kt"], kinds: ["source"], name: (m) => m[1] },
330
+ { kind: "env", regex: /\bENV(?:\[\s*|\.fetch\(\s*)["']([A-Z][A-Z0-9_]*)["']/g, extensions: ["rb"], kinds: ["source"], name: (m) => m[1] },
331
+ // An environment variable named by a constant - `ENV_HTTPIE_CONFIG_DIR = 'HTTPIE_CONFIG_DIR'` - and read through it.
332
+ { kind: "env", regex: /^\s*(?:export\s+)?(?:const\s+|let\s+|var\s+|static\s+final\s+String\s+|pub\s+const\s+)?(?:\w*_)?ENV(?:_\w+)?(?:\s*:\s*\w+)?\s*:?=\s*["']([A-Z][A-Z0-9]*_[A-Z0-9_]+)["']/gm, kinds: ["source"], name: (m) => m[1] },
333
+ // Screens: React Router, Vue Router, Angular.
334
+ { kind: "screen", regex: /<Route\b[^>]*\bpath=\{?["'`]([^"'`]+)["'`]/g, extensions: JS, name: (m) => m[1] },
335
+ { kind: "screen", regex: /\bpath:\s*["'`](\/?[\w\-/:*.]*)["'`]\s*,\s*(?:component|element|loadComponent|loadChildren|children|name|redirectTo|lazy)/g, extensions: JS, name: (m) => (m[1].startsWith("/") ? m[1] : `/${m[1]}`) },
336
+ // Tables and models.
337
+ { kind: "table", regex: /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"[]?(?:\w+\.)?(\w+)/gi, name: (m) => m[1] },
338
+ { kind: "table", regex: /__tablename__\s*=\s*["'](\w+)["']/g, extensions: PY, name: (m) => m[1] },
339
+ { kind: "table", regex: /^class\s+(\w+)\((?:[\w.]*\bBase|db\.Model|SQLModel|models\.Model|Document|Model)\b[^)]*\)/gm, extensions: PY, name: (m) => m[1] },
340
+ { kind: "table", regex: /^model\s+(\w+)\s*\{/gm, extensions: ["prisma"], name: (m) => m[1] },
341
+ { kind: "table", regex: /@Entity\b[^\n]*\n(?:\s*@[^\n]*\n)*\s*(?:export\s+)?(?:public\s+)?class\s+(\w+)/g, extensions: ["ts", "java", "kt"], name: (m) => m[1] },
342
+ { kind: "table", regex: /\bmodel\(\s*["'](\w+)["']\s*,/g, extensions: JS, name: (m) => m[1] },
343
+ { kind: "table", regex: /^type\s+(\w+)\s+struct\s*\{[^}]*gorm/gm, extensions: ["go"], name: (m) => m[1] },
344
+ // Test names.
345
+ { kind: "test", regex: /^\s*(?:async\s+)?def\s+(test_\w+)/gm, extensions: PY, kinds: ["test"], name: (m) => m[1] },
346
+ { kind: "test", regex: /\b(?:it|test)(?:\.(?:only|skip|each\([^)]*\)))?\(\s*["'`]([^"'`]+)["'`]/g, extensions: JS, kinds: ["test"], name: (m) => m[1] },
347
+ { kind: "test", regex: /^func\s+(Test\w+)\(/gm, extensions: ["go"], kinds: ["test"], name: (m) => m[1] },
348
+ { kind: "test", regex: /@Test\b[^\n]*\n(?:\s*@[^\n]*\n)*\s*(?:public\s+)?(?:void|fun)\s+(\w+)/g, extensions: ["java", "kt"], kinds: ["test"], name: (m) => m[1] },
349
+ { kind: "test", regex: /#\[(?:tokio::)?test\][^\n]*\n\s*(?:async\s+)?fn\s+(\w+)/g, extensions: ["rs"], name: (m) => m[1] },
350
+ { kind: "test", regex: /^\s*it\s+["']([^"']+)["']/gm, extensions: ["rb"], kinds: ["test"], name: (m) => m[1] },
351
+ // Exports: what a library offers.
352
+ { kind: "export", regex: /^export\s+(?:default\s+)?(?:async\s+)?(?:function\*?|class|const|let|interface|type|enum)\s+(\w+)/gm, extensions: JS, kinds: ["source"], name: (m) => m[1] },
353
+ { kind: "export", regex: /^(?:async\s+)?def\s+([a-zA-Z]\w*)\s*\(|^class\s+([A-Z]\w*)/gm, extensions: PY, kinds: ["source"], name: (m) => m[1] ?? m[2] },
354
+ { kind: "export", regex: /^func\s+(?:\([^)]*\)\s*)?([A-Z]\w*)|^type\s+([A-Z]\w*)/gm, extensions: ["go"], kinds: ["source"], name: (m) => m[1] ?? m[2] },
355
+ { kind: "export", regex: /^pub\s+(?:async\s+)?(?:fn|struct|enum|trait)\s+(\w+)/gm, extensions: ["rs"], kinds: ["source"], name: (m) => m[1] },
356
+ { kind: "export", regex: /^public\s+(?:final\s+|abstract\s+)?(?:class|interface|enum|record)\s+(\w+)/gm, extensions: ["java"], kinds: ["source"], name: (m) => m[1] },
357
+ ];
358
+ /** The surfaces a file shows, by the patterns that apply to it - each kind kept to a few dozen. */
359
+ export function surfacesOf(path, text, kind) {
360
+ const extension = extensionOf(path.split("/").at(-1));
361
+ const found = [];
362
+ const seen = new Set();
363
+ const counts = new Map();
364
+ for (const pattern of PATTERNS) {
365
+ if (pattern.extensions !== undefined && !pattern.extensions.includes(extension))
366
+ continue;
367
+ if (pattern.kinds !== undefined && !pattern.kinds.includes(kind))
368
+ continue;
369
+ // A table pattern written for SQL applies to SQL files, and to source that embeds it.
370
+ pattern.regex.lastIndex = 0;
371
+ for (let match = pattern.regex.exec(text); match !== null; match = pattern.regex.exec(text)) {
372
+ if (match[0] === "")
373
+ pattern.regex.lastIndex += 1;
374
+ const name = pattern.name(match)?.trim();
375
+ if (name === undefined || name === "")
376
+ continue;
377
+ const key = `${pattern.kind} ${name}`;
378
+ if (seen.has(key))
379
+ continue;
380
+ const count = counts.get(pattern.kind) ?? 0;
381
+ if (count >= MAX_SURFACES_PER_KIND && !INTERFACE_KINDS.has(pattern.kind))
382
+ continue;
383
+ seen.add(key);
384
+ counts.set(pattern.kind, count + 1);
385
+ found.push({ kind: pattern.kind, name });
386
+ }
387
+ }
388
+ // A source file with routes, commands, options or screens: what it exports is how they are built, not what it offers.
389
+ if (found.some((surface) => INTERFACE_KINDS.has(surface.kind) && surface.kind !== "env"))
390
+ return found.filter((surface) => surface.kind !== "export");
391
+ return found;
392
+ }
393
+ /**
394
+ * What resolves a file's imports to the codebase's own files - relative ones in JavaScript, Python's modules, Go's
395
+ * packages under go.mod's module, Java's packages, Rust's crate paths. Best effort: what it cannot place is left out,
396
+ * and an import of a library is not the codebase's.
397
+ */
398
+ function importResolver(root, paths) {
399
+ const all = new Set(paths);
400
+ const dirs = new Set();
401
+ for (const path of paths)
402
+ for (let dir = posix.dirname(path); dir !== "."; dir = posix.dirname(dir))
403
+ dirs.add(dir);
404
+ // Python: a module by its dotted name, from the root and from each folder that holds packages (src/ and the like).
405
+ const pythonModules = new Map();
406
+ for (const path of paths.filter((path) => path.endsWith(".py"))) {
407
+ const dotted = path.replace(/\.py$/, "").replace(/\/__init__$/, "").split("/");
408
+ for (let start = 0; start < dotted.length; start += 1) {
409
+ const name = dotted.slice(start).join(".");
410
+ if (!pythonModules.has(name))
411
+ pythonModules.set(name, path);
412
+ }
413
+ }
414
+ // Go: the module path go.mod declares.
415
+ let goModule;
416
+ try {
417
+ goModule = /^module\s+(\S+)/m.exec(readFileSync(join(root, "go.mod"), "utf8"))?.[1];
418
+ }
419
+ catch {
420
+ goModule = undefined;
421
+ }
422
+ // Java and Kotlin: a package by the folder it is in.
423
+ const packageDirs = new Map();
424
+ for (const dir of dirs) {
425
+ const parts = dir.split("/");
426
+ for (let start = 0; start < parts.length; start += 1) {
427
+ const name = parts.slice(start).join(".");
428
+ if (!packageDirs.has(name))
429
+ packageDirs.set(name, dir);
430
+ }
431
+ }
432
+ const filesIn = (dir) => paths.filter((path) => posix.dirname(path) === dir);
433
+ const resolveRelative = (from, target) => {
434
+ const base = target.startsWith("@/") ? posix.join(dirs.has("src") ? "src" : ".", target.slice(2)) : posix.join(posix.dirname(from), target);
435
+ const normal = posix.normalize(base);
436
+ const candidates = [normal, ...["ts", "tsx", "js", "jsx", "mjs", "cjs", "mts", "vue", "svelte", "json"].flatMap((ext) => [`${normal}.${ext}`, `${normal}/index.${ext}`])];
437
+ // TypeScript written with .js imports of .ts files.
438
+ if (/\.js$/.test(normal))
439
+ candidates.push(normal.replace(/\.js$/, ".ts"), normal.replace(/\.js$/, ".tsx"));
440
+ return candidates.find((candidate) => all.has(candidate));
441
+ };
442
+ return (path, text) => {
443
+ const found = new Set();
444
+ const extension = extensionOf(path);
445
+ if (JS.includes(extension)) {
446
+ for (const match of text.matchAll(/(?:from\s+|require\(\s*|import\(\s*|import\s+)["'`]((?:\.{1,2}\/|@\/)[^"'`]+)["'`]/g)) {
447
+ const target = resolveRelative(path, match[1]);
448
+ if (target !== undefined)
449
+ found.add(target);
450
+ }
451
+ }
452
+ else if (extension === "py") {
453
+ // `from x import a, b` on one line, or `from x import (a,\n b)` over several - never into the next line's import.
454
+ for (const match of text.matchAll(/^[ \t]*from[ \t]+(\.*)([\w.]*)[ \t]+import[ \t]+(\([^)]*\)|[\w, \t*]+)|^[ \t]*import[ \t]+([\w.]+)/gm)) {
455
+ let name;
456
+ if (match[4] !== undefined) {
457
+ name = match[4];
458
+ }
459
+ else if (match[1] !== "") {
460
+ // Relative: from the file's own package up.
461
+ const levels = match[1].length;
462
+ const pkg = posix.dirname(path).split("/").filter((part) => part !== ".");
463
+ const base = pkg.slice(0, Math.max(0, pkg.length - (levels - 1)));
464
+ name = [...base, ...(match[2] !== "" ? match[2].split(".") : [])].join(".");
465
+ }
466
+ else {
467
+ name = match[2];
468
+ }
469
+ // The longest dotted prefix that is one of the codebase's modules.
470
+ const parts = name.split(".");
471
+ for (let end = parts.length; end > 0; end -= 1) {
472
+ const module = pythonModules.get(parts.slice(0, end).join("."));
473
+ if (module !== undefined) {
474
+ found.add(module);
475
+ break;
476
+ }
477
+ }
478
+ // `from pkg import module`: each name may be a module of the package.
479
+ if (match[3] !== undefined) {
480
+ for (const imported of match[3].replace(/[()]/g, "").split(",").map((name) => name.trim().split(/\s+/)[0])) {
481
+ const module = pythonModules.get(`${name}.${imported}`);
482
+ if (module !== undefined)
483
+ found.add(module);
484
+ }
485
+ }
486
+ }
487
+ }
488
+ else if (extension === "go" && goModule !== undefined) {
489
+ for (const match of text.matchAll(/"([^"\s]+)"/g)) {
490
+ const target = match[1];
491
+ if (!target.startsWith(`${goModule}/`))
492
+ continue;
493
+ const dir = target.slice(goModule.length + 1);
494
+ for (const file of filesIn(dir))
495
+ if (file.endsWith(".go"))
496
+ found.add(file);
497
+ }
498
+ }
499
+ else if (extension === "java" || extension === "kt") {
500
+ for (const match of text.matchAll(/^import\s+(?:static\s+)?([\w.]+?)(?:\.\*|\.[A-Z]\w*)*\s*;?$/gm)) {
501
+ const dir = packageDirs.get(match[1]);
502
+ if (dir === undefined)
503
+ continue;
504
+ const className = /\.([A-Z]\w*)/.exec(match[0])?.[1];
505
+ const files = filesIn(dir).filter((file) => className === undefined || posix.basename(file).startsWith(`${className}.`));
506
+ for (const file of files)
507
+ found.add(file);
508
+ }
509
+ }
510
+ else if (extension === "rs") {
511
+ for (const match of text.matchAll(/\buse\s+crate::(\w+)/g)) {
512
+ const srcDir = path.includes("/") ? path.slice(0, path.indexOf("/")) : ".";
513
+ for (const candidate of [posix.join(srcDir, `${match[1]}.rs`), posix.join(srcDir, match[1], "mod.rs")])
514
+ if (all.has(candidate))
515
+ found.add(candidate);
516
+ }
517
+ }
518
+ return [...found].sort();
519
+ };
520
+ }
521
+ /** Whether the map has a file or folder at a path - `.` being the whole codebase. */
522
+ export function existsInMap(map, path) {
523
+ if (path === "." || path === "")
524
+ return true;
525
+ return map.files.some((file) => file.path === path || file.path.startsWith(`${path}/`));
526
+ }
527
+ /** Whether a folder named on the codebase's disk is there - for paths an agent gives that the map leaves out. */
528
+ export function existsOnDisk(map, path) {
529
+ return existsSync(join(map.root, ...path.split("/")));
530
+ }
@@ -0,0 +1,8 @@
1
+ import { type CodeMap } from "./map.ts";
2
+ export interface CapturePlan {
3
+ kind: "compact" | "staged";
4
+ reason: string;
5
+ }
6
+ export declare const COMPACT_SURFACES = 12;
7
+ /** Choose the pipeline from the map, without a planning agent. The survey, reference or writer may later uncover more work. */
8
+ export declare function capturePlan(map: CodeMap, leafLines: number): CapturePlan;
@@ -0,0 +1,13 @@
1
+ import { INTERFACE_KINDS } from "./map.js";
2
+ // One writer can follow this much code and test evidence in a turn. Bound bytes too: minified code may be one line.
3
+ const COMPACT = { files: 12, lines: 800, bytes: 64 * 1024 };
4
+ export const COMPACT_SURFACES = 12;
5
+ /** Choose the pipeline from the map, without a planning agent. The survey, reference or writer may later uncover more work. */
6
+ export function capturePlan(map, leafLines) {
7
+ const files = map.files.filter((file) => file.kind === "source" || file.kind === "test" || file.kind === "contract");
8
+ const lines = files.reduce((n, file) => n + file.lines, 0);
9
+ const bytes = files.reduce((n, file) => n + (file.bytes ?? Infinity), 0);
10
+ const surfaces = files.reduce((n, file) => n + (file.kind === "test" ? 0 : file.surfaces.filter((surface) => INTERFACE_KINDS.has(surface.kind)).length), 0);
11
+ const fits = files.length <= COMPACT.files && lines <= Math.min(leafLines, COMPACT.lines) && bytes <= COMPACT.bytes && surfaces <= COMPACT_SURFACES;
12
+ return { kind: fits ? "compact" : "staged", reason: `${files.length} source, test and contract files, ${lines} lines, ${Number.isFinite(bytes) ? `${Math.ceil(bytes / 1024)} KiB` : "size unknown"}, ${surfaces} mapped interface entries` };
13
+ }