@seanhogg/builderforce-memory 2026.10.43 → 2026.10.45

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 (85) hide show
  1. package/dist/knowledge/build.d.ts.map +1 -1
  2. package/dist/knowledge/build.js +28 -2
  3. package/dist/knowledge/build.js.map +1 -1
  4. package/dist/knowledge/extractFile.d.ts +15 -0
  5. package/dist/knowledge/extractFile.d.ts.map +1 -1
  6. package/dist/knowledge/extractFile.js +40 -17
  7. package/dist/knowledge/extractFile.js.map +1 -1
  8. package/dist/knowledge/extractJob.d.ts +64 -0
  9. package/dist/knowledge/extractJob.d.ts.map +1 -0
  10. package/dist/knowledge/extractJob.js +47 -0
  11. package/dist/knowledge/extractJob.js.map +1 -0
  12. package/dist/knowledge/findings.d.ts.map +1 -1
  13. package/dist/knowledge/findings.js +9 -1
  14. package/dist/knowledge/findings.js.map +1 -1
  15. package/dist/knowledge/index.d.ts +12 -2
  16. package/dist/knowledge/index.d.ts.map +1 -1
  17. package/dist/knowledge/index.js +7 -1
  18. package/dist/knowledge/index.js.map +1 -1
  19. package/dist/knowledge/judge.d.ts +23 -5
  20. package/dist/knowledge/judge.d.ts.map +1 -1
  21. package/dist/knowledge/judge.js +14 -76
  22. package/dist/knowledge/judge.js.map +1 -1
  23. package/dist/knowledge/judgeCalls.d.ts +52 -0
  24. package/dist/knowledge/judgeCalls.d.ts.map +1 -0
  25. package/dist/knowledge/judgeCalls.js +107 -0
  26. package/dist/knowledge/judgeCalls.js.map +1 -0
  27. package/dist/knowledge/model.d.ts +57 -0
  28. package/dist/knowledge/model.d.ts.map +1 -1
  29. package/dist/knowledge/modelLimiter.d.ts +20 -0
  30. package/dist/knowledge/modelLimiter.d.ts.map +1 -0
  31. package/dist/knowledge/modelLimiter.js +63 -0
  32. package/dist/knowledge/modelLimiter.js.map +1 -0
  33. package/dist/knowledge/outline.d.ts.map +1 -1
  34. package/dist/knowledge/outline.js +14 -1
  35. package/dist/knowledge/outline.js.map +1 -1
  36. package/dist/knowledge/review.d.ts +6 -2
  37. package/dist/knowledge/review.d.ts.map +1 -1
  38. package/dist/knowledge/review.js +108 -112
  39. package/dist/knowledge/review.js.map +1 -1
  40. package/dist/knowledge/reviewJudge.d.ts +95 -0
  41. package/dist/knowledge/reviewJudge.d.ts.map +1 -0
  42. package/dist/knowledge/reviewJudge.js +119 -0
  43. package/dist/knowledge/reviewJudge.js.map +1 -0
  44. package/dist/knowledge/reviewModel.d.ts +30 -2
  45. package/dist/knowledge/reviewModel.d.ts.map +1 -1
  46. package/dist/knowledge/reviewPrefetch.d.ts +53 -0
  47. package/dist/knowledge/reviewPrefetch.d.ts.map +1 -0
  48. package/dist/knowledge/reviewPrefetch.js +65 -0
  49. package/dist/knowledge/reviewPrefetch.js.map +1 -0
  50. package/dist/knowledge/reviewRun.d.ts +70 -0
  51. package/dist/knowledge/reviewRun.d.ts.map +1 -0
  52. package/dist/knowledge/reviewRun.js +88 -0
  53. package/dist/knowledge/reviewRun.js.map +1 -0
  54. package/dist/knowledge/reviewRunModel.d.ts +35 -0
  55. package/dist/knowledge/reviewRunModel.d.ts.map +1 -0
  56. package/dist/knowledge/reviewRunModel.js +27 -0
  57. package/dist/knowledge/reviewRunModel.js.map +1 -0
  58. package/dist/knowledge/systems.d.ts +18 -0
  59. package/dist/knowledge/systems.d.ts.map +1 -0
  60. package/dist/knowledge/systems.js +29 -0
  61. package/dist/knowledge/systems.js.map +1 -0
  62. package/package.json +3 -3
  63. package/src/knowledge/build.ts +25 -3
  64. package/src/knowledge/extractFile.ts +49 -17
  65. package/src/knowledge/extractJob.ts +91 -0
  66. package/src/knowledge/findings.ts +9 -1
  67. package/src/knowledge/index.ts +12 -1
  68. package/src/knowledge/judge.ts +24 -70
  69. package/src/knowledge/judgeCalls.ts +136 -0
  70. package/src/knowledge/model.ts +49 -0
  71. package/src/knowledge/modelLimiter.test.ts +68 -0
  72. package/src/knowledge/modelLimiter.ts +68 -0
  73. package/src/knowledge/outline.test.ts +50 -0
  74. package/src/knowledge/outline.ts +15 -1
  75. package/src/knowledge/review.failures.test.ts +277 -0
  76. package/src/knowledge/review.ordered.test.ts +114 -0
  77. package/src/knowledge/review.ts +102 -100
  78. package/src/knowledge/reviewJudge.ts +155 -0
  79. package/src/knowledge/reviewModel.ts +30 -2
  80. package/src/knowledge/reviewPrefetch.ts +86 -0
  81. package/src/knowledge/reviewRun.test.ts +96 -0
  82. package/src/knowledge/reviewRun.ts +137 -0
  83. package/src/knowledge/reviewRunModel.ts +53 -0
  84. package/src/knowledge/systems.test.ts +107 -0
  85. package/src/knowledge/systems.ts +32 -0
@@ -0,0 +1,136 @@
1
+ /**
2
+ * knowledge/judgeCalls.ts — judging one file's sections, in two stages (PRD 41 A8).
3
+ *
4
+ * • {@link callSections} — the CALL stage: one model call per section within a budget slice, touching
5
+ * no shared state, so several files can be in it at once (optionally under ONE shared
6
+ * {@link ModelLimiter}).
7
+ * • {@link applyAnswers} — the APPLY stage: merges answers into the batch and the shared entity map.
8
+ * Synchronous; the review's one ordered writer calls it in plan order, which keeps the stored
9
+ * bytes independent of how many files were judged at once.
10
+ *
11
+ * {@link judgeSections} is both stages for one file.
12
+ */
13
+
14
+ import { hashText } from '../ingest/hash.js';
15
+ import {
16
+ budgetLeft, call, claimContent, JUDGE_CONCURRENCY, REVIEW_FACT_SOURCE, runPool, validateExtract,
17
+ type ExtractArgs, type JudgeBudget, type SectionToJudge,
18
+ } from './judge.js';
19
+ import type { ModelLimiter } from './modelLimiter.js';
20
+ import type { JudgementPort, NodeRef, StoredFact } from './model.js';
21
+ import { compareStr, factRef } from './refs.js';
22
+ import { entityKey, normalizeKey } from './resolve.js';
23
+ import { reasonOf } from './reviewRunModel.js';
24
+
25
+ /** A section's validated answer: the output of the call stage, applied later by {@link applyAnswers}. */
26
+ export interface SectionAnswer { section: SectionToJudge; v: ReturnType<typeof validateExtract> }
27
+
28
+ export interface CallSectionsArgs {
29
+ port: JudgementPort;
30
+ fileHash: string;
31
+ sections: readonly SectionToJudge[];
32
+ /** This file's slice of the review budget (its own `used`). */
33
+ budget: JudgeBudget;
34
+ /** Shared across the files of a review: caps the calls in flight and adapts to rate limits. */
35
+ limiter?: ModelLimiter;
36
+ signal?: AbortSignal;
37
+ }
38
+
39
+ export interface CallSectionsResult {
40
+ answers: SectionAnswer[];
41
+ /** Sections cut by the budget or whose call failed. */
42
+ unjudged: number;
43
+ /** Calls the port (or the provider behind it) failed. */
44
+ errors: number;
45
+ /** The first failure's message, single line. */
46
+ firstError?: string;
47
+ }
48
+
49
+
50
+ /** Answers come back in section order. Throws on abort. */
51
+ export async function callSections(a: CallSectionsArgs): Promise<CallSectionsResult> {
52
+ const slots: Array<SectionAnswer | undefined> = new Array(a.sections.length);
53
+ let unjudged = 0;
54
+ let errors = 0;
55
+ let firstError: string | undefined;
56
+ const hooks = {
57
+ ...(a.limiter ? { limiter: a.limiter } : {}),
58
+ onError: (err: unknown) => { errors += 1; firstError ??= reasonOf(err); },
59
+ };
60
+ // The budget check and `call`'s synchronous `used` increment happen on the same tick (no await
61
+ // between), so concurrency cannot overshoot `modelCalls`.
62
+ const abortError = () => a.signal?.reason ?? new Error('aborted');
63
+ await runPool(a.sections.map((section, idx) => ({ section, idx })), JUDGE_CONCURRENCY, async ({ section, idx }) => {
64
+ // Honoured per section, not only when the port throws: the caller drops this file whole.
65
+ if (a.signal?.aborted) throw abortError();
66
+ if (!budgetLeft(a.budget)) { unjudged += 1; return; }
67
+ const answer = await call(a.port, {
68
+ kind: 'extract', items: [{ ref: section.ref, text: section.text, sourceHash: a.fileHash }],
69
+ ...(a.signal ? { signal: a.signal } : {}),
70
+ }, a.budget, hooks);
71
+ // A failed call judged nothing: not counted judged, so the file stays changed and is retried.
72
+ if (!answer) { unjudged += 1; return; }
73
+ // The abort can land while a call is in flight (the port sees the signal): a section that
74
+ // finished after the abort must not count as judged, or the caller would not re-judge it.
75
+ if (a.signal?.aborted) throw abortError();
76
+ slots[idx] = { section, v: validateExtract(answer.result, section.ref) };
77
+ });
78
+ return { answers: slots.filter((s): s is SectionAnswer => !!s), unjudged, errors, ...(firstError !== undefined ? { firstError } : {}) };
79
+ }
80
+
81
+ /** Judges each section within the budget; the rest — and any whose call failed — are counted `unjudged`. */
82
+ export async function judgeSections(a: ExtractArgs): Promise<Array<{ ref: NodeRef; text: string }>> {
83
+ const { answers, unjudged } = await callSections({
84
+ port: a.port, fileHash: a.fileHash, sections: a.sections, budget: a.budget, ...(a.signal ? { signal: a.signal } : {}),
85
+ });
86
+ a.batch.unjudged += unjudged;
87
+ return applyAnswers(a, answers);
88
+ }
89
+
90
+ /** Merges answers into the batch and the shared entities map, in the order given. */
91
+ export function applyAnswers(
92
+ a: Pick<ExtractArgs, 'pack' | 'path' | 'fileHash' | 'batch' | 'entities' | 'onJudged'>,
93
+ answers: readonly SectionAnswer[],
94
+ ): Array<{ ref: NodeRef; text: string }> {
95
+ const claims: Array<{ ref: NodeRef; text: string }> = [];
96
+ const anchor = { path: a.path, contentHash: a.fileHash };
97
+ for (const { section, v } of answers) {
98
+ a.batch.invalid += v.invalid;
99
+ a.batch.judged += 1;
100
+ a.onJudged(section.ref);
101
+ const rel = (from: NodeRef, to: NodeRef, kind: string) =>
102
+ a.batch.relation({ from, to, kind, weight: 1, origin: 'model', sourceHash: a.fileHash });
103
+
104
+ const entityRefs = new Map<string, NodeRef>();
105
+ for (const e of v.entities) {
106
+ const key = entityKey(a.pack, e.name);
107
+ const prior = a.entities.get(key);
108
+ const anchors = [...(prior?.fileAnchors ?? []).filter((x) => x.path !== a.path), anchor]
109
+ .sort((x, y) => compareStr(x.path, y.path));
110
+ const fact: StoredFact = {
111
+ key, content: prior?.content ?? `${e.name} (${e.type})`, source: REVIEW_FACT_SOURCE,
112
+ importance: prior?.importance ?? 0.5, origin: prior?.origin ?? 'model', fileAnchors: anchors,
113
+ };
114
+ a.entities.set(key, fact);
115
+ a.batch.fact(fact);
116
+ entityRefs.set(normalizeKey(e.name), key);
117
+ rel(section.ref, key, 'mentions');
118
+ }
119
+ for (const c of v.claims) {
120
+ const key = `claim:${hashText([section.ref, c.subject, c.predicate, c.object].join('\u0000'))}`;
121
+ const text = `${c.subject} ${c.predicate} ${c.object}`;
122
+ a.batch.fact({
123
+ key, content: claimContent(text, c.quote), source: REVIEW_FACT_SOURCE,
124
+ importance: 0.5, origin: 'model', fileAnchors: [anchor],
125
+ });
126
+ const ref = factRef(key);
127
+ rel(ref, section.ref, 'about');
128
+ for (const term of [c.subject, c.object]) {
129
+ const ent = entityRefs.get(normalizeKey(term));
130
+ if (ent) rel(ref, ent, 'mentions');
131
+ }
132
+ claims.push({ ref, text });
133
+ }
134
+ }
135
+ return claims;
136
+ }
@@ -34,6 +34,12 @@ export interface KNode {
34
34
  stale?: boolean;
35
35
  /** Pack data, e.g. { added, removed }, { unused: 'file' }, { line: 12 }. */
36
36
  badges?: Record<string, number | string>;
37
+ /** The system (a repository or project folder of the root) a file belongs to; '' when the root is one system. File nodes only. */
38
+ system?: string;
39
+ /** The workspace package (app) of the system the file belongs to, as a root-relative folder. */
40
+ app?: string;
41
+ /** On a file of a duplicated copy: the path of the system it is a copy of, so a view can fold it. */
42
+ copyOf?: string;
37
43
  }
38
44
 
39
45
  export type EdgeVerdict = 'allowed' | 'same' | 'skips' | 'upward';
@@ -233,11 +239,40 @@ export interface LiveOverlay {
233
239
  runFiles?: string[];
234
240
  }
235
241
 
242
+ /** A workspace package of a system. */
243
+ export interface GraphApp { path: string; name: string }
244
+
245
+ /** Why a file the repo graph could have read was not read. */
246
+ export interface GraphReadSkip { reason: string; count: number }
247
+
248
+ /**
249
+ * One system of a review root (a repository, or a folder whose manifest names a project): the unit
250
+ * the reference graph, layer verdicts and partition violations are computed within (PRD 41 A9).
251
+ * `path` is root-relative, '' when the root itself is the system.
252
+ */
253
+ export interface GraphSystem {
254
+ path: string;
255
+ name: string;
256
+ /** File nodes the graph holds under it. */
257
+ files: number;
258
+ apps: GraphApp[];
259
+ /** The repo graph did not read every file of it (see `graphRead.skipped`). */
260
+ truncated?: boolean;
261
+ /** Set on a duplicated copy: the path of the system it copies. */
262
+ copyOf?: string;
263
+ copySimilarity?: number;
264
+ copyReason?: 'no-git' | 'name-mismatch' | 'later-name';
265
+ /** The reference graph's reading of this system: files read, and files left out by reason. */
266
+ graphRead?: { read: number; skipped: GraphReadSkip[] };
267
+ }
268
+
236
269
  export interface KnowledgeGraph {
237
270
  scope: { rootId: string; packs: string[]; digest: string };
238
271
  nodes: KNode[];
239
272
  edges: KEdge[];
240
273
  findings: Finding[];
274
+ /** Present only when the root held systems to report (see {@link GraphSystem}). */
275
+ meta?: { systems?: GraphSystem[] };
241
276
  stats: { sources: number; nodes: number; edges: number; stale: number; truncated: boolean };
242
277
  /**
243
278
  * Attached only when the graph was truncated (`stats.truncated`): the whole graph's files,
@@ -258,6 +293,12 @@ export interface GraphOutline {
258
293
  areas: NodeRef[];
259
294
  /** Distinct partitions, sorted; `OutlineFile.partition` indexes into it. */
260
295
  partitions: string[];
296
+ /** Distinct system paths of the files (and the systems they copy), sorted; `OutlineFile.system` / `copyOf` index into it. Absent when no file has a system. */
297
+ systems?: string[];
298
+ /** Distinct app paths, sorted; `OutlineFile.app` indexes into it. Absent when no file has an app. */
299
+ apps?: string[];
300
+ /** The root's systems with their file counts, copies and graph reads — `KnowledgeGraph.meta.systems`, carried so the outline stands alone. */
301
+ systemInfo?: GraphSystem[];
261
302
  /** File nodes of the full graph, sorted by ref. */
262
303
  files: OutlineFile[];
263
304
  /**
@@ -277,6 +318,12 @@ export interface OutlineFile {
277
318
  area?: number;
278
319
  /** Index into `GraphOutline.partitions`, when the file has a partition. */
279
320
  partition?: number;
321
+ /** Index into `GraphOutline.systems`, when the file has a system ('' is a system too). */
322
+ system?: number;
323
+ /** Index into `GraphOutline.apps`, when the file has an app. */
324
+ app?: number;
325
+ /** Index into `GraphOutline.systems` of the system this file's system copies. */
326
+ copyOf?: number;
280
327
  importance: number;
281
328
  /** The first 12 characters of the node's sourceHash. */
282
329
  hash?: string;
@@ -292,6 +339,8 @@ export interface BuildGraphInput {
292
339
  packs: KnowledgePack[];
293
340
  live?: LiveOverlay;
294
341
  nearDuplicates?: SimilarPair[];
342
+ /** The root's systems (file counts are computed by the build): each file node is stamped with its system, app and copyOf. */
343
+ systems?: GraphSystem[];
295
344
  }
296
345
 
297
346
  export interface BuildGraphOptions {
@@ -0,0 +1,68 @@
1
+ /**
2
+ * src/knowledge/modelLimiter.test.ts
3
+ * The review's ONE cap on model calls in flight (PRD 41 A8): bounded, AIMD on rate limits, and
4
+ * nothing starts once the signal has aborted.
5
+ */
6
+
7
+ import { createModelLimiter, isRateLimit } from './modelLimiter.js';
8
+
9
+ const rateLimited = () => Object.assign(new Error('429 rate limited'), { status: 429 });
10
+ const ok = async () => 'ok';
11
+
12
+ describe('createModelLimiter', () => {
13
+ it('never has more calls in flight than its width', async () => {
14
+ const limiter = createModelLimiter(3);
15
+ let live = 0;
16
+ let max = 0;
17
+ await Promise.all(Array.from({ length: 12 }, () => limiter.run(async () => {
18
+ live += 1; max = Math.max(max, live);
19
+ await new Promise((r) => setTimeout(r, 1));
20
+ live -= 1;
21
+ })));
22
+ expect(max).toBe(3);
23
+ });
24
+
25
+ it('halves on a rate limit (minimum 1) and grows back by 1 per growEvery successes', async () => {
26
+ const limiter = createModelLimiter(8, { growEvery: 3 });
27
+ await expect(limiter.run(async () => { throw rateLimited(); })).rejects.toThrow('429');
28
+ expect(limiter.width).toBe(4);
29
+ await expect(limiter.run(async () => { throw rateLimited(); })).rejects.toThrow('429');
30
+ expect(limiter.width).toBe(2);
31
+ await expect(limiter.run(async () => { throw rateLimited(); })).rejects.toThrow('429');
32
+ await expect(limiter.run(async () => { throw rateLimited(); })).rejects.toThrow('429');
33
+ expect(limiter.width).toBe(1);
34
+
35
+ for (let i = 0; i < 3; i++) await limiter.run(ok);
36
+ expect(limiter.width).toBe(2);
37
+ for (let i = 0; i < 3 * 10; i++) await limiter.run(ok);
38
+ expect(limiter.width).toBe(8); // back at the cap, never above
39
+ });
40
+
41
+ it('a failure that is not a rate limit leaves the width alone', async () => {
42
+ const limiter = createModelLimiter(4);
43
+ await expect(limiter.run(async () => { throw new Error('boom'); })).rejects.toThrow('boom');
44
+ expect(limiter.width).toBe(4);
45
+ });
46
+
47
+ it('rejects a waiting call whose signal aborted instead of starting it', async () => {
48
+ const limiter = createModelLimiter(1);
49
+ const controller = new AbortController();
50
+ let started = 0;
51
+ const first = limiter.run(async () => { started += 1; await new Promise((r) => setTimeout(r, 5)); });
52
+ const waiting = limiter.run(async () => { started += 1; }, controller.signal);
53
+ controller.abort();
54
+ await expect(waiting).rejects.toBeDefined();
55
+ await first;
56
+ expect(started).toBe(1);
57
+ });
58
+ });
59
+
60
+ describe('isRateLimit', () => {
61
+ it('recognises a 429 status or the usual wording', () => {
62
+ expect(isRateLimit({ status: 429 })).toBe(true);
63
+ expect(isRateLimit(new Error('Rate limit exceeded'))).toBe(true);
64
+ expect(isRateLimit(new Error('HTTP 429'))).toBe(true);
65
+ expect(isRateLimit(new Error('401 unauthorized'))).toBe(false);
66
+ expect(isRateLimit(null)).toBe(false);
67
+ });
68
+ });
@@ -0,0 +1,68 @@
1
+ /**
2
+ * knowledge/modelLimiter.ts — ONE cap on the model calls in flight across every file of a review
3
+ * (PRD 41 A8), so judging N files at once does not multiply the provider's load.
4
+ *
5
+ * AIMD: a rate-limit answer halves the width (minimum 1); every `growEvery` successful calls grow it
6
+ * by 1, back up to the cap. Waiting calls start in order; one whose signal has aborted is rejected
7
+ * instead of started, so nothing starts after an abort.
8
+ */
9
+
10
+ export interface ModelLimiter {
11
+ /** Calls allowed in flight right now (1..max). */
12
+ readonly width: number;
13
+ readonly max: number;
14
+ run<T>(fn: () => Promise<T>, signal?: AbortSignal): Promise<T>;
15
+ }
16
+
17
+ /** An error that says the provider is rate limiting us (HTTP 429 or the usual wording). */
18
+ export function isRateLimit(err: unknown): boolean {
19
+ const e = err as { status?: unknown; statusCode?: unknown; message?: unknown } | null;
20
+ if (e?.status === 429 || e?.statusCode === 429) return true;
21
+ return typeof e?.message === 'string' && /\b429\b|rate.?limit|too many requests/i.test(e.message);
22
+ }
23
+
24
+ interface Waiter { start(): void; reject(reason: unknown): void; signal: AbortSignal | undefined }
25
+
26
+ export function createModelLimiter(max: number, opts: { growEvery?: number } = {}): ModelLimiter {
27
+ const cap = Math.max(1, Math.floor(max));
28
+ const growEvery = Math.max(1, Math.floor(opts.growEvery ?? 20));
29
+ let width = cap;
30
+ let active = 0;
31
+ let successes = 0;
32
+ const waiting: Waiter[] = [];
33
+
34
+ const pump = () => {
35
+ while (active < width && waiting.length > 0) {
36
+ const w = waiting.shift()!;
37
+ if (w.signal?.aborted) { w.reject(w.signal.reason ?? new Error('aborted')); continue; }
38
+ active += 1;
39
+ w.start();
40
+ }
41
+ };
42
+
43
+ return {
44
+ get width() { return width; },
45
+ max: cap,
46
+ run<T>(fn: () => Promise<T>, signal?: AbortSignal): Promise<T> {
47
+ return new Promise<T>((resolve, reject) => {
48
+ waiting.push({
49
+ signal, reject,
50
+ start: () => {
51
+ (async () => fn())().then(
52
+ (v) => {
53
+ successes += 1;
54
+ if (successes >= growEvery && width < cap) { width += 1; successes = 0; }
55
+ resolve(v);
56
+ },
57
+ (err) => {
58
+ if (isRateLimit(err)) { width = Math.max(1, Math.floor(width / 2)); successes = 0; }
59
+ reject(err);
60
+ },
61
+ ).finally(() => { active -= 1; pump(); });
62
+ },
63
+ });
64
+ pump();
65
+ });
66
+ },
67
+ };
68
+ }
@@ -166,3 +166,53 @@ describe('buildOutline caps', () => {
166
166
  expect(buildOutline(synthetic(10, [refEdge(0, 1)])).capped).toBe(false);
167
167
  });
168
168
  });
169
+
170
+ describe('buildOutline — systems', () => {
171
+ const files = ['a/x.ts', 'a/packages/web/y.ts', 'b/z.ts'];
172
+ const withSystems = (): KnowledgeGraph => {
173
+ const g = buildGraph({
174
+ rootId: ROOT, packs: [PACK], facts: [], relations: [],
175
+ extracted: files.map((p) => extractedOf(fileNode(p))),
176
+ systems: [
177
+ { path: 'a', name: 'a', files: 0, apps: [{ path: 'a/packages/web', name: 'web' }] },
178
+ { path: 'b', name: 'b', files: 0, apps: [], copyOf: 'a', copySimilarity: 1, copyReason: 'no-git' },
179
+ ],
180
+ });
181
+ return g;
182
+ };
183
+
184
+ it('files carry system, app and copyOf as indexes into the outline pools, and the outline carries the systems', () => {
185
+ const o = buildOutline(withSystems());
186
+ expect(o.systems).toEqual(['a', 'b']);
187
+ expect(o.apps).toEqual(['a/packages/web']);
188
+ const byPath = (p: string) => o.files.find((f) => f.path.endsWith(p))!;
189
+ expect(byPath('a/x.ts')).toMatchObject({ system: 0 });
190
+ expect(byPath('a/x.ts').app).toBeUndefined();
191
+ expect(byPath('y.ts')).toMatchObject({ system: 0, app: 0 });
192
+ expect(byPath('b/z.ts')).toMatchObject({ system: 1, copyOf: 0 });
193
+ expect(o.systemInfo?.map((s) => [s.path, s.files, s.copyOf])).toEqual([['a', 2, undefined], ['b', 1, 'a']]);
194
+ });
195
+
196
+ it('a root without systems has none of these fields', () => {
197
+ const o = buildOutline(buildGraph({ rootId: ROOT, packs: [PACK], facts: [], relations: [], extracted: files.map((p) => extractedOf(fileNode(p))) }));
198
+ expect(o.systems).toBeUndefined();
199
+ expect(o.apps).toBeUndefined();
200
+ expect(o.systemInfo).toBeUndefined();
201
+ expect(o.files.every((f) => f.system === undefined)).toBe(true);
202
+ });
203
+
204
+ it('a one-system root keeps the empty system as index 0', () => {
205
+ const g = buildGraph({
206
+ rootId: ROOT, packs: [PACK], facts: [], relations: [], extracted: files.map((p) => extractedOf(fileNode(p))),
207
+ systems: [{ path: '', name: 'r', files: 0, apps: [] }],
208
+ });
209
+ const o = buildOutline(g);
210
+ expect(o.systems).toEqual(['']);
211
+ expect(o.files.every((f) => f.system === 0)).toBe(true);
212
+ });
213
+
214
+ it('survives a JSON round trip (the wire form)', () => {
215
+ const o = buildOutline(withSystems());
216
+ expect(JSON.parse(JSON.stringify(o))).toEqual(o);
217
+ });
218
+ });
@@ -60,6 +60,11 @@ export function buildOutline(full: KnowledgeGraph): GraphOutline {
60
60
  const areaIndex = new Map<NodeRef, number>(areas.map((a, i) => [a, i] as const));
61
61
  const partitionIndex = new Map<string, number>(partitions.map((p, i) => [p, i] as const));
62
62
 
63
+ const systems = [...new Set(fileNodes.flatMap((n) => [...(n.system !== undefined ? [n.system] : []), ...(n.copyOf !== undefined ? [n.copyOf] : [])]))].sort(compareStr);
64
+ const apps = [...new Set(fileNodes.flatMap((n) => (n.app !== undefined ? [n.app] : [])))].sort(compareStr);
65
+ const systemIndex = new Map<string, number>(systems.map((s, i) => [s, i] as const));
66
+ const appIndex = new Map<string, number>(apps.map((a, i) => [a, i] as const));
67
+
63
68
  const files: OutlineFile[] = fileNodes.map((n) => {
64
69
  const badges: Record<string, number | string> = {};
65
70
  for (const k of OUTLINE_BADGE_KEYS) {
@@ -70,6 +75,9 @@ export function buildOutline(full: KnowledgeGraph): GraphOutline {
70
75
  path: n.ref.slice(prefix.length),
71
76
  ...(n.area !== undefined ? { area: areaIndex.get(n.area)! } : {}),
72
77
  ...(n.partition !== undefined ? { partition: partitionIndex.get(n.partition)! } : {}),
78
+ ...(n.system !== undefined ? { system: systemIndex.get(n.system)! } : {}),
79
+ ...(n.app !== undefined ? { app: appIndex.get(n.app)! } : {}),
80
+ ...(n.copyOf !== undefined ? { copyOf: systemIndex.get(n.copyOf)! } : {}),
73
81
  importance: n.importance,
74
82
  ...(n.sourceHash !== undefined ? { hash: n.sourceHash.slice(0, HASH_CHARS) } : {}),
75
83
  ...(Object.keys(badges).length > 0 ? { badges } : {}),
@@ -104,5 +112,11 @@ export function buildOutline(full: KnowledgeGraph): GraphOutline {
104
112
  }
105
113
  list.sort((a, b) => a.from - b.from || a.to - b.to);
106
114
  const links = list.map((m) => [m.from, m.to, m.verdict, m.cycle ? OUTLINE_FLAG_CYCLE : 0] as [number, number, number, number]);
107
- return { prefix, areas, partitions, files, links, capped };
115
+ return {
116
+ prefix, areas, partitions,
117
+ ...(systems.length > 0 ? { systems } : {}),
118
+ ...(apps.length > 0 ? { apps } : {}),
119
+ ...(full.meta?.systems ? { systemInfo: full.meta.systems } : {}),
120
+ files, links, capped,
121
+ };
108
122
  }