@stateward/core 1.3.0 → 1.3.1

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.
@@ -0,0 +1,121 @@
1
+ import type { ProgramSize } from "./backend/program-size.js";
2
+ /**
3
+ * How much memory a check needs, estimated from its input before anything is built (the text of
4
+ * each program and of its own files), never from the live heap: the same input gives the same
5
+ * plan on every machine and run (SW5).
6
+ *
7
+ * The estimate, in MB, while a project is checked:
8
+ *
9
+ * BASE
10
+ * + PARSED_BASE + PARSED_BYTES_PER_CODE_CHAR × its program's code (its text without comments
11
+ * and white space) + PARSED_BYTES_PER_FILE × its files (syntax trees, binder; not sliced)
12
+ * + RESULT_BYTES_PER_OWN_CHAR × every project's own text (findings and summaries kept to the end)
13
+ * + CHECKER_BASE + the least of
14
+ * CHECKER_BYTES_PER_OWN_CHAR × the own text one type checker checks (a small slice), and
15
+ * WIDE_CHECKER_MB + WIDE_CHECKER_BYTES_PER_OWN_CHAR × that text (a large one)
16
+ *
17
+ * plus, when the programs are kept (fixes are tried), the other projects' programs and checkers.
18
+ * It must stay within USABLE_SHARE of the budget: V8 collects at length, then fails, when the live
19
+ * heap nears its limit.
20
+ *
21
+ * Measured on 2026-12-02 (all eight packs, `recommended`, results cache on), the live heap read
22
+ * after a forced collection every 1 to 3 s by a rule that samples it, with a new checker every
23
+ * 139 to 555 files (the smaller app) and every 676 to 10,822 files (the larger):
24
+ *
25
+ * - a React app of 21,016 files, 95.2 M characters (the walk counts 96.9 M), 10,822 own files of
26
+ * 35.4 M: 2,303 MB once parsed and bound (23.3 bytes a character over the 47 MB at start);
27
+ * about 407 MB of results after 10,141 files (12.1 bytes an own character); one checker for
28
+ * all files 1,060 MB (30 bytes an own character); slices of 676 files 200 to 490 MB, the
29
+ * densest near 110 bytes an own character;
30
+ * - a React app of 1,549 files, 18.9 M characters, 555 own files of 6.6 M: 466 MB parsed and bound
31
+ * (22.2 bytes a character); 68 MB of results after 438 files (13 bytes an own character); one
32
+ * checker 268 MB (40 bytes), slices of 139 files about 130 MB (79 bytes).
33
+ *
34
+ * Parsing and binding, measured on 2026-12-03 apart from the check (a program built as stateward
35
+ * builds it, its checker created, the heap read after a forced collection), on seven projects:
36
+ * the two apps above (2,216 and 406 MB), a server of 25,785 files whose 295 M characters are
37
+ * mostly the documentation comments of a library's declaration files (105 M of code: 3,620 MB),
38
+ * two libraries of 4,226 and 2,889 files (604 and 269 MB), 40,000 own files of two lines each
39
+ * (359 MB) and a small example (126 MB). 35 bytes a character of code, 3.5 KB a file and 100 MB
40
+ * fit all seven within 12% but the smallest (37% over); per character of text they range from
41
+ * 6.5 to 70 bytes. On the server, a budget of 5,120 MB in 9 slices was measured at 4,794 MB of
42
+ * live heap; this estimate puts that plan at 5,133.
43
+ *
44
+ * The checker's cost per character varies fourfold between slices of one project, so the
45
+ * constant is near the densest measured; the others are rounded up. One checker for all files
46
+ * costs less per character (they share their types): 30 bytes for all 10,822 files, 40 for all
47
+ * 555. So a second line bounds it, above both: 400 MB + 40 bytes an own character (1,816 MB
48
+ * against the 1,060 measured; 652 against 268). A slice keeps the first line (`checkerMb`).
49
+ */
50
+ export declare const MEMORY_MODEL: {
51
+ /** Node, TypeScript and stateward's code, before any project (MB). */
52
+ baseMb: number;
53
+ /** Syntax trees, binder, module resolution: what any program costs (MB). */
54
+ parsedBaseMb: number;
55
+ /** The same, per character of the program's code (its text without comments and white space). */
56
+ parsedBytesPerCodeChar: number;
57
+ /** The same, per file of the program. */
58
+ parsedBytesPerFile: number;
59
+ /** What the run keeps to its end (findings, summaries, the results cache): per own character. */
60
+ resultBytesPerOwnChar: number;
61
+ /** What any type checker computes first (MB), paid again by each new one. */
62
+ checkerBaseMb: number;
63
+ /** What a type checker adds per character of the own files it checks, in a small slice. */
64
+ checkerBytesPerOwnChar: number;
65
+ /** A large checker's cost (MB), before its share per character (`wideCheckerBytesPerOwnChar`). */
66
+ wideCheckerMb: number;
67
+ /** What a type checker adds per character of the own files it checks, in a large slice. */
68
+ wideCheckerBytesPerOwnChar: number;
69
+ /** The share of the budget the estimate may fill. */
70
+ usableShare: number;
71
+ /** The fewest files a type checker is started for; a budget that allows fewer is too small. */
72
+ minFilesPerChecker: number;
73
+ };
74
+ /** One project's part of the plan. */
75
+ export type ProjectPlan = {
76
+ readonly tsconfig: string;
77
+ /** Its own files. */
78
+ readonly files: number;
79
+ /** How many type checkers share them, one after the other (1: one for all). */
80
+ readonly slices: number;
81
+ /** The files of each, the last one's fewer. */
82
+ readonly filesPerChecker: number;
83
+ };
84
+ export type MemoryPlan = {
85
+ readonly kind: "fits";
86
+ readonly budgetMb: number;
87
+ readonly projects: readonly ProjectPlan[];
88
+ } | {
89
+ readonly kind: "below-floor";
90
+ readonly budgetMb: number;
91
+ /** The least budget the plan fits in, rounded up to 256 MB. */
92
+ readonly neededMb: number;
93
+ /** Files and text of the project that needs it. */
94
+ readonly tsconfig: string;
95
+ readonly size: ProgramSize;
96
+ };
97
+ /**
98
+ * The plan for a check of `projects` (in the order the file phase reaches them) within `budgetMb`:
99
+ * how many own files of each project share one type checker. `keepsPrograms`: the programs stay
100
+ * built to the end (fixes are tried), so every program counts at once; otherwise one at a time.
101
+ */
102
+ export declare function planMemory(budgetMb: number, projects: readonly {
103
+ readonly tsconfig: string;
104
+ readonly size: ProgramSize;
105
+ }[], keepsPrograms: boolean): MemoryPlan;
106
+ /**
107
+ * The plan as stateward prints it once, before the check: "memory budget 3,072 MB: 4 slices of
108
+ * about 900 files". Undefined when every project keeps one type checker (nothing to say).
109
+ * `shown` names a project's tsconfig as the reader would type it.
110
+ */
111
+ export declare function describePlan(plan: Extract<MemoryPlan, {
112
+ kind: "fits";
113
+ }>, shown: (tsconfig: string) => string): string | undefined;
114
+ /** The budget is below what parsing and binding the project needs: the check does not start. */
115
+ export declare class MemoryBudgetError extends Error {
116
+ readonly hint: string;
117
+ constructor(plan: Extract<MemoryPlan, {
118
+ kind: "below-floor";
119
+ }>, shown: string);
120
+ }
121
+ //# sourceMappingURL=memory-plan.d.ts.map
@@ -0,0 +1,174 @@
1
+ /**
2
+ * How much memory a check needs, estimated from its input before anything is built (the text of
3
+ * each program and of its own files), never from the live heap: the same input gives the same
4
+ * plan on every machine and run (SW5).
5
+ *
6
+ * The estimate, in MB, while a project is checked:
7
+ *
8
+ * BASE
9
+ * + PARSED_BASE + PARSED_BYTES_PER_CODE_CHAR × its program's code (its text without comments
10
+ * and white space) + PARSED_BYTES_PER_FILE × its files (syntax trees, binder; not sliced)
11
+ * + RESULT_BYTES_PER_OWN_CHAR × every project's own text (findings and summaries kept to the end)
12
+ * + CHECKER_BASE + the least of
13
+ * CHECKER_BYTES_PER_OWN_CHAR × the own text one type checker checks (a small slice), and
14
+ * WIDE_CHECKER_MB + WIDE_CHECKER_BYTES_PER_OWN_CHAR × that text (a large one)
15
+ *
16
+ * plus, when the programs are kept (fixes are tried), the other projects' programs and checkers.
17
+ * It must stay within USABLE_SHARE of the budget: V8 collects at length, then fails, when the live
18
+ * heap nears its limit.
19
+ *
20
+ * Measured on 2026-12-02 (all eight packs, `recommended`, results cache on), the live heap read
21
+ * after a forced collection every 1 to 3 s by a rule that samples it, with a new checker every
22
+ * 139 to 555 files (the smaller app) and every 676 to 10,822 files (the larger):
23
+ *
24
+ * - a React app of 21,016 files, 95.2 M characters (the walk counts 96.9 M), 10,822 own files of
25
+ * 35.4 M: 2,303 MB once parsed and bound (23.3 bytes a character over the 47 MB at start);
26
+ * about 407 MB of results after 10,141 files (12.1 bytes an own character); one checker for
27
+ * all files 1,060 MB (30 bytes an own character); slices of 676 files 200 to 490 MB, the
28
+ * densest near 110 bytes an own character;
29
+ * - a React app of 1,549 files, 18.9 M characters, 555 own files of 6.6 M: 466 MB parsed and bound
30
+ * (22.2 bytes a character); 68 MB of results after 438 files (13 bytes an own character); one
31
+ * checker 268 MB (40 bytes), slices of 139 files about 130 MB (79 bytes).
32
+ *
33
+ * Parsing and binding, measured on 2026-12-03 apart from the check (a program built as stateward
34
+ * builds it, its checker created, the heap read after a forced collection), on seven projects:
35
+ * the two apps above (2,216 and 406 MB), a server of 25,785 files whose 295 M characters are
36
+ * mostly the documentation comments of a library's declaration files (105 M of code: 3,620 MB),
37
+ * two libraries of 4,226 and 2,889 files (604 and 269 MB), 40,000 own files of two lines each
38
+ * (359 MB) and a small example (126 MB). 35 bytes a character of code, 3.5 KB a file and 100 MB
39
+ * fit all seven within 12% but the smallest (37% over); per character of text they range from
40
+ * 6.5 to 70 bytes. On the server, a budget of 5,120 MB in 9 slices was measured at 4,794 MB of
41
+ * live heap; this estimate puts that plan at 5,133.
42
+ *
43
+ * The checker's cost per character varies fourfold between slices of one project, so the
44
+ * constant is near the densest measured; the others are rounded up. One checker for all files
45
+ * costs less per character (they share their types): 30 bytes for all 10,822 files, 40 for all
46
+ * 555. So a second line bounds it, above both: 400 MB + 40 bytes an own character (1,816 MB
47
+ * against the 1,060 measured; 652 against 268). A slice keeps the first line (`checkerMb`).
48
+ */
49
+ export const MEMORY_MODEL = {
50
+ /** Node, TypeScript and stateward's code, before any project (MB). */
51
+ baseMb: 50,
52
+ /** Syntax trees, binder, module resolution: what any program costs (MB). */
53
+ parsedBaseMb: 100,
54
+ /** The same, per character of the program's code (its text without comments and white space). */
55
+ parsedBytesPerCodeChar: 35,
56
+ /** The same, per file of the program. */
57
+ parsedBytesPerFile: 3584,
58
+ /** What the run keeps to its end (findings, summaries, the results cache): per own character. */
59
+ resultBytesPerOwnChar: 13,
60
+ /** What any type checker computes first (MB), paid again by each new one. */
61
+ checkerBaseMb: 40,
62
+ /** What a type checker adds per character of the own files it checks, in a small slice. */
63
+ checkerBytesPerOwnChar: 112,
64
+ /** A large checker's cost (MB), before its share per character (`wideCheckerBytesPerOwnChar`). */
65
+ wideCheckerMb: 400,
66
+ /** What a type checker adds per character of the own files it checks, in a large slice. */
67
+ wideCheckerBytesPerOwnChar: 40,
68
+ /** The share of the budget the estimate may fill. */
69
+ usableShare: 0.9,
70
+ /** The fewest files a type checker is started for; a budget that allows fewer is too small. */
71
+ minFilesPerChecker: 200,
72
+ };
73
+ const MB = 1024 * 1024;
74
+ function parsedMb(size) {
75
+ return (MEMORY_MODEL.parsedBaseMb +
76
+ (MEMORY_MODEL.parsedBytesPerCodeChar * size.codeChars +
77
+ MEMORY_MODEL.parsedBytesPerFile * size.files) /
78
+ MB);
79
+ }
80
+ /**
81
+ * A checker of `files` of the project's own files, at their average length. One checker for all of
82
+ * them is bounded by the large line too; a slice is not: the types a project makes are not spread
83
+ * evenly over its files, and one slice of three was measured making 475,000 of the 590,000 types
84
+ * one checker makes for all files (`--max-memory 4096` on the larger app above: a higher peak
85
+ * than one checker's).
86
+ */
87
+ function checkerMb(size, files) {
88
+ const chars = size.ownFiles === 0 ? 0 : (size.ownChars * files) / size.ownFiles;
89
+ const small = (MEMORY_MODEL.checkerBytesPerOwnChar * chars) / MB;
90
+ if (files < size.ownFiles)
91
+ return MEMORY_MODEL.checkerBaseMb + small;
92
+ const large = MEMORY_MODEL.wideCheckerMb + (MEMORY_MODEL.wideCheckerBytesPerOwnChar * chars) / MB;
93
+ return MEMORY_MODEL.checkerBaseMb + Math.min(small, large);
94
+ }
95
+ /** The most own files one checker of a slice can take within `roomMb` (after its base). */
96
+ function filesWithin(size, roomMb) {
97
+ if (size.ownChars === 0)
98
+ return size.ownFiles;
99
+ const charsPerFile = size.ownChars / size.ownFiles;
100
+ return Math.floor((roomMb * MB) / (MEMORY_MODEL.checkerBytesPerOwnChar * charsPerFile));
101
+ }
102
+ /**
103
+ * The plan for a check of `projects` (in the order the file phase reaches them) within `budgetMb`:
104
+ * how many own files of each project share one type checker. `keepsPrograms`: the programs stay
105
+ * built to the end (fixes are tried), so every program counts at once; otherwise one at a time.
106
+ */
107
+ export function planMemory(budgetMb, projects, keepsPrograms) {
108
+ const usable = budgetMb * MEMORY_MODEL.usableShare;
109
+ const results = (MEMORY_MODEL.resultBytesPerOwnChar *
110
+ projects.reduce((sum, project) => sum + project.size.ownChars, 0)) /
111
+ MB;
112
+ const planned = [];
113
+ /** The programs and checkers of the projects before this one, when they are kept. */
114
+ let kept = 0;
115
+ let worst;
116
+ for (const [at, { tsconfig, size }] of projects.entries()) {
117
+ const later = keepsPrograms
118
+ ? projects.slice(at + 1).reduce((sum, project) => sum + parsedMb(project.size), 0)
119
+ : 0;
120
+ const fixed = MEMORY_MODEL.baseMb + results + kept + later + parsedMb(size);
121
+ const least = Math.min(size.ownFiles, MEMORY_MODEL.minFilesPerChecker);
122
+ // One checker for all files, priced by the large line too, can cost less than the smallest
123
+ // slice (a few hundred long files): the floor is the lesser.
124
+ const whole = fixed + checkerMb(size, size.ownFiles);
125
+ const floor = Math.min(whole, fixed + checkerMb(size, least));
126
+ if (floor > usable) {
127
+ const neededMb = Math.ceil(floor / MEMORY_MODEL.usableShare / 256) * 256;
128
+ if (worst === undefined || neededMb > worst.neededMb)
129
+ worst = { neededMb, tsconfig, size };
130
+ continue;
131
+ }
132
+ // One checker for all files when it fits; else the most files a slice can take, at least
133
+ // `least`, which fits as checked above.
134
+ const room = usable - fixed - MEMORY_MODEL.checkerBaseMb;
135
+ const slices = whole <= usable
136
+ ? 1
137
+ : Math.max(1, Math.ceil(size.ownFiles / Math.max(least, filesWithin(size, room))));
138
+ const filesPerChecker = Math.ceil(size.ownFiles / slices);
139
+ planned.push({ tsconfig, files: size.ownFiles, slices, filesPerChecker });
140
+ if (keepsPrograms)
141
+ kept += parsedMb(size) + checkerMb(size, filesPerChecker);
142
+ }
143
+ if (worst !== undefined)
144
+ return { kind: "below-floor", budgetMb, ...worst };
145
+ return { kind: "fits", budgetMb, projects: planned };
146
+ }
147
+ function count(n) {
148
+ return n.toLocaleString("en-US");
149
+ }
150
+ /**
151
+ * The plan as stateward prints it once, before the check: "memory budget 3,072 MB: 4 slices of
152
+ * about 900 files". Undefined when every project keeps one type checker (nothing to say).
153
+ * `shown` names a project's tsconfig as the reader would type it.
154
+ */
155
+ export function describePlan(plan, shown) {
156
+ const sliced = plan.projects.filter((project) => project.slices > 1);
157
+ if (sliced.length === 0)
158
+ return undefined;
159
+ const slicesOf = (project) => `${count(project.slices)} slices of about ${count(project.filesPerChecker)} files`;
160
+ const parts = plan.projects.length === 1
161
+ ? sliced.map(slicesOf)
162
+ : sliced.map((project) => `\`${shown(project.tsconfig)}\` in ${slicesOf(project)}`);
163
+ return `memory budget ${count(plan.budgetMb)} MB: ${parts.join(", ")}`;
164
+ }
165
+ /** The budget is below what parsing and binding the project needs: the check does not start. */
166
+ export class MemoryBudgetError extends Error {
167
+ hint;
168
+ constructor(plan, shown) {
169
+ super(`memory budget ${count(plan.budgetMb)} MB is below the ${count(plan.neededMb)} MB \`${shown}\` needs: ${count(plan.size.files)} files to parse and bind, ${count(Math.round(plan.size.chars / 1e6))} million characters`);
170
+ this.name = "MemoryBudgetError";
171
+ this.hint = `set \`--max-memory ${String(plan.neededMb)}\` or \`maxMemory: ${String(plan.neededMb)}\` in the config, or more`;
172
+ }
173
+ }
174
+ //# sourceMappingURL=memory-plan.js.map
package/dist/timing.d.ts CHANGED
@@ -17,15 +17,10 @@ export type RuleCost = {
17
17
  readonly projectMs: number;
18
18
  /**
19
19
  * Of `ms`, the time inside type questions (`TypeQueries`): mostly the type checking a question
20
- * triggers first, which later questions of any rule then reuse.
20
+ * triggers first, which later questions of any rule then reuse. The rest of `ms` is the rule's
21
+ * own work.
21
22
  */
22
23
  readonly typeMs: number;
23
- /**
24
- * Of `typeMs`, the first answer to each question (a method asked about the same node, symbol or
25
- * value): the shared type checking, which later questions of any rule reuse. The rest of `ms` is
26
- * the rule's own work.
27
- */
28
- readonly firstTypeMs: number;
29
24
  /** Files the rule ran on (not counting results reused from the cache). */
30
25
  readonly files: number;
31
26
  /**
@@ -39,12 +34,6 @@ export type RuleCost = {
39
34
  readonly warmTypeMs: number | undefined;
40
35
  /** Files whose result was taken from the cache instead. */
41
36
  readonly reused: number;
42
- /**
43
- * Bytes the heap grew by while the rule ran, summed over its runs: an estimate of what it
44
- * allocated (most of it freed again), not memory it holds. It undercounts when a garbage
45
- * collection lands inside a run.
46
- */
47
- readonly allocatedBytes: number;
48
37
  };
49
38
  /** One run's costs: the phases around the rules, and each rule (by time, largest first). */
50
39
  export type RunTiming = {
@@ -54,8 +43,12 @@ export type RunTiming = {
54
43
  readonly programMs: number;
55
44
  /** Of the rules' time, inside type questions: the type checking the rules ask for. */
56
45
  readonly typeMs: number;
57
- /** Of `typeMs`, the first answer to each question: the shared type checking (`RuleCost.firstTypeMs`). */
58
- readonly firstTypeMs: number;
46
+ /**
47
+ * The heap still in use at the end of the file phase, after a full garbage collection: about
48
+ * what the check needs at its largest (the programs, their type checkers and the results), as
49
+ * opposed to the peak, which follows the heap limit. Undefined when no collection could be forced.
50
+ */
51
+ readonly liveHeapBytes: number | undefined;
59
52
  /** Dependency fingerprints for the results cache. */
60
53
  readonly fingerprintMs: number;
61
54
  /**
@@ -84,6 +77,11 @@ export type TimingRecorder = {
84
77
  readonly secondPass: boolean;
85
78
  /** Runs `run` as `ruleId`'s file side on one file in the second pass and records its cost. */
86
79
  warmSide(ruleId: string, kind: "file" | "project", run: () => void): void;
80
+ /**
81
+ * A project's file phase has ended, its program not yet let go: the live heap is measured, and
82
+ * the largest over the projects kept (`RunTiming.liveHeapBytes`).
83
+ */
84
+ filesDone(): void;
87
85
  /** Runs `run` as a project rule's check and records its cost. */
88
86
  projectSide<T>(ruleId: string, run: () => T): T;
89
87
  /** `types` with the time of every question added to the rule that is running. */
@@ -93,6 +91,10 @@ export type TimingRecorder = {
93
91
  /** The costs so far, with the run's total measured up to now. */
94
92
  result(): RunTiming;
95
93
  };
94
+ /**
95
+ * The recorder holds one record per rule and a few totals, whatever the size of the project: a
96
+ * type question adds its time to the rule that asked it and keeps nothing.
97
+ */
96
98
  export declare function createTimingRecorder({ secondPass, }?: {
97
99
  /** Run every rule a second time after the check (`RuleCost.warmMs`): for benchmarks. */
98
100
  secondPass?: boolean;
package/dist/timing.js CHANGED
@@ -1,40 +1,40 @@
1
- import { getHeapStatistics } from "node:v8";
2
- const usedHeap = () => getHeapStatistics().used_heap_size;
1
+ import { getHeapStatistics, setFlagsFromString } from "node:v8";
2
+ import { runInNewContext } from "node:vm";
3
+ /**
4
+ * A function that runs a full garbage collection, or undefined when none can be had. Node gives
5
+ * one only to a process started with `--expose-gc`; the flag set now takes effect for a new
6
+ * context, which hands out its `gc`, and is unset again. Asked for only under `--timing`.
7
+ */
8
+ function fullCollection() {
9
+ try {
10
+ setFlagsFromString("--expose-gc");
11
+ const found = runInNewContext("gc");
12
+ // Back as it was: later contexts of the process get no `gc`.
13
+ setFlagsFromString("--no-expose-gc");
14
+ if (typeof found !== "function")
15
+ return undefined;
16
+ return () => {
17
+ Reflect.apply(found, undefined, []);
18
+ };
19
+ }
20
+ catch {
21
+ // A runtime without V8 flags: the live heap is not measured.
22
+ return undefined;
23
+ }
24
+ }
25
+ /**
26
+ * The recorder holds one record per rule and a few totals, whatever the size of the project: a
27
+ * type question adds its time to the rule that asked it and keeps nothing.
28
+ */
3
29
  export function createTimingRecorder({ secondPass = false, } = {}) {
4
30
  const rules = new Map();
5
31
  let started = performance.now();
6
32
  let programMs = 0;
7
33
  let fingerprintMs = 0;
8
34
  let ledgerMs = 0;
35
+ let liveHeapBytes;
9
36
  /** The type time of the rule that is running; undefined between rules. */
10
37
  let current;
11
- const wrapped = new WeakMap();
12
- /** The questions asked so far, by their first argument, then the method: a second ask is not first. */
13
- const askedOn = new WeakMap();
14
- const askedBy = new Map();
15
- /** Whether this is the first time `method` is asked about `subject` in the run; notes it. */
16
- const firstAsk = (method, subject) => {
17
- let methods;
18
- if (typeof subject === "object" && subject !== null) {
19
- methods = askedOn.get(subject);
20
- if (methods === undefined) {
21
- methods = new Set();
22
- askedOn.set(subject, methods);
23
- }
24
- }
25
- else {
26
- const key = `${typeof subject}:${String(subject)}`;
27
- methods = askedBy.get(key);
28
- if (methods === undefined) {
29
- methods = new Set();
30
- askedBy.set(key, methods);
31
- }
32
- }
33
- if (methods.has(method))
34
- return false;
35
- methods.add(method);
36
- return true;
37
- };
38
38
  const costOf = (ruleId, kind) => {
39
39
  let found = rules.get(ruleId);
40
40
  if (found === undefined) {
@@ -46,10 +46,8 @@ export function createTimingRecorder({ secondPass = false, } = {}) {
46
46
  fileMs: 0,
47
47
  projectMs: 0,
48
48
  typeMs: 0,
49
- firstTypeMs: 0,
50
49
  files: 0,
51
50
  reused: 0,
52
- allocatedBytes: 0,
53
51
  };
54
52
  rules.set(ruleId, found);
55
53
  }
@@ -62,16 +60,12 @@ export function createTimingRecorder({ secondPass = false, } = {}) {
62
60
  const outerSide = typeSide;
63
61
  current = cost;
64
62
  typeSide = side === "warmMs" ? "warmTypeMs" : "typeMs";
65
- const heap = usedHeap();
66
63
  const at = performance.now();
67
64
  try {
68
65
  return run();
69
66
  }
70
67
  finally {
71
68
  cost[side] += performance.now() - at;
72
- // The heap is the check's own: the second pass's growth is not added.
73
- if (side !== "warmMs")
74
- cost.allocatedBytes += Math.max(0, usedHeap() - heap);
75
69
  current = outer;
76
70
  typeSide = outerSide;
77
71
  }
@@ -98,51 +92,46 @@ export function createTimingRecorder({ secondPass = false, } = {}) {
98
92
  reused(ruleId, kind) {
99
93
  costOf(ruleId, kind).reused += 1;
100
94
  },
95
+ filesDone() {
96
+ const collect = fullCollection();
97
+ if (collect === undefined)
98
+ return;
99
+ // Not part of the check's time: the collection is the recorder's own.
100
+ const at = performance.now();
101
+ collect();
102
+ liveHeapBytes = Math.max(liveHeapBytes ?? 0, getHeapStatistics().used_heap_size);
103
+ started += performance.now() - at;
104
+ },
101
105
  projectSide(ruleId, run) {
102
106
  return measure(costOf(ruleId, "project"), "projectMs", run);
103
107
  },
104
108
  timedTypes(types) {
105
- const known = wrapped.get(types);
106
- if (known !== undefined)
107
- return known;
108
- const methods = new Map();
109
- const proxy = new Proxy(types, {
109
+ // A new proxy per call, held by nobody once the rule has run: nothing grows with the project.
110
+ return new Proxy(types, {
110
111
  get(target, key, receiver) {
111
112
  const value = Reflect.get(target, key, receiver);
112
113
  if (typeof value !== "function")
113
114
  return value;
114
- let method = methods.get(key);
115
- if (method === undefined) {
116
- method = (...args) => {
117
- const cost = current;
118
- if (cost === undefined) {
119
- const untimed = Reflect.apply(value, target, args);
120
- return untimed;
121
- }
122
- // A question asked inside another (none today) is counted once, by the outer one.
123
- current = undefined;
124
- // The second pass asks everything again: only the check's first asks are shared.
125
- const first = typeSide === "typeMs" && firstAsk(key, args[0]);
126
- const at = performance.now();
127
- try {
128
- const answer = Reflect.apply(value, target, args);
129
- return answer;
130
- }
131
- finally {
132
- const spent = performance.now() - at;
133
- cost[typeSide] += spent;
134
- if (first)
135
- cost.firstTypeMs += spent;
136
- current = cost;
137
- }
138
- };
139
- methods.set(key, method);
140
- }
141
- return method;
115
+ return (...args) => {
116
+ const cost = current;
117
+ if (cost === undefined) {
118
+ const untimed = Reflect.apply(value, target, args);
119
+ return untimed;
120
+ }
121
+ // A question asked inside another (none today) is counted once, by the outer one.
122
+ current = undefined;
123
+ const at = performance.now();
124
+ try {
125
+ const answer = Reflect.apply(value, target, args);
126
+ return answer;
127
+ }
128
+ finally {
129
+ cost[typeSide] += performance.now() - at;
130
+ current = cost;
131
+ }
132
+ };
142
133
  },
143
134
  });
144
- wrapped.set(types, proxy);
145
- return proxy;
146
135
  },
147
136
  start() {
148
137
  started = performance.now();
@@ -160,14 +149,13 @@ export function createTimingRecorder({ secondPass = false, } = {}) {
160
149
  const ruleMs = costs.reduce((sum, cost) => sum + cost.ms, 0);
161
150
  const warmMs = costs.reduce((sum, cost) => sum + (cost.warmMs ?? 0), 0);
162
151
  const typeMs = costs.reduce((sum, cost) => sum + cost.typeMs, 0);
163
- const firstTypeMs = costs.reduce((sum, cost) => sum + cost.firstTypeMs, 0);
164
152
  // The second pass is not part of the check: the total is what the check alone took.
165
153
  const totalMs = elapsed - warmMs;
166
154
  return {
167
155
  totalMs,
168
156
  programMs,
169
157
  typeMs,
170
- firstTypeMs,
158
+ liveHeapBytes,
171
159
  fingerprintMs,
172
160
  ledgerMs,
173
161
  otherMs: Math.max(0, totalMs - programMs - fingerprintMs - ledgerMs - ruleMs),
package/dist/types.d.ts CHANGED
@@ -1722,6 +1722,14 @@ export type ProjectContext<O extends Options = Options, A extends Analyses = Ana
1722
1722
  * runs only when every one of them is there. `{}` for a rule that reads none.
1723
1723
  */
1724
1724
  readonly analyses: A;
1725
+ /**
1726
+ * The per-file summaries of an analysis the rule reads that its own plugin publishes, as that
1727
+ * analysis's `solve` receives them: the same map for every rule of the plugin in one check, so
1728
+ * a pack's rules share one copy of the facts instead of each keeping its own. The format of the
1729
+ * summaries is the plugin's own; a rule of another plugin reads only `analyses` (and is refused
1730
+ * here). The rule is checked again when any of these summaries changes.
1731
+ */
1732
+ analysisSummaries(id: Extract<keyof A, string>): ReadonlyMap<string, Json>;
1725
1733
  report(problem: {
1726
1734
  message: string;
1727
1735
  hint: string;
@@ -1830,6 +1838,8 @@ export type ProjectRule<Summary extends Json = Json, S extends OptionSpecs = Opt
1830
1838
  */
1831
1839
  silentReason?(summaries: ReadonlyMap<string, Summary>, ctx: {
1832
1840
  readonly options: OptionsOf<S>;
1841
+ /** As `ProjectContext.analysisSummaries`: empty when the analysis did not run. */
1842
+ analysisSummaries(id: Extract<keyof A, string>): ReadonlyMap<string, Json>;
1833
1843
  }): string | undefined;
1834
1844
  };
1835
1845
  export type Rule = FileRule | ProjectRule;
@@ -1894,7 +1904,8 @@ export type EditorContributions = {
1894
1904
  * The summaries a project rule produced in the last full `check` (JSON, by file), or undefined
1895
1905
  * when that rule did not run or no full check ran yet. The same `Map` object is handed out
1896
1906
  * until a full check produces different summaries, so a plugin may cache what it derives
1897
- * from it.
1907
+ * from it. An analysis's id (`errors/throws`) gives the analysis's summaries, when a rule
1908
+ * read it in that check.
1898
1909
  */
1899
1910
  projectSummaries(ruleId: string): ReadonlyMap<string, Json> | undefined;
1900
1911
  }): string | undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stateward/core",
3
- "version": "1.3.0",
3
+ "version": "1.3.1",
4
4
  "description": "The engine of stateward (exclusive states and predictable code paths for TypeScript) and the API for writing your own rules and packs.",
5
5
  "license": "MIT",
6
6
  "repository": {