thumbgate 1.40.1 → 1.40.2
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/.claude-plugin/plugin.json +1 -1
- package/.well-known/mcp/server-card.json +1 -1
- package/adapters/claude/.mcp.json +3 -3
- package/adapters/forge/forge.yaml +3 -3
- package/adapters/future-agi/.mcp.json +1 -1
- package/adapters/future-agi/config.toml +1 -1
- package/adapters/future-agi/opencode.json +1 -1
- package/adapters/herdr/herdr-plugin.toml +2 -2
- package/adapters/mcp/server-stdio.js +1 -1
- package/adapters/opencode/opencode.json +1 -1
- package/config/github-about.json +1 -1
- package/package.json +38 -5
- package/public/index.html +38 -152
- package/public/install.html +8 -8
- package/public/numbers.html +2 -2
- package/public/pricing.html +54 -335
- package/scripts/analytics-report.js +363 -0
- package/scripts/auto-context-packs.js +249 -0
- package/scripts/billing-setup.js +137 -0
- package/scripts/check-update.js +236 -0
- package/scripts/conversion-rate-stats.js +442 -0
- package/scripts/cost-cli.js +147 -0
- package/scripts/creator-campaigns.js +239 -0
- package/scripts/cuda-gate-batch.js +560 -0
- package/scripts/daemon-manager.js +108 -0
- package/scripts/dashboard.js +2 -2
- package/scripts/delegation-runtime.js +1036 -0
- package/scripts/dispatch-brief.js +159 -0
- package/scripts/distribution-surfaces.js +110 -0
- package/scripts/egm-goldfish-packet.js +95 -0
- package/scripts/embeddinggemma-adapter.js +407 -0
- package/scripts/funnel-analytics.js +35 -0
- package/scripts/gate-semantic-layer.js +292 -0
- package/scripts/implementation-notes.js +241 -0
- package/scripts/intent-router.js +518 -0
- package/scripts/latency-budget.js +164 -0
- package/scripts/mcp-writeguard.js +158 -0
- package/scripts/model-candidates.js +414 -0
- package/scripts/openrouter-armor-partnership-diode.js +2419 -0
- package/scripts/operational-dashboard.js +172 -0
- package/scripts/operational-summary.js +190 -0
- package/scripts/operator-artifacts.js +622 -0
- package/scripts/optimize-context.js +17 -0
- package/scripts/predictive-insights.js +449 -0
- package/scripts/profound-aeo-citation-engine.js +583 -0
- package/scripts/pulse.js +80 -0
- package/scripts/rrsi-doctor.js +2698 -0
- package/scripts/session-report.js +120 -0
- package/scripts/subagent-profiles.js +79 -0
- package/scripts/third-author-cli.js +118 -0
- package/scripts/third-author-governance.js +437 -0
- package/scripts/thumbgate-dream.js +878 -0
- package/server.json +2 -2
- package/skills/thumbgate-daily-discoveries/SKILL.md +25 -41
- package/scripts/install-thumbgate-daily-publish-launchd.sh +0 -83
- package/scripts/thumbgate-daily-discoveries-publish.js +0 -461
- package/scripts/thumbgate-daily-discoveries-publish.sh +0 -18
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const { loadOptionalModule } = require('./private-core-boundary');
|
|
5
|
+
const { getActiveMcpProfile, getAllowedTools } = require('./mcp-policy');
|
|
6
|
+
const { loadGatesConfig } = require('./gates-engine');
|
|
7
|
+
const { loadModel, samplePosteriors } = require('./thompson-sampling');
|
|
8
|
+
const { analyzeCodeGraphImpact } = require('./codegraph-context');
|
|
9
|
+
const {
|
|
10
|
+
buildPartnerStrategy,
|
|
11
|
+
getPartnerActionBias,
|
|
12
|
+
} = loadOptionalModule('./partner-orchestration', () => ({
|
|
13
|
+
buildPartnerStrategy: ({ partnerProfile } = {}) => ({
|
|
14
|
+
profile: partnerProfile || 'public-shell',
|
|
15
|
+
verificationMode: 'local-only',
|
|
16
|
+
recommendedChecks: [],
|
|
17
|
+
}),
|
|
18
|
+
getPartnerActionBias: () => 0,
|
|
19
|
+
}));
|
|
20
|
+
const {
|
|
21
|
+
evaluateDelegation,
|
|
22
|
+
normalizeDelegationMode,
|
|
23
|
+
} = require('./delegation-runtime');
|
|
24
|
+
const { resolveFeedbackDir } = require('./feedback-paths');
|
|
25
|
+
|
|
26
|
+
const PROJECT_ROOT = path.join(__dirname, '..');
|
|
27
|
+
const DEFAULT_BUNDLE_DIR = path.join(PROJECT_ROOT, 'config', 'policy-bundles');
|
|
28
|
+
const RISK_LEVELS = ['low', 'medium', 'high', 'critical'];
|
|
29
|
+
|
|
30
|
+
function getDefaultBundleId() {
|
|
31
|
+
return process.env.THUMBGATE_POLICY_BUNDLE || 'default-v1';
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function getBundlePath(bundleId = getDefaultBundleId()) {
|
|
35
|
+
if (process.env.THUMBGATE_POLICY_BUNDLE_PATH) {
|
|
36
|
+
return process.env.THUMBGATE_POLICY_BUNDLE_PATH;
|
|
37
|
+
}
|
|
38
|
+
// Prevent path traversal: resolve and verify result stays within bundle dir (CodeQL S2083)
|
|
39
|
+
const candidate = path.resolve(DEFAULT_BUNDLE_DIR, `${bundleId}.json`);
|
|
40
|
+
if (!candidate.startsWith(path.resolve(DEFAULT_BUNDLE_DIR))) {
|
|
41
|
+
throw new Error(`Invalid bundle ID: path traversal detected in "${bundleId}"`);
|
|
42
|
+
}
|
|
43
|
+
return candidate;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function validateBundle(bundle) {
|
|
47
|
+
if (!bundle || typeof bundle !== 'object') {
|
|
48
|
+
throw new Error('Invalid policy bundle: expected object');
|
|
49
|
+
}
|
|
50
|
+
if (!bundle.bundleId || typeof bundle.bundleId !== 'string') {
|
|
51
|
+
throw new Error('Invalid policy bundle: missing bundleId');
|
|
52
|
+
}
|
|
53
|
+
if (!Array.isArray(bundle.intents) || bundle.intents.length === 0) {
|
|
54
|
+
throw new Error('Invalid policy bundle: intents must be a non-empty array');
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
bundle.intents.forEach((intent) => {
|
|
58
|
+
if (!intent.id || typeof intent.id !== 'string') {
|
|
59
|
+
throw new Error('Invalid policy bundle: intent id is required');
|
|
60
|
+
}
|
|
61
|
+
if (!RISK_LEVELS.includes(intent.risk)) {
|
|
62
|
+
throw new Error(`Invalid policy bundle: unsupported risk '${intent.risk}' for intent '${intent.id}'`);
|
|
63
|
+
}
|
|
64
|
+
if (!Array.isArray(intent.actions) || intent.actions.length === 0) {
|
|
65
|
+
throw new Error(`Invalid policy bundle: intent '${intent.id}' must define actions`);
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function loadPolicyBundle(bundleId = getDefaultBundleId()) {
|
|
73
|
+
const raw = fs.readFileSync(getBundlePath(bundleId), 'utf-8');
|
|
74
|
+
const parsed = JSON.parse(raw);
|
|
75
|
+
validateBundle(parsed);
|
|
76
|
+
return parsed;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function getRequiredApprovalRisks(bundle, mcpProfile) {
|
|
80
|
+
const approval = bundle.approval || {};
|
|
81
|
+
if (approval.profileOverrides && Array.isArray(approval.profileOverrides[mcpProfile])) {
|
|
82
|
+
return approval.profileOverrides[mcpProfile];
|
|
83
|
+
}
|
|
84
|
+
return Array.isArray(approval.requiredRisks) ? approval.requiredRisks : ['high', 'critical'];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function assertKnownMcpProfile(profile) {
|
|
88
|
+
getAllowedTools(profile);
|
|
89
|
+
return profile;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function listIntents(options = {}) {
|
|
93
|
+
const bundle = loadPolicyBundle(options.bundleId);
|
|
94
|
+
const profile = assertKnownMcpProfile(options.mcpProfile || getActiveMcpProfile());
|
|
95
|
+
const requiredRisks = getRequiredApprovalRisks(bundle, profile);
|
|
96
|
+
const partnerStrategy = buildPartnerStrategy({
|
|
97
|
+
partnerProfile: options.partnerProfile,
|
|
98
|
+
tokenBudget: DEFAULT_TOKEN_BUDGET,
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
return {
|
|
102
|
+
bundleId: bundle.bundleId,
|
|
103
|
+
mcpProfile: profile,
|
|
104
|
+
partnerProfile: partnerStrategy.profile,
|
|
105
|
+
partnerStrategy: {
|
|
106
|
+
verificationMode: partnerStrategy.verificationMode,
|
|
107
|
+
recommendedChecks: partnerStrategy.recommendedChecks,
|
|
108
|
+
},
|
|
109
|
+
intents: bundle.intents.map((intent) => ({
|
|
110
|
+
id: intent.id,
|
|
111
|
+
description: intent.description,
|
|
112
|
+
risk: intent.risk,
|
|
113
|
+
actionCount: intent.actions.length,
|
|
114
|
+
requiresApproval: requiredRisks.includes(intent.risk),
|
|
115
|
+
})),
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/* ── Token Budget Defaults ──────────────────────────────────────── */
|
|
120
|
+
const DEFAULT_TOKEN_BUDGET = {
|
|
121
|
+
total: 12000,
|
|
122
|
+
perAction: 4000,
|
|
123
|
+
contextPack: 6000,
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
function resolveTokenBudget(overrides = {}) {
|
|
127
|
+
const budget = { ...DEFAULT_TOKEN_BUDGET };
|
|
128
|
+
if (typeof overrides.total === 'number' && overrides.total > 0) budget.total = overrides.total;
|
|
129
|
+
if (typeof overrides.perAction === 'number' && overrides.perAction > 0) budget.perAction = overrides.perAction;
|
|
130
|
+
if (typeof overrides.contextPack === 'number' && overrides.contextPack > 0) budget.contextPack = overrides.contextPack;
|
|
131
|
+
return budget;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/* ── Planning Decomposition ────────────────────────────────────── */
|
|
135
|
+
|
|
136
|
+
function decomposeActions(actions) {
|
|
137
|
+
if (!Array.isArray(actions) || actions.length === 0) return [];
|
|
138
|
+
|
|
139
|
+
const phases = [];
|
|
140
|
+
let currentPhase = { kind: actions[0].kind, actions: [] };
|
|
141
|
+
|
|
142
|
+
actions.forEach((action) => {
|
|
143
|
+
if (action.kind === currentPhase.kind) {
|
|
144
|
+
currentPhase.actions.push(action);
|
|
145
|
+
} else {
|
|
146
|
+
phases.push(currentPhase);
|
|
147
|
+
currentPhase = { kind: action.kind, actions: [action] };
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
phases.push(currentPhase);
|
|
151
|
+
|
|
152
|
+
return phases.map((phase, i) => ({
|
|
153
|
+
phaseIndex: i,
|
|
154
|
+
kind: phase.kind,
|
|
155
|
+
parallel: phase.actions.length > 1,
|
|
156
|
+
actions: phase.actions,
|
|
157
|
+
}));
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function mergeUnique(values = []) {
|
|
161
|
+
return Array.from(new Set(values.filter(Boolean)));
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function normalizeContextForQuality(context) {
|
|
165
|
+
return String(context || '').trim().toLowerCase();
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function hasAny(context, terms) {
|
|
169
|
+
return terms.some((term) => context.includes(term));
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function inferMissingContext(context) {
|
|
173
|
+
const normalized = normalizeContextForQuality(context);
|
|
174
|
+
const missing = [];
|
|
175
|
+
|
|
176
|
+
if (!normalized || normalized.length < 24) {
|
|
177
|
+
missing.push('problem_statement');
|
|
178
|
+
}
|
|
179
|
+
if (!hasAny(normalized, ['done when', 'acceptance', 'success', 'verify', 'test', 'passing', 'expected'])) {
|
|
180
|
+
missing.push('acceptance_criteria');
|
|
181
|
+
}
|
|
182
|
+
if (!hasAny(normalized, ['user', 'customer', 'operator', 'developer', 'agent', 'buyer', 'admin'])) {
|
|
183
|
+
missing.push('target_user');
|
|
184
|
+
}
|
|
185
|
+
if (!hasAny(normalized, ['must not', 'avoid', 'without', 'constraint', 'keep', 'preserve', 'do not'])) {
|
|
186
|
+
missing.push('constraints');
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
return missing;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function inferImplicitAssumptions(context, intentId) {
|
|
193
|
+
const normalized = normalizeContextForQuality(context);
|
|
194
|
+
const assumptions = [];
|
|
195
|
+
|
|
196
|
+
if (!hasAny(normalized, ['file', 'module', 'script', 'api', 'cli', 'mcp', 'test'])) {
|
|
197
|
+
assumptions.push('implementation_surface_is_known');
|
|
198
|
+
}
|
|
199
|
+
if (!hasAny(normalized, ['verify', 'test', 'prove', 'smoke', 'manual'])) {
|
|
200
|
+
assumptions.push('verification_path_is_known');
|
|
201
|
+
}
|
|
202
|
+
if (intentId && intentId.includes('publish') && !hasAny(normalized, ['redact', 'privacy', 'public', 'secret'])) {
|
|
203
|
+
assumptions.push('publication_safety_is_satisfied');
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
return assumptions;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function buildClarifyingQuestions(missingContext) {
|
|
210
|
+
const questions = {
|
|
211
|
+
problem_statement: 'What specific user-visible problem should this plan solve?',
|
|
212
|
+
acceptance_criteria: 'What evidence will prove the plan is complete?',
|
|
213
|
+
target_user: 'Who is the target user or operator for this change?',
|
|
214
|
+
constraints: 'What must remain unchanged while executing this plan?',
|
|
215
|
+
};
|
|
216
|
+
return missingContext.map((item) => questions[item]).filter(Boolean);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function inferAbstractionLevel(context) {
|
|
220
|
+
const normalized = normalizeContextForQuality(context);
|
|
221
|
+
if (hasAny(normalized, ['file', 'line', 'function', 'module', 'script', 'endpoint', 'test'])) {
|
|
222
|
+
return 'implementation';
|
|
223
|
+
}
|
|
224
|
+
if (hasAny(normalized, ['workflow', 'pipeline', 'system', 'architecture', 'orchestration'])) {
|
|
225
|
+
return 'system';
|
|
226
|
+
}
|
|
227
|
+
return 'concept';
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function buildValidationChecklist({ context, intent, missingContext }) {
|
|
231
|
+
const normalized = normalizeContextForQuality(context);
|
|
232
|
+
const checklist = [
|
|
233
|
+
'Confirm the plan addresses the stated intent before tool use.',
|
|
234
|
+
'Verify all checkpoint reasons are resolved before claiming ready.',
|
|
235
|
+
];
|
|
236
|
+
|
|
237
|
+
if (missingContext.length > 0) {
|
|
238
|
+
checklist.push('Resolve missing context or document why defaults are safe.');
|
|
239
|
+
}
|
|
240
|
+
if (intent && ['high', 'critical'].includes(intent.risk)) {
|
|
241
|
+
checklist.push('Preserve approval and safety checks for high-risk execution.');
|
|
242
|
+
}
|
|
243
|
+
if (hasAny(normalized, ['code', 'file', 'test', 'refactor', 'implement'])) {
|
|
244
|
+
checklist.push('Run targeted tests for the touched implementation surface.');
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
return checklist;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function evaluatePlanQuality({ intentId, intent = null, context = '' } = {}) {
|
|
251
|
+
const missingContext = inferMissingContext(context);
|
|
252
|
+
const implicitAssumptions = inferImplicitAssumptions(context, intentId);
|
|
253
|
+
const clarifyingQuestions = buildClarifyingQuestions(missingContext);
|
|
254
|
+
const abstractionLevel = inferAbstractionLevel(context);
|
|
255
|
+
const score = Math.max(0, 1 - ((missingContext.length * 0.18) + (implicitAssumptions.length * 0.08)));
|
|
256
|
+
const gate = missingContext.length >= 2 ? 'block' : missingContext.length === 1 ? 'warn' : 'pass';
|
|
257
|
+
|
|
258
|
+
return {
|
|
259
|
+
gate,
|
|
260
|
+
score: Number(score.toFixed(2)),
|
|
261
|
+
abstractionLevel,
|
|
262
|
+
missingContext,
|
|
263
|
+
implicitAssumptions,
|
|
264
|
+
clarifyingQuestions,
|
|
265
|
+
validationChecklist: buildValidationChecklist({ context, intent, missingContext }),
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function planIntent(options = {}) {
|
|
270
|
+
const bundle = loadPolicyBundle(options.bundleId);
|
|
271
|
+
const profile = assertKnownMcpProfile(options.mcpProfile || getActiveMcpProfile());
|
|
272
|
+
const intentId = String(options.intentId || '').trim();
|
|
273
|
+
const context = String(options.context || '').trim();
|
|
274
|
+
const approved = options.approved === true;
|
|
275
|
+
const enforcePlanQuality = options.enforcePlanQuality === true;
|
|
276
|
+
const tokenBudget = resolveTokenBudget(options.tokenBudget);
|
|
277
|
+
const delegationMode = normalizeDelegationMode(options.delegationMode);
|
|
278
|
+
|
|
279
|
+
if (!intentId) {
|
|
280
|
+
throw new Error('intentId is required');
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const intent = bundle.intents.find((item) => item.id === intentId);
|
|
284
|
+
if (!intent) {
|
|
285
|
+
throw new Error(`Unknown intent: ${intentId}`);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const requiredRisks = getRequiredApprovalRisks(bundle, profile);
|
|
289
|
+
const requiresApproval = requiredRisks.includes(intent.risk);
|
|
290
|
+
const approvalCheckpointRequired = requiresApproval && !approved;
|
|
291
|
+
const planQuality = evaluatePlanQuality({ intentId, intent, context });
|
|
292
|
+
const qualityCheckpointRequired = enforcePlanQuality && planQuality.gate === 'block';
|
|
293
|
+
const checkpointRequired = approvalCheckpointRequired || qualityCheckpointRequired;
|
|
294
|
+
const partnerStrategy = buildPartnerStrategy({
|
|
295
|
+
partnerProfile: options.partnerProfile,
|
|
296
|
+
tokenBudget,
|
|
297
|
+
});
|
|
298
|
+
const rankedActions = rankActions(intent.actions, {
|
|
299
|
+
modelPath: options.modelPath,
|
|
300
|
+
partnerStrategy,
|
|
301
|
+
});
|
|
302
|
+
const plannedActions = partnerStrategy.profile === 'balanced'
|
|
303
|
+
? intent.actions
|
|
304
|
+
: rankedActions.ranked;
|
|
305
|
+
const phases = decomposeActions(plannedActions);
|
|
306
|
+
const codegraphImpact = analyzeCodeGraphImpact({
|
|
307
|
+
intentId,
|
|
308
|
+
context,
|
|
309
|
+
repoPath: options.repoPath,
|
|
310
|
+
});
|
|
311
|
+
const partnerChecks = mergeUnique([
|
|
312
|
+
...partnerStrategy.recommendedChecks,
|
|
313
|
+
...codegraphImpact.verificationHints,
|
|
314
|
+
]);
|
|
315
|
+
const enrichedPartnerStrategy = {
|
|
316
|
+
...partnerStrategy,
|
|
317
|
+
recommendedChecks: partnerChecks,
|
|
318
|
+
};
|
|
319
|
+
const basePlan = {
|
|
320
|
+
bundleId: bundle.bundleId,
|
|
321
|
+
mcpProfile: profile,
|
|
322
|
+
partnerProfile: enrichedPartnerStrategy.profile,
|
|
323
|
+
generatedAt: new Date().toISOString(),
|
|
324
|
+
status: checkpointRequired ? 'checkpoint_required' : 'ready',
|
|
325
|
+
intent: {
|
|
326
|
+
id: intent.id,
|
|
327
|
+
description: intent.description,
|
|
328
|
+
risk: intent.risk,
|
|
329
|
+
},
|
|
330
|
+
context,
|
|
331
|
+
planQuality,
|
|
332
|
+
requiresApproval,
|
|
333
|
+
approved,
|
|
334
|
+
checkpoint: checkpointRequired
|
|
335
|
+
? approvalCheckpointRequired
|
|
336
|
+
? {
|
|
337
|
+
type: 'human_approval',
|
|
338
|
+
reason: `Intent '${intent.id}' has risk '${intent.risk}' under profile '${profile}'.`,
|
|
339
|
+
requiredForRiskLevels: requiredRisks,
|
|
340
|
+
}
|
|
341
|
+
: {
|
|
342
|
+
type: 'plan_quality',
|
|
343
|
+
reason: 'Plan context is too underspecified for safe execution.',
|
|
344
|
+
missingContext: planQuality.missingContext,
|
|
345
|
+
clarifyingQuestions: planQuality.clarifyingQuestions,
|
|
346
|
+
}
|
|
347
|
+
: null,
|
|
348
|
+
actions: plannedActions,
|
|
349
|
+
phases,
|
|
350
|
+
tokenBudget: enrichedPartnerStrategy.tokenBudget || tokenBudget,
|
|
351
|
+
partnerStrategy: enrichedPartnerStrategy,
|
|
352
|
+
actionScores: rankedActions.scores,
|
|
353
|
+
codegraphImpact,
|
|
354
|
+
killSwitches: loadGatesConfig().gates
|
|
355
|
+
.filter((g) => {
|
|
356
|
+
const isHighRisk = ['high', 'critical'].includes(intent.risk);
|
|
357
|
+
if (isHighRisk && (g.severity === 'high' || g.severity === 'critical')) return true;
|
|
358
|
+
|
|
359
|
+
const actionNames = plannedActions.map((a) => a.name);
|
|
360
|
+
return g.trigger && actionNames.some((name) => g.trigger.toLowerCase().includes(name.toLowerCase()));
|
|
361
|
+
})
|
|
362
|
+
.map((g) => ({
|
|
363
|
+
id: g.id,
|
|
364
|
+
layer: g.layer || 'Execution',
|
|
365
|
+
action: g.action,
|
|
366
|
+
severity: g.severity,
|
|
367
|
+
})),
|
|
368
|
+
};
|
|
369
|
+
const delegation = evaluateDelegation({
|
|
370
|
+
delegationMode,
|
|
371
|
+
plan: basePlan,
|
|
372
|
+
mcpProfile: profile,
|
|
373
|
+
context,
|
|
374
|
+
repoPath: options.repoPath,
|
|
375
|
+
});
|
|
376
|
+
|
|
377
|
+
return {
|
|
378
|
+
...basePlan,
|
|
379
|
+
executionMode: delegation.executionMode,
|
|
380
|
+
delegationEligible: delegation.delegationEligible,
|
|
381
|
+
delegationScore: delegation.delegationScore,
|
|
382
|
+
delegationReason: delegation.delegationReason,
|
|
383
|
+
delegateProfile: delegation.delegateProfile,
|
|
384
|
+
handoffContract: delegation.handoffContract,
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
const ACTION_CATEGORY_MAP = {
|
|
389
|
+
capture_feedback: 'code_edit',
|
|
390
|
+
feedback_summary: 'debugging',
|
|
391
|
+
search_lessons: 'search',
|
|
392
|
+
retrieve_lessons: 'search',
|
|
393
|
+
search_thumbgate: 'search',
|
|
394
|
+
prevention_rules: 'security',
|
|
395
|
+
construct_context_pack: 'architecture',
|
|
396
|
+
export_dpo_pairs: 'testing',
|
|
397
|
+
export_databricks_bundle: 'testing',
|
|
398
|
+
context_provenance: 'search',
|
|
399
|
+
evaluate_context_pack: 'pr_review',
|
|
400
|
+
};
|
|
401
|
+
|
|
402
|
+
function getDefaultModelPath() {
|
|
403
|
+
const feedbackDir = resolveFeedbackDir();
|
|
404
|
+
return path.join(feedbackDir, 'feedback_model.json');
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function getPartnerActionPriority(action, partnerStrategy) {
|
|
408
|
+
if (!action || !partnerStrategy || partnerStrategy.verificationMode !== 'evidence_first') {
|
|
409
|
+
return 1;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
if (action.name === 'construct_context_pack' || action.name === 'context_provenance') {
|
|
413
|
+
return 0;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
return 1;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function scoreActions(actions, modelPath, options = {}) {
|
|
420
|
+
const partnerStrategy = options.partnerStrategy || buildPartnerStrategy({
|
|
421
|
+
partnerProfile: options.partnerProfile,
|
|
422
|
+
});
|
|
423
|
+
const model = loadModel(modelPath || getDefaultModelPath());
|
|
424
|
+
const posteriors = samplePosteriors(model);
|
|
425
|
+
const partnerScore = posteriors[partnerStrategy.partnerCategory] !== undefined
|
|
426
|
+
? posteriors[partnerStrategy.partnerCategory]
|
|
427
|
+
: 0.5;
|
|
428
|
+
|
|
429
|
+
return actions.map((action, index) => {
|
|
430
|
+
const category = ACTION_CATEGORY_MAP[action.name] || 'uncategorized';
|
|
431
|
+
const categoryScore = posteriors[category] !== undefined ? posteriors[category] : 0.5;
|
|
432
|
+
const partnerBias = getPartnerActionBias(action, partnerStrategy);
|
|
433
|
+
const score = Math.max(0, Math.min(1, (categoryScore * 0.7) + (partnerScore * 0.3) + partnerBias));
|
|
434
|
+
return {
|
|
435
|
+
action,
|
|
436
|
+
category,
|
|
437
|
+
actionScore: categoryScore,
|
|
438
|
+
partnerProfile: partnerStrategy.profile,
|
|
439
|
+
partnerCategory: partnerStrategy.partnerCategory,
|
|
440
|
+
partnerScore,
|
|
441
|
+
partnerBias,
|
|
442
|
+
partnerPriority: getPartnerActionPriority(action, partnerStrategy),
|
|
443
|
+
score,
|
|
444
|
+
index,
|
|
445
|
+
};
|
|
446
|
+
}).sort((a, b) => {
|
|
447
|
+
if (a.partnerPriority !== b.partnerPriority) {
|
|
448
|
+
return a.partnerPriority - b.partnerPriority;
|
|
449
|
+
}
|
|
450
|
+
return b.score - a.score || a.index - b.index;
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
function rankActions(actions, options = {}) {
|
|
455
|
+
const modelPath = options.modelPath || getDefaultModelPath();
|
|
456
|
+
const partnerStrategy = options.partnerStrategy || buildPartnerStrategy({
|
|
457
|
+
partnerProfile: options.partnerProfile,
|
|
458
|
+
});
|
|
459
|
+
const scored = scoreActions(actions, modelPath, { partnerStrategy });
|
|
460
|
+
return {
|
|
461
|
+
ranked: scored.map((s) => s.action),
|
|
462
|
+
scores: scored.map((s) => ({
|
|
463
|
+
name: s.action.name,
|
|
464
|
+
category: s.category,
|
|
465
|
+
partnerProfile: s.partnerProfile,
|
|
466
|
+
partnerCategory: s.partnerCategory,
|
|
467
|
+
actionScore: s.actionScore,
|
|
468
|
+
partnerScore: s.partnerScore,
|
|
469
|
+
partnerBias: s.partnerBias,
|
|
470
|
+
partnerPriority: s.partnerPriority,
|
|
471
|
+
score: s.score,
|
|
472
|
+
})),
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
module.exports = {
|
|
477
|
+
DEFAULT_BUNDLE_DIR,
|
|
478
|
+
DEFAULT_TOKEN_BUDGET,
|
|
479
|
+
RISK_LEVELS,
|
|
480
|
+
getDefaultBundleId,
|
|
481
|
+
getBundlePath,
|
|
482
|
+
validateBundle,
|
|
483
|
+
loadPolicyBundle,
|
|
484
|
+
getRequiredApprovalRisks,
|
|
485
|
+
assertKnownMcpProfile,
|
|
486
|
+
listIntents,
|
|
487
|
+
planIntent,
|
|
488
|
+
evaluatePlanQuality,
|
|
489
|
+
resolveTokenBudget,
|
|
490
|
+
decomposeActions,
|
|
491
|
+
ACTION_CATEGORY_MAP,
|
|
492
|
+
scoreActions,
|
|
493
|
+
rankActions,
|
|
494
|
+
};
|
|
495
|
+
|
|
496
|
+
if (require.main === module) {
|
|
497
|
+
const args = process.argv.slice(2);
|
|
498
|
+
const intentArg = args.find((arg) => arg.startsWith('--intent='));
|
|
499
|
+
const profileArg = args.find((arg) => arg.startsWith('--profile='));
|
|
500
|
+
const bundleArg = args.find((arg) => arg.startsWith('--bundle='));
|
|
501
|
+
const approved = args.includes('--approved');
|
|
502
|
+
|
|
503
|
+
if (!intentArg) {
|
|
504
|
+
console.log(JSON.stringify(listIntents({
|
|
505
|
+
mcpProfile: profileArg ? profileArg.replace('--profile=', '') : undefined,
|
|
506
|
+
bundleId: bundleArg ? bundleArg.replace('--bundle=', '') : undefined,
|
|
507
|
+
}), null, 2));
|
|
508
|
+
process.exit(0);
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
const plan = planIntent({
|
|
512
|
+
intentId: intentArg.replace('--intent=', ''),
|
|
513
|
+
mcpProfile: profileArg ? profileArg.replace('--profile=', '') : undefined,
|
|
514
|
+
bundleId: bundleArg ? bundleArg.replace('--bundle=', '') : undefined,
|
|
515
|
+
approved,
|
|
516
|
+
});
|
|
517
|
+
console.log(JSON.stringify(plan, null, 2));
|
|
518
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* ThumbGate Latency Budget CLI & Hop-Level SLA Auditor
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const path = require('node:path');
|
|
9
|
+
const { LatencyTracker, PROFILES } = require('../src/latency-budget.js');
|
|
10
|
+
|
|
11
|
+
function parseArgs(args) {
|
|
12
|
+
const options = {
|
|
13
|
+
profile: 'standard_agent',
|
|
14
|
+
sample: null,
|
|
15
|
+
benchmark: false,
|
|
16
|
+
json: false,
|
|
17
|
+
help: false,
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
for (let i = 0; i < args.length; i++) {
|
|
21
|
+
const arg = args[i];
|
|
22
|
+
if (arg === '--help' || arg === '-h') {
|
|
23
|
+
options.help = true;
|
|
24
|
+
} else if (arg === '--json') {
|
|
25
|
+
options.json = true;
|
|
26
|
+
} else if (arg === '--benchmark') {
|
|
27
|
+
options.benchmark = true;
|
|
28
|
+
} else if (arg === '--profile') {
|
|
29
|
+
options.profile = args[++i];
|
|
30
|
+
} else if (arg === '--sample') {
|
|
31
|
+
try {
|
|
32
|
+
options.sample = JSON.parse(args[++i]);
|
|
33
|
+
} catch (err) {
|
|
34
|
+
console.error('Invalid JSON for --sample:', err.message);
|
|
35
|
+
process.exit(1);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return options;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const VALID_SAMPLE_PHASES = new Set([
|
|
44
|
+
'reasoning_inference',
|
|
45
|
+
'governance_gate',
|
|
46
|
+
'tool_dispatch_transport',
|
|
47
|
+
'cpu_data_processing',
|
|
48
|
+
'memory_recall',
|
|
49
|
+
]);
|
|
50
|
+
|
|
51
|
+
function runBenchmark(tracker) {
|
|
52
|
+
// Simulate standard 500ms enterprise agent cycle
|
|
53
|
+
tracker.recordHop('reasoning_inference', 180, 'LLM initial step');
|
|
54
|
+
tracker.recordHop('governance_gate', 4, 'ThumbGate local pre-action check');
|
|
55
|
+
tracker.recordHop('tool_dispatch_transport', 65, 'MCP tool dispatch');
|
|
56
|
+
tracker.recordHop('cpu_data_processing', 40, 'JSON filtering & transformation');
|
|
57
|
+
tracker.recordHop('memory_recall', 15, 'LanceDB vector similarity');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Validate --sample payload. Rejects non-arrays and malformed hops.
|
|
62
|
+
* @param {*} sample
|
|
63
|
+
* @returns {Array<{phase: string, durationMs: number, label?: string, metadata?: Object}>}
|
|
64
|
+
*/
|
|
65
|
+
function validateSampleHops(sample) {
|
|
66
|
+
if (!Array.isArray(sample)) {
|
|
67
|
+
throw new Error('--sample must be a JSON array of hop objects [{ phase, durationMs, label }]');
|
|
68
|
+
}
|
|
69
|
+
if (sample.length === 0) {
|
|
70
|
+
throw new Error('--sample array must contain at least one hop object');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return sample.map((hop, index) => {
|
|
74
|
+
if (!hop || typeof hop !== 'object' || Array.isArray(hop)) {
|
|
75
|
+
throw new Error(`--sample[${index}] must be an object with phase and durationMs`);
|
|
76
|
+
}
|
|
77
|
+
const phase = hop.phase;
|
|
78
|
+
if (typeof phase !== 'string' || !phase.trim()) {
|
|
79
|
+
throw new Error(`--sample[${index}].phase must be a non-empty string`);
|
|
80
|
+
}
|
|
81
|
+
if (!VALID_SAMPLE_PHASES.has(phase)) {
|
|
82
|
+
throw new Error(
|
|
83
|
+
`--sample[${index}].phase must be one of: ${[...VALID_SAMPLE_PHASES].join(', ')}`,
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
if (typeof hop.durationMs !== 'number' || !Number.isFinite(hop.durationMs)) {
|
|
87
|
+
throw new Error(`--sample[${index}].durationMs must be a finite number`);
|
|
88
|
+
}
|
|
89
|
+
return hop;
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function main() {
|
|
94
|
+
const args = process.argv.slice(2);
|
|
95
|
+
const opts = parseArgs(args);
|
|
96
|
+
|
|
97
|
+
if (opts.help) {
|
|
98
|
+
console.log(`ThumbGate Latency Budget — Hop-Level SLA & CPU Bottleneck Auditor
|
|
99
|
+
|
|
100
|
+
Usage:
|
|
101
|
+
thumbgate latency-budget [--profile standard_agent|interactive_voice|batch_workflow] [--json]
|
|
102
|
+
thumbgate latency-budget --benchmark [--profile <name>] [--json]
|
|
103
|
+
thumbgate latency-budget --sample <json-hops-array> [--json]
|
|
104
|
+
|
|
105
|
+
Options:
|
|
106
|
+
--profile <name> SLA profile to evaluate (standard_agent: 500ms, interactive_voice: 250ms, batch_workflow: 5000ms)
|
|
107
|
+
--benchmark Run standard local fast-path benchmark
|
|
108
|
+
--sample <json> Evaluate an array of hop objects [{ phase, durationMs, label }]
|
|
109
|
+
--json Emit structured JSON report
|
|
110
|
+
--help, -h Show this help text
|
|
111
|
+
`);
|
|
112
|
+
process.exit(0);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const tracker = new LatencyTracker(opts.profile);
|
|
116
|
+
|
|
117
|
+
if (opts.sample !== null) {
|
|
118
|
+
let hops;
|
|
119
|
+
try {
|
|
120
|
+
hops = validateSampleHops(opts.sample);
|
|
121
|
+
} catch (err) {
|
|
122
|
+
console.error(err.message);
|
|
123
|
+
process.exit(1);
|
|
124
|
+
}
|
|
125
|
+
for (const h of hops) {
|
|
126
|
+
tracker.recordHop(h.phase, h.durationMs, h.label || h.phase, h.metadata || {});
|
|
127
|
+
}
|
|
128
|
+
} else {
|
|
129
|
+
runBenchmark(tracker);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const report = tracker.analyze();
|
|
133
|
+
|
|
134
|
+
if (opts.json) {
|
|
135
|
+
console.log(JSON.stringify({ ...report, otelAttributes: tracker.exportOtelAttributes() }, null, 2));
|
|
136
|
+
} else {
|
|
137
|
+
console.log(`\n⏱️ ThumbGate Latency Budget Report [${report.profile.toUpperCase()}]`);
|
|
138
|
+
console.log(`──────────────────────────────────────────────────────────`);
|
|
139
|
+
console.log(` SLA Target : <= ${report.slaMs}ms (${report.meetsSla ? '✅ MET' : '❌ BREACHED'})`);
|
|
140
|
+
console.log(` Total Duration : ${report.totalDurationMs}ms (across ${report.hopCount} hops)`);
|
|
141
|
+
console.log(` GPU Inference : ${report.gpuDurationMs}ms (${Math.round((report.gpuDurationMs / (report.totalDurationMs || 1)) * 100)}%)`);
|
|
142
|
+
console.log(` CPU/Transport : ${report.cpuDurationMs}ms (${Math.round(report.cpuRatio * 100)}%) ${report.cpuBottleneck ? '⚠️ BOTTLENECK' : '✅ HEALTHY'}`);
|
|
143
|
+
console.log(`\n Phase Breakdown:`);
|
|
144
|
+
for (const [phase, dur] of Object.entries(report.phaseTotals)) {
|
|
145
|
+
console.log(` - ${phase.padEnd(25)} : ${dur}ms`);
|
|
146
|
+
}
|
|
147
|
+
if (report.recommendations.length > 0) {
|
|
148
|
+
console.log(`\n Optimization Directives:`);
|
|
149
|
+
for (const rec of report.recommendations) {
|
|
150
|
+
console.log(` 👉 ${rec}`);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
console.log('');
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
process.exit(report.meetsSla ? 0 : 1);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const isMain = process.argv[1] && path.resolve(process.argv[1]) === __filename;
|
|
160
|
+
if (isMain) {
|
|
161
|
+
main();
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
module.exports = { parseArgs, main, validateSampleHops, VALID_SAMPLE_PHASES };
|