@eduardbar/drift 1.1.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/workflows/publish-vscode.yml +3 -3
- package/.github/workflows/publish.yml +3 -3
- package/.github/workflows/review-pr.yml +153 -0
- package/AGENTS.md +6 -0
- package/README.md +192 -4
- package/ROADMAP.md +6 -5
- package/dist/analyzer.d.ts +2 -2
- package/dist/analyzer.js +420 -159
- package/dist/benchmark.d.ts +2 -0
- package/dist/benchmark.js +185 -0
- package/dist/cli.js +509 -23
- package/dist/diff.js +74 -10
- package/dist/git.js +12 -0
- package/dist/index.d.ts +5 -1
- package/dist/index.js +3 -0
- package/dist/map.d.ts +3 -2
- package/dist/map.js +98 -10
- package/dist/plugins.d.ts +2 -1
- package/dist/plugins.js +177 -28
- package/dist/printer.js +4 -0
- package/dist/review.js +2 -2
- package/dist/rules/comments.js +2 -2
- package/dist/rules/complexity.js +2 -7
- package/dist/rules/nesting.js +3 -13
- package/dist/rules/phase0-basic.js +10 -10
- package/dist/rules/shared.d.ts +2 -0
- package/dist/rules/shared.js +27 -3
- package/dist/saas.d.ts +219 -0
- package/dist/saas.js +762 -0
- package/dist/trust-kpi.d.ts +9 -0
- package/dist/trust-kpi.js +445 -0
- package/dist/trust.d.ts +65 -0
- package/dist/trust.js +571 -0
- package/dist/types.d.ts +160 -0
- package/docs/PRD.md +199 -172
- package/docs/plugin-contract.md +61 -0
- package/docs/trust-core-release-checklist.md +55 -0
- package/package.json +5 -3
- package/packages/vscode-drift/src/code-actions.ts +53 -0
- package/packages/vscode-drift/src/extension.ts +11 -0
- package/src/analyzer.ts +484 -155
- package/src/benchmark.ts +244 -0
- package/src/cli.ts +628 -36
- package/src/diff.ts +75 -10
- package/src/git.ts +16 -0
- package/src/index.ts +63 -0
- package/src/map.ts +112 -10
- package/src/plugins.ts +354 -26
- package/src/printer.ts +4 -0
- package/src/review.ts +2 -2
- package/src/rules/comments.ts +2 -2
- package/src/rules/complexity.ts +2 -7
- package/src/rules/nesting.ts +3 -13
- package/src/rules/phase0-basic.ts +11 -12
- package/src/rules/shared.ts +31 -3
- package/src/saas.ts +1031 -0
- package/src/trust-kpi.ts +518 -0
- package/src/trust.ts +774 -0
- package/src/types.ts +177 -0
- package/tests/diff.test.ts +124 -0
- package/tests/new-features.test.ts +98 -0
- package/tests/plugins.test.ts +219 -0
- package/tests/rules.test.ts +23 -1
- package/tests/saas-foundation.test.ts +464 -0
- package/tests/trust-kpi.test.ts +120 -0
- package/tests/trust.test.ts +584 -0
package/dist/trust.js
ADDED
|
@@ -0,0 +1,571 @@
|
|
|
1
|
+
import { RULE_WEIGHTS } from './analyzer.js';
|
|
2
|
+
const ARCHITECTURE_RULES = new Set([
|
|
3
|
+
'circular-dependency',
|
|
4
|
+
'layer-violation',
|
|
5
|
+
'cross-boundary-import',
|
|
6
|
+
'controller-no-db',
|
|
7
|
+
'service-no-http',
|
|
8
|
+
]);
|
|
9
|
+
const RULE_SUGGESTIONS = {
|
|
10
|
+
'circular-dependency': 'Break cycles first to reduce hidden merge blast radius.',
|
|
11
|
+
'layer-violation': 'Fix layer violations to keep architecture boundaries enforceable.',
|
|
12
|
+
'high-complexity': 'Split branch-heavy functions before adding more logic.',
|
|
13
|
+
'deep-nesting': 'Flatten control flow with early returns.',
|
|
14
|
+
'large-file': 'Split monolithic files by responsibility before merge.',
|
|
15
|
+
'large-function': 'Extract smaller functions to reduce review complexity.',
|
|
16
|
+
'catch-swallow': 'Handle or rethrow swallowed errors to avoid silent failures.',
|
|
17
|
+
'debug-leftover': 'Remove debug leftovers from production paths.',
|
|
18
|
+
'semantic-duplication': 'Consolidate duplicated logic to prevent divergent fixes.',
|
|
19
|
+
'dead-file': 'Delete or wire dead files to avoid stale merge artifacts.',
|
|
20
|
+
};
|
|
21
|
+
const SYSTEMIC_RULES = new Set([
|
|
22
|
+
'circular-dependency',
|
|
23
|
+
'layer-violation',
|
|
24
|
+
'cross-boundary-import',
|
|
25
|
+
'unused-export',
|
|
26
|
+
'unused-dependency',
|
|
27
|
+
'dead-file',
|
|
28
|
+
'semantic-duplication',
|
|
29
|
+
'controller-no-db',
|
|
30
|
+
'service-no-http',
|
|
31
|
+
]);
|
|
32
|
+
function formatTrustGatePolicyValues(values) {
|
|
33
|
+
const enabled = typeof values.enabled === 'boolean' ? String(values.enabled) : 'inherit';
|
|
34
|
+
const minTrust = typeof values.minTrust === 'number' ? String(values.minTrust) : 'inherit';
|
|
35
|
+
const maxRisk = values.maxRisk ?? 'inherit';
|
|
36
|
+
return `enabled=${enabled} minTrust=${minTrust} maxRisk=${maxRisk}`;
|
|
37
|
+
}
|
|
38
|
+
export const MERGE_RISK_ORDER = ['LOW', 'MEDIUM', 'HIGH', 'CRITICAL'];
|
|
39
|
+
const BRANCH_ENV_CANDIDATES = [
|
|
40
|
+
'DRIFT_BRANCH',
|
|
41
|
+
'GITHUB_HEAD_REF',
|
|
42
|
+
'GITHUB_REF_NAME',
|
|
43
|
+
'CI_COMMIT_REF_NAME',
|
|
44
|
+
'BRANCH_NAME',
|
|
45
|
+
];
|
|
46
|
+
export function normalizeMergeRiskLevel(value) {
|
|
47
|
+
const normalized = value.toUpperCase();
|
|
48
|
+
return MERGE_RISK_ORDER.find((level) => level === normalized);
|
|
49
|
+
}
|
|
50
|
+
function branchPatternToRegExp(pattern) {
|
|
51
|
+
const escaped = pattern.replace(/[|\\{}()[\]^$+?.]/g, '\\$&').replace(/\*/g, '.*');
|
|
52
|
+
return new RegExp(`^${escaped}$`);
|
|
53
|
+
}
|
|
54
|
+
function patternSpecificity(pattern) {
|
|
55
|
+
const wildcardCount = (pattern.match(/\*/g) ?? []).length;
|
|
56
|
+
const staticChars = pattern.replace(/\*/g, '').length;
|
|
57
|
+
const exactBoost = wildcardCount === 0 ? 10_000 : 0;
|
|
58
|
+
return exactBoost + staticChars * 10 - wildcardCount;
|
|
59
|
+
}
|
|
60
|
+
function resolvePresetsForBranch(branchName, presets) {
|
|
61
|
+
if (!presets || presets.length === 0)
|
|
62
|
+
return [];
|
|
63
|
+
const matched = [];
|
|
64
|
+
for (let index = 0; index < presets.length; index += 1) {
|
|
65
|
+
const preset = presets[index];
|
|
66
|
+
if (!preset?.branch)
|
|
67
|
+
continue;
|
|
68
|
+
const regex = branchPatternToRegExp(preset.branch);
|
|
69
|
+
if (!regex.test(branchName))
|
|
70
|
+
continue;
|
|
71
|
+
matched.push({ preset, specificity: patternSpecificity(preset.branch), index });
|
|
72
|
+
}
|
|
73
|
+
matched.sort((a, b) => a.specificity - b.specificity || a.index - b.index);
|
|
74
|
+
return matched.map((entry) => entry.preset);
|
|
75
|
+
}
|
|
76
|
+
function normalizeMinTrust(value) {
|
|
77
|
+
return typeof value === 'number' && !Number.isNaN(value) ? value : undefined;
|
|
78
|
+
}
|
|
79
|
+
function normalizeMaxRisk(value) {
|
|
80
|
+
if (typeof value !== 'string')
|
|
81
|
+
return undefined;
|
|
82
|
+
return normalizeMergeRiskLevel(value);
|
|
83
|
+
}
|
|
84
|
+
function normalizeTrustGateOptions(source) {
|
|
85
|
+
if (!source)
|
|
86
|
+
return {};
|
|
87
|
+
return {
|
|
88
|
+
enabled: typeof source.enabled === 'boolean' ? source.enabled : undefined,
|
|
89
|
+
minTrust: normalizeMinTrust(source.minTrust),
|
|
90
|
+
maxRisk: normalizeMaxRisk(source.maxRisk),
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
function mergeTrustGateOptions(base, layer) {
|
|
94
|
+
return {
|
|
95
|
+
enabled: typeof layer.enabled === 'boolean' ? layer.enabled : base.enabled,
|
|
96
|
+
minTrust: layer.minTrust ?? base.minTrust,
|
|
97
|
+
maxRisk: layer.maxRisk ?? base.maxRisk,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
function normalizeResolutionOptions(branchNameOrOptions, explicitOverrides) {
|
|
101
|
+
if (typeof branchNameOrOptions === 'string') {
|
|
102
|
+
return {
|
|
103
|
+
branchName: branchNameOrOptions,
|
|
104
|
+
overrides: explicitOverrides,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
if (!branchNameOrOptions) {
|
|
108
|
+
return {
|
|
109
|
+
overrides: explicitOverrides,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
return {
|
|
113
|
+
...branchNameOrOptions,
|
|
114
|
+
overrides: explicitOverrides
|
|
115
|
+
? mergeTrustGateOptions(normalizeTrustGateOptions(branchNameOrOptions.overrides), normalizeTrustGateOptions(explicitOverrides))
|
|
116
|
+
: branchNameOrOptions.overrides,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
function resolvePolicyPack(policyPacks, policyPackName) {
|
|
120
|
+
const normalizedName = policyPackName?.trim();
|
|
121
|
+
if (!normalizedName)
|
|
122
|
+
return {};
|
|
123
|
+
if (!policyPacks) {
|
|
124
|
+
return { name: normalizedName, invalid: normalizedName };
|
|
125
|
+
}
|
|
126
|
+
const pack = policyPacks[normalizedName];
|
|
127
|
+
if (!pack) {
|
|
128
|
+
return { name: normalizedName, invalid: normalizedName };
|
|
129
|
+
}
|
|
130
|
+
return { name: normalizedName, pack };
|
|
131
|
+
}
|
|
132
|
+
export function detectBranchName(env = process.env) {
|
|
133
|
+
for (const key of BRANCH_ENV_CANDIDATES) {
|
|
134
|
+
const value = env[key]?.trim();
|
|
135
|
+
if (value)
|
|
136
|
+
return value;
|
|
137
|
+
}
|
|
138
|
+
return undefined;
|
|
139
|
+
}
|
|
140
|
+
export function explainTrustGatePolicy(config, branchNameOrOptions, explicitOverrides) {
|
|
141
|
+
const policy = config?.trustGate;
|
|
142
|
+
const resolution = normalizeResolutionOptions(branchNameOrOptions, explicitOverrides);
|
|
143
|
+
const normalizedBranch = resolution.branchName?.trim();
|
|
144
|
+
const packResolution = resolvePolicyPack(policy?.policyPacks, resolution.policyPack);
|
|
145
|
+
const steps = [];
|
|
146
|
+
const base = normalizeTrustGateOptions(policy);
|
|
147
|
+
let effective = base;
|
|
148
|
+
steps.push({ source: 'base', name: 'trustGate', values: base });
|
|
149
|
+
if (packResolution.pack) {
|
|
150
|
+
const packOptions = normalizeTrustGateOptions(packResolution.pack);
|
|
151
|
+
effective = mergeTrustGateOptions(effective, packOptions);
|
|
152
|
+
steps.push({ source: 'policy-pack', name: packResolution.name ?? 'unknown', values: packOptions });
|
|
153
|
+
}
|
|
154
|
+
if (normalizedBranch) {
|
|
155
|
+
const matchedPresets = resolvePresetsForBranch(normalizedBranch, policy?.presets);
|
|
156
|
+
for (const preset of matchedPresets) {
|
|
157
|
+
const presetOptions = normalizeTrustGateOptions(preset);
|
|
158
|
+
effective = mergeTrustGateOptions(effective, presetOptions);
|
|
159
|
+
steps.push({ source: 'branch-preset', name: preset.branch, values: presetOptions });
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
const overrides = normalizeTrustGateOptions(resolution.overrides);
|
|
163
|
+
if (Object.values(overrides).some((value) => value !== undefined)) {
|
|
164
|
+
effective = mergeTrustGateOptions(effective, overrides);
|
|
165
|
+
steps.push({ source: 'overrides', name: 'cli', values: overrides });
|
|
166
|
+
}
|
|
167
|
+
return {
|
|
168
|
+
effectivePolicy: effective,
|
|
169
|
+
branchName: normalizedBranch,
|
|
170
|
+
selectedPolicyPack: packResolution.name,
|
|
171
|
+
invalidPolicyPack: packResolution.invalid,
|
|
172
|
+
steps,
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
export function resolveTrustGatePolicy(config, branchNameOrOptions, explicitOverrides) {
|
|
176
|
+
const options = normalizeResolutionOptions(branchNameOrOptions, explicitOverrides);
|
|
177
|
+
return explainTrustGatePolicy(config, options).effectivePolicy;
|
|
178
|
+
}
|
|
179
|
+
export function formatTrustGatePolicyExplanation(explanation) {
|
|
180
|
+
const lines = ['Trust gate policy resolution:'];
|
|
181
|
+
lines.push(`- branch: ${explanation.branchName ?? 'not provided'}`);
|
|
182
|
+
lines.push(`- policy pack: ${explanation.selectedPolicyPack ?? 'not selected'}`);
|
|
183
|
+
if (explanation.invalidPolicyPack) {
|
|
184
|
+
lines.push(`- invalid policy pack: ${explanation.invalidPolicyPack}`);
|
|
185
|
+
}
|
|
186
|
+
lines.push('- steps:');
|
|
187
|
+
for (const [index, step] of explanation.steps.entries()) {
|
|
188
|
+
lines.push(` ${index + 1}. ${step.source} (${step.name}): ${formatTrustGatePolicyValues(step.values)}`);
|
|
189
|
+
}
|
|
190
|
+
lines.push(`- effective: ${formatTrustGatePolicyValues(explanation.effectivePolicy)}`);
|
|
191
|
+
return lines.join('\n');
|
|
192
|
+
}
|
|
193
|
+
function clamp(value, min, max) {
|
|
194
|
+
return Math.max(min, Math.min(max, value));
|
|
195
|
+
}
|
|
196
|
+
function toMergeRisk(trustScore) {
|
|
197
|
+
if (trustScore >= 80)
|
|
198
|
+
return 'LOW';
|
|
199
|
+
if (trustScore >= 60)
|
|
200
|
+
return 'MEDIUM';
|
|
201
|
+
if (trustScore >= 40)
|
|
202
|
+
return 'HIGH';
|
|
203
|
+
return 'CRITICAL';
|
|
204
|
+
}
|
|
205
|
+
function computeReasons(report) {
|
|
206
|
+
const architectureIssues = Object.entries(report.summary.byRule)
|
|
207
|
+
.filter(([rule]) => ARCHITECTURE_RULES.has(rule))
|
|
208
|
+
.reduce((sum, [, count]) => sum + count, 0);
|
|
209
|
+
const worstHotspot = report.maintenanceRisk.hotspots[0];
|
|
210
|
+
const reasons = [
|
|
211
|
+
{
|
|
212
|
+
label: 'Drift score pressure',
|
|
213
|
+
detail: `Repository drift score is ${report.totalScore}/100.`,
|
|
214
|
+
impact: Math.round(report.totalScore * 0.55),
|
|
215
|
+
},
|
|
216
|
+
{
|
|
217
|
+
label: 'Error-level issues',
|
|
218
|
+
detail: `${report.summary.errors} error issue(s) increase merge volatility.`,
|
|
219
|
+
impact: Math.min(22, report.summary.errors * 4),
|
|
220
|
+
},
|
|
221
|
+
{
|
|
222
|
+
label: 'Architecture signals',
|
|
223
|
+
detail: `${architectureIssues} architecture-related issue(s) detected.`,
|
|
224
|
+
impact: Math.min(24, architectureIssues * 6),
|
|
225
|
+
},
|
|
226
|
+
{
|
|
227
|
+
label: 'Maintenance hotspots',
|
|
228
|
+
detail: `Maintenance risk is ${report.maintenanceRisk.level.toUpperCase()} (${report.maintenanceRisk.score}/100).`,
|
|
229
|
+
impact: Math.min(25, Math.round(report.maintenanceRisk.score * 0.25)),
|
|
230
|
+
},
|
|
231
|
+
{
|
|
232
|
+
label: 'Highest-risk file',
|
|
233
|
+
detail: worstHotspot
|
|
234
|
+
? `${worstHotspot.file} has hotspot risk ${worstHotspot.risk}/100.`
|
|
235
|
+
: 'No hotspot concentration detected.',
|
|
236
|
+
impact: worstHotspot ? Math.min(15, Math.round(worstHotspot.risk * 0.15)) : 0,
|
|
237
|
+
},
|
|
238
|
+
];
|
|
239
|
+
return reasons
|
|
240
|
+
.filter((reason) => reason.impact > 0)
|
|
241
|
+
.sort((a, b) => b.impact - a.impact)
|
|
242
|
+
.slice(0, 4);
|
|
243
|
+
}
|
|
244
|
+
function effortFromWeight(weight) {
|
|
245
|
+
if (weight <= 6)
|
|
246
|
+
return 'low';
|
|
247
|
+
if (weight <= 12)
|
|
248
|
+
return 'medium';
|
|
249
|
+
return 'high';
|
|
250
|
+
}
|
|
251
|
+
function computeDiffContext(diff) {
|
|
252
|
+
const scoreRegressionPenalty = Math.max(0, diff.totalDelta) * 2;
|
|
253
|
+
const newIssuePenalty = diff.newIssuesCount * 3;
|
|
254
|
+
const churnPenalty = diff.files.length >= 15 ? 4 : 0;
|
|
255
|
+
const penalty = clamp(scoreRegressionPenalty + newIssuePenalty + churnPenalty, 0, 30);
|
|
256
|
+
const scoreImprovementBonus = Math.max(0, -diff.totalDelta) * 2;
|
|
257
|
+
const resolvedIssueBonus = diff.resolvedIssuesCount * 2;
|
|
258
|
+
const bonus = clamp(scoreImprovementBonus + resolvedIssueBonus, 0, 20);
|
|
259
|
+
const netImpact = penalty - bonus;
|
|
260
|
+
const status = netImpact > 0 ? 'regressed' : netImpact < 0 ? 'improved' : 'neutral';
|
|
261
|
+
return {
|
|
262
|
+
baseRef: diff.baseRef,
|
|
263
|
+
status,
|
|
264
|
+
scoreDelta: diff.totalDelta,
|
|
265
|
+
newIssues: diff.newIssuesCount,
|
|
266
|
+
resolvedIssues: diff.resolvedIssuesCount,
|
|
267
|
+
filesChanged: diff.files.length,
|
|
268
|
+
penalty,
|
|
269
|
+
bonus,
|
|
270
|
+
netImpact,
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
function confidenceFromPrioritySignals(occurrences, severity, systemic) {
|
|
274
|
+
const severityScore = severity === 'error' ? 4 : severity === 'warning' ? 2 : 1;
|
|
275
|
+
const systemicScore = systemic ? 2 : 0;
|
|
276
|
+
const score = occurrences * 2 + severityScore + systemicScore;
|
|
277
|
+
if (score >= 12)
|
|
278
|
+
return 'high';
|
|
279
|
+
if (score >= 7)
|
|
280
|
+
return 'medium';
|
|
281
|
+
return 'low';
|
|
282
|
+
}
|
|
283
|
+
function computeFixPriorities(report, advancedMode = false) {
|
|
284
|
+
const ordered = Object.entries(report.summary.byRule)
|
|
285
|
+
.map(([rule, occurrences]) => {
|
|
286
|
+
const weightConfig = RULE_WEIGHTS[rule] ?? { severity: 'warning', weight: 6 };
|
|
287
|
+
const severityBoost = weightConfig.severity === 'error' ? 25 : weightConfig.severity === 'warning' ? 12 : 4;
|
|
288
|
+
const systemic = SYSTEMIC_RULES.has(rule);
|
|
289
|
+
const systemicBoost = advancedMode && systemic ? 25 : 0;
|
|
290
|
+
const priorityScore = occurrences * weightConfig.weight + severityBoost + systemicBoost;
|
|
291
|
+
const confidence = confidenceFromPrioritySignals(occurrences, weightConfig.severity, systemic);
|
|
292
|
+
const explanation = advancedMode
|
|
293
|
+
? systemic
|
|
294
|
+
? 'System-level rule that propagates risk across multiple teams and modules.'
|
|
295
|
+
: 'Local rule with contained impact; treat as team-level cleanup after systemic fixes.'
|
|
296
|
+
: undefined;
|
|
297
|
+
return {
|
|
298
|
+
rule,
|
|
299
|
+
severity: weightConfig.severity,
|
|
300
|
+
occurrences,
|
|
301
|
+
systemic,
|
|
302
|
+
priorityScore,
|
|
303
|
+
estimatedTrustGain: Math.min(30, Math.max(3, Math.round(priorityScore / 4))),
|
|
304
|
+
effort: effortFromWeight(weightConfig.weight),
|
|
305
|
+
suggestion: RULE_SUGGESTIONS[rule] ?? 'Address this rule in the highest-scored files first.',
|
|
306
|
+
confidence,
|
|
307
|
+
explanation,
|
|
308
|
+
};
|
|
309
|
+
})
|
|
310
|
+
.sort((a, b) => b.priorityScore - a.priorityScore)
|
|
311
|
+
.slice(0, 5);
|
|
312
|
+
return ordered.map((item, index) => ({
|
|
313
|
+
rank: index + 1,
|
|
314
|
+
rule: item.rule,
|
|
315
|
+
severity: item.severity,
|
|
316
|
+
occurrences: item.occurrences,
|
|
317
|
+
estimated_trust_gain: item.estimatedTrustGain,
|
|
318
|
+
effort: item.effort,
|
|
319
|
+
suggestion: item.suggestion,
|
|
320
|
+
...(advancedMode ? { confidence: item.confidence, explanation: item.explanation, systemic: item.systemic } : {}),
|
|
321
|
+
}));
|
|
322
|
+
}
|
|
323
|
+
function buildComparisonFromPreviousTrust(trustScore, previousTrust) {
|
|
324
|
+
if (!previousTrust || typeof previousTrust.trust_score !== 'number')
|
|
325
|
+
return undefined;
|
|
326
|
+
const trustDelta = trustScore - previousTrust.trust_score;
|
|
327
|
+
const trend = trustDelta > 0 ? 'improving' : trustDelta < 0 ? 'regressing' : 'stable';
|
|
328
|
+
return {
|
|
329
|
+
source: 'previous-trust-json',
|
|
330
|
+
trend,
|
|
331
|
+
summary: `Trust moved ${trustDelta >= 0 ? '+' : ''}${trustDelta} vs provided previous trust JSON.`,
|
|
332
|
+
trust_delta: trustDelta,
|
|
333
|
+
previous_trust_score: previousTrust.trust_score,
|
|
334
|
+
previous_merge_risk: previousTrust.merge_risk,
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
function buildComparisonFromSnapshotHistory(report, snapshots) {
|
|
338
|
+
const lastSnapshot = snapshots && snapshots.length > 0 ? snapshots[snapshots.length - 1] : undefined;
|
|
339
|
+
if (!lastSnapshot)
|
|
340
|
+
return undefined;
|
|
341
|
+
const snapshotScoreDelta = report.totalScore - lastSnapshot.score;
|
|
342
|
+
const trend = snapshotScoreDelta < 0 ? 'improving' : snapshotScoreDelta > 0 ? 'regressing' : 'stable';
|
|
343
|
+
const snapshotContext = lastSnapshot.label
|
|
344
|
+
? `${lastSnapshot.timestamp} (${lastSnapshot.label})`
|
|
345
|
+
: lastSnapshot.timestamp;
|
|
346
|
+
return {
|
|
347
|
+
source: 'snapshot-history',
|
|
348
|
+
trend,
|
|
349
|
+
summary: `Drift score moved ${snapshotScoreDelta >= 0 ? '+' : ''}${snapshotScoreDelta} vs snapshot ${snapshotContext}.`,
|
|
350
|
+
snapshot_score_delta: snapshotScoreDelta,
|
|
351
|
+
snapshot_label: lastSnapshot.label || undefined,
|
|
352
|
+
snapshot_timestamp: lastSnapshot.timestamp,
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
function buildTeamGuidance(priorities, comparison, diffContext) {
|
|
356
|
+
const systemicTargets = priorities
|
|
357
|
+
.filter((priority) => priority.systemic)
|
|
358
|
+
.slice(0, 2)
|
|
359
|
+
.map((priority) => `${priority.rule} (x${priority.occurrences})`);
|
|
360
|
+
const guidance = [];
|
|
361
|
+
if (systemicTargets.length > 0) {
|
|
362
|
+
guidance.push(`Start with systemic rules: ${systemicTargets.join(', ')}.`);
|
|
363
|
+
}
|
|
364
|
+
if (comparison?.trend === 'regressing') {
|
|
365
|
+
guidance.push('Trend regressed; freeze net-new debt in CI and assign owners per systemic rule.');
|
|
366
|
+
}
|
|
367
|
+
if (diffContext && diffContext.newIssues > 0) {
|
|
368
|
+
guidance.push(`Block net-new issue growth first (+${diffContext.newIssues} new issue(s) in diff context).`);
|
|
369
|
+
}
|
|
370
|
+
if (guidance.length === 0) {
|
|
371
|
+
guidance.push('Maintain current baseline and schedule periodic systemic debt cleanup by rule ownership.');
|
|
372
|
+
}
|
|
373
|
+
return guidance.slice(0, 3);
|
|
374
|
+
}
|
|
375
|
+
export function buildTrustReport(report, options) {
|
|
376
|
+
const reasons = computeReasons(report);
|
|
377
|
+
const advancedMode = options?.advanced?.enabled === true;
|
|
378
|
+
const diffContext = options?.diff ? computeDiffContext(options.diff) : undefined;
|
|
379
|
+
if (diffContext && diffContext.netImpact > 0) {
|
|
380
|
+
reasons.push({
|
|
381
|
+
label: 'Diff regression signals',
|
|
382
|
+
detail: `Against ${diffContext.baseRef}: score delta ${diffContext.scoreDelta >= 0 ? '+' : ''}${diffContext.scoreDelta}, +${diffContext.newIssues} new issue(s), -${diffContext.resolvedIssues} resolved.`,
|
|
383
|
+
impact: diffContext.netImpact,
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
const rankedReasons = reasons
|
|
387
|
+
.filter((reason) => reason.impact > 0)
|
|
388
|
+
.sort((a, b) => b.impact - a.impact)
|
|
389
|
+
.slice(0, 4);
|
|
390
|
+
const totalPenalty = rankedReasons.reduce((sum, reason) => sum + reason.impact, 0);
|
|
391
|
+
const totalBonus = diffContext && diffContext.netImpact < 0 ? Math.abs(diffContext.netImpact) : 0;
|
|
392
|
+
const trustScore = clamp(Math.round(100 - totalPenalty + totalBonus), 0, 100);
|
|
393
|
+
const comparison = advancedMode
|
|
394
|
+
? buildComparisonFromPreviousTrust(trustScore, options?.advanced?.previousTrust)
|
|
395
|
+
?? buildComparisonFromSnapshotHistory(report, options?.advanced?.snapshots)
|
|
396
|
+
: undefined;
|
|
397
|
+
const fixPriorities = computeFixPriorities(report, advancedMode);
|
|
398
|
+
const advancedContext = advancedMode
|
|
399
|
+
? {
|
|
400
|
+
comparison,
|
|
401
|
+
team_guidance: buildTeamGuidance(fixPriorities, comparison, diffContext),
|
|
402
|
+
}
|
|
403
|
+
: undefined;
|
|
404
|
+
return {
|
|
405
|
+
scannedAt: new Date().toISOString(),
|
|
406
|
+
targetPath: report.targetPath,
|
|
407
|
+
trust_score: trustScore,
|
|
408
|
+
merge_risk: toMergeRisk(trustScore),
|
|
409
|
+
top_reasons: rankedReasons,
|
|
410
|
+
fix_priorities: fixPriorities,
|
|
411
|
+
diff_context: diffContext,
|
|
412
|
+
...(advancedContext ? { advanced_context: advancedContext } : {}),
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
export function formatTrustConsole(trust) {
|
|
416
|
+
const diffContext = trust.diff_context;
|
|
417
|
+
const diffLines = diffContext
|
|
418
|
+
? [
|
|
419
|
+
`- base: ${diffContext.baseRef}`,
|
|
420
|
+
`- status: ${diffContext.status.toUpperCase()}`,
|
|
421
|
+
`- score delta: ${diffContext.scoreDelta >= 0 ? '+' : ''}${diffContext.scoreDelta}`,
|
|
422
|
+
`- issues: +${diffContext.newIssues} new / -${diffContext.resolvedIssues} resolved`,
|
|
423
|
+
`- impact: +${diffContext.penalty} penalty / -${diffContext.bonus} bonus (net ${diffContext.netImpact >= 0 ? '+' : ''}${diffContext.netImpact})`,
|
|
424
|
+
].join('\n')
|
|
425
|
+
: undefined;
|
|
426
|
+
const reasons = trust.top_reasons.length === 0
|
|
427
|
+
? '- none'
|
|
428
|
+
: trust.top_reasons.map((reason) => `- ${reason.label}: ${reason.detail} (impact ${reason.impact})`).join('\n');
|
|
429
|
+
const priorities = trust.fix_priorities.length === 0
|
|
430
|
+
? '- none'
|
|
431
|
+
: trust.fix_priorities
|
|
432
|
+
.map((priority) => `- #${priority.rank} ${priority.rule} (${priority.severity}, x${priority.occurrences}${priority.confidence ? `, confidence ${priority.confidence}` : ''}): ${priority.suggestion}`)
|
|
433
|
+
.join('\n');
|
|
434
|
+
const advanced = trust.advanced_context;
|
|
435
|
+
const advancedComparison = advanced?.comparison
|
|
436
|
+
? [
|
|
437
|
+
`- source: ${advanced.comparison.source}`,
|
|
438
|
+
`- trend: ${advanced.comparison.trend.toUpperCase()}`,
|
|
439
|
+
`- summary: ${advanced.comparison.summary}`,
|
|
440
|
+
].join('\n')
|
|
441
|
+
: '- no historical comparison available';
|
|
442
|
+
const advancedGuidance = advanced?.team_guidance?.length
|
|
443
|
+
? advanced.team_guidance.map((item) => `- ${item}`).join('\n')
|
|
444
|
+
: '- none';
|
|
445
|
+
const sections = [
|
|
446
|
+
'drift trust',
|
|
447
|
+
'',
|
|
448
|
+
`Trust Score: ${trust.trust_score}/100`,
|
|
449
|
+
`Merge Risk: ${trust.merge_risk}`,
|
|
450
|
+
'',
|
|
451
|
+
'Top Reasons:',
|
|
452
|
+
reasons,
|
|
453
|
+
'',
|
|
454
|
+
'Fix Priorities:',
|
|
455
|
+
priorities,
|
|
456
|
+
];
|
|
457
|
+
if (diffLines) {
|
|
458
|
+
sections.splice(5, 0, 'Diff Context:', diffLines, '');
|
|
459
|
+
}
|
|
460
|
+
if (advanced) {
|
|
461
|
+
sections.push('', 'Advanced Team Guidance:', advancedComparison, '', advancedGuidance);
|
|
462
|
+
}
|
|
463
|
+
return sections.join('\n');
|
|
464
|
+
}
|
|
465
|
+
export function formatTrustMarkdown(trust) {
|
|
466
|
+
const diffContext = trust.diff_context;
|
|
467
|
+
const reasons = trust.top_reasons.length === 0
|
|
468
|
+
? '- none'
|
|
469
|
+
: trust.top_reasons.map((reason) => `- **${reason.label}**: ${reason.detail} (impact ${reason.impact})`).join('\n');
|
|
470
|
+
const priorities = trust.fix_priorities.length === 0
|
|
471
|
+
? '- none'
|
|
472
|
+
: trust.fix_priorities
|
|
473
|
+
.map((priority) => `- #${priority.rank} \`${priority.rule}\` (${priority.severity}, x${priority.occurrences}, effort: ${priority.effort}${priority.confidence ? `, confidence: ${priority.confidence}` : ''}) - ${priority.suggestion}${priority.explanation ? ` ${priority.explanation}` : ''}`)
|
|
474
|
+
.join('\n');
|
|
475
|
+
const diffBlock = !diffContext
|
|
476
|
+
? [
|
|
477
|
+
'- Base ref: not provided',
|
|
478
|
+
'- Diff-aware adjustment: not applied',
|
|
479
|
+
].join('\n')
|
|
480
|
+
: [
|
|
481
|
+
`- Base ref: \`${diffContext.baseRef}\``,
|
|
482
|
+
`- Diff status: **${diffContext.status.toUpperCase()}**`,
|
|
483
|
+
`- Score delta: **${diffContext.scoreDelta >= 0 ? '+' : ''}${diffContext.scoreDelta}**`,
|
|
484
|
+
`- Issues: **+${diffContext.newIssues}** new / **-${diffContext.resolvedIssues}** resolved`,
|
|
485
|
+
`- Trust adjustment: **+${diffContext.penalty}** penalty / **-${diffContext.bonus}** bonus (net ${diffContext.netImpact >= 0 ? '+' : ''}${diffContext.netImpact})`,
|
|
486
|
+
].join('\n');
|
|
487
|
+
const advancedComparison = trust.advanced_context?.comparison
|
|
488
|
+
? [
|
|
489
|
+
`- Source: \`${trust.advanced_context.comparison.source}\``,
|
|
490
|
+
`- Trend: **${trust.advanced_context.comparison.trend.toUpperCase()}**`,
|
|
491
|
+
`- Summary: ${trust.advanced_context.comparison.summary}`,
|
|
492
|
+
].join('\n')
|
|
493
|
+
: '- Historical comparison not available';
|
|
494
|
+
const advancedGuidance = trust.advanced_context?.team_guidance?.length
|
|
495
|
+
? trust.advanced_context.team_guidance.map((item) => `- ${item}`).join('\n')
|
|
496
|
+
: '- none';
|
|
497
|
+
const sections = [
|
|
498
|
+
'## drift trust',
|
|
499
|
+
'',
|
|
500
|
+
`- Trust Score: **${trust.trust_score}/100**`,
|
|
501
|
+
`- Merge Risk: **${trust.merge_risk}**`,
|
|
502
|
+
`- Target: \`${trust.targetPath}\``,
|
|
503
|
+
'',
|
|
504
|
+
'### Diff signals',
|
|
505
|
+
diffBlock,
|
|
506
|
+
'',
|
|
507
|
+
'### Top reasons',
|
|
508
|
+
reasons,
|
|
509
|
+
'',
|
|
510
|
+
'### Fix priorities',
|
|
511
|
+
priorities,
|
|
512
|
+
];
|
|
513
|
+
if (trust.advanced_context) {
|
|
514
|
+
sections.push('', '### Advanced comparison', advancedComparison, '', '### Team guidance', advancedGuidance);
|
|
515
|
+
}
|
|
516
|
+
return sections.join('\n');
|
|
517
|
+
}
|
|
518
|
+
export function formatTrustJson(trust) {
|
|
519
|
+
return JSON.stringify(trust, null, 2);
|
|
520
|
+
}
|
|
521
|
+
export function renderTrustOutput(trust, options) {
|
|
522
|
+
if (options?.json)
|
|
523
|
+
return formatTrustJson(trust);
|
|
524
|
+
if (options?.markdown)
|
|
525
|
+
return formatTrustMarkdown(trust);
|
|
526
|
+
return formatTrustConsole(trust);
|
|
527
|
+
}
|
|
528
|
+
export function shouldFailByMaxRisk(actual, allowedMaxRisk) {
|
|
529
|
+
return MERGE_RISK_ORDER.indexOf(actual) > MERGE_RISK_ORDER.indexOf(allowedMaxRisk);
|
|
530
|
+
}
|
|
531
|
+
export function evaluateTrustGate(trust, options) {
|
|
532
|
+
if (options.enabled === false) {
|
|
533
|
+
return {
|
|
534
|
+
shouldFail: false,
|
|
535
|
+
reasons: ['trust gate disabled by policy'],
|
|
536
|
+
checks: {
|
|
537
|
+
gateDisabled: true,
|
|
538
|
+
belowMinTrust: false,
|
|
539
|
+
aboveMaxRisk: false,
|
|
540
|
+
minTrust: options.minTrust,
|
|
541
|
+
maxRisk: options.maxRisk,
|
|
542
|
+
},
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
const belowMinTrust = typeof options.minTrust === 'number' &&
|
|
546
|
+
!Number.isNaN(options.minTrust) &&
|
|
547
|
+
trust.trust_score < options.minTrust;
|
|
548
|
+
const aboveMaxRisk = Boolean(options.maxRisk && shouldFailByMaxRisk(trust.merge_risk, options.maxRisk));
|
|
549
|
+
const reasons = [];
|
|
550
|
+
if (belowMinTrust) {
|
|
551
|
+
reasons.push(`trust ${trust.trust_score} is below minTrust ${options.minTrust}`);
|
|
552
|
+
}
|
|
553
|
+
if (aboveMaxRisk && options.maxRisk) {
|
|
554
|
+
reasons.push(`merge risk ${trust.merge_risk} exceeds maxRisk ${options.maxRisk}`);
|
|
555
|
+
}
|
|
556
|
+
return {
|
|
557
|
+
shouldFail: belowMinTrust || aboveMaxRisk,
|
|
558
|
+
reasons,
|
|
559
|
+
checks: {
|
|
560
|
+
gateDisabled: false,
|
|
561
|
+
belowMinTrust,
|
|
562
|
+
aboveMaxRisk,
|
|
563
|
+
minTrust: options.minTrust,
|
|
564
|
+
maxRisk: options.maxRisk,
|
|
565
|
+
},
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
export function shouldFailTrustGate(trust, options) {
|
|
569
|
+
return evaluateTrustGate(trust, options).shouldFail;
|
|
570
|
+
}
|
|
571
|
+
//# sourceMappingURL=trust.js.map
|