@mmerterden/multi-agent-pipeline 20.40.0 → 20.41.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 (76) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +4 -1
  3. package/README.tr.md +4 -1
  4. package/docs/adr/0019-product-tree.md +143 -0
  5. package/docs/adr/README.md +1 -0
  6. package/docs/ecosystem.md +9 -9
  7. package/docs/facts.json +4 -4
  8. package/docs/features.md +6 -0
  9. package/install/claude.mjs +12 -3
  10. package/install/templates/claude-hooks.json +12 -1
  11. package/manifest.json +79 -60
  12. package/package.json +2 -2
  13. package/pipeline/commands/multi-agent/review-analysis/SKILL.md +1 -1
  14. package/pipeline/contract/types/index.d.ts +53 -49
  15. package/pipeline/lib/context-budget.mjs +5 -42
  16. package/pipeline/lib/hook-registration.mjs +5 -0
  17. package/pipeline/lib/md2confluence-v3.py +12 -4
  18. package/pipeline/lib/tiered-budget.mjs +87 -0
  19. package/pipeline/multi-agent-refs/analysis/review.md +23 -1
  20. package/pipeline/multi-agent-refs/features/code-graph.md +11 -1
  21. package/pipeline/multi-agent-refs/features/doctor.md +32 -1
  22. package/pipeline/multi-agent-refs/features/product-tree.md +68 -0
  23. package/pipeline/multi-agent-refs/features/unattended-security.md +88 -1
  24. package/pipeline/multi-agent-refs/features/usage-reporting.md +31 -0
  25. package/pipeline/multi-agent-refs/help/en.md +1 -0
  26. package/pipeline/multi-agent-refs/help/tr.md +1 -0
  27. package/pipeline/multi-agent-refs/knowledge.md +58 -0
  28. package/pipeline/multi-agent-refs/phases/phase-0-init.md +4 -0
  29. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +4 -0
  30. package/pipeline/multi-agent-refs/phases/phase-5-report.md +2 -0
  31. package/pipeline/office/index.html +13 -7
  32. package/pipeline/office/toolkit.json +1 -1
  33. package/pipeline/preferences-template.json +1 -0
  34. package/pipeline/schemas/learnings-ledger.schema.json +35 -2
  35. package/pipeline/schemas/office-archive.schema.json +225 -128
  36. package/pipeline/schemas/prefs.schema.json +83 -0
  37. package/pipeline/schemas/product-tree-overlay.schema.json +57 -0
  38. package/pipeline/schemas/product-tree.schema.json +136 -0
  39. package/pipeline/schemas/toolkit-path-params.json +1 -1
  40. package/pipeline/scripts/_eval-stats.mjs +182 -0
  41. package/pipeline/scripts/_guard_rules.py +130 -1
  42. package/pipeline/scripts/_learnings-promotion.mjs +229 -0
  43. package/pipeline/scripts/_locate.mjs +539 -0
  44. package/pipeline/scripts/_memory-policy.mjs +213 -14
  45. package/pipeline/scripts/_product-tree-extract.mjs +761 -0
  46. package/pipeline/scripts/_product-tree.mjs +923 -0
  47. package/pipeline/scripts/_retrieval.mjs +13 -2
  48. package/pipeline/scripts/_stack-routing.mjs +1 -0
  49. package/pipeline/scripts/_user_guard_rules.py +744 -0
  50. package/pipeline/scripts/agent-guard.py +61 -5
  51. package/pipeline/scripts/agent-guard.sh +8 -1
  52. package/pipeline/scripts/doctor.mjs +157 -1
  53. package/pipeline/scripts/graph-query.mjs +257 -17
  54. package/pipeline/scripts/learnings-ledger.mjs +664 -43
  55. package/pipeline/scripts/note-mcp-failure.mjs +356 -0
  56. package/pipeline/scripts/note-mcp-failure.sh +19 -0
  57. package/pipeline/scripts/note-skill-use.mjs +93 -23
  58. package/pipeline/scripts/office-archive.mjs +23 -10
  59. package/pipeline/scripts/office-memory.mjs +4 -1
  60. package/pipeline/scripts/persona-walk-anchors.mjs +443 -0
  61. package/pipeline/scripts/product-tree-eval.mjs +685 -0
  62. package/pipeline/scripts/product-tree.mjs +544 -0
  63. package/pipeline/skills/.skill-manifest.json +11 -7
  64. package/pipeline/skills/.skills-index.json +12 -1
  65. package/pipeline/skills/shared/README.md +4 -3
  66. package/pipeline/skills/shared/core/google-play-compliance/references/examples.md +1 -1
  67. package/pipeline/skills/shared/core/multi-agent-review-analysis/SKILL.md +1 -1
  68. package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
  69. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
  70. package/pipeline/skills/shared/external/spec-persona-walk/SKILL.md +118 -0
  71. package/pipeline/skills/shared/external/spec-persona-walk/evals/evals.json +50 -0
  72. package/pipeline/skills/shared/external/spec-persona-walk/scripts/persona-walk-anchors.mjs +443 -0
  73. package/pipeline/skills/shared/external/storekit/SKILL.md +1 -1
  74. package/pipeline/skills/shared/external/swiftdata/SKILL.md +1 -1
  75. package/pipeline/skills/skill-copies.json +5 -1
  76. package/pipeline/skills/skills-index.md +2 -1
@@ -0,0 +1,923 @@
1
+ /**
2
+ * @file _product-tree.mjs - the screen layer over the code graph.
3
+ *
4
+ * A bug report names what a person saw: a button label, a screen, a step in a
5
+ * flow. The code graph knows files and symbols. This module joins the two,
6
+ * deterministically and without a model:
7
+ *
8
+ * localized text -> string key -> files that reference it -> screen
9
+ * route -> screen -> the files it owns -> endpoints it calls
10
+ * test -> the screens it names
11
+ *
12
+ * Extraction is regex over comment-stripped source, the same trade the code
13
+ * graph makes (ADR-0010). Per stack:
14
+ *
15
+ * ios SwiftUI views with a body named *Screen, *Scene or *Page, plus any
16
+ * view that is a navigation target: NavigationLink (destination,
17
+ * trailing closure, value), navigationDestination (a switch over a
18
+ * route enum, or a single view), sheet / fullScreenCover / popover,
19
+ * the first view inside NavigationStack / NavigationView, every
20
+ * view in a TabView, scene entries (WindowGroup, Window, Settings,
21
+ * MenuBarExtra, DocumentGroup), any view that hosts one of those
22
+ * navigation forms, and UIHostingController
23
+ * roots inside a coordinator, which becomes a flow node
24
+ * android NavHost registrations: composable, entry, dialog and bottomSheet,
25
+ * each as ("route") or <Type>,
26
+ * @Serializable route types, a startDestination, and @Composable
27
+ * functions named *Screen; a registration whose body calls a
28
+ * wrapper composable is followed one hop to the *Screen it calls
29
+ * web Next.js app/ and pages/ routes (only when a package.json depends
30
+ * on next), app router API handlers, and react-router route tables
31
+ * and <Route> elements
32
+ *
33
+ * Programmatic navigation (path.append, navigate(...), push / present,
34
+ * navController.navigate, router.push) is counted per stack, and each call is
35
+ * resolved only when its argument is a literal route or a view constructor.
36
+ * The rest are listed as unresolved, because coverage is a measured number:
37
+ * an app that navigates through a coordinator with computed destinations
38
+ * shows up as low coverage rather than as a complete-looking tree.
39
+ *
40
+ * Strings files (Localizable.strings, .xcstrings, strings.xml, i18n JSON) give
41
+ * the value -> key index; a key is referenced by a file that holds it as a
42
+ * string literal or names it as R.string.<key>. Endpoints come from Retrofit
43
+ * annotations, app router handlers, and API-shaped path literals.
44
+ *
45
+ * The repository is untrusted input. Files are read only when they are
46
+ * regular files inside the root, at most MAX_INPUT_BYTES, never through a
47
+ * symlink, and decoded from UTF-8 or UTF-16. Every git call goes through
48
+ * safeGit, which turns off the repository's fsmonitor, hooks, external diff,
49
+ * pager, signature checks and gpg programs, and reads no global or system
50
+ * config.
51
+ *
52
+ * Zero dependencies (ADR-0004).
53
+ *
54
+ * @module pipeline/scripts/_product-tree
55
+ */
56
+
57
+ import {
58
+ closeSync,
59
+ constants,
60
+ fstatSync,
61
+ lstatSync,
62
+ openSync,
63
+ readSync,
64
+ readdirSync,
65
+ realpathSync,
66
+ } from "node:fs";
67
+ import { execFileSync } from "node:child_process";
68
+ import { basename, join, relative, sep, posix } from "node:path";
69
+ import { loadRules, extractFile, buildGraph, isTestPath } from "./_code-graph.mjs";
70
+ import { isExcludedBy } from "./_path-match.mjs";
71
+ import {
72
+ EXTENSIONS,
73
+ API_LITERAL,
74
+ stackOf,
75
+ detectStacks,
76
+ extractSwiftUI,
77
+ extractCompose,
78
+ extractWeb,
79
+ nextRouteFromPath,
80
+ nextApiFromPath,
81
+ isStringsFile,
82
+ parseStringsFile,
83
+ pathPattern,
84
+ templateLiteralPath,
85
+ decodeText,
86
+ } from "./_product-tree-extract.mjs";
87
+
88
+ export {
89
+ TREE_STACKS,
90
+ stackOf,
91
+ detectStacks,
92
+ scanSource,
93
+ stripCommentsKeepStrings,
94
+ extractSwiftUI,
95
+ extractCompose,
96
+ extractWeb,
97
+ nextRouteFromPath,
98
+ nextApiFromPath,
99
+ isStringsFile,
100
+ localeFromPath,
101
+ parseStringsFile,
102
+ pathPattern,
103
+ decodeText,
104
+ } from "./_product-tree-extract.mjs";
105
+
106
+ export const PRODUCT_TREE_SCHEMA_VERSION = "1.0.0";
107
+
108
+ /** The largest input file the build and the eval read; both skip anything larger. */
109
+ export const MAX_INPUT_BYTES = 2 * 1024 * 1024;
110
+
111
+ /**
112
+ * Settings that keep a repository's own config from running a program during
113
+ * a read: an fsmonitor, a hook, an external diff, a pager, or a gpg program
114
+ * that log.showSignature would start for a signed commit. Textconv drivers
115
+ * and filters are kept out by the call shapes instead: diff-tree passes
116
+ * --no-ext-diff and --no-textconv, and no call reads a working-tree file
117
+ * through git.
118
+ */
119
+ export const SAFE_GIT_CONFIG = [
120
+ "-c",
121
+ "core.fsmonitor=false",
122
+ "-c",
123
+ "core.hooksPath=/dev/null",
124
+ "-c",
125
+ "diff.external=",
126
+ "-c",
127
+ "core.pager=cat",
128
+ "-c",
129
+ "log.showSignature=false",
130
+ "-c",
131
+ "gpg.program=false",
132
+ "-c",
133
+ "gpg.ssh.program=false",
134
+ "-c",
135
+ "gpg.x509.program=false",
136
+ ];
137
+
138
+ /**
139
+ * git in `repo` with SAFE_GIT_CONFIG and no shell. The environment's
140
+ * GIT_EXTERNAL_DIFF is dropped for the same reason, and the global and
141
+ * system config files are not read, so a key set there cannot start a
142
+ * program either.
143
+ *
144
+ * @param {string} repo
145
+ * @param {string[]} args
146
+ * @param {{encoding?: BufferEncoding|null, input?: string, maxBuffer?: number}} [opts]
147
+ * @returns {string|Buffer}
148
+ */
149
+ export function safeGit(repo, args, opts = {}) {
150
+ const env = { ...process.env };
151
+ delete env.GIT_EXTERNAL_DIFF;
152
+ env.GIT_CONFIG_NOSYSTEM = "1";
153
+ env.GIT_CONFIG_GLOBAL = "/dev/null";
154
+ return execFileSync("git", ["-C", repo, ...SAFE_GIT_CONFIG, ...args], {
155
+ encoding: opts.encoding === undefined ? "utf8" : (opts.encoding ?? "buffer"),
156
+ maxBuffer: opts.maxBuffer ?? 256 * 1024 * 1024,
157
+ input: opts.input === undefined ? undefined : Buffer.from(opts.input, "utf8"),
158
+ env,
159
+ stdio: [opts.input === undefined ? "ignore" : "pipe", "pipe", "ignore"],
160
+ });
161
+ }
162
+ const RULES_FOR = { ios: "ios", android: "android", web: "node" };
163
+ const MAX_MEMBERS = 12;
164
+ const MAX_UNRESOLVED = 50;
165
+ const HUB_INBOUND = 25;
166
+
167
+ // ------------------------------------------------------------------ build --
168
+
169
+ /**
170
+ * Build the product tree from file contents.
171
+ *
172
+ * @param {object} params
173
+ * @param {Map<string, string|{text: string, id?: string}>} params.files repo-relative path -> content
174
+ * @param {string[]} [params.stacks] default: detected
175
+ * @param {string} [params.project]
176
+ * @param {string|null} [params.baseCommit]
177
+ * @param {string} [params.generatedAt]
178
+ * @param {Map<string, any>} [params.cache] memo for per-file work, keyed by content id
179
+ * @returns {object} a document valid against product-tree.schema.json, plus
180
+ * `graphs` (non-enumerable) holding the in-memory code graph per stack
181
+ */
182
+ export function buildProductTree({
183
+ files,
184
+ stacks,
185
+ project = "project",
186
+ baseCommit = null,
187
+ generatedAt = new Date().toISOString(),
188
+ cache = null,
189
+ }) {
190
+ const textOf = (p) => {
191
+ const v = files.get(p);
192
+ return typeof v === "string" ? v : (v?.text ?? "");
193
+ };
194
+ const memo = (kind, p, fn) => {
195
+ const v = files.get(p);
196
+ const id = typeof v === "object" && v?.id ? v.id : null;
197
+ if (!cache || !id) return fn();
198
+ const k = `${kind}\0${p}\0${id}`;
199
+ if (!cache.has(k)) cache.set(k, fn());
200
+ return cache.get(k);
201
+ };
202
+ const paths = [...files.keys()].sort();
203
+ const active = stacks && stacks.length ? stacks : detectStacks(paths);
204
+ const nodes = new Map();
205
+ const edges = [];
206
+ const edgeKeys = new Set();
207
+ const addNode = (n) => {
208
+ if (!nodes.has(n.id)) nodes.set(n.id, n);
209
+ return nodes.get(n.id);
210
+ };
211
+ const addEdge = (from, to, kind, extra = {}) => {
212
+ const k = `${from}\0${to}\0${kind}`;
213
+ if (edgeKeys.has(k) || from === to) return;
214
+ edgeKeys.add(k);
215
+ edges.push({ from, to, kind, ...extra });
216
+ };
217
+ addNode({ id: "app", kind: "app", name: project });
218
+
219
+ const graphs = {};
220
+ const coverage = {};
221
+ const fileLiterals = new Map();
222
+ const fileStringRefs = new Map();
223
+ const screensByStack = {};
224
+ const endpointDefs = [];
225
+ const endpointCalls = new Map();
226
+
227
+ for (const stack of active) {
228
+ const rules = loadRules(RULES_FOR[stack]);
229
+ const exts = new Set([...rules.sourceExtensions, ...EXTENSIONS[stack]]);
230
+ const sources = paths.filter(
231
+ (p) =>
232
+ [...exts].some((e) => p.endsWith(e)) &&
233
+ EXTENSIONS[stack].some((e) => p.endsWith(e)) &&
234
+ !isExcludedBy(p, rules.excludePathGlobs),
235
+ );
236
+ const extracted = new Map();
237
+ for (const p of sources) {
238
+ try {
239
+ extracted.set(
240
+ p,
241
+ memo(`graph-${stack}`, p, () => extractFile(textOf(p), rules)),
242
+ );
243
+ } catch {
244
+ /* unreadable source: it simply does not reach the graph */
245
+ }
246
+ }
247
+ const graph = buildGraph({ root: "", stack: RULES_FOR[stack], extracted, rules, generatedAt });
248
+ graphs[stack] = graph;
249
+ const isTest = (p) => isTestPath(p, rules);
250
+ const facts = new Map();
251
+ for (const p of sources) {
252
+ const f = memo(`tree-${stack}`, p, () =>
253
+ stack === "ios"
254
+ ? extractSwiftUI(textOf(p))
255
+ : stack === "android"
256
+ ? extractCompose(textOf(p))
257
+ : extractWeb(textOf(p)),
258
+ );
259
+ facts.set(p, f);
260
+ fileLiterals.set(p, f.literals);
261
+ if (f.stringRefs) fileStringRefs.set(p, f.stringRefs);
262
+ }
263
+ const ctx = { stack, sources, facts, isTest, addNode, addEdge, nodes, textOf, paths };
264
+ const result =
265
+ stack === "ios"
266
+ ? resolveIos(ctx)
267
+ : stack === "android"
268
+ ? resolveAndroid(ctx)
269
+ : resolveWeb(ctx);
270
+ screensByStack[stack] = result.screens;
271
+ endpointDefs.push(...result.endpointDefs);
272
+ for (const [p, calls] of result.endpointCalls) endpointCalls.set(p, calls);
273
+ attachMembers(result.screens, graph, facts, stack);
274
+ linkTests(ctx, result.screens, extracted);
275
+ coverage[stack] = {
276
+ screens: result.screens.length,
277
+ reachable: 0,
278
+ routes: result.routeCount,
279
+ routesWithScreen: result.routesWithScreen,
280
+ programmatic: {
281
+ total: result.programmatic.length,
282
+ resolved: result.programmatic.filter((x) => x.resolved).length,
283
+ unresolved: result.programmatic
284
+ .filter((x) => !x.resolved)
285
+ .slice(0, MAX_UNRESOLVED)
286
+ .map(({ path, line, text }) => ({ path, line, text })),
287
+ },
288
+ };
289
+ }
290
+
291
+ // Strings: value index plus the files that reference each key.
292
+ const strings = new Map();
293
+ for (const p of paths.filter(isStringsFile)) {
294
+ for (const row of memo("strings", p, () => parseStringsFile(textOf(p), p))) {
295
+ if (!strings.has(row.key)) strings.set(row.key, { values: {}, path: p });
296
+ const s = strings.get(row.key);
297
+ if (s.values[row.locale] === undefined) s.values[row.locale] = row.value;
298
+ }
299
+ }
300
+ const keyFiles = new Map();
301
+ for (const [p, lits] of fileLiterals) {
302
+ for (const v of lits) if (strings.has(v)) push(keyFiles, v, p);
303
+ }
304
+ for (const [p, refs] of fileStringRefs) {
305
+ for (const k of refs) if (strings.has(k)) push(keyFiles, k, p);
306
+ }
307
+ for (const key of [...strings.keys()].sort()) {
308
+ const s = strings.get(key);
309
+ addNode({
310
+ id: `string:${key}`,
311
+ kind: "string",
312
+ name: key,
313
+ path: s.path,
314
+ values: sortObject(s.values),
315
+ files: [...new Set(keyFiles.get(key) || [])].sort(),
316
+ });
317
+ }
318
+
319
+ // Endpoints: definitions, then calls matched to them by path pattern.
320
+ const defByPattern = new Map();
321
+ for (const d of endpointDefs) {
322
+ const id = `endpoint:${d.method} ${d.path}`;
323
+ addNode({ id, kind: "endpoint", name: `${d.method} ${d.path}`, path: d.file, line: d.line });
324
+ push(defByPattern, pathPattern(d.path), id);
325
+ }
326
+ const endpointsOfFile = new Map();
327
+ for (const d of endpointDefs) push(endpointsOfFile, d.file, `endpoint:${d.method} ${d.path}`);
328
+ for (const [p, calls] of endpointCalls) {
329
+ for (const c of calls) {
330
+ const matched = defByPattern.get(pathPattern(c.path));
331
+ if (matched) {
332
+ for (const id of matched) push(endpointsOfFile, p, id);
333
+ continue;
334
+ }
335
+ const id = `endpoint:ANY ${c.path}`;
336
+ addNode({ id, kind: "endpoint", name: `ANY ${c.path}`, path: p, line: c.line });
337
+ push(endpointsOfFile, p, id);
338
+ }
339
+ }
340
+
341
+ for (const stack of active) {
342
+ for (const s of screensByStack[stack]) {
343
+ const node = nodes.get(s.id);
344
+ node.files = s.files;
345
+ const owned = new Set(s.files);
346
+ for (const key of strings.keys()) {
347
+ if ((keyFiles.get(key) || []).some((f) => owned.has(f))) {
348
+ addEdge(s.id, `string:${key}`, "uses-string");
349
+ }
350
+ }
351
+ for (const f of s.files) {
352
+ for (const id of endpointsOfFile.get(f) || []) addEdge(s.id, id, "calls");
353
+ }
354
+ }
355
+ const inbound = new Set(
356
+ edges
357
+ .filter((e) => ["shows", "navigates", "presents", "entry"].includes(e.kind))
358
+ .map((e) => e.to),
359
+ );
360
+ coverage[stack].reachable = screensByStack[stack].filter((s) => inbound.has(s.id)).length;
361
+ }
362
+
363
+ const tree = {
364
+ schemaVersion: PRODUCT_TREE_SCHEMA_VERSION,
365
+ project,
366
+ stacks: active,
367
+ baseCommit,
368
+ generatedAt,
369
+ coverage,
370
+ stats: {
371
+ nodes: nodes.size,
372
+ edges: edges.length,
373
+ screens: [...nodes.values()].filter((n) => n.kind === "screen").length,
374
+ strings: strings.size,
375
+ },
376
+ nodes: [...nodes.values()].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)),
377
+ edges: edges.sort((a, b) =>
378
+ a.from !== b.from
379
+ ? a.from < b.from
380
+ ? -1
381
+ : 1
382
+ : a.to !== b.to
383
+ ? a.to < b.to
384
+ ? -1
385
+ : 1
386
+ : a.kind < b.kind
387
+ ? -1
388
+ : a.kind > b.kind
389
+ ? 1
390
+ : 0,
391
+ ),
392
+ };
393
+ Object.defineProperty(tree, "graphs", { value: graphs, enumerable: false });
394
+ return tree;
395
+ }
396
+
397
+ function push(map, k, v) {
398
+ if (!map.has(k)) map.set(k, []);
399
+ map.get(k).push(v);
400
+ }
401
+
402
+ function sortObject(o) {
403
+ return Object.fromEntries(Object.entries(o).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
404
+ }
405
+
406
+ const screenId = (path, name) => `screen:${path}#${name}`;
407
+
408
+ function resolveIos({ sources, facts, addNode, addEdge, isTest }) {
409
+ const views = new Map();
410
+ const typeFile = new Map();
411
+ const routeEnums = new Map();
412
+ for (const p of sources) {
413
+ if (isTest(p)) continue;
414
+ for (const t of facts.get(p).types) {
415
+ if (t.isView && !views.has(t.name)) views.set(t.name, { path: p, line: t.line });
416
+ if (!typeFile.has(t.name) && t.kind !== "extension") typeFile.set(t.name, { path: p, ...t });
417
+ if (t.kind === "enum") routeEnums.set(t.name, { path: p, line: t.line, cases: t.cases });
418
+ }
419
+ }
420
+ const routeEnumNames = new Set();
421
+ const routeTargets = new Map();
422
+ const targeted = new Map();
423
+ const navs = [];
424
+ const entryNames = new Set();
425
+ for (const p of sources) {
426
+ if (isTest(p)) continue;
427
+ const f = facts.get(p);
428
+ for (const e of f.entries) if (views.has(e)) entryNames.add(e);
429
+ for (const r of f.refs) {
430
+ if (r.via === "route") {
431
+ const enumName = r.route.type.split(".").pop();
432
+ if (!views.has(r.target)) continue;
433
+ routeEnumNames.add(enumName);
434
+ const key = r.route.name ? `${enumName}.${r.route.name}` : enumName;
435
+ routeTargets.set(key, { target: r.target, path: p, line: r.line });
436
+ targeted.set(r.target, true);
437
+ continue;
438
+ }
439
+ navs.push({ ...r, path: p });
440
+ if (r.target && views.has(r.target)) targeted.set(r.target, true);
441
+ if (r.source && views.has(r.source)) targeted.set(r.source, true);
442
+ }
443
+ }
444
+ for (const name of routeEnums.keys()) {
445
+ if (/(Route|Destination)s?$/.test(name)) routeEnumNames.add(name);
446
+ }
447
+ const isScreenName = (n) =>
448
+ views.has(n) && (/(Screen|Scene|Page)$/.test(n) || targeted.has(n) || entryNames.has(n));
449
+ const screens = [];
450
+ for (const [name, v] of [...views].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
451
+ if (!isScreenName(name)) continue;
452
+ const id = screenId(v.path, name);
453
+ addNode({ id, kind: "screen", name, stack: "ios", path: v.path, line: v.line });
454
+ screens.push({ id, name, path: v.path, files: [v.path] });
455
+ }
456
+ const sid = (n) => (isScreenName(n) ? screenId(views.get(n).path, n) : null);
457
+ for (const n of entryNames) addEdge("app", sid(n), "entry");
458
+
459
+ let routeCount = 0;
460
+ let routesWithScreen = 0;
461
+ const caseOwner = new Map();
462
+ for (const name of [...routeEnumNames].sort()) {
463
+ const e = routeEnums.get(name);
464
+ const cases = e ? e.cases : [];
465
+ for (const c of cases) {
466
+ push(caseOwner, c, name);
467
+ const rid = `route:ios:${name}.${c}`;
468
+ addNode({
469
+ id: rid,
470
+ kind: "route",
471
+ name: `${name}.${c}`,
472
+ stack: "ios",
473
+ path: e.path,
474
+ line: e.line,
475
+ });
476
+ routeCount++;
477
+ const t = routeTargets.get(`${name}.${c}`);
478
+ if (t && sid(t.target)) {
479
+ addEdge(rid, sid(t.target), "shows");
480
+ routesWithScreen++;
481
+ }
482
+ }
483
+ if (!cases.length && routeTargets.has(name)) {
484
+ const t = routeTargets.get(name);
485
+ const rid = `route:ios:${name}`;
486
+ const tf = typeFile.get(name);
487
+ addNode({
488
+ id: rid,
489
+ kind: "route",
490
+ name,
491
+ stack: "ios",
492
+ path: tf ? tf.path : t.path,
493
+ line: tf ? tf.line : t.line,
494
+ });
495
+ routeCount++;
496
+ if (sid(t.target)) {
497
+ addEdge(rid, sid(t.target), "shows");
498
+ routesWithScreen++;
499
+ }
500
+ }
501
+ }
502
+ const screenOfRoute = (route) => {
503
+ if (!route) return null;
504
+ let enumName = route.type;
505
+ if (!enumName) {
506
+ const owners = caseOwner.get(route.name) || [];
507
+ if (owners.length !== 1) return null;
508
+ enumName = owners[0];
509
+ }
510
+ const t = routeTargets.get(`${enumName}.${route.name}`);
511
+ return t ? sid(t.target) : null;
512
+ };
513
+ for (const n of navs) {
514
+ const to = n.route ? screenOfRoute(n.route) : n.target ? sid(n.target) : null;
515
+ if (!to) continue;
516
+ if (n.via === "hosting") {
517
+ const src = n.source && sid(n.source);
518
+ if (src) addEdge(src, to, "navigates", { via: "hosting" });
519
+ else if (n.source) {
520
+ const t = typeFile.get(n.source);
521
+ const fid = `flow:${t ? t.path : n.path}#${n.source}`;
522
+ addNode({
523
+ id: fid,
524
+ kind: "flow",
525
+ name: n.source,
526
+ stack: "ios",
527
+ path: t ? t.path : n.path,
528
+ line: t ? t.line : n.line,
529
+ });
530
+ addEdge(fid, to, "presents");
531
+ }
532
+ continue;
533
+ }
534
+ const src = n.source && sid(n.source);
535
+ if (src) addEdge(src, to, "navigates", { via: n.via });
536
+ }
537
+ const programmatic = [];
538
+ for (const p of sources) {
539
+ if (isTest(p)) continue;
540
+ for (const c of facts.get(p).programmatic) {
541
+ const to = c.target ? sid(c.target) : screenOfRoute(c.route);
542
+ const src = c.source && sid(c.source);
543
+ if (to && src) addEdge(src, to, "navigates", { via: "programmatic" });
544
+ programmatic.push({ path: p, line: c.line, text: c.text, resolved: Boolean(to) });
545
+ }
546
+ }
547
+ const endpointCalls = new Map();
548
+ for (const p of sources) {
549
+ if (isTest(p)) continue;
550
+ const calls = [...facts.get(p).literals]
551
+ .filter((l) => API_LITERAL.test(l))
552
+ .map((l) => ({ path: l, line: 0 }));
553
+ if (calls.length) endpointCalls.set(p, calls);
554
+ }
555
+ return { screens, routeCount, routesWithScreen, programmatic, endpointDefs: [], endpointCalls };
556
+ }
557
+
558
+ function resolveAndroid({ sources, facts, addNode, addEdge, isTest }) {
559
+ const composables = new Map();
560
+ const routeTypes = new Map();
561
+ const regs = [];
562
+ const starts = [];
563
+ for (const p of sources) {
564
+ if (isTest(p)) continue;
565
+ const f = facts.get(p);
566
+ for (const c of f.composables)
567
+ if (!composables.has(c.name)) composables.set(c.name, { ...c, path: p });
568
+ for (const r of f.routeTypes)
569
+ if (!routeTypes.has(r.name)) routeTypes.set(r.name, { ...r, path: p });
570
+ for (const r of f.registrations) regs.push({ ...r, path: p });
571
+ starts.push(...f.starts);
572
+ }
573
+ const resolveTarget = (name) => {
574
+ if (!name || !composables.has(name)) return null;
575
+ if (/Screen$/.test(name)) return name;
576
+ const inner = composables.get(name).calls.find((c) => /Screen$/.test(c) && composables.has(c));
577
+ return inner || name;
578
+ };
579
+ const screenNames = new Set();
580
+ for (const r of regs) {
581
+ const t = resolveTarget(r.target);
582
+ r.screen = t;
583
+ if (t) screenNames.add(t);
584
+ }
585
+ for (const n of composables.keys()) if (/Screen$/.test(n)) screenNames.add(n);
586
+ const screens = [];
587
+ const sid = (n) => (screenNames.has(n) ? screenId(composables.get(n).path, n) : null);
588
+ for (const n of [...screenNames].sort()) {
589
+ const c = composables.get(n);
590
+ addNode({ id: sid(n), kind: "screen", name: n, stack: "android", path: c.path, line: c.line });
591
+ screens.push({ id: sid(n), name: n, path: c.path, files: [c.path] });
592
+ }
593
+ const routeIdOf = new Map();
594
+ for (const r of regs) {
595
+ const rid = `route:android:${r.route}`;
596
+ addNode({
597
+ id: rid,
598
+ kind: "route",
599
+ name: r.route,
600
+ stack: "android",
601
+ path: r.path,
602
+ line: r.line,
603
+ });
604
+ routeIdOf.set(r.route, rid);
605
+ if (r.screen && sid(r.screen)) addEdge(rid, sid(r.screen), "shows");
606
+ }
607
+ for (const [name, t] of routeTypes) {
608
+ const rid = `route:android:${name}`;
609
+ addNode({ id: rid, kind: "route", name, stack: "android", path: t.path, line: t.line });
610
+ routeIdOf.set(name, rid);
611
+ }
612
+ const routeCount = new Set(routeIdOf.values()).size;
613
+ const withScreen = new Set(regs.filter((r) => r.screen).map((r) => r.route));
614
+ const routesWithScreen = [...routeIdOf.keys()].filter((k) => withScreen.has(k)).length;
615
+ for (const s of starts) {
616
+ const r = regs.find((x) => x.route === s && x.screen);
617
+ if (r) addEdge("app", sid(r.screen), "entry");
618
+ }
619
+ const regByPattern = new Map();
620
+ for (const r of regs) if (!r.typed && r.screen) regByPattern.set(pathPattern(r.route), r);
621
+ const programmatic = [];
622
+ for (const p of sources) {
623
+ if (isTest(p)) continue;
624
+ for (const c of facts.get(p).programmatic) {
625
+ let reg = null;
626
+ if (c.routeLiteral !== null) reg = regByPattern.get(pathPattern(c.routeLiteral)) || null;
627
+ else if (c.routeType)
628
+ reg = regs.find((r) => r.typed && r.route === c.routeType && r.screen) || null;
629
+ const to = reg ? sid(reg.screen) : null;
630
+ const srcReg = c.inRegistration ? regs.find((r) => r.route === c.inRegistration) : null;
631
+ const src = srcReg?.screen ? sid(srcReg.screen) : c.source ? sid(c.source) : null;
632
+ if (to && src) addEdge(src, to, "navigates", { via: "programmatic" });
633
+ programmatic.push({ path: p, line: c.line, text: c.text, resolved: Boolean(to) });
634
+ }
635
+ }
636
+ const endpointDefs = [];
637
+ const endpointCalls = new Map();
638
+ for (const p of sources) {
639
+ if (isTest(p)) continue;
640
+ const f = facts.get(p);
641
+ for (const e of f.endpoints)
642
+ endpointDefs.push({ method: e.method, path: e.path, file: p, line: e.line });
643
+ const calls = [...f.literals]
644
+ .filter((l) => API_LITERAL.test(l))
645
+ .map((l) => ({ path: l, line: 0 }));
646
+ if (calls.length) endpointCalls.set(p, calls);
647
+ }
648
+ return { screens, routeCount, routesWithScreen, programmatic, endpointDefs, endpointCalls };
649
+ }
650
+
651
+ function resolveWeb({ sources, facts, addNode, addEdge, isTest, textOf, paths }) {
652
+ const usesNext = paths
653
+ .filter((p) => basename(p) === "package.json" && !p.includes("node_modules/"))
654
+ .some((p) => /"next"\s*:/.test(textOf(p)));
655
+ const compFiles = new Map();
656
+ for (const p of sources) {
657
+ if (isTest(p)) continue;
658
+ for (const c of facts.get(p).components) push(compFiles, c.name, { path: p, line: c.line });
659
+ }
660
+ const screens = [];
661
+ const screenIds = new Map();
662
+ const addScreen = (name, path, line) => {
663
+ const id = screenId(path, name);
664
+ if (!screenIds.has(id)) {
665
+ addNode({ id, kind: "screen", name, stack: "web", path, line });
666
+ screens.push({ id, name, path, files: [path] });
667
+ screenIds.set(id, true);
668
+ }
669
+ return id;
670
+ };
671
+ let routeCount = 0;
672
+ let routesWithScreen = 0;
673
+ const routePatterns = new Map();
674
+ const endpointDefs = [];
675
+ for (const p of sources) {
676
+ if (isTest(p) || !usesNext) continue;
677
+ const route = nextRouteFromPath(p);
678
+ const f = facts.get(p);
679
+ if (route !== null) {
680
+ const name = f.defaultExport || `Page${route === "/" ? "Root" : route}`;
681
+ const comp = (compFiles.get(name) || []).find((c) => c.path === p);
682
+ const sidv = addScreen(name, p, comp ? comp.line : 1);
683
+ const rid = `route:web:${route}`;
684
+ addNode({ id: rid, kind: "route", name: route, stack: "web", path: p, line: 1 });
685
+ addEdge(rid, sidv, "shows");
686
+ routePatterns.set(pathPattern(route), sidv);
687
+ routeCount++;
688
+ routesWithScreen++;
689
+ }
690
+ const api = nextApiFromPath(p);
691
+ if (api !== null) {
692
+ const methods = f.handlers.length ? f.handlers : [{ method: "ANY", line: 1 }];
693
+ for (const h of methods)
694
+ endpointDefs.push({ method: h.method, path: api, file: p, line: h.line });
695
+ }
696
+ }
697
+ for (const p of sources) {
698
+ if (isTest(p)) continue;
699
+ const f = facts.get(p);
700
+ for (const r of f.routes) {
701
+ const rid = `route:web:${r.path}`;
702
+ addNode({ id: rid, kind: "route", name: r.path, stack: "web", path: p, line: r.line });
703
+ routeCount++;
704
+ const file = resolveComponentFile(r.target, p, textOf(p), compFiles);
705
+ if (!file) continue;
706
+ const sidv = addScreen(r.target, file.path, file.line);
707
+ addEdge(rid, sidv, "shows");
708
+ routePatterns.set(pathPattern(r.path), sidv);
709
+ routesWithScreen++;
710
+ }
711
+ }
712
+ const programmatic = [];
713
+ for (const p of sources) {
714
+ if (isTest(p)) continue;
715
+ for (const c of facts.get(p).programmatic) {
716
+ const to = c.path ? routePatterns.get(pathPattern(templateLiteralPath(c.path))) : null;
717
+ const src = screens.find((s) => s.path === p);
718
+ if (to && src) addEdge(src.id, to, "navigates", { via: "programmatic" });
719
+ programmatic.push({ path: p, line: c.line, text: c.text, resolved: Boolean(to) });
720
+ }
721
+ }
722
+ const endpointCalls = new Map();
723
+ for (const p of sources) {
724
+ if (isTest(p)) continue;
725
+ const calls = [...facts.get(p).literals]
726
+ .map(templateLiteralPath)
727
+ .filter((l) => API_LITERAL.test(l))
728
+ .map((l) => ({ path: l, line: 0 }));
729
+ if (calls.length) endpointCalls.set(p, calls);
730
+ }
731
+ return { screens, routeCount, routesWithScreen, programmatic, endpointDefs, endpointCalls };
732
+ }
733
+
734
+ function resolveComponentFile(name, fromPath, text, compFiles) {
735
+ const defs = compFiles.get(name) || [];
736
+ const imp = text.match(
737
+ new RegExp(
738
+ `import\\s+(?:\\{[^}]*\\b${name}\\b[^}]*\\}|${name})\\s+from\\s+["'](\\.{1,2}/[^"']+)["']`,
739
+ ),
740
+ );
741
+ if (imp) {
742
+ const base = posix.normalize(posix.join(posix.dirname(fromPath), imp[1]));
743
+ const hit = defs.find(
744
+ (d) => d.path.replace(/\.[^.]+$/, "") === base || d.path.startsWith(`${base}/index.`),
745
+ );
746
+ if (hit) return hit;
747
+ }
748
+ if (defs.length === 1) return defs[0];
749
+ const local = defs.find((d) => d.path === fromPath);
750
+ return local || null;
751
+ }
752
+
753
+ /**
754
+ * The files a screen owns: its own file, then the files it depends on one and
755
+ * two steps out in the code graph (and, on the web, through relative
756
+ * imports), skipping tests, other screens' files and widely shared hubs.
757
+ */
758
+ function attachMembers(screens, graph, facts, stack) {
759
+ const byPath = new Map();
760
+ const inbound = new Map();
761
+ const symPath = new Map(
762
+ graph.nodes.filter((n) => n.kind === "symbol").map((n) => [n.id, n.path]),
763
+ );
764
+ const testFiles = new Set(
765
+ graph.nodes.filter((n) => n.kind === "file" && n.isTest).map((n) => n.path),
766
+ );
767
+ for (const e of graph.edges) {
768
+ if (e.kind !== "references" && e.kind !== "imports") continue;
769
+ const from = e.from.startsWith("file:") ? e.from.slice(5) : null;
770
+ const to = e.to.startsWith("file:") ? e.to.slice(5) : symPath.get(e.to);
771
+ if (!from || !to || from === to) continue;
772
+ push(byPath, from, to);
773
+ }
774
+ if (stack === "web") {
775
+ const known = new Set(facts.keys());
776
+ for (const [p, f] of facts) {
777
+ for (const spec of f.imports || []) {
778
+ const base = posix.normalize(posix.join(posix.dirname(p), spec));
779
+ for (const ext of EXTENSIONS.web) {
780
+ for (const cand of [`${base}${ext}`, `${base}/index${ext}`]) {
781
+ if (known.has(cand)) push(byPath, p, cand);
782
+ }
783
+ }
784
+ }
785
+ }
786
+ }
787
+ for (const [, tos] of byPath)
788
+ for (const t of new Set(tos)) inbound.set(t, (inbound.get(t) || 0) + 1);
789
+ const screenFiles = new Set(screens.map((s) => s.path));
790
+ for (const s of screens) {
791
+ const out = [s.path];
792
+ const seen = new Set(out);
793
+ let frontier = [s.path];
794
+ for (let depth = 0; depth < 2 && out.length < MAX_MEMBERS; depth++) {
795
+ const next = [];
796
+ for (const f of frontier) {
797
+ for (const t of [...new Set(byPath.get(f) || [])].sort()) {
798
+ if (seen.has(t) || testFiles.has(t) || screenFiles.has(t)) continue;
799
+ if ((inbound.get(t) || 0) > HUB_INBOUND) continue;
800
+ seen.add(t);
801
+ next.push(t);
802
+ if (out.length < MAX_MEMBERS) out.push(t);
803
+ }
804
+ }
805
+ frontier = next;
806
+ }
807
+ s.files = out;
808
+ }
809
+ }
810
+
811
+ function linkTests({ sources, isTest, addNode, addEdge }, screens, extracted) {
812
+ const byName = new Map();
813
+ for (const s of screens) push(byName, s.name, s.id);
814
+ for (const p of sources) {
815
+ if (!isTest(p) || !extracted.has(p)) continue;
816
+ const ids = extracted.get(p).tokens;
817
+ let linked = false;
818
+ for (const [name, sids] of byName) {
819
+ if (!ids.has(name)) continue;
820
+ if (!linked) {
821
+ addNode({ id: `test:${p}`, kind: "test", name: basename(p), path: p });
822
+ linked = true;
823
+ }
824
+ for (const id of sids) addEdge(`test:${p}`, id, "tests");
825
+ }
826
+ }
827
+ }
828
+
829
+ /**
830
+ * Every file under root that the tree reads, with its content.
831
+ *
832
+ * @param {string} root
833
+ * @returns {Map<string, string>}
834
+ */
835
+ export function readRepoFiles(root) {
836
+ let list;
837
+ try {
838
+ list = safeGit(root, ["ls-files", "-z", "-co", "--exclude-standard"])
839
+ .split("\0")
840
+ .filter(Boolean);
841
+ if (!list.length) throw new Error("empty");
842
+ } catch {
843
+ list = walk(root, root);
844
+ }
845
+ let realRoot;
846
+ try {
847
+ realRoot = realpathSync(root);
848
+ } catch {
849
+ return new Map();
850
+ }
851
+ const files = new Map();
852
+ for (const p of list.sort()) {
853
+ if (!isTreeInput(p)) continue;
854
+ const buf = readInput(realRoot, p);
855
+ if (buf) files.set(p, decodeText(buf));
856
+ }
857
+ return files;
858
+ }
859
+
860
+ /**
861
+ * The bytes of one regular file inside the repository, or null. A symlink, a
862
+ * device, a FIFO, a path that resolves outside the root, or a file larger than
863
+ * MAX_INPUT_BYTES is skipped. The open is non-blocking and does not follow a
864
+ * final symlink, and the type and size are checked on the descriptor, so the
865
+ * name cannot be swapped between the check and the read.
866
+ *
867
+ * @param {string} realRoot the repository root, already resolved by realpath
868
+ * @param {string} p repo-relative path
869
+ * @returns {Buffer|null}
870
+ */
871
+ export function readInput(realRoot, p) {
872
+ const abs = join(realRoot, p);
873
+ let fd;
874
+ try {
875
+ if (!lstatSync(abs).isFile()) return null;
876
+ if (!realpathSync(abs).startsWith(realRoot + sep)) return null;
877
+ fd = openSync(
878
+ abs,
879
+ constants.O_RDONLY | (constants.O_NONBLOCK ?? 0) | (constants.O_NOFOLLOW ?? 0),
880
+ );
881
+ const st = fstatSync(fd);
882
+ if (!st.isFile() || st.size > MAX_INPUT_BYTES) return null;
883
+ const buf = Buffer.alloc(st.size);
884
+ let n = 0;
885
+ while (n < buf.length) {
886
+ const got = readSync(fd, buf, n, buf.length - n, null);
887
+ if (got === 0) break;
888
+ n += got;
889
+ }
890
+ return buf.subarray(0, n);
891
+ } catch {
892
+ return null;
893
+ } finally {
894
+ if (fd !== undefined) closeSync(fd);
895
+ }
896
+ }
897
+
898
+ /** True for a path the tree reads: source, strings or package.json. */
899
+ export function isTreeInput(p) {
900
+ if (p.includes("node_modules/")) return false;
901
+ return Boolean(stackOf(p)) || isStringsFile(p) || basename(p) === "package.json";
902
+ }
903
+
904
+ function walk(dir, root, acc = []) {
905
+ let entries;
906
+ try {
907
+ entries = readdirSync(dir, { withFileTypes: true });
908
+ } catch {
909
+ return acc;
910
+ }
911
+ for (const e of entries) {
912
+ if (e.name === ".git" || e.name === "node_modules") continue;
913
+ const full = join(dir, e.name);
914
+ if (e.isDirectory()) walk(full, root, acc);
915
+ else if (e.isFile()) acc.push(relative(root, full).split(sep).join("/"));
916
+ }
917
+ return acc;
918
+ }
919
+
920
+ /** Build the tree for a directory on disk. */
921
+ export function buildTreeFromDisk(root, opts = {}) {
922
+ return buildProductTree({ files: readRepoFiles(root), project: basename(root), ...opts });
923
+ }