@clear-capabilities/agentic-security-scanner 0.184.0 → 0.185.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.
- package/CHANGELOG.md +15 -0
- package/bin/agentic-security.js +87 -0
- package/dist/{dad58d1113a12c23a142.json → 0b301d45b231f144a1b4.json} +26 -9
- package/dist/1128.index.js +908 -0
- package/dist/1336.index.js +261 -112
- package/dist/1665.index.js +828 -0
- package/dist/9579.index.js +1 -1
- package/dist/agentic-security.mjs +15 -15
- package/dist/agentic-security.mjs.sha256 +1 -1
- package/dist/frontend/src/shell.js +12 -2
- package/package.json +26 -9
- package/src/dataflow/CLAUDE.md +43 -1
- package/src/dataflow/backward.js +42 -7
- package/src/dataflow/cross-service-taint.js +83 -1
- package/src/dataflow/demand-query.js +929 -0
- package/src/dataflow/dep-fingerprint.js +718 -0
- package/src/dataflow/engine.js +48 -6
- package/src/dataflow/ifds-precise.js +22 -0
- package/src/dataflow/incremental-replay.js +118 -0
- package/src/dataflow/incremental-session.js +257 -0
- package/src/dataflow/incremental.js +237 -35
- package/src/dataflow/index.js +25 -94
- package/src/dataflow/summaries.js +72 -6
- package/src/dataflow/tabulation.js +80 -24
- package/src/engine.js +51 -3
- package/src/graph/CLAUDE.md +31 -0
- package/src/graph/adapters/artifact.js +81 -0
- package/src/graph/adapters/crossrepo.js +75 -0
- package/src/graph/adapters/dataflow.js +76 -0
- package/src/graph/adapters/provenance.js +92 -0
- package/src/graph/adapters/semantic.js +89 -0
- package/src/graph/crosswalk-builders.js +152 -0
- package/src/graph/crosswalk.js +146 -0
- package/src/graph/index.js +15 -0
- package/src/graph/observation.js +57 -0
- package/src/graph/refs.js +105 -0
- package/src/graph/registry.js +129 -0
- package/src/graph/relations.js +81 -0
- package/src/graph/scc.js +241 -0
- package/src/graph/view.js +254 -0
- package/src/lineage/CLAUDE.md +71 -8
- package/src/lineage/DESIGN_GRAPH_BUILDER.md +1 -1
- package/src/lineage/DESIGN_PATH_PROVENANCE.md +6 -0
- package/src/lineage/boundary-contract.js +273 -0
- package/src/lineage/completion.js +205 -0
- package/src/lineage/continuation.js +140 -0
- package/src/lineage/control-credit.js +313 -0
- package/src/lineage/correlation.js +199 -0
- package/src/lineage/coverage.js +8 -1
- package/src/lineage/cross-repo-link.js +22 -0
- package/src/lineage/cut-planner.js +548 -0
- package/src/lineage/driver.js +219 -66
- package/src/lineage/engine.js +166 -21
- package/src/lineage/export-json.js +5 -0
- package/src/lineage/graph-builder.js +84 -7
- package/src/lineage/haskell-view.js +59 -0
- package/src/lineage/index.js +3 -0
- package/src/lineage/nix-view.js +35 -0
- package/src/lineage/owned-build.js +77 -0
- package/src/lineage/owned-worker-entry.js +22 -0
- package/src/lineage/owned-worker.js +95 -0
- package/src/lineage/path-evidence.js +123 -0
- package/src/lineage/path-predicates.js +529 -0
- package/src/lineage/path-query.js +189 -20
- package/src/lineage/path-store.js +191 -17
- package/src/lineage/scc-solver.js +186 -0
- package/src/lineage/smt-orchestrator.js +138 -0
- package/src/lineage/source-seeding.js +36 -2
- package/src/lineage/summaries.js +66 -4
- package/src/lineage/value-versions.js +130 -0
- package/src/lineage/witness-selection.js +95 -0
- package/src/pipeline/scan-health.js +18 -0
- package/src/posture/CLAUDE.md +13 -0
- package/src/posture/evidence-bundle.js +1 -1
- package/src/posture/witness-bundle.js +573 -0
- package/src/posture/witness-runtime.js +276 -0
- package/src/report/index.js +2 -0
|
@@ -0,0 +1,718 @@
|
|
|
1
|
+
// DAG-05: dependency fingerprints for cross-scan incremental analysis.
|
|
2
|
+
//
|
|
3
|
+
// What a cached result may be reused for is decided here, from CONTENT:
|
|
4
|
+
//
|
|
5
|
+
// * a per-function OWN fingerprint: the canonical body (node ids renamed, they
|
|
6
|
+
// come from a process-global counter), the resolution of every name the body
|
|
7
|
+
// calls or passes along (so a callee that appeared, vanished or moved changes
|
|
8
|
+
// the caller even when the caller's text did not), the file-level facts the
|
|
9
|
+
// engine shares between functions of one file, and the class hierarchy;
|
|
10
|
+
// * a dependency graph over those functions: calls, callbacks, class-field
|
|
11
|
+
// coupling between methods and the request-object seeding of one file;
|
|
12
|
+
// * the strongly connected components of that graph (graph/scc.js), so a
|
|
13
|
+
// function in a cycle is only ever reused together with its whole cycle;
|
|
14
|
+
// * a CLOSURE fingerprint per component: its members' own fingerprints plus
|
|
15
|
+
// the closure fingerprints of everything it depends on;
|
|
16
|
+
// * GLOBAL components (analysis options, build and language configuration,
|
|
17
|
+
// graph schema, catalog / sanitizer / analyzer content digests, stubs,
|
|
18
|
+
// policies, boundary contracts). They are digests of CONTENT, never entry
|
|
19
|
+
// counts: a sanitizer whose behaviour changed keeps the catalog size.
|
|
20
|
+
//
|
|
21
|
+
// `planIncremental` compares a prior persisted model with the current one and
|
|
22
|
+
// answers, per function, clean or dirty and why. A removed or renamed symbol is
|
|
23
|
+
// found through the PRIOR graph (persisted file-to-symbol mapping and prior
|
|
24
|
+
// callees), because the current IR no longer contains it.
|
|
25
|
+
//
|
|
26
|
+
// Everything here is pure except `globalComponents`, which reads build and
|
|
27
|
+
// policy files under the scan root and the analyzer sources next to this file.
|
|
28
|
+
|
|
29
|
+
import * as crypto from 'node:crypto';
|
|
30
|
+
import * as fs from 'node:fs';
|
|
31
|
+
import * as path from 'node:path';
|
|
32
|
+
import { fileURLToPath } from 'node:url';
|
|
33
|
+
|
|
34
|
+
import { computeScc } from '../graph/scc.js';
|
|
35
|
+
import { CATALOG } from './catalog.js';
|
|
36
|
+
import { classOfVar } from '../ir/class-hierarchy.js';
|
|
37
|
+
import { isLanguageManifest, isExplicitExport, readExplicitExports } from '../language/discovery.js';
|
|
38
|
+
import { stateDir } from '../posture/state-dir.js';
|
|
39
|
+
|
|
40
|
+
export const DEP_GRAPH_SCHEMA = 'dep-graph/1';
|
|
41
|
+
const MODEL_VERSION = 1;
|
|
42
|
+
const sha = (s) => crypto.createHash('sha256').update(s).digest('hex');
|
|
43
|
+
|
|
44
|
+
// ── stable serialisation ────────────────────────────────────────────────────
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Deterministic text for any value: object keys sorted, Map / Set / RegExp /
|
|
48
|
+
* function handled, cycles marked. Returns null when the value is too deep to
|
|
49
|
+
* serialise safely (the caller treats that as "cannot fingerprint").
|
|
50
|
+
*/
|
|
51
|
+
export function stableSerialize(value, maxDepth = 1500) {
|
|
52
|
+
const seen = new WeakSet();
|
|
53
|
+
const out = [];
|
|
54
|
+
let tooDeep = false;
|
|
55
|
+
const walk = (v, depth) => {
|
|
56
|
+
if (tooDeep) return;
|
|
57
|
+
if (depth > maxDepth) { tooDeep = true; return; }
|
|
58
|
+
if (v === null) { out.push('null'); return; }
|
|
59
|
+
switch (typeof v) {
|
|
60
|
+
case 'undefined': out.push('undefined'); return;
|
|
61
|
+
case 'number': out.push(Number.isFinite(v) ? String(v) : `"n:${v}"`); return;
|
|
62
|
+
case 'boolean': out.push(v ? 'true' : 'false'); return;
|
|
63
|
+
case 'bigint': out.push(`"b:${v}"`); return;
|
|
64
|
+
case 'string': out.push(JSON.stringify(v)); return;
|
|
65
|
+
case 'symbol': out.push(JSON.stringify(String(v))); return;
|
|
66
|
+
case 'function': out.push(JSON.stringify(`fn:${Function.prototype.toString.call(v)}`)); return;
|
|
67
|
+
default: break;
|
|
68
|
+
}
|
|
69
|
+
if (v instanceof RegExp) { out.push(JSON.stringify(`re:${v.source}/${v.flags}`)); return; }
|
|
70
|
+
if (seen.has(v)) { out.push('"[cycle]"'); return; }
|
|
71
|
+
seen.add(v);
|
|
72
|
+
if (Array.isArray(v)) {
|
|
73
|
+
out.push('[');
|
|
74
|
+
for (let i = 0; i < v.length; i++) { if (i) out.push(','); walk(v[i], depth + 1); }
|
|
75
|
+
out.push(']');
|
|
76
|
+
} else if (v instanceof Set) {
|
|
77
|
+
const parts = [...v].map((x) => stableSerialize(x, maxDepth - depth)).sort();
|
|
78
|
+
out.push(`{"$set":[${parts.join(',')}]}`);
|
|
79
|
+
} else if (v instanceof Map) {
|
|
80
|
+
const parts = [...v].map(([k, x]) => `[${stableSerialize(k, maxDepth - depth)},${stableSerialize(x, maxDepth - depth)}]`).sort();
|
|
81
|
+
out.push(`{"$map":[${parts.join(',')}]}`);
|
|
82
|
+
} else {
|
|
83
|
+
const keys = Object.keys(v).sort();
|
|
84
|
+
out.push('{');
|
|
85
|
+
let first = true;
|
|
86
|
+
for (const k of keys) {
|
|
87
|
+
if (v[k] === undefined) continue;
|
|
88
|
+
if (!first) out.push(',');
|
|
89
|
+
first = false;
|
|
90
|
+
out.push(JSON.stringify(k), ':');
|
|
91
|
+
walk(v[k], depth + 1);
|
|
92
|
+
}
|
|
93
|
+
out.push('}');
|
|
94
|
+
}
|
|
95
|
+
seen.delete(v);
|
|
96
|
+
};
|
|
97
|
+
try { walk(value, 0); } catch { return null; }
|
|
98
|
+
if (tooDeep) return null;
|
|
99
|
+
return out.join('');
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// ── canonical function body ─────────────────────────────────────────────────
|
|
103
|
+
|
|
104
|
+
const ID_VALUE_KEYS = new Set(['id', 'entry', 'exit', 'site', 'node']);
|
|
105
|
+
const ID_ARRAY_KEYS = new Set(['succ', 'pred', 'returns']);
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Native JSON text with Map / Set / RegExp / function made representable. Key
|
|
109
|
+
* order is the producer's own, which is deterministic for a given source and
|
|
110
|
+
* analyzer version (the analyzer digest is a global component), so it is not
|
|
111
|
+
* re-sorted: a reorder can only cause an unneeded invalidation, never a stale
|
|
112
|
+
* reuse. Returns null when the value cannot be serialised (cycle, too deep).
|
|
113
|
+
*/
|
|
114
|
+
function fastSerialize(value, extra = null) {
|
|
115
|
+
try {
|
|
116
|
+
return JSON.stringify(value, function replacer(k, v) {
|
|
117
|
+
if (v instanceof Set) return { $set: [...v] };
|
|
118
|
+
if (v instanceof Map) return { $map: [...v] };
|
|
119
|
+
if (v instanceof RegExp) return `re:${v.source}/${v.flags}`;
|
|
120
|
+
if (typeof v === 'function') return `fn:${Function.prototype.toString.call(v)}`;
|
|
121
|
+
return extra ? extra(k, v) : v;
|
|
122
|
+
});
|
|
123
|
+
} catch { return null; }
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* The function as text with its CFG node ids renamed to their position. The IR
|
|
128
|
+
* assigns ids from a process-global counter, so two builds of identical source
|
|
129
|
+
* differ in ids; everything else (kinds, expressions, lines, spans) is kept
|
|
130
|
+
* verbatim. Null when the function cannot be serialised.
|
|
131
|
+
*/
|
|
132
|
+
export function canonicalFunctionText(fn) {
|
|
133
|
+
const nodes = (fn && fn.cfg && fn.cfg.nodes) || {};
|
|
134
|
+
const ids = Object.keys(nodes);
|
|
135
|
+
const rename = new Map(ids.map((id, i) => [id, `#${i}`]));
|
|
136
|
+
const shell = {};
|
|
137
|
+
for (const k of Object.keys(fn || {})) if (k !== 'cfg') shell[k] = fn[k];
|
|
138
|
+
shell.cfg = fn && fn.cfg ? {
|
|
139
|
+
entry: rename.get(fn.cfg.entry) ?? fn.cfg.entry,
|
|
140
|
+
exit: rename.get(fn.cfg.exit) ?? fn.cfg.exit,
|
|
141
|
+
nodes: ids.map((id) => nodes[id]),
|
|
142
|
+
} : null;
|
|
143
|
+
return fastSerialize(shell, (k, v) => {
|
|
144
|
+
if (typeof v === 'string') return ID_VALUE_KEYS.has(k) && rename.has(v) ? rename.get(v) : v;
|
|
145
|
+
if (Array.isArray(v) && ID_ARRAY_KEYS.has(k)) return v.map((x) => (typeof x === 'string' && rename.has(x) ? rename.get(x) : x));
|
|
146
|
+
return v;
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// ── names a function resolves ───────────────────────────────────────────────
|
|
151
|
+
|
|
152
|
+
function flattenCallee(c) {
|
|
153
|
+
if (typeof c === 'string') return c;
|
|
154
|
+
if (!c || typeof c !== 'object') return null;
|
|
155
|
+
// the Babel frontend spells `this` as `_this_`; the engine converts it before resolving (engine.js _flattenCalleeName)
|
|
156
|
+
if (c.kind === 'ident') return c.name === '_this_' ? 'this' : (c.name || null);
|
|
157
|
+
if (c.kind === 'member') {
|
|
158
|
+
const o = flattenCallee(c.object);
|
|
159
|
+
return o && c.prop ? `${o}.${c.prop}` : (c.prop || null);
|
|
160
|
+
}
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const MAX_NAMES_PER_FN = 600;
|
|
165
|
+
|
|
166
|
+
/** Names a function calls, passes as a callback argument, or references by qid. */
|
|
167
|
+
function referencedNames(fn, functionsByQid) {
|
|
168
|
+
const names = new Set();
|
|
169
|
+
const qids = new Set();
|
|
170
|
+
const visit = (v, depth) => {
|
|
171
|
+
if (!v || typeof v !== 'object' || depth > 60) return;
|
|
172
|
+
if (Array.isArray(v)) { for (const x of v) visit(x, depth + 1); return; }
|
|
173
|
+
if (v.kind === 'call') {
|
|
174
|
+
const nm = flattenCallee(v.callee);
|
|
175
|
+
if (nm) names.add(nm);
|
|
176
|
+
if (Array.isArray(v.args)) for (const a of v.args) if (a && a.kind === 'ident' && a.name) names.add(a.name);
|
|
177
|
+
}
|
|
178
|
+
for (const k of Object.keys(v)) {
|
|
179
|
+
const x = v[k];
|
|
180
|
+
if (typeof x === 'string') { if ((k === 'calleeQid' || k === 'qid') && functionsByQid.has(x)) qids.add(x); }
|
|
181
|
+
else visit(x, depth + 1);
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
const nodes = (fn.cfg && fn.cfg.nodes) || {};
|
|
185
|
+
for (const id of Object.keys(nodes)) {
|
|
186
|
+
const n = nodes[id];
|
|
187
|
+
if (!n) continue;
|
|
188
|
+
if (n.kind === 'call' && n.callee != null) {
|
|
189
|
+
const nm = flattenCallee(n.callee);
|
|
190
|
+
if (nm) names.add(nm);
|
|
191
|
+
}
|
|
192
|
+
visit(n, 0);
|
|
193
|
+
if (names.size > MAX_NAMES_PER_FN) break;
|
|
194
|
+
}
|
|
195
|
+
for (const c of fn.calls || []) {
|
|
196
|
+
const nm = typeof c === 'string' ? c : flattenCallee(c && c.callee);
|
|
197
|
+
if (nm) names.add(nm);
|
|
198
|
+
}
|
|
199
|
+
return { names: [...names].sort().slice(0, MAX_NAMES_PER_FN), qids: [...qids].sort() };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// ── class hierarchy digest ──────────────────────────────────────────────────
|
|
203
|
+
|
|
204
|
+
function classHierarchyDigest(cha) {
|
|
205
|
+
if (!cha || !cha.classes || !cha.classes.size) return 'no-classes';
|
|
206
|
+
const classes = [...cha.classes.values()].map((c) => ({
|
|
207
|
+
name: c.name, extends: c.extends || null,
|
|
208
|
+
bases: [...(c.bases || [])].sort(),
|
|
209
|
+
fields: [...(c.fields || [])].sort(),
|
|
210
|
+
methods: [...(c.methods || [])].sort(),
|
|
211
|
+
})).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
212
|
+
const live = cha.liveClasses ? [...cha.liveClasses].sort() : [];
|
|
213
|
+
return sha(stableSerialize({ classes, live }) || 'unserialisable');
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// ── file-level context the engine shares between functions of one file ──────
|
|
217
|
+
|
|
218
|
+
const REQ_PARAM = /^(?:req|request|ctx)$/;
|
|
219
|
+
// Languages whose IR for a file is built from that file's text alone (no include or module merging across files).
|
|
220
|
+
const PER_FILE_IR = /\.(?:m?js|cjs|jsx|tsx?|py|java|go|rs|cs|kt|rb)$/i;
|
|
221
|
+
|
|
222
|
+
function isRegexInit(src) {
|
|
223
|
+
if (!src || typeof src !== 'object') return false;
|
|
224
|
+
if (src.kind === 'literal' && src.isRegex) return true;
|
|
225
|
+
return src.kind === 'call' && !!src.callee && src.callee.kind === 'ident' && src.callee.name === 'RegExp';
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Per file: the provably-RegExp names and the functions that seed request fields (mirrors engine.js). */
|
|
229
|
+
function fileContexts(fns) {
|
|
230
|
+
const byFile = new Map();
|
|
231
|
+
for (const fn of fns) {
|
|
232
|
+
if (!fn || !fn.file) continue;
|
|
233
|
+
let rec = byFile.get(fn.file);
|
|
234
|
+
if (!rec) { rec = { names: new Map(), seeders: [] }; byFile.set(fn.file, rec); }
|
|
235
|
+
if (fn.cfg && fn.cfg.nodes) {
|
|
236
|
+
for (const p of fn.params || []) if (typeof p === 'string') rec.names.set(p, false);
|
|
237
|
+
for (const n of Object.values(fn.cfg.nodes)) {
|
|
238
|
+
if (!n || n.kind !== 'assign' || typeof n.target !== 'string' || n.target.includes('.')) continue;
|
|
239
|
+
const prev = rec.names.get(n.target);
|
|
240
|
+
rec.names.set(n.target, (prev === undefined || prev === true) && isRegexInit(n.source));
|
|
241
|
+
}
|
|
242
|
+
if (Array.isArray(fn.params) && REQ_PARAM.test(fn.params[0] || '')) {
|
|
243
|
+
const p0 = fn.params[0];
|
|
244
|
+
for (const n of Object.values(fn.cfg.nodes)) {
|
|
245
|
+
if (n && n.kind === 'assign' && typeof n.target === 'string' && n.target.startsWith(`${p0}.`)) { rec.seeders.push(fn.qid); break; }
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
const out = new Map();
|
|
251
|
+
for (const [file, rec] of byFile) {
|
|
252
|
+
const regex = [...rec.names].filter(([, ok]) => ok).map(([n]) => n).sort();
|
|
253
|
+
out.set(file, { regexDigest: sha(regex.join('|')), seeders: rec.seeders.slice().sort() });
|
|
254
|
+
}
|
|
255
|
+
return out;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// ── the dependency model ────────────────────────────────────────────────────
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* name -> qid exactly as the engine resolves a call (`resolveKnownCallee`; the engine never
|
|
262
|
+
* uses the guessing `resolve`), memoised per (file, name), with a pre-filter: a call can only
|
|
263
|
+
* resolve to a function if the name, its last segment, its `this.`-stripped form or its
|
|
264
|
+
* qualified-name spelling is something some function is called, or the file imports the head
|
|
265
|
+
* of the name, or the project re-exports under that alias. Anything else cannot resolve, and the
|
|
266
|
+
* O(files) global scan inside the resolver is skipped for it.
|
|
267
|
+
*/
|
|
268
|
+
function makeResolver(callGraph, fns, fileContents) {
|
|
269
|
+
const memo = new Map();
|
|
270
|
+
const exact = new Set(); // fn.name as written
|
|
271
|
+
const tails = new Set(); // last segment of a dotted fn.name (bare-tail resolution)
|
|
272
|
+
const classKeys = new Set(); // Class.method
|
|
273
|
+
const qnameFiles = new Set(); // C/C++ files: qualified-name resolution applies
|
|
274
|
+
for (const fn of fns) {
|
|
275
|
+
if (fn.name) { exact.add(fn.name); if (fn.name.includes('.')) tails.add(fn.name.split('.').pop()); }
|
|
276
|
+
if (fn.qname) qnameFiles.add(fn.file);
|
|
277
|
+
const m = /::(\w+)::(\w+)@/.exec(fn.qid);
|
|
278
|
+
if (m) classKeys.add(`${m[1]}.${m[2]}`);
|
|
279
|
+
}
|
|
280
|
+
// Names a re-export can make resolvable under a different spelling (`export { a as b } from`).
|
|
281
|
+
const aliases = new Set();
|
|
282
|
+
for (const src of Object.values(fileContents || {})) {
|
|
283
|
+
if (typeof src !== 'string' || !src.includes(' from ')) continue;
|
|
284
|
+
for (const m of src.matchAll(/export\s*\{\s*([^}]+)\s*\}\s*from\s*['"][^'"]+['"]/g)) {
|
|
285
|
+
for (const part of m[1].split(',')) { const [orig, alias] = part.trim().split(/\s+as\s+/); aliases.add((alias || orig || '').trim()); }
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
const mi = callGraph && callGraph.moduleIndex;
|
|
289
|
+
const real = (name, file) => { try { return callGraph.resolveKnownCallee ? (callGraph.resolveKnownCallee(name, file) || null) : null; } catch { return null; } };
|
|
290
|
+
return (name, file) => {
|
|
291
|
+
const k = `${file}\0${name}`;
|
|
292
|
+
let r = memo.get(k);
|
|
293
|
+
if (r !== undefined) return r;
|
|
294
|
+
let viaImport = false;
|
|
295
|
+
if (mi && typeof mi.resolveCall === 'function' && file) {
|
|
296
|
+
try { const imp = mi.resolveCall(file, name); viaImport = !!(imp && (imp.status === 'resolved' || imp.status === 'external')); } catch { viaImport = true; }
|
|
297
|
+
}
|
|
298
|
+
const bare = name.startsWith('this.') ? name.slice(5) : null;
|
|
299
|
+
const possible = viaImport || aliases.has(name) || qnameFiles.has(file) || exact.has(name) || classKeys.has(name)
|
|
300
|
+
|| (!name.includes('.') && tails.has(name))
|
|
301
|
+
|| (bare !== null && (exact.has(bare) || tails.has(bare)));
|
|
302
|
+
r = possible ? real(name, file) : null;
|
|
303
|
+
memo.set(k, r);
|
|
304
|
+
return r;
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Build the dependency model for one scan.
|
|
310
|
+
*
|
|
311
|
+
* functions[qid] = { file, name, own, closure, scc, callees:[qid], unfingerprintable? }
|
|
312
|
+
* fileSymbols[file] = [qid]
|
|
313
|
+
* sccs[sccId] = [qid] (recursive or coupled components only)
|
|
314
|
+
*/
|
|
315
|
+
export function buildDependencyModel({ perFileIR, callGraph, cha, fileContents, reuse = null }) {
|
|
316
|
+
const fnMap = (callGraph && callGraph.functions) || new Map();
|
|
317
|
+
const fns = [...fnMap.values()].filter((f) => f && f.qid);
|
|
318
|
+
const phase = {}; let _t = Date.now();
|
|
319
|
+
const lap = (name) => { const n = Date.now(); phase[name] = n - _t; _t = n; };
|
|
320
|
+
const chaDigest = classHierarchyDigest(cha);
|
|
321
|
+
lap('cha-digest');
|
|
322
|
+
const hasClasses = chaDigest !== 'no-classes';
|
|
323
|
+
const ctxByFile = fileContexts(fns);
|
|
324
|
+
lap('file-contexts');
|
|
325
|
+
const resolveKnown = makeResolver(callGraph, fns, fileContents);
|
|
326
|
+
|
|
327
|
+
const methodOwner = (cha && cha.methodOwners) || new Map();
|
|
328
|
+
// Classes related to `cls` by inheritance (itself, ancestors, descendants): the candidates the engine's
|
|
329
|
+
// class-hierarchy and instantiated-class dispatch can pick a method from for a receiver typed `cls`.
|
|
330
|
+
const children = new Map();
|
|
331
|
+
if (hasClasses) {
|
|
332
|
+
for (const c of cha.classes.values()) {
|
|
333
|
+
for (const b of new Set([c.extends, ...(c.bases || [])].filter(Boolean))) {
|
|
334
|
+
if (!children.has(b)) children.set(b, []);
|
|
335
|
+
children.get(b).push(c.name);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
const relatedMemo = new Map();
|
|
340
|
+
const related = (cls) => {
|
|
341
|
+
let r = relatedMemo.get(cls);
|
|
342
|
+
if (r) return r;
|
|
343
|
+
r = new Set([cls]);
|
|
344
|
+
const stack = [cls];
|
|
345
|
+
while (stack.length) {
|
|
346
|
+
const c = stack.pop();
|
|
347
|
+
const info = cha.classes.get(c);
|
|
348
|
+
for (const b of new Set([info && info.extends, ...((info && info.bases) || [])].filter(Boolean))) if (!r.has(b)) { r.add(b); stack.push(b); }
|
|
349
|
+
for (const d of children.get(c) || []) if (!r.has(d)) { r.add(d); stack.push(d); }
|
|
350
|
+
}
|
|
351
|
+
relatedMemo.set(cls, r);
|
|
352
|
+
return r;
|
|
353
|
+
};
|
|
354
|
+
const methodsOfClass = new Map();
|
|
355
|
+
for (const [qid, cls] of methodOwner) {
|
|
356
|
+
if (!methodsOfClass.has(cls)) methodsOfClass.set(cls, []);
|
|
357
|
+
methodsOfClass.get(cls).push(qid);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
lap('indexes');
|
|
361
|
+
const ownInfo = new Map();
|
|
362
|
+
const edges = new Map(); // caller -> Set(callee)
|
|
363
|
+
const addEdge = (a, b) => { if (a === b) return; let s = edges.get(a); if (!s) { s = new Set(); edges.set(a, s); } s.add(b); };
|
|
364
|
+
|
|
365
|
+
// A function of an unchanged file, in a language whose IR is built from that one file alone, has
|
|
366
|
+
// the body digest and name list it had last time (same analyzer, same source): they are carried
|
|
367
|
+
// forward instead of re-serialising its IR. Resolution is never carried, it depends on other files.
|
|
368
|
+
const bodyOf = new Map();
|
|
369
|
+
const carried = (fn) => {
|
|
370
|
+
if (!reuse || !PER_FILE_IR.test(fn.file)) return null;
|
|
371
|
+
if (!reuse.priorFiles || reuse.priorFiles[fn.file] === undefined || reuse.priorFiles[fn.file] !== reuse.curFiles[fn.file]) return null;
|
|
372
|
+
const p = reuse.functions && reuse.functions[fn.qid];
|
|
373
|
+
return p && typeof p.body === 'string' && p.refs ? p : null;
|
|
374
|
+
};
|
|
375
|
+
for (const fn of fns) {
|
|
376
|
+
const prev = carried(fn);
|
|
377
|
+
let canon; let refs; let body;
|
|
378
|
+
if (prev) { body = prev.body; refs = prev.refs; canon = body; }
|
|
379
|
+
else {
|
|
380
|
+
canon = canonicalFunctionText(fn);
|
|
381
|
+
body = canon === null ? null : sha(canon);
|
|
382
|
+
refs = referencedNames(fn, fnMap);
|
|
383
|
+
}
|
|
384
|
+
bodyOf.set(fn.qid, { body, refs });
|
|
385
|
+
const res = [];
|
|
386
|
+
for (const name of refs.names) {
|
|
387
|
+
const known = resolveKnown(name, fn.file);
|
|
388
|
+
res.push([name, known]);
|
|
389
|
+
if (known) addEdge(fn.qid, known);
|
|
390
|
+
// A member call the engine resolves through the class hierarchy: `recv.method` where recv is a bare local
|
|
391
|
+
// whose class the hierarchy knows (engine.js _resolveMemberCalleeViaCHA). The candidates are the methods of
|
|
392
|
+
// every related class (inheritance and instantiated-class dispatch); nothing else can be picked.
|
|
393
|
+
if (hasClasses) {
|
|
394
|
+
const dot = name.indexOf('.');
|
|
395
|
+
if (dot > 0 && name.indexOf('.', dot + 1) === -1) {
|
|
396
|
+
const recv = name.slice(0, dot); const method = name.slice(dot + 1);
|
|
397
|
+
if (recv !== 'this' && recv !== '_this_') {
|
|
398
|
+
let cls = null;
|
|
399
|
+
try { cls = classOfVar(cha, fn.file, fn.qid, recv); } catch { cls = null; }
|
|
400
|
+
if (cls) for (const c of related(cls)) {
|
|
401
|
+
const info = cha.classes.get(c);
|
|
402
|
+
if (info && info.methods && info.methods.has(method)) { const q = resolveKnown(`${c}.${method}`, fn.file); if (q) addEdge(fn.qid, q); }
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
for (const q of refs.qids) addEdge(fn.qid, q);
|
|
409
|
+
const ctx = ctxByFile.get(fn.file);
|
|
410
|
+
// Request-object seeding: every request-taking function of a file reads what
|
|
411
|
+
// the file's seeding functions leave tainted.
|
|
412
|
+
if (ctx && ctx.seeders.length && Array.isArray(fn.params) && REQ_PARAM.test(fn.params[0] || '')) {
|
|
413
|
+
for (const s of ctx.seeders) addEdge(fn.qid, s);
|
|
414
|
+
}
|
|
415
|
+
ownInfo.set(fn.qid, { canon: body === null ? null : canon, body, res, ctx });
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
lap('names-and-resolution');
|
|
419
|
+
// Class-field coupling (engine.js class-field and cross-class passes): a method
|
|
420
|
+
// reads what its sibling methods leave tainted, and the seeds it gets depend on
|
|
421
|
+
// who calls it. Same-class methods are mutually dependent; a method also depends
|
|
422
|
+
// on its callers; a function whose file text names a class with declared fields
|
|
423
|
+
// depends on that class's methods.
|
|
424
|
+
// Only a class with DECLARED fields can take part (the engine's class-field passes start from
|
|
425
|
+
// `cha.classes[c].fields`), so a class without any couples nothing.
|
|
426
|
+
const fieldClassNames = new Set();
|
|
427
|
+
if (hasClasses) for (const [name, c] of cha.classes) if (c.fields && c.fields.size) fieldClassNames.add(name);
|
|
428
|
+
if (fieldClassNames.size) {
|
|
429
|
+
for (const [cls, qids] of methodsOfClass) {
|
|
430
|
+
if (!fieldClassNames.has(cls) || qids.length < 2) continue;
|
|
431
|
+
for (const a of qids) for (const b of qids) addEdge(a, b);
|
|
432
|
+
}
|
|
433
|
+
const callersOf = new Map();
|
|
434
|
+
for (const [a, set] of edges) for (const b of set) { if (!callersOf.has(b)) callersOf.set(b, new Set()); callersOf.get(b).add(a); }
|
|
435
|
+
for (const [qid, cls] of methodOwner) {
|
|
436
|
+
if (!fieldClassNames.has(cls)) continue;
|
|
437
|
+
for (const c of callersOf.get(qid) || []) addEdge(qid, c);
|
|
438
|
+
}
|
|
439
|
+
if (fileContents) {
|
|
440
|
+
const fnsByFile = new Map();
|
|
441
|
+
for (const fn of fns) { if (!fnsByFile.has(fn.file)) fnsByFile.set(fn.file, []); fnsByFile.get(fn.file).push(fn.qid); }
|
|
442
|
+
for (const [file, qids] of fnsByFile) {
|
|
443
|
+
const src = fileContents[file];
|
|
444
|
+
if (typeof src !== 'string') continue;
|
|
445
|
+
for (const cname of fieldClassNames) {
|
|
446
|
+
if (!src.includes(`${cname}.`)) continue;
|
|
447
|
+
for (const m of methodsOfClass.get(cname) || []) for (const q of qids) { addEdge(q, m); addEdge(m, q); }
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
lap('class-coupling');
|
|
453
|
+
// Own fingerprints (after edges: nothing below feeds back into them).
|
|
454
|
+
const own = new Map();
|
|
455
|
+
const unfingerprintable = new Set();
|
|
456
|
+
for (const fn of fns) {
|
|
457
|
+
const info = ownInfo.get(fn.qid);
|
|
458
|
+
if (info.canon === null) { unfingerprintable.add(fn.qid); own.set(fn.qid, `unfingerprintable:${fn.qid}`); continue; }
|
|
459
|
+
const body = info.body;
|
|
460
|
+
own.set(fn.qid, sha(stableSerialize({
|
|
461
|
+
v: MODEL_VERSION, qid: fn.qid, body, res: info.res,
|
|
462
|
+
regex: info.ctx ? info.ctx.regexDigest : null,
|
|
463
|
+
cha: hasClasses ? chaDigest : null,
|
|
464
|
+
})));
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
lap('own-fingerprints');
|
|
468
|
+
// SCCs over callee -> caller, so `order` lists dependencies first.
|
|
469
|
+
const nodes = fns.map((f) => f.qid);
|
|
470
|
+
const sccEdges = [];
|
|
471
|
+
for (const [a, set] of edges) for (const b of set) if (fnMap.has(b)) sccEdges.push([b, a]);
|
|
472
|
+
const scc = computeScc({ nodes, edges: sccEdges });
|
|
473
|
+
const closureOfComp = new Map();
|
|
474
|
+
for (const cid of scc.order) {
|
|
475
|
+
const comp = scc.components[cid];
|
|
476
|
+
const memberOwn = comp.members.map((q) => `${q}=${own.get(q)}`).sort();
|
|
477
|
+
const dep = new Set();
|
|
478
|
+
for (const m of comp.members) for (const b of edges.get(m) || []) {
|
|
479
|
+
if (!fnMap.has(b)) continue;
|
|
480
|
+
const bc = scc.componentOf.get(b);
|
|
481
|
+
if (bc !== cid) dep.add(closureOfComp.get(bc));
|
|
482
|
+
}
|
|
483
|
+
closureOfComp.set(cid, sha(stableSerialize({ own: memberOwn, deps: [...dep].sort() })));
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
lap('scc-and-closure');
|
|
487
|
+
const functions = {};
|
|
488
|
+
const fileSymbols = {};
|
|
489
|
+
const sccs = {};
|
|
490
|
+
const sccKeyOf = new Map();
|
|
491
|
+
for (const fn of fns) {
|
|
492
|
+
const cid = scc.componentOf.get(fn.qid);
|
|
493
|
+
const comp = scc.components[cid];
|
|
494
|
+
let sccKey = null;
|
|
495
|
+
if (comp.members.length > 1) {
|
|
496
|
+
sccKey = sccKeyOf.get(cid);
|
|
497
|
+
if (!sccKey) { sccKey = sha(comp.members.join('\n')).slice(0, 16); sccKeyOf.set(cid, sccKey); sccs[sccKey] = comp.members.slice(); }
|
|
498
|
+
}
|
|
499
|
+
functions[fn.qid] = {
|
|
500
|
+
file: fn.file, name: fn.name || null,
|
|
501
|
+
own: own.get(fn.qid), closure: closureOfComp.get(cid), scc: sccKey,
|
|
502
|
+
body: bodyOf.get(fn.qid).body, refs: bodyOf.get(fn.qid).refs,
|
|
503
|
+
callees: [...(edges.get(fn.qid) || [])].filter((b) => fnMap.has(b)).sort(),
|
|
504
|
+
...(unfingerprintable.has(fn.qid) ? { unfingerprintable: true } : {}),
|
|
505
|
+
};
|
|
506
|
+
(fileSymbols[fn.file] ||= []).push(fn.qid);
|
|
507
|
+
}
|
|
508
|
+
for (const f of Object.keys(fileSymbols)) fileSymbols[f].sort();
|
|
509
|
+
lap('assemble');
|
|
510
|
+
return {
|
|
511
|
+
schema: DEP_GRAPH_SCHEMA, modelVersion: MODEL_VERSION, chaDigest,
|
|
512
|
+
functions, fileSymbols, sccs,
|
|
513
|
+
stats: { functions: fns.length, edges: sccEdges.length, components: scc.components.length, coupled: Object.keys(sccs).length, phaseMs: phase },
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
// ── global components ───────────────────────────────────────────────────────
|
|
518
|
+
|
|
519
|
+
const VOLATILE_ENV = /^AGENTIC_SECURITY_(?:INCREMENTAL(?:_.*)?|HMAC_KEY|DEBUG|NO_GATE_WARM|NO_PRECOMMIT|GATE_.*|NO_STATE|DEEP_TIMEOUT_MS|RESUME|NO_COLOR|QUIET|PROGRESS.*|LLM_.*|OFFLINE|HOME|TMPDIR)$/;
|
|
520
|
+
|
|
521
|
+
function analyzerRoots() {
|
|
522
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
523
|
+
const src = path.resolve(here, '..');
|
|
524
|
+
return { here, src, isSource: path.basename(here) === 'dataflow' && fs.existsSync(path.join(src, 'ir')) };
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
let _analyzerMemo = null;
|
|
528
|
+
/** Digest of the analyzer and parser sources (or the bundle when running from one). */
|
|
529
|
+
function analyzerDigest() {
|
|
530
|
+
if (_analyzerMemo) return _analyzerMemo;
|
|
531
|
+
const { here, src, isSource } = analyzerRoots();
|
|
532
|
+
const h = crypto.createHash('sha256');
|
|
533
|
+
try {
|
|
534
|
+
if (isSource) {
|
|
535
|
+
for (const dir of ['dataflow', 'ir', 'graph', 'language']) {
|
|
536
|
+
const d = path.join(src, dir);
|
|
537
|
+
let names = [];
|
|
538
|
+
try { names = fs.readdirSync(d).filter((n) => /\.(?:m?js|py)$/.test(n)).sort(); } catch { /* absent */ }
|
|
539
|
+
for (const n of names) { h.update(`${dir}/${n}\0`); h.update(fs.readFileSync(path.join(d, n))); h.update('\n'); }
|
|
540
|
+
}
|
|
541
|
+
} else {
|
|
542
|
+
const self = fileURLToPath(import.meta.url);
|
|
543
|
+
h.update(path.basename(self)); h.update(fs.readFileSync(self));
|
|
544
|
+
}
|
|
545
|
+
} catch { h.update(`unreadable:${here}`); }
|
|
546
|
+
_analyzerMemo = h.digest('hex');
|
|
547
|
+
return _analyzerMemo;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
function readIf(p) { try { return fs.readFileSync(p, 'utf8'); } catch { return null; } }
|
|
551
|
+
|
|
552
|
+
const BUILD_FILE = /^(?:package\.json|package-lock\.json|yarn\.lock|pnpm-lock\.yaml|tsconfig[\w.-]*\.json|jsconfig\.json|pyproject\.toml|setup\.cfg|setup\.py|requirements[\w.-]*\.txt|pom\.xml|build\.gradle(?:\.kts)?|settings\.gradle(?:\.kts)?|go\.mod|go\.sum|Cargo\.toml|Cargo\.lock|composer\.json|Gemfile(?:\.lock)?|[\w.-]+\.csproj|[\w.-]+\.cabal|cabal\.project[\w.]*|stack\.yaml(?:\.lock)?|package\.yaml|hie\.yaml|flake\.(?:nix|lock)|default\.nix|shell\.nix|configuration\.nix|CMakeLists\.txt|Makefile)$/;
|
|
553
|
+
const STATE_POLICY = /^(?:rules|policy|policies|stubs?|boundar(?:y|ies)[\w-]*|sanitizers?[\w-]*|assurance)\.(?:ya?ml|json)$/;
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* The global inputs, one digest each, so a mismatch can say WHICH one moved.
|
|
557
|
+
* Every digest is over content.
|
|
558
|
+
*/
|
|
559
|
+
export function globalComponents({ scanRoot, fileContents, opts = {}, env = process.env, stubsProvider = null }) {
|
|
560
|
+
const comp = {};
|
|
561
|
+
// options: the semantically relevant environment plus engine options.
|
|
562
|
+
const envEntries = Object.keys(env).filter((k) => /^AGENTIC_SECURITY_/.test(k) && !VOLATILE_ENV.test(k)).sort().map((k) => [k, env[k]]);
|
|
563
|
+
comp.options = sha(stableSerialize({ env: envEntries, fnLimit: opts.fnLimit ?? null }));
|
|
564
|
+
// build / language configuration: manifests found at the root, in the scanned set, and explicit exports.
|
|
565
|
+
const build = {};
|
|
566
|
+
if (scanRoot) {
|
|
567
|
+
let names = [];
|
|
568
|
+
try { names = fs.readdirSync(scanRoot); } catch { names = []; }
|
|
569
|
+
for (const n of names) if (BUILD_FILE.test(n)) { const t = readIf(path.join(scanRoot, n)); if (t !== null) build[n] = sha(t); }
|
|
570
|
+
}
|
|
571
|
+
const manifestRels = [];
|
|
572
|
+
for (const k of Object.keys(fileContents || {})) {
|
|
573
|
+
const rel = k.replace(/\\/g, '/');
|
|
574
|
+
if (isLanguageManifest(rel) || isExplicitExport(rel) || BUILD_FILE.test(path.posix.basename(rel))) {
|
|
575
|
+
build[rel] = sha(String(fileContents[k] ?? ''));
|
|
576
|
+
if (isLanguageManifest(rel)) manifestRels.push(rel);
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
if (scanRoot) {
|
|
580
|
+
try {
|
|
581
|
+
const { contents } = readExplicitExports(scanRoot, manifestRels);
|
|
582
|
+
for (const [rel, text] of Object.entries(contents)) build[rel] = sha(text);
|
|
583
|
+
} catch { /* unreadable export: absent from the digest, which differs from present */ }
|
|
584
|
+
}
|
|
585
|
+
comp.build = sha(stableSerialize(build));
|
|
586
|
+
comp.graphSchema = sha(`${DEP_GRAPH_SCHEMA}/${MODEL_VERSION}`);
|
|
587
|
+
// rule / model content, not counts.
|
|
588
|
+
comp.catalog = sha(fastSerialize(CATALOG.filter((e) => e && e.kind !== 'sanitizer')) || 'unserialisable');
|
|
589
|
+
comp.sanitizers = sha(fastSerialize(CATALOG.filter((e) => e && e.kind === 'sanitizer')) || 'unserialisable');
|
|
590
|
+
comp.analyzers = analyzerDigest();
|
|
591
|
+
// stubs
|
|
592
|
+
let stubs = 'off';
|
|
593
|
+
if (env.AGENTIC_SECURITY_TYPE_STUBS === '1') {
|
|
594
|
+
try { stubs = sha(stableSerialize(stubsProvider ? stubsProvider(scanRoot) : null) || 'unserialisable'); } catch { stubs = 'unreadable'; }
|
|
595
|
+
}
|
|
596
|
+
comp.stubs = stubs;
|
|
597
|
+
// policies and boundary contracts under the state directory (operator-authored inputs).
|
|
598
|
+
const policy = {}; const boundary = {};
|
|
599
|
+
if (scanRoot) {
|
|
600
|
+
let names = [];
|
|
601
|
+
const stateRoot = stateDir(scanRoot);
|
|
602
|
+
try { names = fs.readdirSync(stateRoot); } catch { names = []; }
|
|
603
|
+
for (const n of names.sort()) {
|
|
604
|
+
if (!STATE_POLICY.test(n)) continue;
|
|
605
|
+
const t = readIf(path.join(stateRoot, n));
|
|
606
|
+
if (t === null) continue;
|
|
607
|
+
(/^boundar/.test(n) ? boundary : policy)[n] = sha(t);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
comp.policies = sha(stableSerialize(policy));
|
|
611
|
+
comp.boundary = sha(stableSerialize(boundary));
|
|
612
|
+
return comp;
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
function digestOfComponents(comp) {
|
|
616
|
+
return sha(stableSerialize(Object.fromEntries(Object.entries(comp).sort())));
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/** Names of the components that differ (both directions). */
|
|
620
|
+
export function diffComponents(prior, current) {
|
|
621
|
+
const names = new Set([...Object.keys(prior || {}), ...Object.keys(current || {})]);
|
|
622
|
+
return [...names].filter((n) => (prior || {})[n] !== (current || {})[n]).sort();
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
// ── the plan ────────────────────────────────────────────────────────────────
|
|
626
|
+
|
|
627
|
+
/**
|
|
628
|
+
* Compare a prior persisted model with the current one.
|
|
629
|
+
* `prior` is { global, deps (model), hasRecord(qid) }, `current` is { global, model }.
|
|
630
|
+
* Returns { mode, reason?, changedComponents?, clean:Set, dirty:Map(qid->reason), removed:[...], ... }.
|
|
631
|
+
*/
|
|
632
|
+
export function planIncremental(prior, current) {
|
|
633
|
+
const changedComponents = diffComponents(prior.global, current.global);
|
|
634
|
+
if (changedComponents.length) {
|
|
635
|
+
return { mode: 'cold', reason: `global input changed: ${changedComponents.join(', ')}`, changedComponents, clean: new Set(), dirty: new Map(), removed: [], renamed: [] };
|
|
636
|
+
}
|
|
637
|
+
const pf = prior.deps.functions || {};
|
|
638
|
+
const cf = current.model.functions;
|
|
639
|
+
const dirty = new Map();
|
|
640
|
+
const mark = (q, r) => { if (!dirty.has(q)) dirty.set(q, r); };
|
|
641
|
+
|
|
642
|
+
// direct changes
|
|
643
|
+
for (const [q, f] of Object.entries(cf)) {
|
|
644
|
+
const p = pf[q];
|
|
645
|
+
if (!p) mark(q, 'new');
|
|
646
|
+
else if (f.unfingerprintable || p.unfingerprintable) mark(q, 'unfingerprintable');
|
|
647
|
+
else if (p.own !== f.own) mark(q, 'changed-body-or-resolution');
|
|
648
|
+
}
|
|
649
|
+
// removals and renames: found through the PRIOR graph, the current IR has no trace of them
|
|
650
|
+
const removed = Object.keys(pf).filter((q) => !(q in cf)).sort();
|
|
651
|
+
const priorCallers = new Map();
|
|
652
|
+
for (const [q, p] of Object.entries(pf)) for (const c of p.callees || []) { if (!priorCallers.has(c)) priorCallers.set(c, []); priorCallers.get(c).push(q); }
|
|
653
|
+
const currentFileSet = new Set(Object.keys(current.model.fileSymbols));
|
|
654
|
+
const renamed = [];
|
|
655
|
+
for (const q of removed) {
|
|
656
|
+
const p = pf[q];
|
|
657
|
+
if (p && currentFileSet.has(p.file)) renamed.push({ qid: q, file: p.file, name: p.name }); // file still exists: moved, renamed or deleted inside it
|
|
658
|
+
for (const caller of priorCallers.get(q) || []) if (caller in cf) mark(caller, 'callee-removed-or-renamed');
|
|
659
|
+
}
|
|
660
|
+
// current callers (reverse of the current edges) for the closure
|
|
661
|
+
const currentCallers = new Map();
|
|
662
|
+
for (const [q, f] of Object.entries(cf)) for (const c of f.callees) { if (!currentCallers.has(c)) currentCallers.set(c, []); currentCallers.get(c).push(q); }
|
|
663
|
+
const seeds = [...dirty.keys()];
|
|
664
|
+
const stack = seeds.slice();
|
|
665
|
+
while (stack.length) {
|
|
666
|
+
const q = stack.pop();
|
|
667
|
+
for (const caller of currentCallers.get(q) || []) {
|
|
668
|
+
if (!dirty.has(caller)) { dirty.set(caller, 'depends-on-changed'); stack.push(caller); }
|
|
669
|
+
}
|
|
670
|
+
for (const caller of priorCallers.get(q) || []) {
|
|
671
|
+
if (caller in cf && !dirty.has(caller)) { dirty.set(caller, 'depends-on-changed'); stack.push(caller); }
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
// whole SCCs: current coupled components, and the prior component of anything dirty
|
|
675
|
+
const priorScc = new Map();
|
|
676
|
+
for (const [key, members] of Object.entries(prior.deps.sccs || {})) priorScc.set(key, members);
|
|
677
|
+
const curScc = current.model.sccs || {};
|
|
678
|
+
let widened = 0;
|
|
679
|
+
let again = true;
|
|
680
|
+
while (again) {
|
|
681
|
+
again = false;
|
|
682
|
+
for (const q of [...dirty.keys()]) {
|
|
683
|
+
const f = cf[q]; const p = pf[q];
|
|
684
|
+
const groups = [];
|
|
685
|
+
if (f && f.scc && curScc[f.scc]) groups.push(curScc[f.scc]);
|
|
686
|
+
if (p && p.scc && priorScc.has(p.scc)) groups.push(priorScc.get(p.scc));
|
|
687
|
+
for (const g of groups) for (const m of g) if (m in cf && !dirty.has(m)) { dirty.set(m, 'scc-member'); widened++; again = true; }
|
|
688
|
+
}
|
|
689
|
+
if (again) {
|
|
690
|
+
// newly dirty members have callers too
|
|
691
|
+
const st = [...dirty.keys()];
|
|
692
|
+
while (st.length) {
|
|
693
|
+
const q = st.pop();
|
|
694
|
+
for (const caller of currentCallers.get(q) || []) if (!dirty.has(caller)) { dirty.set(caller, 'depends-on-changed'); st.push(caller); }
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
// belt and braces: the closure fingerprint must agree with the explicit walk
|
|
699
|
+
for (const [q, f] of Object.entries(cf)) {
|
|
700
|
+
const p = pf[q];
|
|
701
|
+
if (p && !dirty.has(q) && p.closure !== f.closure) dirty.set(q, 'closure-fingerprint');
|
|
702
|
+
}
|
|
703
|
+
const clean = new Set();
|
|
704
|
+
for (const q of Object.keys(cf)) {
|
|
705
|
+
if (dirty.has(q)) continue;
|
|
706
|
+
if (!prior.hasRecord(q)) { dirty.set(q, 'no-cached-record'); continue; }
|
|
707
|
+
clean.add(q);
|
|
708
|
+
}
|
|
709
|
+
// files that held symbols last time and are gone (their symbols are in `removed`)
|
|
710
|
+
const removedFiles = Object.keys(prior.deps.fileSymbols || {}).filter((f) => !(f in current.model.fileSymbols)).sort();
|
|
711
|
+
return { mode: 'warm', clean, dirty, removed, removedFiles, renamed, widened, changedComponents: [] };
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
export function countByReason(dirty) {
|
|
715
|
+
const o = {};
|
|
716
|
+
for (const r of dirty.values()) o[r] = (o[r] || 0) + 1;
|
|
717
|
+
return Object.fromEntries(Object.entries(o).sort());
|
|
718
|
+
}
|