@seanhogg/builderforce-memory 2026.10.70 → 2026.10.72
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/dist/knowledge/build.d.ts +3 -1
- package/dist/knowledge/build.d.ts.map +1 -1
- package/dist/knowledge/build.js +5 -1
- package/dist/knowledge/build.js.map +1 -1
- package/dist/knowledge/coChange.d.ts +106 -0
- package/dist/knowledge/coChange.d.ts.map +1 -0
- package/dist/knowledge/coChange.js +309 -0
- package/dist/knowledge/coChange.js.map +1 -0
- package/dist/knowledge/communities.d.ts +2 -0
- package/dist/knowledge/communities.d.ts.map +1 -1
- package/dist/knowledge/communities.js +5 -1
- package/dist/knowledge/communities.js.map +1 -1
- package/dist/knowledge/extractFile.d.ts +10 -0
- package/dist/knowledge/extractFile.d.ts.map +1 -1
- package/dist/knowledge/extractFile.js +16 -5
- package/dist/knowledge/extractFile.js.map +1 -1
- package/dist/knowledge/extractJob.d.ts +18 -1
- package/dist/knowledge/extractJob.d.ts.map +1 -1
- package/dist/knowledge/extractJob.js +10 -4
- package/dist/knowledge/extractJob.js.map +1 -1
- package/dist/knowledge/facts/extractorVersion.d.ts +45 -0
- package/dist/knowledge/facts/extractorVersion.d.ts.map +1 -0
- package/dist/knowledge/facts/extractorVersion.js +56 -0
- package/dist/knowledge/facts/extractorVersion.js.map +1 -0
- package/dist/knowledge/facts/fileFacts.d.ts +166 -0
- package/dist/knowledge/facts/fileFacts.d.ts.map +1 -0
- package/dist/knowledge/facts/fileFacts.js +156 -0
- package/dist/knowledge/facts/fileFacts.js.map +1 -0
- package/dist/knowledge/findings.d.ts +17 -14
- package/dist/knowledge/findings.d.ts.map +1 -1
- package/dist/knowledge/findings.js +29 -129
- package/dist/knowledge/findings.js.map +1 -1
- package/dist/knowledge/index.d.ts +17 -1
- package/dist/knowledge/index.d.ts.map +1 -1
- package/dist/knowledge/index.js +10 -1
- package/dist/knowledge/index.js.map +1 -1
- package/dist/knowledge/model.d.ts +6 -0
- package/dist/knowledge/model.d.ts.map +1 -1
- package/dist/knowledge/outline.d.ts.map +1 -1
- package/dist/knowledge/outline.js +2 -0
- package/dist/knowledge/outline.js.map +1 -1
- package/dist/knowledge/owedFiles.d.ts +14 -4
- package/dist/knowledge/owedFiles.d.ts.map +1 -1
- package/dist/knowledge/owedFiles.js +30 -8
- package/dist/knowledge/owedFiles.js.map +1 -1
- package/dist/knowledge/plan.d.ts +10 -1
- package/dist/knowledge/plan.d.ts.map +1 -1
- package/dist/knowledge/plan.js +9 -4
- package/dist/knowledge/plan.js.map +1 -1
- package/dist/knowledge/refs.d.ts.map +1 -1
- package/dist/knowledge/refs.js +3 -1
- package/dist/knowledge/refs.js.map +1 -1
- package/dist/knowledge/review.js +1 -0
- package/dist/knowledge/review.js.map +1 -1
- package/dist/knowledge/reviewContext.d.ts.map +1 -1
- package/dist/knowledge/reviewContext.js +5 -2
- package/dist/knowledge/reviewContext.js.map +1 -1
- package/dist/knowledge/reviewFinish.d.ts.map +1 -1
- package/dist/knowledge/reviewFinish.js +3 -1
- package/dist/knowledge/reviewFinish.js.map +1 -1
- package/dist/knowledge/reviewModel.d.ts +12 -0
- package/dist/knowledge/reviewModel.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.d.ts +2 -0
- package/dist/knowledge/reviewPrefetch.d.ts.map +1 -1
- package/dist/knowledge/reviewPrefetch.js +1 -0
- package/dist/knowledge/reviewPrefetch.js.map +1 -1
- package/dist/knowledge/rules/cloneGroup.d.ts +10 -0
- package/dist/knowledge/rules/cloneGroup.d.ts.map +1 -0
- package/dist/knowledge/rules/cloneGroup.js +46 -0
- package/dist/knowledge/rules/cloneGroup.js.map +1 -0
- package/dist/knowledge/rules/components.d.ts +8 -0
- package/dist/knowledge/rules/components.d.ts.map +1 -0
- package/dist/knowledge/rules/components.js +34 -0
- package/dist/knowledge/rules/components.js.map +1 -0
- package/dist/knowledge/rules/cycle.d.ts +7 -0
- package/dist/knowledge/rules/cycle.d.ts.map +1 -0
- package/dist/knowledge/rules/cycle.js +18 -0
- package/dist/knowledge/rules/cycle.js.map +1 -0
- package/dist/knowledge/rules/duplicateCopy.d.ts +7 -0
- package/dist/knowledge/rules/duplicateCopy.d.ts.map +1 -0
- package/dist/knowledge/rules/duplicateCopy.js +18 -0
- package/dist/knowledge/rules/duplicateCopy.js.map +1 -0
- package/dist/knowledge/rules/evaluateRules.d.ts +60 -0
- package/dist/knowledge/rules/evaluateRules.d.ts.map +1 -0
- package/dist/knowledge/rules/evaluateRules.js +164 -0
- package/dist/knowledge/rules/evaluateRules.js.map +1 -0
- package/dist/knowledge/rules/factGraph.d.ts +51 -0
- package/dist/knowledge/rules/factGraph.d.ts.map +1 -0
- package/dist/knowledge/rules/factGraph.js +77 -0
- package/dist/knowledge/rules/factGraph.js.map +1 -0
- package/dist/knowledge/rules/factRule.d.ts +56 -0
- package/dist/knowledge/rules/factRule.d.ts.map +1 -0
- package/dist/knowledge/rules/factRule.js +46 -0
- package/dist/knowledge/rules/factRule.js.map +1 -0
- package/dist/knowledge/rules/godModule.d.ts +8 -0
- package/dist/knowledge/rules/godModule.d.ts.map +1 -0
- package/dist/knowledge/rules/godModule.js +16 -0
- package/dist/knowledge/rules/godModule.js.map +1 -0
- package/dist/knowledge/rules/knowledgeInput.d.ts +35 -0
- package/dist/knowledge/rules/knowledgeInput.d.ts.map +1 -0
- package/dist/knowledge/rules/knowledgeInput.js +33 -0
- package/dist/knowledge/rules/knowledgeInput.js.map +1 -0
- package/dist/knowledge/rules/nearDuplicate.d.ts +7 -0
- package/dist/knowledge/rules/nearDuplicate.d.ts.map +1 -0
- package/dist/knowledge/rules/nearDuplicate.js +20 -0
- package/dist/knowledge/rules/nearDuplicate.js.map +1 -0
- package/dist/knowledge/rules/partitionViolation.d.ts +10 -0
- package/dist/knowledge/rules/partitionViolation.d.ts.map +1 -0
- package/dist/knowledge/rules/partitionViolation.js +27 -0
- package/dist/knowledge/rules/partitionViolation.js.map +1 -0
- package/dist/knowledge/rules/possibleSame.d.ts +7 -0
- package/dist/knowledge/rules/possibleSame.d.ts.map +1 -0
- package/dist/knowledge/rules/possibleSame.js +15 -0
- package/dist/knowledge/rules/possibleSame.js.map +1 -0
- package/dist/knowledge/rules/stale.d.ts +7 -0
- package/dist/knowledge/rules/stale.d.ts.map +1 -0
- package/dist/knowledge/rules/stale.js +28 -0
- package/dist/knowledge/rules/stale.js.map +1 -0
- package/dist/knowledge/rules/unpartitioned.d.ts +7 -0
- package/dist/knowledge/rules/unpartitioned.d.ts.map +1 -0
- package/dist/knowledge/rules/unpartitioned.js +26 -0
- package/dist/knowledge/rules/unpartitioned.js.map +1 -0
- package/dist/knowledge/sources.d.ts +14 -1
- package/dist/knowledge/sources.d.ts.map +1 -1
- package/dist/knowledge/sources.js +17 -1
- package/dist/knowledge/sources.js.map +1 -1
- package/dist/knowledge/transitions.d.ts +59 -0
- package/dist/knowledge/transitions.d.ts.map +1 -0
- package/dist/knowledge/transitions.js +90 -0
- package/dist/knowledge/transitions.js.map +1 -0
- package/dist/retrieval/knowledge-index/sha256.d.ts.map +1 -1
- package/dist/retrieval/knowledge-index/sha256.js +2 -2
- package/dist/retrieval/knowledge-index/sha256.js.map +1 -1
- package/dist/stats/distributions.d.ts +40 -2
- package/dist/stats/distributions.d.ts.map +1 -1
- package/dist/stats/distributions.js +128 -20
- package/dist/stats/distributions.js.map +1 -1
- package/dist/stats/fitting.d.ts.map +1 -1
- package/dist/stats/fitting.js +1 -6
- package/dist/stats/fitting.js.map +1 -1
- package/dist/stats/index.d.ts +10 -3
- package/dist/stats/index.d.ts.map +1 -1
- package/dist/stats/index.js +10 -3
- package/dist/stats/index.js.map +1 -1
- package/dist/stats/logistic.d.ts +30 -0
- package/dist/stats/logistic.d.ts.map +1 -0
- package/dist/stats/logistic.js +43 -0
- package/dist/stats/logistic.js.map +1 -0
- package/dist/stats/multivariate.d.ts +8 -13
- package/dist/stats/multivariate.d.ts.map +1 -1
- package/dist/stats/multivariate.js +7 -53
- package/dist/stats/multivariate.js.map +1 -1
- package/dist/stats/policies.d.ts.map +1 -1
- package/dist/stats/policies.js +4 -22
- package/dist/stats/policies.js.map +1 -1
- package/package.json +4 -3
- package/src/contract/exports.snapshot.json +57 -1
- package/src/contract/regression.assets.test.ts +4 -0
- package/src/contract/regression.extractorKey.test.ts +202 -0
- package/src/contract/regression.statsEngineFree.test.ts +70 -0
- package/src/contract/regression.thompsonDeterminism.test.ts +23 -0
- package/src/contract/types.contract.test.ts +104 -1
- package/src/knowledge/build.ts +5 -1
- package/src/knowledge/coChange.test.ts +310 -0
- package/src/knowledge/coChange.ts +345 -0
- package/src/knowledge/communities.ts +6 -1
- package/src/knowledge/extractFile.ts +27 -5
- package/src/knowledge/extractJob.ts +24 -5
- package/src/knowledge/facts/extractorVersion.ts +73 -0
- package/src/knowledge/facts/fileFacts.test.ts +157 -0
- package/src/knowledge/facts/fileFacts.ts +305 -0
- package/src/knowledge/findings.ts +30 -127
- package/src/knowledge/index.ts +26 -0
- package/src/knowledge/model.ts +6 -0
- package/src/knowledge/outline.ts +2 -0
- package/src/knowledge/owedFiles.ts +36 -8
- package/src/knowledge/plan.ts +16 -4
- package/src/knowledge/refs.ts +4 -1
- package/src/knowledge/review.ts +1 -0
- package/src/knowledge/reviewContext.ts +5 -2
- package/src/knowledge/reviewFinish.ts +3 -1
- package/src/knowledge/reviewModel.ts +12 -0
- package/src/knowledge/reviewPrefetch.ts +3 -0
- package/src/knowledge/rules/cloneGroup.ts +45 -0
- package/src/knowledge/rules/components.ts +31 -0
- package/src/knowledge/rules/cycle.ts +20 -0
- package/src/knowledge/rules/duplicateCopy.ts +22 -0
- package/src/knowledge/rules/evaluateRules.test.ts +172 -0
- package/src/knowledge/rules/evaluateRules.ts +186 -0
- package/src/knowledge/rules/factGraph.oracle.test.ts +174 -0
- package/src/knowledge/rules/factGraph.ts +107 -0
- package/src/knowledge/rules/factRule.ts +74 -0
- package/src/knowledge/rules/godModule.ts +18 -0
- package/src/knowledge/rules/knowledgeInput.ts +60 -0
- package/src/knowledge/rules/knowledgeRules.test.ts +78 -0
- package/src/knowledge/rules/nearDuplicate.ts +22 -0
- package/src/knowledge/rules/partitionViolation.ts +31 -0
- package/src/knowledge/rules/possibleSame.ts +17 -0
- package/src/knowledge/rules/rules.testkit.test-util.ts +78 -0
- package/src/knowledge/rules/stale.ts +31 -0
- package/src/knowledge/rules/unpartitioned.ts +27 -0
- package/src/knowledge/sources.ts +19 -1
- package/src/knowledge/transitions.test.ts +135 -0
- package/src/knowledge/transitions.ts +115 -0
- package/src/retrieval/knowledge-index/sha256.test.ts +25 -0
- package/src/retrieval/knowledge-index/sha256.ts +2 -1
- package/src/stats/distributions.ts +132 -22
- package/src/stats/fitting.ts +1 -6
- package/src/stats/index.ts +15 -2
- package/src/stats/logistic.test.ts +89 -0
- package/src/stats/logistic.ts +49 -0
- package/src/stats/multivariate.ts +8 -59
- package/src/stats/policies.ts +4 -24
- package/src/stats/stats.test.ts +89 -0
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/coChange.ts — co-change association over git history (PRD 38 P4: impact prediction).
|
|
3
|
+
*
|
|
4
|
+
* For files A and B over the N kept commits:
|
|
5
|
+
* support = together(A, B) (commits touching both; kept when ≥ COCHANGE_MIN_SUPPORT)
|
|
6
|
+
* confidence = P(B|A) = together / ofSelf(A), with its credible interval (`rateInterval`, ../stats)
|
|
7
|
+
* lift = P(A∧B) / (P(A)P(B)) = together·N / (ofSelf(A)·ofSelf(B)) (kept when ≥ COCHANGE_MIN_LIFT)
|
|
8
|
+
*
|
|
9
|
+
* A commit touching more than COCHANGE_MAX_COMMIT_FILES files (its whole-repo `fileCount` when given, else its distinct
|
|
10
|
+
* refs) is a bulk change and is dropped before anything is counted (it is not in N either); so is a commit touching no
|
|
11
|
+
* ref. Of the rest, the newest COCHANGE_MAX_COMMITS are kept. Each file keeps at most COCHANGE_MAX_PARTNERS partners,
|
|
12
|
+
* ranked confidence desc, lift desc, ref asc.
|
|
13
|
+
*
|
|
14
|
+
* History order: by `Date.parse(at)` (stable) when every commit has a parseable `at`; otherwise the input order, which
|
|
15
|
+
* must then be oldest first.
|
|
16
|
+
*
|
|
17
|
+
* Determinism: refs are deduped per commit and numbered in sorted order; pair counts are integers keyed by index;
|
|
18
|
+
* thresholds compare integers. Same commits in any order ⇒ identical output (when dated, or under the commit cap).
|
|
19
|
+
*
|
|
20
|
+
* The badge `coChange` is a string written ONLY by {@link encodeCoChange} and read ONLY by {@link decodeCoChange}.
|
|
21
|
+
* The caller (it holds the git history) stamps it; `buildGraph` then stamps `coChangeHidden`
|
|
22
|
+
* ({@link applyCoChangeHidden}): the partners that no reference explains.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { rateInterval, type InsufficientData } from '../stats/index.js';
|
|
26
|
+
import { isReferenceEdge } from './communities.js';
|
|
27
|
+
import type { KEdge, KNode, NodeRef } from './model.js';
|
|
28
|
+
import { compareStr, fileRefOf, round6 } from './refs.js';
|
|
29
|
+
|
|
30
|
+
/** Commits a pair must share to be kept. */
|
|
31
|
+
export const COCHANGE_MIN_SUPPORT = 3;
|
|
32
|
+
/** Lift a pair must reach to be kept. */
|
|
33
|
+
export const COCHANGE_MIN_LIFT = 2;
|
|
34
|
+
/** A commit touching more files than this is a bulk change and is excluded. */
|
|
35
|
+
export const COCHANGE_MAX_COMMIT_FILES = 50;
|
|
36
|
+
/** Partners kept per file. */
|
|
37
|
+
export const COCHANGE_MAX_PARTNERS = 8;
|
|
38
|
+
/** At most this many (newest) commits are counted. */
|
|
39
|
+
export const COCHANGE_MAX_COMMITS = 5000;
|
|
40
|
+
/** The badge keys: the encoded partner list, and how many of them no reference explains. */
|
|
41
|
+
export const COCHANGE_BADGE = 'coChange';
|
|
42
|
+
export const COCHANGE_HIDDEN_BADGE = 'coChangeHidden';
|
|
43
|
+
/** First line of a badge value; a reader returns nothing for any other version. */
|
|
44
|
+
const BADGE_VERSION = 'v1';
|
|
45
|
+
|
|
46
|
+
export interface CoChangeCommit {
|
|
47
|
+
/** ISO time of the commit; orders the history. */
|
|
48
|
+
at?: string;
|
|
49
|
+
/** File node refs the commit touched (the caller maps paths to refs). */
|
|
50
|
+
refs: readonly NodeRef[];
|
|
51
|
+
/** Files the commit touched in the whole repo (refs only cover the root); the bulk cut uses the larger. */
|
|
52
|
+
fileCount?: number;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface CoChangePartner {
|
|
56
|
+
ref: NodeRef;
|
|
57
|
+
/** Kept commits touching both files. */
|
|
58
|
+
together: number;
|
|
59
|
+
/** Kept commits touching the file itself. */
|
|
60
|
+
ofSelf: number;
|
|
61
|
+
/** P(partner | self) = together / ofSelf, round6. */
|
|
62
|
+
confidence: number;
|
|
63
|
+
/** P(self ∧ partner) / (P(self) P(partner)), round6. */
|
|
64
|
+
lift: number;
|
|
65
|
+
/** Credible interval of the confidence (`rateInterval(together, ofSelf)`), round6. */
|
|
66
|
+
low: number;
|
|
67
|
+
high: number;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** What the `coChange` badge carries per partner. */
|
|
71
|
+
export interface CoChangeBadgeEntry {
|
|
72
|
+
ref: NodeRef;
|
|
73
|
+
together: number;
|
|
74
|
+
ofSelf: number;
|
|
75
|
+
low: number;
|
|
76
|
+
high: number;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface CoChangeOptions {
|
|
80
|
+
minSupport?: number;
|
|
81
|
+
minLift?: number;
|
|
82
|
+
maxCommitFiles?: number;
|
|
83
|
+
maxPartners?: number;
|
|
84
|
+
maxCommits?: number;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** `skipped`: held-out (commit, file) cases whose file had no partners to predict with. */
|
|
88
|
+
export type CoChangeRecall = { recall: number; cases: number; skipped: number } | InsufficientData;
|
|
89
|
+
|
|
90
|
+
type KeptCommit = { refs: NodeRef[] };
|
|
91
|
+
|
|
92
|
+
/** The history oldest first: by parsed `at` (stable) when every commit is dated, else as given. */
|
|
93
|
+
function chronological(commits: ReadonlyArray<CoChangeCommit>): CoChangeCommit[] {
|
|
94
|
+
const times = commits.map((c) => (c.at === undefined ? Number.NaN : Date.parse(c.at)));
|
|
95
|
+
if (!times.every(Number.isFinite)) return [...commits];
|
|
96
|
+
return commits.map((c, i) => ({ c, i, t: times[i]! })).sort((a, b) => a.t - b.t || a.i - b.i).map((x) => x.c);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Oldest first: each commit's distinct refs (sorted), bulk and empty commits dropped, the newest `maxCommits` kept. */
|
|
100
|
+
function historyOf(commits: ReadonlyArray<CoChangeCommit>, opts: CoChangeOptions): KeptCommit[] {
|
|
101
|
+
const maxFiles = opts.maxCommitFiles ?? COCHANGE_MAX_COMMIT_FILES;
|
|
102
|
+
const out: KeptCommit[] = [];
|
|
103
|
+
for (const c of chronological(commits)) {
|
|
104
|
+
const refs = [...new Set(c.refs)].sort(compareStr);
|
|
105
|
+
if (refs.length === 0 || Math.max(c.fileCount ?? 0, refs.length) > maxFiles) continue;
|
|
106
|
+
out.push({ refs });
|
|
107
|
+
}
|
|
108
|
+
const max = opts.maxCommits ?? COCHANGE_MAX_COMMITS;
|
|
109
|
+
return out.length > max ? out.slice(out.length - max) : out;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const imul = Math.imul;
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Counts (i, j) index pairs in an open-addressing table: one Int32Array of [i, j, count] slots (i = -1 is empty), so a probe
|
|
116
|
+
* touches one cache line and no pair allocates or boxes a key — where a `Map` spent most of the time on a 50-file commit's
|
|
117
|
+
* 1,225 pairs. Linear probing, grown at half load.
|
|
118
|
+
*/
|
|
119
|
+
class PairCounter {
|
|
120
|
+
private cap = 1 << 12;
|
|
121
|
+
private slots = PairCounter.empty(this.cap);
|
|
122
|
+
private size = 0;
|
|
123
|
+
|
|
124
|
+
add(i: number, j: number): void {
|
|
125
|
+
if ((this.size + 1) * 2 > this.cap) this.grow();
|
|
126
|
+
const mask = this.cap - 1;
|
|
127
|
+
const slots = this.slots;
|
|
128
|
+
for (let s = PairCounter.hash(i, j) & mask; ; s = (s + 1) & mask) {
|
|
129
|
+
const at = s * 3;
|
|
130
|
+
const si = slots[at]!;
|
|
131
|
+
if (si === -1) {
|
|
132
|
+
slots[at] = i; slots[at + 1] = j; slots[at + 2] = 1; this.size += 1;
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
if (si === i && slots[at + 1] === j) { slots[at + 2]! += 1; return; }
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
forEach(fn: (i: number, j: number, count: number) => void): void {
|
|
140
|
+
const slots = this.slots;
|
|
141
|
+
for (let at = 0; at < slots.length; at += 3) if (slots[at] !== -1) fn(slots[at]!, slots[at + 1]!, slots[at + 2]!);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
private grow(): void {
|
|
145
|
+
const old = this.slots;
|
|
146
|
+
this.cap *= 2;
|
|
147
|
+
this.slots = PairCounter.empty(this.cap);
|
|
148
|
+
const mask = this.cap - 1;
|
|
149
|
+
for (let from = 0; from < old.length; from += 3) {
|
|
150
|
+
if (old[from] === -1) continue;
|
|
151
|
+
let s = PairCounter.hash(old[from]!, old[from + 1]!) & mask;
|
|
152
|
+
while (this.slots[s * 3] !== -1) s = (s + 1) & mask;
|
|
153
|
+
this.slots.set(old.subarray(from, from + 3), s * 3);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
private static empty(cap: number): Int32Array {
|
|
158
|
+
const slots = new Int32Array(cap * 3);
|
|
159
|
+
for (let at = 0; at < slots.length; at += 3) slots[at] = -1;
|
|
160
|
+
return slots;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** murmur3's 32-bit finaliser over the two indexes. */
|
|
164
|
+
private static hash(i: number, j: number): number {
|
|
165
|
+
let h = imul(i, 0x9e3779b1) ^ j;
|
|
166
|
+
h ^= h >>> 16; h = imul(h, 0x85ebca6b);
|
|
167
|
+
h ^= h >>> 13; h = imul(h, 0xc2b2ae35);
|
|
168
|
+
return (h ^ (h >>> 16)) >>> 0;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const byRank = (a: Pick<CoChangePartner, 'confidence' | 'lift' | 'ref'>, b: Pick<CoChangePartner, 'confidence' | 'lift' | 'ref'>): number =>
|
|
173
|
+
b.confidence - a.confidence || b.lift - a.lift || compareStr(a.ref, b.ref);
|
|
174
|
+
|
|
175
|
+
/** Partners over an already-kept history. */
|
|
176
|
+
function partnersOf(kept: readonly KeptCommit[], opts: CoChangeOptions): Map<NodeRef, CoChangePartner[]> {
|
|
177
|
+
const minSupport = opts.minSupport ?? COCHANGE_MIN_SUPPORT;
|
|
178
|
+
const minLift = opts.minLift ?? COCHANGE_MIN_LIFT;
|
|
179
|
+
const maxPartners = opts.maxPartners ?? COCHANGE_MAX_PARTNERS;
|
|
180
|
+
const n = kept.length;
|
|
181
|
+
|
|
182
|
+
// Pass 1: ofSelf. A file seen in fewer than minSupport commits can be in no kept pair, so pass 2 skips it.
|
|
183
|
+
const order = [...new Set(kept.flatMap((c) => c.refs))].sort(compareStr);
|
|
184
|
+
const index = new Map(order.map((r, i) => [r, i] as const));
|
|
185
|
+
const m = order.length;
|
|
186
|
+
const ofSelf = new Array<number>(m).fill(0);
|
|
187
|
+
for (const c of kept) for (const r of c.refs) ofSelf[index.get(r)!]! += 1;
|
|
188
|
+
|
|
189
|
+
// Pass 2: pair counts over index pairs (i < j).
|
|
190
|
+
const pairs = new PairCounter();
|
|
191
|
+
for (const c of kept) {
|
|
192
|
+
const ids = c.refs.map((r) => index.get(r)!).filter((i) => ofSelf[i]! >= minSupport); // sorted refs ⇒ ascending ids
|
|
193
|
+
for (let x = 0; x < ids.length; x++) {
|
|
194
|
+
for (let y = x + 1; y < ids.length; y++) pairs.add(ids[x]!, ids[y]!);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// Candidates carry only counts and the ranking keys; the interval (an iterative inverse-beta solve) is computed after the
|
|
199
|
+
// cap, for at most maxPartners per file, and memoised by (together, ofSelf) for this call.
|
|
200
|
+
type Candidate = Omit<CoChangePartner, 'low' | 'high'>;
|
|
201
|
+
const lists = new Map<number, Candidate[]>();
|
|
202
|
+
const add = (self: number, other: number, together: number, lift: number) => {
|
|
203
|
+
const list = lists.get(self) ?? [];
|
|
204
|
+
list.push({ ref: order[other]!, together, ofSelf: ofSelf[self]!, confidence: round6(together / ofSelf[self]!), lift });
|
|
205
|
+
lists.set(self, list);
|
|
206
|
+
};
|
|
207
|
+
// Slot order is arbitrary; every list is fully sorted (ref breaks the last tie), so the output is not.
|
|
208
|
+
pairs.forEach((i, j, together) => {
|
|
209
|
+
if (together < minSupport) return;
|
|
210
|
+
// lift ≥ minLift ⇔ together·N ≥ minLift·ofSelf(i)·ofSelf(j): no float at the threshold.
|
|
211
|
+
if (together * n < minLift * ofSelf[i]! * ofSelf[j]!) return;
|
|
212
|
+
const lift = round6((together * n) / (ofSelf[i]! * ofSelf[j]!));
|
|
213
|
+
add(i, j, together, lift);
|
|
214
|
+
add(j, i, together, lift);
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
const intervals = new Map<number, { low: number; high: number }>();
|
|
218
|
+
const intervalOf = (k: number, total: number) => {
|
|
219
|
+
const key = k * (n + 1) + total; // k, total ≤ n
|
|
220
|
+
let hit = intervals.get(key);
|
|
221
|
+
if (!hit) {
|
|
222
|
+
const { low, high } = rateInterval(k, total);
|
|
223
|
+
hit = { low: round6(low), high: round6(high) };
|
|
224
|
+
intervals.set(key, hit);
|
|
225
|
+
}
|
|
226
|
+
return hit;
|
|
227
|
+
};
|
|
228
|
+
const out = new Map<NodeRef, CoChangePartner[]>();
|
|
229
|
+
for (const i of [...lists.keys()].sort((a, b) => a - b)) {
|
|
230
|
+
const top = lists.get(i)!.sort(byRank).slice(0, maxPartners);
|
|
231
|
+
out.set(order[i]!, top.map((c) => ({ ...c, ...intervalOf(c.together, c.ofSelf) })));
|
|
232
|
+
}
|
|
233
|
+
return out;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Every file's co-change partners (only files with at least one kept partner appear), keys in ref order. */
|
|
237
|
+
export function coChangePartners(commits: ReadonlyArray<CoChangeCommit>, opts: CoChangeOptions = {}): Map<NodeRef, CoChangePartner[]> {
|
|
238
|
+
return partnersOf(historyOf(commits, opts), opts);
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* The `coChange` badge value: the line `v1`, then `${together}\t${ofSelf}\t${low}\t${high}\t${ref}` per partner, '\n'-joined
|
|
243
|
+
* (the ref is the line remainder). An entry the decoder would reject is dropped, never written (one bad line would void the
|
|
244
|
+
* whole badge): a ref that is empty or holds a newline, `together` not an integer ≥ 1 or above `ofSelf`, and `low` / `high`
|
|
245
|
+
* that are not numbers in 0 ≤ low ≤ high ≤ 1. Each line is checked by the decoder's own {@link parseLine}.
|
|
246
|
+
*/
|
|
247
|
+
export function encodeCoChange(partners: readonly CoChangePartner[]): string {
|
|
248
|
+
const lines = partners
|
|
249
|
+
.filter((p) => !p.ref.includes('\n'))
|
|
250
|
+
.map((p) => `${p.together}\t${p.ofSelf}\t${p.low}\t${p.high}\t${p.ref}`)
|
|
251
|
+
.filter((line) => parseLine(line) !== undefined);
|
|
252
|
+
return [BADGE_VERSION, ...lines].join('\n');
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const NUM = String.raw`(\d+(?:\.\d+)?(?:e-\d+)?)`;
|
|
256
|
+
// `s`: the ref is the line remainder and may hold '\r', U+2028 or U+2029 (the value is already split on '\n').
|
|
257
|
+
const LINE = new RegExp(String.raw`^(\d+)\t(\d+)\t${NUM}\t${NUM}\t(.+)$`, 's');
|
|
258
|
+
|
|
259
|
+
/** THE validity of one partner line, shared by the encoder (to drop) and the decoder (to reject). */
|
|
260
|
+
function parseLine(line: string): CoChangeBadgeEntry | undefined {
|
|
261
|
+
const hit = LINE.exec(line);
|
|
262
|
+
if (!hit) return undefined;
|
|
263
|
+
const together = Number(hit[1]), ofSelf = Number(hit[2]), low = Number(hit[3]), high = Number(hit[4]);
|
|
264
|
+
if (!Number.isSafeInteger(together) || !Number.isSafeInteger(ofSelf) || together < 1 || together > ofSelf) return undefined;
|
|
265
|
+
if (!(low >= 0 && low <= high && high <= 1)) return undefined;
|
|
266
|
+
return { ref: hit[5]! as NodeRef, together, ofSelf, low, high };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** The partners of a `coChange` badge; [] for anything that is not a well-formed v1 value (one bad line voids it). */
|
|
270
|
+
export function decodeCoChange(value: unknown): CoChangeBadgeEntry[] {
|
|
271
|
+
if (typeof value !== 'string') return [];
|
|
272
|
+
const [version, ...lines] = value.split('\n');
|
|
273
|
+
if (version !== BADGE_VERSION) return [];
|
|
274
|
+
const out: CoChangeBadgeEntry[] = [];
|
|
275
|
+
for (const line of lines) {
|
|
276
|
+
const entry = parseLine(line);
|
|
277
|
+
if (!entry) return [];
|
|
278
|
+
out.push(entry);
|
|
279
|
+
}
|
|
280
|
+
return out;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* The PRD's accept measure: fit on the older (1 − heldOutShare) kept commits, then for each held-out commit and each file A
|
|
285
|
+
* in it that has partners, recall = |top-k partners ∩ (commit − A)| / |commit − A|; the mean over those cases. A held-out
|
|
286
|
+
* file with no partners is counted in `skipped`. Insufficient data when nothing can be held out or no case is predicted.
|
|
287
|
+
*/
|
|
288
|
+
export function coChangeRecallAtK(
|
|
289
|
+
commits: ReadonlyArray<CoChangeCommit>, k: number = COCHANGE_MAX_PARTNERS, heldOutShare = 0.2, opts: CoChangeOptions = {},
|
|
290
|
+
): CoChangeRecall {
|
|
291
|
+
const insufficient: InsufficientData = { status: 'insufficient-data' };
|
|
292
|
+
const kept = historyOf(commits, opts);
|
|
293
|
+
const held = Math.floor(kept.length * heldOutShare);
|
|
294
|
+
if (held < 1 || held >= kept.length || k < 1) return insufficient;
|
|
295
|
+
const model = partnersOf(kept.slice(0, kept.length - held), { ...opts, maxPartners: k });
|
|
296
|
+
let sum = 0, cases = 0, skipped = 0;
|
|
297
|
+
for (const c of kept.slice(kept.length - held)) {
|
|
298
|
+
if (c.refs.length < 2) continue;
|
|
299
|
+
for (const a of c.refs) {
|
|
300
|
+
const predicted = model.get(a);
|
|
301
|
+
if (!predicted || predicted.length === 0) { skipped += 1; continue; }
|
|
302
|
+
const others = new Set(c.refs.filter((r) => r !== a));
|
|
303
|
+
sum += predicted.filter((p) => others.has(p.ref)).length / others.size;
|
|
304
|
+
cases += 1;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
return cases === 0 ? insufficient : { recall: round6(sum / cases), cases, skipped };
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* The one call `buildGraph` makes: on every file node carrying a `coChange` badge, `coChangeHidden` = how many of its
|
|
312
|
+
* partners (that are nodes of the graph) share no reference with it — a live COMMUNITY_EDGE_KINDS edge in either direction,
|
|
313
|
+
* both ends rolled up to their file (a symbol or section ref counts for its file; an out-of-root placeholder explains too).
|
|
314
|
+
* Absent when 0, and removed from a file that no longer carries `coChange`.
|
|
315
|
+
*/
|
|
316
|
+
export function applyCoChangeHidden(nodes: Iterable<KNode>, edges: Iterable<KEdge>): void {
|
|
317
|
+
const all = new Map<NodeRef, KNode>();
|
|
318
|
+
for (const n of nodes) all.set(n.ref, n);
|
|
319
|
+
const explained = new Map<NodeRef, Set<NodeRef>>();
|
|
320
|
+
const link = (a: NodeRef, b: NodeRef) => {
|
|
321
|
+
const set = explained.get(a) ?? new Set<NodeRef>();
|
|
322
|
+
set.add(b);
|
|
323
|
+
explained.set(a, set);
|
|
324
|
+
};
|
|
325
|
+
for (const e of edges) {
|
|
326
|
+
if (!isReferenceEdge(e)) continue;
|
|
327
|
+
const a = fileRefOf(e.from), b = fileRefOf(e.to);
|
|
328
|
+
if (a === b) continue;
|
|
329
|
+
link(a, b);
|
|
330
|
+
link(b, a);
|
|
331
|
+
}
|
|
332
|
+
for (const n of all.values()) {
|
|
333
|
+
if (n.kind !== 'file' || !n.badges) continue;
|
|
334
|
+
const value = n.badges[COCHANGE_BADGE];
|
|
335
|
+
const near = explained.get(n.ref);
|
|
336
|
+
const hidden = value === undefined
|
|
337
|
+
? 0
|
|
338
|
+
: decodeCoChange(value).filter((p) => p.ref !== n.ref && all.has(p.ref) && !near?.has(p.ref)).length;
|
|
339
|
+
const badges = { ...n.badges };
|
|
340
|
+
if (hidden > 0) badges[COCHANGE_HIDDEN_BADGE] = hidden;
|
|
341
|
+
else delete badges[COCHANGE_HIDDEN_BADGE];
|
|
342
|
+
if (Object.keys(badges).length > 0) n.badges = badges;
|
|
343
|
+
else delete n.badges;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
@@ -77,6 +77,11 @@ export function detectCommunities(
|
|
|
77
77
|
return { members, modularity: modularityOf(adj, comm), method };
|
|
78
78
|
}
|
|
79
79
|
|
|
80
|
+
/** THE test of "this edge is a reference between files" (a live edge of COMMUNITY_EDGE_KINDS); coChange.ts reads it too. */
|
|
81
|
+
export function isReferenceEdge(e: Pick<KEdge, 'kind' | 'stale'>): boolean {
|
|
82
|
+
return COMMUNITY_EDGE_KINDS.includes(e.kind) && !e.stale;
|
|
83
|
+
}
|
|
84
|
+
|
|
80
85
|
/**
|
|
81
86
|
* File-to-file links of the chosen kinds, merged per ordered pair. The weights of a pair are summed in ascending
|
|
82
87
|
* order, so the total never depends on the order the edges arrive in (the sort across pairs is `buildAdjacency`'s).
|
|
@@ -84,7 +89,7 @@ export function detectCommunities(
|
|
|
84
89
|
function fileLinks(files: ReadonlySet<NodeRef>, edges: Iterable<KEdge>): Array<{ from: NodeRef; to: NodeRef; weight: number }> {
|
|
85
90
|
const pairs = new Map<string, { from: NodeRef; to: NodeRef; weights: number[] }>();
|
|
86
91
|
for (const e of edges) {
|
|
87
|
-
if (!
|
|
92
|
+
if (!isReferenceEdge(e)) continue;
|
|
88
93
|
const from = fileRefOf(e.from), to = fileRefOf(e.to);
|
|
89
94
|
if (!files.has(from) || !files.has(to)) continue;
|
|
90
95
|
const key = `${from}\u0000${to}`;
|
|
@@ -8,10 +8,13 @@
|
|
|
8
8
|
|
|
9
9
|
import type { ParsedSection, SourceDocument } from '../ingest/types.js';
|
|
10
10
|
import type { Extracted, KnowledgePack, KnowledgeParser, KnowledgeStore, NodeRef } from './model.js';
|
|
11
|
-
import { BinaryContent, CHANGED_SINCE_PLAN, ExtractFailed, jobOf, runExtractor, type ExtractPool } from './extractJob.js';
|
|
11
|
+
import { BinaryContent, CHANGED_SINCE_PLAN, EXTRACTOR_KEY_MISMATCH, ExtractFailed, jobOf, runExtractor, type ExtractPool } from './extractJob.js';
|
|
12
12
|
import { srcRef } from './refs.js';
|
|
13
13
|
import { entityName, knownKeysOf, resolveEntities } from './resolve.js';
|
|
14
|
-
import {
|
|
14
|
+
import {
|
|
15
|
+
asPathSource, composePacks, EXTRACTOR_VERSION, isAssetExtract, isCurrentExtractor, resolveRelativePath, sameExtractorKey, stubSource,
|
|
16
|
+
type ComposedPacks,
|
|
17
|
+
} from './sources.js';
|
|
15
18
|
|
|
16
19
|
/** The normalized entity keys of `ent:` fact keys, for `mentions`. */
|
|
17
20
|
export function knownKeysOfEntities(keys: Iterable<string>): ReadonlyMap<string, NodeRef> {
|
|
@@ -50,6 +53,16 @@ export interface ExtractFileArgs {
|
|
|
50
53
|
onTiming?: (t: { lookupMs: number; poolMs: number }) => void;
|
|
51
54
|
/** Leave the extract cache write to the caller (the review writes it in plan order); default: write it. */
|
|
52
55
|
writeCache?: boolean;
|
|
56
|
+
/**
|
|
57
|
+
* An input the extractors read besides the file's bytes (agent-tools: a digest of the tsconfig path aliases). A fresh
|
|
58
|
+
* extract is stamped with it, and a cached one made under another key (or none) is not reused. Absent or '': no key, as
|
|
59
|
+
* before keys existed.
|
|
60
|
+
*
|
|
61
|
+
* With a `pool`, the job carries it but the worker extracts with what IT holds and echoes its own key
|
|
62
|
+
* (`ExtractJobResult.extractorKey`); a different echo is neither cached nor used (the file stays owed). So a host pool MUST
|
|
63
|
+
* rebuild its key-dependent inputs (re-read the aliases) whenever the key it is asked for changes.
|
|
64
|
+
*/
|
|
65
|
+
extractorKey?: string;
|
|
53
66
|
}
|
|
54
67
|
|
|
55
68
|
export interface FileExtraction {
|
|
@@ -98,9 +111,10 @@ export async function extractFileDetailed(a: ExtractFileArgs): Promise<FileExtra
|
|
|
98
111
|
const tLookup = Date.now();
|
|
99
112
|
const cached = await a.store.getExtracted?.(a.hash);
|
|
100
113
|
const lookupMs = Date.now() - tLookup;
|
|
101
|
-
// A cached entry of another extractor version is ignored: its output may differ from today's. So is an asset's entry
|
|
114
|
+
// A cached entry of another extractor version or key is ignored: its output may differ from today's. So is an asset's entry
|
|
102
115
|
// (a document stored as an asset before a host parser claimed it): it holds no extraction.
|
|
103
|
-
const found = cached?.find((e) => e.sourceRef === ref &&
|
|
116
|
+
const found = cached?.find((e) => e.sourceRef === ref && !isAssetExtract(e)
|
|
117
|
+
&& isCurrentExtractor({ version: e.extractorVersion, key: e.extractorKey }, a.extractorKey));
|
|
104
118
|
if (found) {
|
|
105
119
|
const tSections = Date.now();
|
|
106
120
|
if (a.pool && wants) {
|
|
@@ -117,7 +131,10 @@ export async function extractFileDetailed(a: ExtractFileArgs): Promise<FileExtra
|
|
|
117
131
|
let extracted: Extracted;
|
|
118
132
|
if (a.pool) {
|
|
119
133
|
const tPool = Date.now();
|
|
120
|
-
const out = await a.pool(jobOf({
|
|
134
|
+
const out = await a.pool(jobOf({
|
|
135
|
+
rootId: a.rootId, path: a.path, hash: a.hash, knownKeys, needSections: wants, ...(a.readMs ? { readMs: a.readMs } : {}),
|
|
136
|
+
...(a.extractorKey ? { extractorKey: a.extractorKey } : {}), ...jobSource(a),
|
|
137
|
+
}), a.signal);
|
|
121
138
|
a.onTiming?.({ lookupMs, poolMs: Date.now() - tPool });
|
|
122
139
|
if (out.binary) throw new BinaryContent();
|
|
123
140
|
// Exact match only: a result for another file, or none although the packs accept this one, is a failure.
|
|
@@ -125,6 +142,8 @@ export async function extractFileDetailed(a: ExtractFileArgs): Promise<FileExtra
|
|
|
125
142
|
if (!mine) throw new Error(`extract pool returned no extract for ${a.path}`);
|
|
126
143
|
// The pool read other bytes than the plan hashed: nothing is stored under the planned hash.
|
|
127
144
|
if (mine.sourceHash !== a.hash) throw new Error(CHANGED_SINCE_PLAN); // transient: the bytes may settle
|
|
145
|
+
// The worker extracted under another key than asked (it still holds old aliases): neither cached nor used, the file stays owed.
|
|
146
|
+
if (a.extractorKey && !sameExtractorKey(out.extractorKey, a.extractorKey)) throw new Error(EXTRACTOR_KEY_MISMATCH);
|
|
128
147
|
if (wants) {
|
|
129
148
|
if (!out.sections) throw new Error(`extract pool returned no sections for ${a.path}`);
|
|
130
149
|
sections = out.sections;
|
|
@@ -133,6 +152,9 @@ export async function extractFileDetailed(a: ExtractFileArgs): Promise<FileExtra
|
|
|
133
152
|
} else {
|
|
134
153
|
extracted = proven(() => runExtractor(hit, src, sections, { rootId: a.rootId, knownKeys, resolvePath: resolveRelativePath }, a));
|
|
135
154
|
}
|
|
155
|
+
// The stamp is the key the extract was made under: the worker's echo (equal to the request, checked above) or, in this thread,
|
|
156
|
+
// the caller's. No key asked: nothing is stamped, as before keys existed.
|
|
157
|
+
if (a.extractorKey) extracted = { ...extracted, extractorKey: a.extractorKey };
|
|
136
158
|
if (a.writeCache !== false) await putExtract(a.store, a.hash, extracted, cached ?? []);
|
|
137
159
|
return { extracted, parser: hit.parser, pack: hit.pack, sections, cached: false };
|
|
138
160
|
}
|
|
@@ -28,6 +28,11 @@ export interface ExtractJobBase {
|
|
|
28
28
|
needSections?: boolean;
|
|
29
29
|
/** The extract is already cached and only the sections are wanted: skip extracting. Implies `needSections`. */
|
|
30
30
|
sectionsOnly?: boolean;
|
|
31
|
+
/**
|
|
32
|
+
* The extractor key the review extracts under (`ExtractFileArgs.extractorKey`). A worker does NOT adopt it: it extracts with
|
|
33
|
+
* the inputs it holds and echoes ITS key in {@link ExtractJobResult.extractorKey}; a mismatch is not cached (the file stays owed).
|
|
34
|
+
*/
|
|
35
|
+
extractorKey?: string;
|
|
31
36
|
}
|
|
32
37
|
|
|
33
38
|
/**
|
|
@@ -64,8 +69,18 @@ export interface ExtractJobResult {
|
|
|
64
69
|
binary?: true;
|
|
65
70
|
extracted: Extracted[];
|
|
66
71
|
sections?: ParsedSection[];
|
|
72
|
+
/**
|
|
73
|
+
* The extractor key the worker ACTUALLY extracted under (e.g. the digest of the path aliases it resolved with), absent when it
|
|
74
|
+
* has none. The review stamps the extract with this key, and when a key was asked for and this one differs (a long-lived worker
|
|
75
|
+
* still holding old aliases), the result is neither cached nor used: the file stays owed. A host pool must rebuild its
|
|
76
|
+
* key-dependent inputs (and so its key) when the requested key changes.
|
|
77
|
+
*/
|
|
78
|
+
extractorKey?: string;
|
|
67
79
|
}
|
|
68
80
|
|
|
81
|
+
/** The pool extracted under another extractor key than the review asked for: nothing is cached, the file stays owed. Transient. */
|
|
82
|
+
export const EXTRACTOR_KEY_MISMATCH = 'extractor key mismatch';
|
|
83
|
+
|
|
69
84
|
/**
|
|
70
85
|
* A host's extraction pool: called for a changed file whose extract is not cached (or, with
|
|
71
86
|
* `sectionsOnly`, whose sections are needed). `signal` is the review's: a stopped review should
|
|
@@ -94,12 +109,13 @@ export function runExtractor(
|
|
|
94
109
|
export function jobOf(
|
|
95
110
|
f: {
|
|
96
111
|
rootId: string; path: string; hash: string; knownKeys: ReadonlyMap<string, NodeRef>;
|
|
97
|
-
needSections?: boolean; sectionsOnly?: boolean; readMs?: number;
|
|
112
|
+
needSections?: boolean; sectionsOnly?: boolean; readMs?: number; extractorKey?: string;
|
|
98
113
|
} & ({ doc: SourceDocument; readByPool?: false } | { doc?: undefined; readByPool: true; /** The path the worker opens (the source's spelling); default `path`. */ readPath?: string }),
|
|
99
114
|
): ExtractJob {
|
|
100
115
|
return {
|
|
101
116
|
rootId: f.rootId, path: f.path, hash: f.hash, knownKeys: [...f.knownKeys],
|
|
102
117
|
...(f.needSections ? { needSections: true } : {}), ...(f.sectionsOnly ? { sectionsOnly: true } : {}),
|
|
118
|
+
...(f.extractorKey ? { extractorKey: f.extractorKey } : {}),
|
|
103
119
|
...(f.readByPool ? { readByPool: { path: f.readPath ?? f.path, hash: f.hash, ...(f.readMs ? { readMs: f.readMs } : {}) } } : { doc: f.doc! }),
|
|
104
120
|
} as ExtractJob;
|
|
105
121
|
}
|
|
@@ -107,17 +123,20 @@ export function jobOf(
|
|
|
107
123
|
/**
|
|
108
124
|
* Extracts one file from a job — pure: no store, no clock. `extracted` is `[]` when no pack's parser
|
|
109
125
|
* accepts the file. `packs` is the worker's own pack list (or its composition, to compose once).
|
|
126
|
+
* `workerKey` is the extractor key THESE packs were built under (absent: none); it is echoed as the result's `extractorKey`,
|
|
127
|
+
* never copied from the job, so a worker holding stale inputs is caught by the review rather than stamped with the new key.
|
|
110
128
|
*/
|
|
111
|
-
export function extractJob(job: ExtractJob, packs: readonly KnowledgePack[] | ComposedPacks): ExtractJobResult {
|
|
129
|
+
export function extractJob(job: ExtractJob, packs: readonly KnowledgePack[] | ComposedPacks, workerKey?: string): ExtractJobResult {
|
|
112
130
|
const composed = Array.isArray(packs) ? composePacks(packs as readonly KnowledgePack[]) : (packs as ComposedPacks);
|
|
113
131
|
// A pure job has no filesystem: a `readByPool` job is for a worker that reads (the host's handler), not for this function.
|
|
114
132
|
if (!job.doc) throw new Error(`extract job for ${job.path} carries no document (readByPool needs a reading worker)`);
|
|
133
|
+
const echo = workerKey ? { extractorKey: workerKey } : {};
|
|
115
134
|
const src = asPathSource(job.doc, job.path, job.hash);
|
|
116
135
|
const hit = composed.resolve(src);
|
|
117
|
-
if (!hit) return { extracted: [] };
|
|
136
|
+
if (!hit) return { extracted: [], ...echo };
|
|
118
137
|
const sections = hit.parser.parse(src);
|
|
119
138
|
const wantSections = job.needSections || job.sectionsOnly;
|
|
120
|
-
if (job.sectionsOnly) return { extracted: [], sections };
|
|
139
|
+
if (job.sectionsOnly) return { extracted: [], sections, ...echo };
|
|
121
140
|
const ctx: ExtractContext = { rootId: job.rootId, knownKeys: new Map(job.knownKeys), resolvePath: resolveRelativePath };
|
|
122
|
-
return { extracted: [runExtractor(hit, src, sections, ctx, job)], ...(wantSections ? { sections } : {}) };
|
|
141
|
+
return { extracted: [runExtractor(hit, src, sections, ctx, job)], ...(wantSections ? { sections } : {}), ...echo };
|
|
123
142
|
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/facts/extractorVersion.ts — the COMPOSITE extractor version of `FileFacts` (PRD 41 §B3).
|
|
3
|
+
*
|
|
4
|
+
* A fact set is identified by more than one number: the extractor code version, each tree-sitter
|
|
5
|
+
* grammar's package version, and the content-hash (EOL) rule. {@link factsExtractorTag} composes them into
|
|
6
|
+
* the `extractor` tag a `FileFacts` carries — per LANGUAGE, so a grammar bump changes the tag of (and so
|
|
7
|
+
* re-extracts) only the files of that language. {@link extractorStampMeta} gives the whole stamp as a
|
|
8
|
+
* `ComparabilityMeta` so `comparable()` (C9) reports a family, code, grammar or EOL change by reason.
|
|
9
|
+
*
|
|
10
|
+
* Separate from `EXTRACTOR_VERSION` (sources.ts), which versions the knowledge packs' `Extracted`
|
|
11
|
+
* nodes and edges; this one versions the fact contract the rules read.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { ComparabilityMeta } from '../comparability.js';
|
|
15
|
+
import { CONTENT_HASH_RULE, contentHashRuleOf } from '../contentHash.js';
|
|
16
|
+
import { compareStr } from '../refs.js';
|
|
17
|
+
|
|
18
|
+
/** The FileFacts contract version (v3: exports, calls, entry points, capability imports, test facts). Bump on a shape change. */
|
|
19
|
+
export const FACTS_EXTRACTOR_VERSION = 3;
|
|
20
|
+
|
|
21
|
+
/** Tree-sitter in Node hosts; the regex fallback in the Worker. The two never mix in one comparison (§B3, C9). */
|
|
22
|
+
export type ExtractorFamily = 'tree-sitter' | 'regex';
|
|
23
|
+
|
|
24
|
+
/** What a host's extractor is built from. */
|
|
25
|
+
export interface ExtractorStamp {
|
|
26
|
+
family: ExtractorFamily;
|
|
27
|
+
/** The host extractor's own revision within {@link FACTS_EXTRACTOR_VERSION} (queries changed, same shape). Default 0. */
|
|
28
|
+
revision?: number;
|
|
29
|
+
/** Language → grammar package version (`typescript` → `0.23.2`). A regex extractor has none. */
|
|
30
|
+
grammars?: Readonly<Record<string, string>>;
|
|
31
|
+
/** The content-hash rule the host hashes with. Default {@link CONTENT_HASH_RULE}. */
|
|
32
|
+
contentHashRule?: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const codeOf = (stamp: ExtractorStamp) => `${stamp.family}@${FACTS_EXTRACTOR_VERSION}.${stamp.revision ?? 0}`;
|
|
36
|
+
const ruleOf = (stamp: ExtractorStamp) => contentHashRuleOf(stamp.contentHashRule ?? CONTENT_HASH_RULE);
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The composite tag: `<family>@<version>.<revision>/<language>=<grammar>/<eol rule>` for one language (the grammar
|
|
40
|
+
* part omitted when that language has none), or with every grammar (`a=1,b=2`, sorted) when `language` is omitted.
|
|
41
|
+
* The family is the part before the first `@`, as `comparable()` reads it.
|
|
42
|
+
*/
|
|
43
|
+
export function factsExtractorTag(stamp: ExtractorStamp, language?: string): string {
|
|
44
|
+
const grammars = stamp.grammars ?? {};
|
|
45
|
+
const parts = [codeOf(stamp)];
|
|
46
|
+
if (language !== undefined) {
|
|
47
|
+
if (grammars[language] !== undefined) parts.push(`${language}=${grammars[language]}`);
|
|
48
|
+
} else {
|
|
49
|
+
const all = Object.keys(grammars).sort(compareStr).map((l) => `${l}=${grammars[l]}`);
|
|
50
|
+
if (all.length > 0) parts.push(all.join(','));
|
|
51
|
+
}
|
|
52
|
+
parts.push(ruleOf(stamp));
|
|
53
|
+
return parts.join('/');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Whether facts were produced by this stamp for their language: false ⇒ the file is owed a re-extraction. */
|
|
57
|
+
export function isFactsCurrent(facts: { factsVersion: number; extractor: string; language: string }, stamp: ExtractorStamp): boolean {
|
|
58
|
+
return facts.factsVersion === FACTS_EXTRACTOR_VERSION && facts.extractor === factsExtractorTag(stamp, facts.language);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The stamp as comparability meta: `extractor` = family@version.revision, the EOL rule, and each grammar as tool
|
|
63
|
+
* `grammar:<language>` — so `comparable()` names exactly which part moved.
|
|
64
|
+
*/
|
|
65
|
+
export function extractorStampMeta(stamp: ExtractorStamp): ComparabilityMeta {
|
|
66
|
+
const grammars = stamp.grammars ?? {};
|
|
67
|
+
return {
|
|
68
|
+
extractor: codeOf(stamp),
|
|
69
|
+
extractorVersion: FACTS_EXTRACTOR_VERSION,
|
|
70
|
+
contentHashRule: ruleOf(stamp),
|
|
71
|
+
tools: Object.fromEntries(Object.keys(grammars).sort(compareStr).map((l) => [`grammar:${l}`, grammars[l]!])),
|
|
72
|
+
};
|
|
73
|
+
}
|