@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
package/src/knowledge/index.ts
CHANGED
|
@@ -32,6 +32,13 @@ export {
|
|
|
32
32
|
COMMUNITY_MAX_PASSES, COMMUNITY_MAX_ITERATIONS, COMMUNITY_LP_ITERATIONS,
|
|
33
33
|
} from './communities.js';
|
|
34
34
|
export type { CommunityMembership, CommunityMethod, CommunityResult, NodePlacement } from './communities.js';
|
|
35
|
+
export {
|
|
36
|
+
coChangePartners, encodeCoChange, decodeCoChange, coChangeRecallAtK, applyCoChangeHidden, COCHANGE_MIN_SUPPORT, COCHANGE_MIN_LIFT,
|
|
37
|
+
COCHANGE_MAX_COMMIT_FILES, COCHANGE_MAX_PARTNERS, COCHANGE_MAX_COMMITS, COCHANGE_BADGE, COCHANGE_HIDDEN_BADGE,
|
|
38
|
+
} from './coChange.js';
|
|
39
|
+
export type { CoChangeBadgeEntry, CoChangeCommit, CoChangeOptions, CoChangePartner, CoChangeRecall } from './coChange.js';
|
|
40
|
+
export { transitionsFromWeights, transitionsFromSequences, stationTransitions, transitionOf, mostLikelyWalk } from './transitions.js';
|
|
41
|
+
export type { StationTransition, TransitionRow, TransitionSource, TransitionTable } from './transitions.js';
|
|
35
42
|
export { pageRank, byImportance, areaImportance, PAGERANK_DAMPING, PAGERANK_ITERATIONS } from './importance.js';
|
|
36
43
|
export {
|
|
37
44
|
loadPartitions, partitionOf, partitionOrder, verdictOf, globToRegExp, matchGlob, TOP_LEVEL_FOLDER,
|
|
@@ -42,7 +49,26 @@ export {
|
|
|
42
49
|
export type { LanedTrace, TraceOptions } from './trace.js';
|
|
43
50
|
export {
|
|
44
51
|
computeFindings, genericFindings, finding, findingId, partitionSeverity, requestKeyFor, components, CLONE_GROUP_BADGE, MAX_FINDING_NODES,
|
|
52
|
+
GENERIC_FINDING_RULES, KNOWLEDGE_FINDING_RULES,
|
|
45
53
|
} from './findings.js';
|
|
54
|
+
// PRD 41 §B1/§B3/§B5: FileFacts v3, the composite extractor version, FactRule + the incremental evaluator, the fact graph.
|
|
55
|
+
export {
|
|
56
|
+
FACT_KINDS, FACT_KIND_FIELDS, MATCHER_STRENGTH_ORDER, canonicalFileFacts, factKindHashes, factsHash, readFileFacts, isFileFactsV3, projectFileFacts,
|
|
57
|
+
} from './facts/fileFacts.js';
|
|
58
|
+
export type {
|
|
59
|
+
FactKind, FileFacts, SymbolFact, ImportFact, ExportFact, CallFact, ComplexityFact, EntryPointKind, EntryPointFact, CapabilityKind,
|
|
60
|
+
CapabilityImportFact, MatcherStrength, MatcherUse, TestModifier, TestCaseFact, TestFacts,
|
|
61
|
+
} from './facts/fileFacts.js';
|
|
62
|
+
export { FACTS_EXTRACTOR_VERSION, factsExtractorTag, isFactsCurrent, extractorStampMeta } from './facts/extractorVersion.js';
|
|
63
|
+
export type { ExtractorFamily, ExtractorStamp } from './facts/extractorVersion.js';
|
|
64
|
+
export { defineRule, DEFAULT_RULE_HOPS, MAX_RULE_HOPS } from './rules/factRule.js';
|
|
65
|
+
export type { FactRule, RuleInput, RuleScope } from './rules/factRule.js';
|
|
66
|
+
export { evaluateRules, importNeighbours, derivedRowKey } from './rules/evaluateRules.js';
|
|
67
|
+
export type { RuleWorld, DerivedRow, DerivedRows, RuleTraceEntry, RuleEvaluation } from './rules/evaluateRules.js';
|
|
68
|
+
export { emptyFactGraph, updateFactGraph, buildFactGraph, factGraphDump, FACT_GRAPH_DUMP_VERSION } from './rules/factGraph.js';
|
|
69
|
+
export type { FactGraph, FactManifestEntry, FactChange, FactGraphOptions, FactGraphUpdate } from './rules/factGraph.js';
|
|
70
|
+
export { knowledgeFacts, knowledgeInputHash, runKnowledgeRules, packOfRef, KNOWLEDGE_INPUT } from './rules/knowledgeInput.js';
|
|
71
|
+
export type { KnowledgeFacts, KnowledgeRuleExtra, KnowledgeRule } from './rules/knowledgeInput.js';
|
|
46
72
|
export { refAnchor, type FindingAnchor } from './findingBuilder.js';
|
|
47
73
|
export {
|
|
48
74
|
identityOf, defaultAnchorOf, composeAnchor, anchorWithSnippet, anchorKindOfRef, kindOfAnchor, normalizeSnippet, DEFAULT_RULE_VERSION,
|
package/src/knowledge/model.ts
CHANGED
|
@@ -92,6 +92,12 @@ export interface Extracted {
|
|
|
92
92
|
sourceHash: string;
|
|
93
93
|
/** The extractor version (`EXTRACTOR_VERSION`) that produced it; a cached entry of another version is ignored. */
|
|
94
94
|
extractorVersion?: number;
|
|
95
|
+
/**
|
|
96
|
+
* The caller's extractor key it was made under (`ExtractFileArgs.extractorKey`), absent when none was given. A cached entry
|
|
97
|
+
* made under another key, or with none when one is now given, is ignored (`isCurrentExtractor`). Not carried by the BFKP
|
|
98
|
+
* pack: an extract that went through a pack reads as keyless, so a keyed host re-extracts it once.
|
|
99
|
+
*/
|
|
100
|
+
extractorKey?: string;
|
|
95
101
|
nodes: KNode[];
|
|
96
102
|
edges: KEdge[];
|
|
97
103
|
/** Exact keys for entity resolution and the index's exact tier. */
|
package/src/knowledge/outline.ts
CHANGED
|
@@ -19,6 +19,8 @@ export const OUTLINE_BADGE_KEYS: readonly string[] = [
|
|
|
19
19
|
'complexity', 'maxComplexity', 'coverage', 'churn', 'owner', 'patterns', 'cloneGroup', 'unused', 'unusedExports',
|
|
20
20
|
'entry', 'layerRule', 'unusedDependencies', 'externals', 'added', 'removed', 'changed', 'status',
|
|
21
21
|
'communityId', 'communityConfidence',
|
|
22
|
+
// PRD 38 P4 (coChange.ts): the encoded co-change partners (read with decodeCoChange) and how many no reference explains.
|
|
23
|
+
'coChange', 'coChangeHidden',
|
|
22
24
|
// An asset file (assetFile.ts): a binary file the review stores as a node, never read.
|
|
23
25
|
'asset', 'mediaType', 'size', 'oversized',
|
|
24
26
|
];
|
|
@@ -13,6 +13,8 @@
|
|
|
13
13
|
*
|
|
14
14
|
* Stored under {@link extractorManifestKey} as fingerprints: `{ id: 'version', hash: '<version>' }`
|
|
15
15
|
* plus `{ id: 'documents', hash: '<pdf,docx|->' }` (the document types the packs claimed, see {@link withDocuments}),
|
|
16
|
+
* `{ id: 'extractorKey', hash: '<key>' }` when the run had a caller-supplied extractor key (another key, or none recorded while one is
|
|
17
|
+
* given, owes every file like a version change; see `isCurrentExtractor`),
|
|
16
18
|
* `{ id: 'contentHash', hash: '<rule>' }` once {@link CONTENT_HASH_RULE} moves past {@link BASELINE_CONTENT_HASH_RULE} (no record reads as the baseline; another rule is an upgrade),
|
|
17
19
|
* and one `{ id: 'owed:<path>', hash: '<calls>' }` per owed file, where `<calls>` is the
|
|
18
20
|
* decimal number of model calls the file is still expected to cost (the plan's estimate):
|
|
@@ -30,11 +32,12 @@
|
|
|
30
32
|
import type { IngestManifest } from '../ingest/types.js';
|
|
31
33
|
import { BASELINE_CONTENT_HASH_RULE, CONTENT_HASH_RULE, contentHashRuleOf } from './contentHash.js';
|
|
32
34
|
import { compareStr } from './refs.js';
|
|
33
|
-
import { EXTRACTOR_VERSION, extOf, extractorManifestKey, isBinaryPath, isDocumentPath } from './sources.js';
|
|
35
|
+
import { EXTRACTOR_VERSION, extOf, extractorManifestKey, isBinaryPath, isCurrentExtractor, isDocumentPath } from './sources.js';
|
|
34
36
|
|
|
35
37
|
const VERSION_ID = 'version';
|
|
36
38
|
const DOCUMENTS_ID = 'documents';
|
|
37
39
|
const CONTENT_HASH_ID = 'contentHash';
|
|
40
|
+
const EXTRACTOR_KEY_ID = 'extractorKey';
|
|
38
41
|
/** No document type claimed — also what an entry with no `documents` record means, so a root that never had a host parser stores nothing extra. */
|
|
39
42
|
const NO_DOCUMENTS = '-';
|
|
40
43
|
const OWED_PREFIX = 'owed:';
|
|
@@ -47,6 +50,10 @@ export interface ExtractorState {
|
|
|
47
50
|
version: number | undefined;
|
|
48
51
|
/** The content-hash rule (contentHash.ts) the files were hashed under, when the entry records one; absent for `eol-lf@1` and for every entry written before the rule existed. */
|
|
49
52
|
contentHashRule?: string;
|
|
53
|
+
/** The caller's extractor key the files were last reviewed under (`ReviewArgs.extractorKey`); absent when none was given. */
|
|
54
|
+
extractorKey?: string;
|
|
55
|
+
/** The key this run extracts under: set by the plan, carried to *Continue*, saved by the run. Another key than `extractorKey` owes every file. */
|
|
56
|
+
extractorKeyNow?: string;
|
|
50
57
|
/** Paths a previous run left unfinished under that version → model calls each still costs. */
|
|
51
58
|
owed: ReadonlyMap<string, number>;
|
|
52
59
|
/** Consecutive transient failures of a path at one content hash (stored beside its owed entry); a success or a new hash resets it. Optional: a caller that builds a state by hand need not know it. */
|
|
@@ -88,6 +95,7 @@ export async function loadExtractorState(manifest: IngestManifest, rootId: strin
|
|
|
88
95
|
let version: number | undefined;
|
|
89
96
|
let documents: string | undefined;
|
|
90
97
|
let contentHashRule: string | undefined;
|
|
98
|
+
let extractorKey: string | undefined;
|
|
91
99
|
const owed = new Map<string, number>();
|
|
92
100
|
const failures = new Map<string, { hash: string; count: number }>();
|
|
93
101
|
for (const { id, hash } of (await manifest.get(extractorManifestKey(rootId))) ?? []) {
|
|
@@ -98,6 +106,8 @@ export async function loadExtractorState(manifest: IngestManifest, rootId: strin
|
|
|
98
106
|
documents = hash;
|
|
99
107
|
} else if (id === CONTENT_HASH_ID) {
|
|
100
108
|
contentHashRule = hash;
|
|
109
|
+
} else if (id === EXTRACTOR_KEY_ID) {
|
|
110
|
+
extractorKey = hash;
|
|
101
111
|
} else if (id.startsWith(FAIL_PREFIX)) {
|
|
102
112
|
const at = hash.indexOf(':');
|
|
103
113
|
const count = Number(hash.slice(0, at));
|
|
@@ -107,7 +117,15 @@ export async function loadExtractorState(manifest: IngestManifest, rootId: strin
|
|
|
107
117
|
owed.set(id.slice(OWED_PREFIX.length), Number.isFinite(calls) && calls >= 0 ? calls : UPGRADE_CALLS);
|
|
108
118
|
}
|
|
109
119
|
}
|
|
110
|
-
return {
|
|
120
|
+
return {
|
|
121
|
+
version, owed, failures, documents: documents ?? NO_DOCUMENTS,
|
|
122
|
+
...(contentHashRule !== undefined ? { contentHashRule } : {}), ...(extractorKey !== undefined ? { extractorKey } : {}),
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** The state with the key this run extracts under (absent or empty: none, as before keys existed). */
|
|
127
|
+
export function withExtractorKey(state: ExtractorState, keyNow: string | undefined): ExtractorState {
|
|
128
|
+
return keyNow ? { ...state, extractorKeyNow: keyNow } : state;
|
|
111
129
|
}
|
|
112
130
|
|
|
113
131
|
/**
|
|
@@ -116,9 +134,16 @@ export async function loadExtractorState(manifest: IngestManifest, rootId: strin
|
|
|
116
134
|
* nothing by itself — a host switching to `contentHash` moves the hash of every CRLF file, and those re-extract by content
|
|
117
135
|
* (`contentChanged`, an extract-cache miss). The entry writes no record for the baseline; a later rule writes one.
|
|
118
136
|
*/
|
|
119
|
-
const
|
|
137
|
+
const versionUpgradePending = (state: ExtractorState): boolean =>
|
|
120
138
|
state.version !== EXTRACTOR_VERSION || contentHashRuleOf(state.contentHashRule) !== CONTENT_HASH_RULE;
|
|
121
139
|
|
|
140
|
+
/**
|
|
141
|
+
* True while the files were last reviewed under another extractor version, content-hash rule or caller extractor key
|
|
142
|
+
* ({@link isCurrentExtractor}): every file owes one re-extraction.
|
|
143
|
+
*/
|
|
144
|
+
const upgradePending = (state: ExtractorState): boolean =>
|
|
145
|
+
!isCurrentExtractor({ version: state.version, key: state.extractorKey }, state.extractorKeyNow) || versionUpgradePending(state);
|
|
146
|
+
|
|
122
147
|
/** The file's document extension when its asset-ness flipped (a host parser arrived or left since the last run). */
|
|
123
148
|
const isFlipped = (state: ExtractorState, path: string): boolean => !!state.flipped?.size && state.flipped.has(extOf(path));
|
|
124
149
|
|
|
@@ -136,11 +161,13 @@ const isAssetNow = (state: ExtractorState, path: string): boolean => {
|
|
|
136
161
|
};
|
|
137
162
|
|
|
138
163
|
/**
|
|
139
|
-
* Model calls an owed `path` is expected to cost: its recorded count, plus one while
|
|
140
|
-
*
|
|
164
|
+
* Model calls an owed `path` is expected to cost: its recorded count, plus one while a version (or content-hash rule) upgrade is
|
|
165
|
+
* pending or its asset-ness flipped. A change of the caller's extractor key alone adds nothing: the files re-extract, but their
|
|
166
|
+
* sections' text is the same, so the judgements are re-anchored, not made again. An asset costs none (it is never read or judged);
|
|
167
|
+
* a file that flipped TO a document does.
|
|
141
168
|
*/
|
|
142
169
|
export const owedCalls = (state: ExtractorState, path: string): number =>
|
|
143
|
-
isAssetNow(state, path) ? 0 : (
|
|
170
|
+
isAssetNow(state, path) ? 0 : (versionUpgradePending(state) || isFlipped(state, path) ? UPGRADE_CALLS : 0) + (state.owed.get(path) ?? 0);
|
|
144
171
|
|
|
145
172
|
/**
|
|
146
173
|
* Paths in the files manifest that the plan does not list yet are owed: ignored, claimed by
|
|
@@ -179,14 +206,15 @@ export function owedAfterRun(a: {
|
|
|
179
206
|
return out;
|
|
180
207
|
}
|
|
181
208
|
|
|
182
|
-
/** Records today's version and exactly the files still owed after this run. */
|
|
209
|
+
/** Records today's version (and extractor key, when the run had one) and exactly the files still owed after this run. */
|
|
183
210
|
export async function saveExtractorState(
|
|
184
211
|
manifest: IngestManifest, rootId: string, owed: ReadonlyMap<string, number>, failures: ReadonlyMap<string, { hash: string; count: number }> = new Map(),
|
|
185
|
-
documents?: string,
|
|
212
|
+
documents?: string, extractorKey?: string,
|
|
186
213
|
): Promise<void> {
|
|
187
214
|
await manifest.set(extractorManifestKey(rootId), [
|
|
188
215
|
{ id: VERSION_ID, hash: String(EXTRACTOR_VERSION) },
|
|
189
216
|
...(CONTENT_HASH_RULE !== BASELINE_CONTENT_HASH_RULE ? [{ id: CONTENT_HASH_ID, hash: CONTENT_HASH_RULE }] : []),
|
|
217
|
+
...(extractorKey ? [{ id: EXTRACTOR_KEY_ID, hash: extractorKey }] : []),
|
|
190
218
|
...(documents !== undefined && documents !== NO_DOCUMENTS ? [{ id: DOCUMENTS_ID, hash: documents }] : []),
|
|
191
219
|
...[...owed].sort((a, b) => compareStr(a[0], b[0])).map(([path, calls]) => ({ id: `${OWED_PREFIX}${path}`, hash: String(calls) })),
|
|
192
220
|
...[...failures].filter(([path]) => owed.has(path)).sort((a, b) => compareStr(a[0], b[0])).map(([path, f]) => ({ id: `${FAIL_PREFIX}${path}`, hash: `${f.count}:${f.hash}` })),
|
package/src/knowledge/plan.ts
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
import type { IngestManifest } from '../ingest/types.js';
|
|
13
13
|
import type { DirectorySource, KnowledgePack, ReviewPlan } from './model.js';
|
|
14
14
|
import { canonicalListing, merkleTree, type MerkleTree } from './merkle.js';
|
|
15
|
-
import { carriedOwed, type ExtractorState, isOwed, loadExtractorState, owedCalls, withDocuments } from './owedFiles.js';
|
|
15
|
+
import { carriedOwed, type ExtractorState, isOwed, loadExtractorState, owedCalls, withDocuments, withExtractorKey } from './owedFiles.js';
|
|
16
16
|
import {
|
|
17
17
|
claimedDocumentExts, compareManifestKey, composePacks, DEFAULT_MAX_FILE_BYTES, filesManifestKey, ignoreMatcher, ignoreSourcesOf,
|
|
18
18
|
isAssetPath, isDocumentPath, manifestMap, resolveDocument, stubSource,
|
|
@@ -44,6 +44,13 @@ export interface PlanOptions {
|
|
|
44
44
|
* estimate of the plan it continues; it is not recomputed.)
|
|
45
45
|
*/
|
|
46
46
|
compare?: boolean;
|
|
47
|
+
/**
|
|
48
|
+
* An input the host's extractors read besides the file bytes (agent-tools: a digest of the tsconfig path aliases). When it
|
|
49
|
+
* differs from the key the root was last reviewed under (or one is given where none was recorded), every file is owed a
|
|
50
|
+
* re-extraction, its content unchanged or not — at no estimated model calls (the judgements are re-anchored). Absent or '':
|
|
51
|
+
* no key, as before keys existed.
|
|
52
|
+
*/
|
|
53
|
+
extractorKey?: string;
|
|
47
54
|
}
|
|
48
55
|
|
|
49
56
|
export interface PlannedFile {
|
|
@@ -133,7 +140,10 @@ export async function planDetail(
|
|
|
133
140
|
// A file's asset-ness depends on the packs (a pdf is an asset until a host parser claims it): a change in the document types the
|
|
134
141
|
// packs claim since the last run owes the files of those types a re-processing, whatever their hash (see withDocuments).
|
|
135
142
|
const oversized = new Set<string>();
|
|
136
|
-
const extractor: ExtractorState = {
|
|
143
|
+
const extractor: ExtractorState = {
|
|
144
|
+
...withExtractorKey(withDocuments(await loadExtractorState(manifest, source.rootId), claimedDocumentExts(composed)), opts.extractorKey),
|
|
145
|
+
oversized,
|
|
146
|
+
};
|
|
137
147
|
const packById = new Map(packs.map((p) => [p.id, p] as const));
|
|
138
148
|
|
|
139
149
|
const files: PlannedFile[] = [];
|
|
@@ -212,11 +222,13 @@ export async function planDetail(
|
|
|
212
222
|
* *Continue*: the confirmed plan without a re-walk. Only `changed` is re-read — against the
|
|
213
223
|
* manifest and owed list as the last run left them — so files finished since are not reviewed
|
|
214
224
|
* again, and files it left owed (an upgrade cut short, a failed read) are picked up.
|
|
225
|
+
* `extractorKey` is the key this run extracts under (`PlanOptions.extractorKey`; `''` = no key). A host must pass a FRESHLY
|
|
226
|
+
* computed key: the default, the plan's, is stale when the extractor inputs changed since the plan was made.
|
|
215
227
|
*/
|
|
216
|
-
export async function refreshPlan(detail: PlanDetail, manifest: IngestManifest): Promise<PlanDetail> {
|
|
228
|
+
export async function refreshPlan(detail: PlanDetail, manifest: IngestManifest, extractorKey = detail.extractor.extractorKeyNow): Promise<PlanDetail> {
|
|
217
229
|
const prior = await manifestMap(manifest, filesManifestKey(detail.plan.rootId));
|
|
218
230
|
const extractor: ExtractorState = {
|
|
219
|
-
...withDocuments(await loadExtractorState(manifest, detail.plan.rootId), detail.extractor.documentsNow),
|
|
231
|
+
...withExtractorKey(withDocuments(await loadExtractorState(manifest, detail.plan.rootId), detail.extractor.documentsNow), extractorKey),
|
|
220
232
|
...(detail.extractor.oversized ? { oversized: detail.extractor.oversized } : {}),
|
|
221
233
|
};
|
|
222
234
|
const files = detail.files.map((f) => {
|
package/src/knowledge/refs.ts
CHANGED
|
@@ -106,9 +106,12 @@ export function basenameOf(path: string): string {
|
|
|
106
106
|
return i < 0 ? path : path.slice(i + 1);
|
|
107
107
|
}
|
|
108
108
|
|
|
109
|
+
/** Bound once: a bare `Math.round` is a global lookup per call, ~1 µs inside a vm context (jest) on hot paths. */
|
|
110
|
+
const mathRound = Math.round;
|
|
111
|
+
|
|
109
112
|
/** Rounds to 6 decimals so floating noise never reaches the JSON. */
|
|
110
113
|
export function round6(n: number): number {
|
|
111
|
-
return
|
|
114
|
+
return mathRound(n * 1e6) / 1e6;
|
|
112
115
|
}
|
|
113
116
|
|
|
114
117
|
/** JSON with object keys sorted and `undefined` members dropped — the canonical form for digests. */
|
package/src/knowledge/review.ts
CHANGED
|
@@ -115,6 +115,7 @@ async function applyChangedFiles(c: ReviewContext): Promise<AbortSignal> {
|
|
|
115
115
|
const prefetch = createPrefetch({
|
|
116
116
|
args, signal: runSignal, rootId: c.rootId, packs: args.packs, store: args.store, composed: c.composed, knownKeys: c.knownKeys,
|
|
117
117
|
width: readAhead, extractWidth: concurrency,
|
|
118
|
+
...(c.detail.extractor.extractorKeyNow ? { extractorKey: c.detail.extractor.extractorKeyNow } : {}),
|
|
118
119
|
});
|
|
119
120
|
const dispatch = {
|
|
120
121
|
// A mechanical run (pass 1) makes no model call: judged files stay owed.
|
|
@@ -78,8 +78,11 @@ export async function openReview(args: ReviewArgs): Promise<ReviewContext> {
|
|
|
78
78
|
const progress = (p: ReviewProgressEvent) => args.onProgress?.(p);
|
|
79
79
|
|
|
80
80
|
const detail = args.plan
|
|
81
|
-
? await refreshPlan(args.plan, manifest)
|
|
82
|
-
: await planDetail(source, manifest, packs, {
|
|
81
|
+
? await refreshPlan(args.plan, manifest, args.extractorKey ?? args.plan.extractor.extractorKeyNow)
|
|
82
|
+
: await planDetail(source, manifest, packs, {
|
|
83
|
+
...(args.force ? { force: true } : {}), compare: !!args.similar && !!args.judgement,
|
|
84
|
+
...(args.extractorKey ? { extractorKey: args.extractorKey } : {}),
|
|
85
|
+
});
|
|
83
86
|
progress({ phase: 'plan', done: detail.files.length, total: detail.files.length });
|
|
84
87
|
const packIds = packs.map((p) => p.id).sort(compareStr);
|
|
85
88
|
const [storedFacts, storedRelations] = await Promise.all([store.facts(scope), store.relations(scope)]);
|
|
@@ -55,7 +55,9 @@ export async function finishReview(c: ReviewContext, flush: () => Promise<void>)
|
|
|
55
55
|
await saveExtractorState(manifest, c.rootId, owedAfterRun({
|
|
56
56
|
state: c.detail.extractor, changed: c.changed, prior: c.detail.prior, finished: c.finished, carried: c.detail.carried,
|
|
57
57
|
live: c.filesNow, measured: c.measured, unreadable: c.unreadable,
|
|
58
|
-
}), c.failures, c.detail.extractor.documentsNow
|
|
58
|
+
}), c.failures, c.detail.extractor.documentsNow,
|
|
59
|
+
// An aborted run keeps the key the root was last reviewed under: every file stays owed until a run under the new key finishes.
|
|
60
|
+
report.aborted ? c.detail.extractor.extractorKey : c.detail.extractor.extractorKeyNow);
|
|
59
61
|
await writeBatch(c, report.aborted ? c.scopeRecord : { ...c.scopeRecord, lastDigest: report.digest, lastReviewedAt: new Date(c.now()).toISOString() });
|
|
60
62
|
report.durationMs = c.now() - c.started;
|
|
61
63
|
c.progress({ phase: 'done', done: c.work.length, total: c.work.length });
|
|
@@ -124,6 +124,18 @@ export interface ReviewArgs {
|
|
|
124
124
|
plan?: PlanDetail;
|
|
125
125
|
/** *Re-review all*: every file is reviewed whatever its hash (see `PlanOptions.force`). Ignored with `plan`. */
|
|
126
126
|
force?: boolean;
|
|
127
|
+
/**
|
|
128
|
+
* An input the host's extractors read besides the file bytes (agent-tools: a digest of the tsconfig path aliases); see
|
|
129
|
+
* `PlanOptions.extractorKey`. A changed key owes every file and bypasses extracts cached under another key.
|
|
130
|
+
* - Pass a FRESHLY computed key on every run, *Continue* included: with `plan`, an absent key falls back to the plan's,
|
|
131
|
+
* which is stale if the inputs changed since the plan (new-alias extracts would be stamped with the old key).
|
|
132
|
+
* - `''` is an explicit "no key" (also with `plan`); absent without `plan` is no key too — as before keys existed.
|
|
133
|
+
* - With `extractPool`, the pool must rebuild its key-dependent inputs when the key changes: a worker echoing another key
|
|
134
|
+
* (`ExtractJobResult.extractorKey`) has its result dropped and the file stays owed.
|
|
135
|
+
* - An aborted run does not record the new key: the next run owes every file again (cheap — the extracts made under the
|
|
136
|
+
* new key are reused).
|
|
137
|
+
*/
|
|
138
|
+
extractorKey?: string;
|
|
127
139
|
signal?: AbortSignal;
|
|
128
140
|
/**
|
|
129
141
|
* Files read + extracted ahead of judging (1..32, default 8). With an `extractPool` this is the pool's width.
|
|
@@ -43,6 +43,8 @@ export interface PrefetchContext {
|
|
|
43
43
|
width: number;
|
|
44
44
|
/** Files in the extract stage at once (the pool's width); default `width`. */
|
|
45
45
|
extractWidth?: number;
|
|
46
|
+
/** The run's extractor key (the plan's `extractor.extractorKeyNow`), passed to every extraction. */
|
|
47
|
+
extractorKey?: string;
|
|
46
48
|
}
|
|
47
49
|
|
|
48
50
|
/** A {@link Prefetch} before its timing is stamped. */
|
|
@@ -110,6 +112,7 @@ export function createPrefetch(c: PrefetchContext): (f: PrefetchFile) => Promise
|
|
|
110
112
|
try { return await withDeadline(byPool ? extractMs + (readOverrideOf(readPath) ?? 0) : extractMs,(signal) => extractFileDetailed({
|
|
111
113
|
rootId: c.rootId, path: f.path, hash: f.hash, ...(doc ? { doc } : {}), packs: c.packs, store: c.store, composed: c.composed,
|
|
112
114
|
knownKeys: c.knownKeys, writeCache: false,
|
|
115
|
+
...(c.extractorKey ? { extractorKey: c.extractorKey } : {}),
|
|
113
116
|
onTiming: (t) => { parts.lookupMs = t.lookupMs; parts.poolMs = t.poolMs; },
|
|
114
117
|
...(c.args.extractPool ? { pool: c.args.extractPool, signal, wantsSections, ...(byPool ? {
|
|
115
118
|
readByPool: true, ...(f.listedPath !== undefined ? { readPath } : {}), ...(readOverrideOf(readPath) ? { readMs: readOverrideOf(readPath)! } : {}),
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/rules/cloneGroup.ts — `clone-group`: duplicate edges grouped by the clone-group badge
|
|
3
|
+
* (e.g. a jscpd issue id), else by connected component. Anchor (PRD 41 §C3): the badge, else the
|
|
4
|
+
* sorted-first member — so a group that gains a member keeps its identity (lineage `changed (grew)`).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { finding, refAnchor, type FindingAnchor } from '../findingBuilder.js';
|
|
8
|
+
import type { KEdge, NodeRef } from '../model.js';
|
|
9
|
+
import { compareStr } from '../refs.js';
|
|
10
|
+
import { defineRule } from './factRule.js';
|
|
11
|
+
import { components } from './components.js';
|
|
12
|
+
import { packOfRef, type KnowledgeRuleExtra } from './knowledgeInput.js';
|
|
13
|
+
|
|
14
|
+
/** Node badge naming the clone group (e.g. a jscpd issue id) its `duplicate` edges belong to. */
|
|
15
|
+
export const CLONE_GROUP_BADGE = 'cloneGroup';
|
|
16
|
+
|
|
17
|
+
export const cloneGroupRule = defineRule<KnowledgeRuleExtra>({
|
|
18
|
+
id: 'clone-group',
|
|
19
|
+
version: 1,
|
|
20
|
+
reads: [], // the knowledge graph only (its digest covers the duplicate edges)
|
|
21
|
+
scope: 'global',
|
|
22
|
+
extraInputs: ['knowledge'],
|
|
23
|
+
derive: ({ extra: { knowledge: k } }) => {
|
|
24
|
+
const byBadge = new Map<string, KEdge[]>();
|
|
25
|
+
const unbadged: KEdge[] = [];
|
|
26
|
+
for (const e of k.graph.edges) {
|
|
27
|
+
if (e.kind !== 'duplicate') continue;
|
|
28
|
+
const badge = k.byRef.get(e.from)?.badges?.[CLONE_GROUP_BADGE] ?? k.byRef.get(e.to)?.badges?.[CLONE_GROUP_BADGE];
|
|
29
|
+
if (badge === undefined) { unbadged.push(e); continue; }
|
|
30
|
+
const list = byBadge.get(String(badge)) ?? [];
|
|
31
|
+
list.push(e);
|
|
32
|
+
byBadge.set(String(badge), list);
|
|
33
|
+
}
|
|
34
|
+
const groups: Array<{ group: string; refs: NodeRef[] }> = [
|
|
35
|
+
...[...byBadge].map(([group, es]) => ({ group, refs: es.flatMap((e) => [e.from, e.to]) })),
|
|
36
|
+
...components(unbadged).map((refs) => ({ group: '', refs })),
|
|
37
|
+
];
|
|
38
|
+
return groups.map(({ group, refs }) => {
|
|
39
|
+
const unique = [...new Set(refs)];
|
|
40
|
+
const first = unique.sort(compareStr)[0]!;
|
|
41
|
+
const anchor: FindingAnchor = group ? { anchor: `${CLONE_GROUP_BADGE}:${group}`, anchorKind: 'group' } : refAnchor(first);
|
|
42
|
+
return finding('clone-group', packOfRef(k, first), unique, 'warn', { group, members: unique.length }, undefined, anchor);
|
|
43
|
+
});
|
|
44
|
+
},
|
|
45
|
+
});
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/rules/components.ts — connected components over edges (union-find), shared by the
|
|
3
|
+
* `cycle` and `clone-group` rules. Moved from findings.ts, which re-exports it.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { KEdge, NodeRef } from '../model.js';
|
|
7
|
+
import { compareStr } from '../refs.js';
|
|
8
|
+
|
|
9
|
+
/** Connected components over edges, each sorted; components sorted by first ref. */
|
|
10
|
+
export function components(edges: readonly KEdge[]): NodeRef[][] {
|
|
11
|
+
const parent = new Map<NodeRef, NodeRef>();
|
|
12
|
+
const find = (x: NodeRef): NodeRef => {
|
|
13
|
+
let r = x;
|
|
14
|
+
while (parent.get(r) !== r) r = parent.get(r)!;
|
|
15
|
+
parent.set(x, r);
|
|
16
|
+
return r;
|
|
17
|
+
};
|
|
18
|
+
for (const e of edges) {
|
|
19
|
+
for (const r of [e.from, e.to]) if (!parent.has(r)) parent.set(r, r);
|
|
20
|
+
const a = find(e.from), b = find(e.to);
|
|
21
|
+
if (a !== b) parent.set(compareStr(a, b) < 0 ? b : a, compareStr(a, b) < 0 ? a : b);
|
|
22
|
+
}
|
|
23
|
+
const groups = new Map<NodeRef, NodeRef[]>();
|
|
24
|
+
for (const r of [...parent.keys()].sort(compareStr)) {
|
|
25
|
+
const root = find(r);
|
|
26
|
+
let g = groups.get(root);
|
|
27
|
+
if (!g) groups.set(root, (g = []));
|
|
28
|
+
g.push(r);
|
|
29
|
+
}
|
|
30
|
+
return [...groups.values()].sort((a, b) => compareStr(a[0]!, b[0]!));
|
|
31
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/rules/cycle.ts — `cycle`: one finding per connected group of cycle edges (PRD 38 §3.5).
|
|
3
|
+
* Anchor (PRD 41 §C3): the group's sorted-first member.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { finding, refAnchor } from '../findingBuilder.js';
|
|
7
|
+
import { defineRule } from './factRule.js';
|
|
8
|
+
import { components } from './components.js';
|
|
9
|
+
import { packOfRef, type KnowledgeRuleExtra } from './knowledgeInput.js';
|
|
10
|
+
|
|
11
|
+
export const cycleRule = defineRule<KnowledgeRuleExtra>({
|
|
12
|
+
id: 'cycle',
|
|
13
|
+
version: 1,
|
|
14
|
+
reads: [], // the knowledge graph only
|
|
15
|
+
scope: 'global',
|
|
16
|
+
extraInputs: ['knowledge'],
|
|
17
|
+
derive: ({ extra: { knowledge: k } }) =>
|
|
18
|
+
components(k.graph.edges.filter((e) => e.cycle))
|
|
19
|
+
.map((refs) => finding('cycle', packOfRef(k, refs[0]!), refs, 'warn', { nodes: refs.length }, undefined, refAnchor(refs[0]!))),
|
|
20
|
+
});
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* knowledge/rules/duplicateCopy.ts — `duplicate-copy`: a copy of another system in the same root (PRD 41 A9).
|
|
3
|
+
* Its refs name the two systems' folders. Anchor (PRD 41 §C3): the copy's folder.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { finding } from '../findingBuilder.js';
|
|
7
|
+
import { FALLBACK_PACK_ID, srcRef } from '../refs.js';
|
|
8
|
+
import { defineRule } from './factRule.js';
|
|
9
|
+
import type { KnowledgeRuleExtra } from './knowledgeInput.js';
|
|
10
|
+
|
|
11
|
+
export const duplicateCopyRule = defineRule<KnowledgeRuleExtra>({
|
|
12
|
+
id: 'duplicate-copy',
|
|
13
|
+
version: 1,
|
|
14
|
+
reads: [], // the knowledge graph only
|
|
15
|
+
scope: 'global',
|
|
16
|
+
extraInputs: ['knowledge'],
|
|
17
|
+
derive: ({ extra: { knowledge: { graph: g } } }) =>
|
|
18
|
+
(g.meta?.systems ?? []).filter((s) => s.copyOf !== undefined).map((s) =>
|
|
19
|
+
finding('duplicate-copy', FALLBACK_PACK_ID, [srcRef(g.scope.rootId, s.path), srcRef(g.scope.rootId, s.copyOf!)], 'warn', {
|
|
20
|
+
copy: s.path, original: s.copyOf!, similarity: s.copySimilarity ?? 1, reason: s.copyReason ?? 'later-name',
|
|
21
|
+
}, [s.path, s.copyOf!], { anchor: srcRef(g.scope.rootId, s.path), anchorKind: 'file' })),
|
|
22
|
+
});
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* src/knowledge/rules/evaluateRules.test.ts — the trace tests (PRD 41 §8 Part B):
|
|
3
|
+
* - a body-only edit reruns `body`-reading rules (io-in-loop) and skips `structure`-only rules;
|
|
4
|
+
* - global rules are skipped when the fact kinds they read did not change anywhere;
|
|
5
|
+
* plus neighbourhood hops, guard chains, extra inputs and rule validation.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { FileFacts } from '../facts/fileFacts.js';
|
|
9
|
+
import { defineRule } from './factRule.js';
|
|
10
|
+
import { evaluateRules, type RuleEvaluation } from './evaluateRules.js';
|
|
11
|
+
import { callTotal, contentTag, emptyFacts, exportCount, FIXTURE_RULES, ioInLoop, mutualImport, routeGuard, unresolvedImport } from './rules.testkit.test-util.js';
|
|
12
|
+
|
|
13
|
+
const base = (): Map<string, FileFacts> => new Map([
|
|
14
|
+
['a.ts', { ...emptyFacts('ha'), imports: [{ specifier: './b', resolved: 'b.ts', names: [] }], exports: [{ name: 'a', kind: 'function', signatureHash: 's' }],
|
|
15
|
+
calls: [{ callee: 'db.get', enclosing: 'a', awaited: true, inLoop: true, count: 1 }] }],
|
|
16
|
+
['b.ts', { ...emptyFacts('hb'), imports: [{ specifier: './c', resolved: 'c.ts', names: [] }] }],
|
|
17
|
+
['c.ts', emptyFacts('hc')],
|
|
18
|
+
['d.ts', emptyFacts('hd')],
|
|
19
|
+
]);
|
|
20
|
+
|
|
21
|
+
const ran = (e: RuleEvaluation) => e.trace.filter((t) => t.outcome === 'ran').map((t) => `${t.rule}@${t.focus}`).sort();
|
|
22
|
+
const outcome = (e: RuleEvaluation, rule: string, focus = '') => e.trace.find((t) => t.rule === rule && t.focus === focus)?.outcome;
|
|
23
|
+
|
|
24
|
+
describe('evaluateRules: verifying traces and early cutoff', () => {
|
|
25
|
+
it('a first evaluation runs every row; an identical one reuses every row', () => {
|
|
26
|
+
const files = base();
|
|
27
|
+
const first = evaluateRules(FIXTURE_RULES, { files });
|
|
28
|
+
expect(first.trace.every((t) => t.outcome === 'ran')).toBe(true);
|
|
29
|
+
const second = evaluateRules(FIXTURE_RULES, { files: base() }, first.rows);
|
|
30
|
+
expect(ran(second)).toEqual([]);
|
|
31
|
+
expect(second.findings).toEqual(first.findings);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('a body-only edit reruns body-reading rules (io-in-loop) and skips structure-only rules', () => {
|
|
35
|
+
const first = evaluateRules(FIXTURE_RULES, { files: base() });
|
|
36
|
+
const files = base();
|
|
37
|
+
files.set('a.ts', { ...files.get('a.ts')!, calls: [] });
|
|
38
|
+
const second = evaluateRules(FIXTURE_RULES, { files }, first.rows);
|
|
39
|
+
expect(ran(second)).toEqual(['call-total@', 'io-in-loop@a.ts']);
|
|
40
|
+
expect(outcome(second, 'export-count', 'a.ts')).toBe('reused');
|
|
41
|
+
expect(outcome(second, 'unresolved-import', 'a.ts')).toBe('reused');
|
|
42
|
+
expect(outcome(second, 'mutual-import')).toBe('reused');
|
|
43
|
+
expect(second.findings.some((x) => x.kind === 'io-in-loop')).toBe(false);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('global rules are skipped when their read kinds did not change anywhere (a comment edit)', () => {
|
|
47
|
+
const first = evaluateRules(FIXTURE_RULES, { files: base() });
|
|
48
|
+
const files = base();
|
|
49
|
+
files.set('c.ts', { ...files.get('c.ts')!, contentHash: 'hc2' });
|
|
50
|
+
const second = evaluateRules(FIXTURE_RULES, { files }, first.rows);
|
|
51
|
+
expect(ran(second)).toEqual(['content-tag@c.ts']);
|
|
52
|
+
expect(outcome(second, 'mutual-import')).toBe('reused');
|
|
53
|
+
expect(outcome(second, 'call-total')).toBe('reused');
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
it('a structure edit reruns the global structure rule and the neighbourhood of the edited file only', () => {
|
|
57
|
+
const first = evaluateRules(FIXTURE_RULES, { files: base() });
|
|
58
|
+
const files = base();
|
|
59
|
+
files.set('c.ts', { ...files.get('c.ts')!, imports: [{ specifier: './b', resolved: 'b.ts', names: [] }] });
|
|
60
|
+
const second = evaluateRules(FIXTURE_RULES, { files }, first.rows);
|
|
61
|
+
// Graph a–b–c, d alone. unresolved-import (1 hop): b {a,b,c} and c {b,c} see c; a {a,b} and d do not.
|
|
62
|
+
// route-guard (2 hops): a, b and c all reach c; d does not.
|
|
63
|
+
expect(ran(second)).toEqual([
|
|
64
|
+
'export-count@c.ts', 'mutual-import@', 'route-guard@a.ts', 'route-guard@b.ts', 'route-guard@c.ts',
|
|
65
|
+
'unresolved-import@b.ts', 'unresolved-import@c.ts',
|
|
66
|
+
]);
|
|
67
|
+
expect(second.findings.map((x) => x.id)).toContain('mutual-import:b.ts<->c.ts');
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it('a file added or deleted drops or adds its rows, and its neighbours see the new set', () => {
|
|
71
|
+
const first = evaluateRules(FIXTURE_RULES, { files: base() });
|
|
72
|
+
const files = base();
|
|
73
|
+
files.delete('c.ts');
|
|
74
|
+
const second = evaluateRules(FIXTURE_RULES, { files }, first.rows);
|
|
75
|
+
expect([...second.rows.keys()].some((k) => k.endsWith('\u0000c.ts'))).toBe(false);
|
|
76
|
+
expect(second.findings.map((x) => x.id)).toContain('unresolved-import:b.ts->c.ts');
|
|
77
|
+
expect(outcome(second, 'unresolved-import', 'b.ts')).toBe('ran');
|
|
78
|
+
expect(outcome(second, 'unresolved-import', 'd.ts')).toBe('reused');
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
describe('evaluateRules: derive sees only what its trace covers', () => {
|
|
83
|
+
it('a rule that reads an undeclared field sees it empty, and an undeclared extra input absent', () => {
|
|
84
|
+
const seen: unknown[] = [];
|
|
85
|
+
const sneaky = defineRule<{ secret: string }>({
|
|
86
|
+
id: 'sneaky', version: 1, reads: ['body'], scope: 'file',
|
|
87
|
+
derive: ({ focus, files, extra }) => {
|
|
88
|
+
const f = files.get(focus!)!;
|
|
89
|
+
seen.push({ exports: f.exports, imports: f.imports, contentHash: f.contentHash, calls: f.calls.length, secret: extra.secret });
|
|
90
|
+
return [];
|
|
91
|
+
},
|
|
92
|
+
});
|
|
93
|
+
evaluateRules([sneaky], { files: new Map([['a.ts', base().get('a.ts')!]]), extra: { secret: 's' } });
|
|
94
|
+
expect(seen).toEqual([{ exports: [], imports: [], contentHash: '', calls: 1, secret: undefined }]);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it('a global rule reading only extra inputs (reads: []) sees no files', () => {
|
|
98
|
+
let count = -1;
|
|
99
|
+
const onlyExtra = defineRule<{ g: string }>({
|
|
100
|
+
id: 'only-extra', version: 1, reads: [], scope: 'global', extraInputs: ['g'],
|
|
101
|
+
derive: ({ files }) => { count = files.size; return []; },
|
|
102
|
+
});
|
|
103
|
+
evaluateRules([onlyExtra], { files: base(), extra: { g: 'x' }, extraHashes: { g: 'h' } });
|
|
104
|
+
expect(count).toBe(0);
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
describe('evaluateRules: guard chains', () => {
|
|
109
|
+
const routed = (): Map<string, FileFacts> => new Map([
|
|
110
|
+
['routes.ts', { ...emptyFacts('r'), entryPoints: [{ kind: 'http-route', key: 'POST /x', symbol: 'h', guards: ['requireAuth'], inputs: [], chain: ['far/auth.ts'] }] }],
|
|
111
|
+
['far/auth.ts', { ...emptyFacts('m'), exports: [{ name: 'requireAuth', kind: 'function', signatureHash: 's' }] }],
|
|
112
|
+
]);
|
|
113
|
+
|
|
114
|
+
it('a route reads its guard-chain file however far it is, and reruns when that file loses the guard', () => {
|
|
115
|
+
const first = evaluateRules([routeGuard], { files: routed() });
|
|
116
|
+
expect(first.findings).toEqual([]);
|
|
117
|
+
const files = routed();
|
|
118
|
+
files.set('far/auth.ts', { ...files.get('far/auth.ts')!, exports: [] });
|
|
119
|
+
const second = evaluateRules([routeGuard], { files }, first.rows);
|
|
120
|
+
expect(outcome(second, 'route-guard', 'routes.ts')).toBe('ran');
|
|
121
|
+
expect(second.findings.map((x) => x.id)).toEqual(['route-guard:routes.ts#POST /x']);
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
describe('evaluateRules: extra inputs', () => {
|
|
126
|
+
const readsGraph = defineRule<{ graph: string }>({
|
|
127
|
+
id: 'reads-graph', version: 1, reads: ['structure'], scope: 'global', extraInputs: ['graph'],
|
|
128
|
+
derive: ({ extra }) => [{ id: `g:${extra.graph}`, kind: 'g', pack: 'p', nodes: [], severity: 'info', params: {} }],
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
it('reruns when the extra input hash moves, and reuses when it holds', () => {
|
|
132
|
+
const files = base();
|
|
133
|
+
const first = evaluateRules([readsGraph], { files, extra: { graph: 'v1' }, extraHashes: { graph: 'h1' } });
|
|
134
|
+
expect(outcome(evaluateRules([readsGraph], { files, extra: { graph: 'v1' }, extraHashes: { graph: 'h1' } }, first.rows), 'reads-graph')).toBe('reused');
|
|
135
|
+
const moved = evaluateRules([readsGraph], { files, extra: { graph: 'v2' }, extraHashes: { graph: 'h2' } }, first.rows);
|
|
136
|
+
expect(outcome(moved, 'reads-graph')).toBe('ran');
|
|
137
|
+
expect(moved.findings.map((x) => x.id)).toEqual(['g:v2']);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it('throws when a declared extra input has no hash', () => {
|
|
141
|
+
expect(() => evaluateRules([readsGraph], { files: base(), extra: { graph: 'v1' } })).toThrow('rule_extra_input_unhashed:reads-graph:graph');
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it('a rule version bump reruns the rule', () => {
|
|
145
|
+
const first = evaluateRules([ioInLoop], { files: base() });
|
|
146
|
+
const bumped = defineRule({ ...ioInLoop, version: 2 });
|
|
147
|
+
expect(ran(evaluateRules([bumped], { files: base() }, first.rows))).toEqual(['io-in-loop@a.ts', 'io-in-loop@b.ts', 'io-in-loop@c.ts', 'io-in-loop@d.ts']);
|
|
148
|
+
});
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
describe('defineRule', () => {
|
|
152
|
+
it('rejects invalid declarations', () => {
|
|
153
|
+
const ok = { id: 'r', version: 1, reads: ['body'] as const, scope: 'neighbourhood' as const, derive: () => [] };
|
|
154
|
+
expect(() => defineRule({ ...ok, hops: 3 })).toThrow('fact_rule_invalid:r:hops');
|
|
155
|
+
expect(() => defineRule({ ...ok, scope: 'file', hops: 1 })).toThrow('fact_rule_invalid:r:hops-outside-neighbourhood');
|
|
156
|
+
expect(() => defineRule({ ...ok, reads: [] })).toThrow('fact_rule_invalid:r:reads');
|
|
157
|
+
expect(() => defineRule({ ...ok, scope: 'global', reads: [] })).toThrow('fact_rule_invalid:r:reads');
|
|
158
|
+
expect(defineRule<{ g: number }>({ ...ok, scope: 'global', reads: [], extraInputs: ['g'] }).reads).toEqual([]);
|
|
159
|
+
expect(() => defineRule({ ...ok, version: 0 })).toThrow('fact_rule_invalid:r:version');
|
|
160
|
+
expect(() => defineRule({ ...ok, scope: 'global', readsGuardChain: true })).toThrow('fact_rule_invalid:r:guard-chain-outside-neighbourhood');
|
|
161
|
+
expect(defineRule({ ...ok, reads: ['structure', 'body', 'body'] }).reads).toEqual(['body', 'structure']);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it('evaluateRules refuses two rules with one id', () => {
|
|
165
|
+
expect(() => evaluateRules([exportCount, { ...contentTag, id: 'export-count' }], { files: base() })).toThrow('fact_rule_duplicate:export-count');
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
it('uses every fixture rule', () => {
|
|
169
|
+
expect([ioInLoop, exportCount, contentTag, unresolvedImport, routeGuard, mutualImport, callTotal].map((r) => r.id).sort())
|
|
170
|
+
.toEqual(FIXTURE_RULES.map((r) => r.id).sort());
|
|
171
|
+
});
|
|
172
|
+
});
|