@longarc/mdash 3.0.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/README.md +278 -0
- package/dist/checkpoint/engine.d.ts +208 -0
- package/dist/checkpoint/engine.d.ts.map +1 -0
- package/dist/checkpoint/engine.js +369 -0
- package/dist/checkpoint/engine.js.map +1 -0
- package/dist/context/engine.d.ts +197 -0
- package/dist/context/engine.d.ts.map +1 -0
- package/dist/context/engine.js +392 -0
- package/dist/context/engine.js.map +1 -0
- package/dist/core/commitment.d.ts +154 -0
- package/dist/core/commitment.d.ts.map +1 -0
- package/dist/core/commitment.js +305 -0
- package/dist/core/commitment.js.map +1 -0
- package/dist/core/crypto.d.ts +100 -0
- package/dist/core/crypto.d.ts.map +1 -0
- package/dist/core/crypto.js +243 -0
- package/dist/core/crypto.js.map +1 -0
- package/dist/index.d.ts +121 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +234 -0
- package/dist/index.js.map +1 -0
- package/dist/mcca/engine.d.ts +260 -0
- package/dist/mcca/engine.d.ts.map +1 -0
- package/dist/mcca/engine.js +518 -0
- package/dist/mcca/engine.js.map +1 -0
- package/dist/physics/engine.d.ts +165 -0
- package/dist/physics/engine.d.ts.map +1 -0
- package/dist/physics/engine.js +371 -0
- package/dist/physics/engine.js.map +1 -0
- package/dist/tee/engine.d.ts +285 -0
- package/dist/tee/engine.d.ts.map +1 -0
- package/dist/tee/engine.js +505 -0
- package/dist/tee/engine.js.map +1 -0
- package/dist/warrant/engine.d.ts +195 -0
- package/dist/warrant/engine.d.ts.map +1 -0
- package/dist/warrant/engine.js +409 -0
- package/dist/warrant/engine.js.map +1 -0
- package/dist/zk/engine.d.ts +243 -0
- package/dist/zk/engine.d.ts.map +1 -0
- package/dist/zk/engine.js +489 -0
- package/dist/zk/engine.js.map +1 -0
- package/package.json +25 -0
- package/src/__tests__/phase1.test.ts +1120 -0
- package/src/__tests__/phase2-4.test.ts +898 -0
- package/src/checkpoint/engine.ts +532 -0
- package/src/context/engine.ts +598 -0
- package/src/core/commitment.ts +438 -0
- package/src/core/crypto.ts +304 -0
- package/src/index.ts +320 -0
- package/src/mcca/engine.ts +778 -0
- package/src/physics/engine.ts +563 -0
- package/src/tee/engine.ts +810 -0
- package/src/warrant/engine.ts +625 -0
- package/src/zk/engine.ts +730 -0
- package/tsconfig.json +21 -0
|
@@ -0,0 +1,778 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mdash v3.0 - MCCA v3 (Manifold-Constrained Context Architecture)
|
|
3
|
+
*
|
|
4
|
+
* Based on DeepSeek's research on constrained context windows.
|
|
5
|
+
* Implements manifold commitment proofs and influence budgets.
|
|
6
|
+
*
|
|
7
|
+
* Core Concepts:
|
|
8
|
+
* - Manifold: A bounded region of valid agent behavior
|
|
9
|
+
* - Influence Budget: Maximum context influence per source
|
|
10
|
+
* - Commitment Proofs: Cryptographic proof of context integrity
|
|
11
|
+
* - Drift Detection: Identifies context manipulation attempts
|
|
12
|
+
*
|
|
13
|
+
* @version 3.0.0
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import {
|
|
17
|
+
Hash,
|
|
18
|
+
Seal,
|
|
19
|
+
Timestamp,
|
|
20
|
+
FragmentId,
|
|
21
|
+
generateTimestamp,
|
|
22
|
+
sha256,
|
|
23
|
+
sha256Object,
|
|
24
|
+
hmacSeal,
|
|
25
|
+
deriveKey,
|
|
26
|
+
generateFragmentId,
|
|
27
|
+
} from '../core/crypto.js';
|
|
28
|
+
|
|
29
|
+
import { CommitmentEngine } from '../core/commitment.js';
|
|
30
|
+
|
|
31
|
+
// ============================================================================
|
|
32
|
+
// MCCA TYPES
|
|
33
|
+
// ============================================================================
|
|
34
|
+
|
|
35
|
+
export type SourceClass =
|
|
36
|
+
| 'system' // System prompts, policies
|
|
37
|
+
| 'user' // User messages
|
|
38
|
+
| 'agent' // Agent-generated content
|
|
39
|
+
| 'tool' // Tool outputs
|
|
40
|
+
| 'memory' // Retrieved memories
|
|
41
|
+
| 'external'; // External APIs, web content
|
|
42
|
+
|
|
43
|
+
export type ManifoldRegion =
|
|
44
|
+
| 'core' // Core system behavior
|
|
45
|
+
| 'task' // Current task context
|
|
46
|
+
| 'history' // Conversation history
|
|
47
|
+
| 'reference' // Reference materials
|
|
48
|
+
| 'ephemeral'; // Temporary working context
|
|
49
|
+
|
|
50
|
+
export type DriftSeverity = 'none' | 'low' | 'medium' | 'high' | 'critical';
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Influence budget allocation per source class
|
|
54
|
+
* Total budget must sum to 1.0
|
|
55
|
+
*/
|
|
56
|
+
export interface InfluenceBudget {
|
|
57
|
+
system: number; // Typically 0.30
|
|
58
|
+
user: number; // Typically 0.35
|
|
59
|
+
agent: number; // Typically 0.15
|
|
60
|
+
tool: number; // Typically 0.10
|
|
61
|
+
memory: number; // Typically 0.05
|
|
62
|
+
external: number; // Typically 0.05
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Default influence budget (conservative)
|
|
67
|
+
*/
|
|
68
|
+
export const DEFAULT_INFLUENCE_BUDGET: InfluenceBudget = {
|
|
69
|
+
system: 0.30,
|
|
70
|
+
user: 0.35,
|
|
71
|
+
agent: 0.15,
|
|
72
|
+
tool: 0.10,
|
|
73
|
+
memory: 0.05,
|
|
74
|
+
external: 0.05,
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Context fragment with manifold positioning
|
|
79
|
+
*/
|
|
80
|
+
export interface ManifoldFragment {
|
|
81
|
+
/** Fragment ID */
|
|
82
|
+
id: FragmentId;
|
|
83
|
+
/** Content hash */
|
|
84
|
+
content_hash: Hash;
|
|
85
|
+
/** Source classification */
|
|
86
|
+
source_class: SourceClass;
|
|
87
|
+
/** Manifold region */
|
|
88
|
+
region: ManifoldRegion;
|
|
89
|
+
/** Position in manifold (normalized 0-1) */
|
|
90
|
+
position: {
|
|
91
|
+
x: number; // Influence axis
|
|
92
|
+
y: number; // Recency axis
|
|
93
|
+
z: number; // Relevance axis
|
|
94
|
+
};
|
|
95
|
+
/** Influence weight */
|
|
96
|
+
influence: number;
|
|
97
|
+
/** Tokens in fragment */
|
|
98
|
+
token_count: number;
|
|
99
|
+
/** Creation time */
|
|
100
|
+
timestamp: Timestamp;
|
|
101
|
+
/** Seal */
|
|
102
|
+
seal: Seal;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Manifold commitment proof
|
|
107
|
+
* Proves the context state at a point in time
|
|
108
|
+
*/
|
|
109
|
+
export interface ManifoldCommitmentProof {
|
|
110
|
+
/** Proof ID */
|
|
111
|
+
id: string;
|
|
112
|
+
/** Timestamp of commitment */
|
|
113
|
+
timestamp: Timestamp;
|
|
114
|
+
/** Merkle root of all fragments */
|
|
115
|
+
merkle_root: Hash;
|
|
116
|
+
/** Fragment count */
|
|
117
|
+
fragment_count: number;
|
|
118
|
+
/** Total influence by source class */
|
|
119
|
+
influence_distribution: Record<SourceClass, number>;
|
|
120
|
+
/** Budget compliance */
|
|
121
|
+
budget_compliant: boolean;
|
|
122
|
+
/** Drift score (0 = no drift, 1 = maximum drift) */
|
|
123
|
+
drift_score: number;
|
|
124
|
+
/** L1 commitment reference */
|
|
125
|
+
commitment_id: string;
|
|
126
|
+
/** Seal */
|
|
127
|
+
seal: Seal;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Drift detection result
|
|
132
|
+
*/
|
|
133
|
+
export interface DriftAnalysis {
|
|
134
|
+
/** Overall drift score */
|
|
135
|
+
score: number;
|
|
136
|
+
/** Severity classification */
|
|
137
|
+
severity: DriftSeverity;
|
|
138
|
+
/** Drift by source class */
|
|
139
|
+
by_source: Record<SourceClass, number>;
|
|
140
|
+
/** Specific violations */
|
|
141
|
+
violations: Array<{
|
|
142
|
+
type: 'budget_exceeded' | 'region_overflow' | 'influence_spike' | 'position_anomaly';
|
|
143
|
+
source: SourceClass;
|
|
144
|
+
expected: number;
|
|
145
|
+
actual: number;
|
|
146
|
+
message: string;
|
|
147
|
+
}>;
|
|
148
|
+
/** Recommendations */
|
|
149
|
+
recommendations: string[];
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// ============================================================================
|
|
153
|
+
// MANIFOLD ENGINE
|
|
154
|
+
// ============================================================================
|
|
155
|
+
|
|
156
|
+
export interface MCCAConfig {
|
|
157
|
+
/** Influence budget allocation */
|
|
158
|
+
budget: InfluenceBudget;
|
|
159
|
+
/** Maximum fragments in manifold */
|
|
160
|
+
maxFragments: number;
|
|
161
|
+
/** Maximum total tokens */
|
|
162
|
+
maxTokens: number;
|
|
163
|
+
/** Drift threshold for alerts */
|
|
164
|
+
driftThreshold: number;
|
|
165
|
+
/** Enable automatic pruning */
|
|
166
|
+
autoPrune: boolean;
|
|
167
|
+
/** Region size limits (tokens) */
|
|
168
|
+
regionLimits: Record<ManifoldRegion, number>;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export const DEFAULT_CONFIG: MCCAConfig = {
|
|
172
|
+
budget: DEFAULT_INFLUENCE_BUDGET,
|
|
173
|
+
maxFragments: 1000,
|
|
174
|
+
maxTokens: 100000,
|
|
175
|
+
driftThreshold: 0.3,
|
|
176
|
+
autoPrune: true,
|
|
177
|
+
regionLimits: {
|
|
178
|
+
core: 10000,
|
|
179
|
+
task: 30000,
|
|
180
|
+
history: 40000,
|
|
181
|
+
reference: 15000,
|
|
182
|
+
ephemeral: 5000,
|
|
183
|
+
},
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
export class MCCAEngine {
|
|
187
|
+
private key: CryptoKey | null = null;
|
|
188
|
+
private config: MCCAConfig;
|
|
189
|
+
private commitmentEngine: CommitmentEngine;
|
|
190
|
+
|
|
191
|
+
// Fragment storage
|
|
192
|
+
private fragments: Map<FragmentId, ManifoldFragment> = new Map();
|
|
193
|
+
private fragmentsByRegion: Map<ManifoldRegion, FragmentId[]> = new Map();
|
|
194
|
+
private fragmentsBySource: Map<SourceClass, FragmentId[]> = new Map();
|
|
195
|
+
|
|
196
|
+
// Commitment proofs
|
|
197
|
+
private proofs: Map<string, ManifoldCommitmentProof> = new Map();
|
|
198
|
+
|
|
199
|
+
// Running totals
|
|
200
|
+
private totalTokens: number = 0;
|
|
201
|
+
private influenceBySource: Record<SourceClass, number> = {
|
|
202
|
+
system: 0,
|
|
203
|
+
user: 0,
|
|
204
|
+
agent: 0,
|
|
205
|
+
tool: 0,
|
|
206
|
+
memory: 0,
|
|
207
|
+
external: 0,
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
constructor(commitmentEngine: CommitmentEngine, config: Partial<MCCAConfig> = {}) {
|
|
211
|
+
this.commitmentEngine = commitmentEngine;
|
|
212
|
+
this.config = { ...DEFAULT_CONFIG, ...config };
|
|
213
|
+
|
|
214
|
+
// Initialize region maps
|
|
215
|
+
for (const region of Object.keys(this.config.regionLimits) as ManifoldRegion[]) {
|
|
216
|
+
this.fragmentsByRegion.set(region, []);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Initialize source maps
|
|
220
|
+
for (const source of Object.keys(this.config.budget) as SourceClass[]) {
|
|
221
|
+
this.fragmentsBySource.set(source, []);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Initialize the MCCA engine
|
|
227
|
+
*/
|
|
228
|
+
async initialize(sealKey: string): Promise<void> {
|
|
229
|
+
this.key = await deriveKey(sealKey);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Add a fragment to the manifold
|
|
234
|
+
* Automatically positions it based on source and content
|
|
235
|
+
*/
|
|
236
|
+
async addFragment(params: {
|
|
237
|
+
content: unknown;
|
|
238
|
+
source_class: SourceClass;
|
|
239
|
+
region: ManifoldRegion;
|
|
240
|
+
token_count: number;
|
|
241
|
+
influence?: number;
|
|
242
|
+
}): Promise<ManifoldFragment> {
|
|
243
|
+
if (!this.key) {
|
|
244
|
+
throw new Error('MCCA engine not initialized');
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const startTime = performance.now();
|
|
248
|
+
|
|
249
|
+
// Check region capacity
|
|
250
|
+
const regionTokens = this.getRegionTokens(params.region);
|
|
251
|
+
if (regionTokens + params.token_count > this.config.regionLimits[params.region]) {
|
|
252
|
+
if (this.config.autoPrune) {
|
|
253
|
+
await this.pruneRegion(params.region, params.token_count);
|
|
254
|
+
} else {
|
|
255
|
+
throw new Error(`Region ${params.region} capacity exceeded`);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// Calculate influence
|
|
260
|
+
const baseInfluence = params.influence ?? this.calculateBaseInfluence(
|
|
261
|
+
params.source_class,
|
|
262
|
+
params.token_count
|
|
263
|
+
);
|
|
264
|
+
|
|
265
|
+
// Calculate position in manifold
|
|
266
|
+
const position = this.calculatePosition(
|
|
267
|
+
params.source_class,
|
|
268
|
+
params.region,
|
|
269
|
+
baseInfluence
|
|
270
|
+
);
|
|
271
|
+
|
|
272
|
+
// Create fragment
|
|
273
|
+
const id = generateFragmentId();
|
|
274
|
+
const contentHash = await sha256Object(params.content);
|
|
275
|
+
const now = generateTimestamp();
|
|
276
|
+
|
|
277
|
+
const fragmentData = {
|
|
278
|
+
id,
|
|
279
|
+
content_hash: contentHash,
|
|
280
|
+
source_class: params.source_class,
|
|
281
|
+
region: params.region,
|
|
282
|
+
position,
|
|
283
|
+
influence: baseInfluence,
|
|
284
|
+
token_count: params.token_count,
|
|
285
|
+
timestamp: now,
|
|
286
|
+
};
|
|
287
|
+
|
|
288
|
+
const seal = await hmacSeal(fragmentData, this.key);
|
|
289
|
+
|
|
290
|
+
const fragment: ManifoldFragment = {
|
|
291
|
+
...fragmentData,
|
|
292
|
+
seal,
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
// Store fragment
|
|
296
|
+
this.fragments.set(id, fragment);
|
|
297
|
+
this.fragmentsByRegion.get(params.region)!.push(id);
|
|
298
|
+
this.fragmentsBySource.get(params.source_class)!.push(id);
|
|
299
|
+
|
|
300
|
+
// Update totals
|
|
301
|
+
this.totalTokens += params.token_count;
|
|
302
|
+
this.influenceBySource[params.source_class] += baseInfluence;
|
|
303
|
+
|
|
304
|
+
// Commit to L1
|
|
305
|
+
await this.commitmentEngine.commit(fragment, `mcca:${id}`);
|
|
306
|
+
|
|
307
|
+
const elapsed = performance.now() - startTime;
|
|
308
|
+
if (elapsed > 5) {
|
|
309
|
+
console.warn(`[MCCA] Fragment addition exceeded 5ms: ${elapsed.toFixed(2)}ms`);
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
return fragment;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* Calculate base influence for a fragment
|
|
317
|
+
*/
|
|
318
|
+
private calculateBaseInfluence(source: SourceClass, tokens: number): number {
|
|
319
|
+
const budgetShare = this.config.budget[source];
|
|
320
|
+
const currentUsage = this.influenceBySource[source];
|
|
321
|
+
const remaining = budgetShare - currentUsage;
|
|
322
|
+
|
|
323
|
+
// Scale by token count (normalized)
|
|
324
|
+
const tokenFactor = Math.min(tokens / 1000, 1);
|
|
325
|
+
|
|
326
|
+
return Math.max(0, Math.min(remaining * tokenFactor, remaining));
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Calculate position in manifold
|
|
331
|
+
*/
|
|
332
|
+
private calculatePosition(
|
|
333
|
+
source: SourceClass,
|
|
334
|
+
region: ManifoldRegion,
|
|
335
|
+
influence: number
|
|
336
|
+
): { x: number; y: number; z: number } {
|
|
337
|
+
// X-axis: Influence (based on source class priority)
|
|
338
|
+
const sourcePriority: Record<SourceClass, number> = {
|
|
339
|
+
system: 0.9,
|
|
340
|
+
user: 0.8,
|
|
341
|
+
agent: 0.5,
|
|
342
|
+
tool: 0.6,
|
|
343
|
+
memory: 0.4,
|
|
344
|
+
external: 0.3,
|
|
345
|
+
};
|
|
346
|
+
const x = sourcePriority[source] * influence;
|
|
347
|
+
|
|
348
|
+
// Y-axis: Recency (newer = higher)
|
|
349
|
+
const y = this.fragments.size > 0
|
|
350
|
+
? 1 - (this.fragments.size / this.config.maxFragments)
|
|
351
|
+
: 1;
|
|
352
|
+
|
|
353
|
+
// Z-axis: Region relevance
|
|
354
|
+
const regionRelevance: Record<ManifoldRegion, number> = {
|
|
355
|
+
core: 1.0,
|
|
356
|
+
task: 0.9,
|
|
357
|
+
history: 0.5,
|
|
358
|
+
reference: 0.6,
|
|
359
|
+
ephemeral: 0.2,
|
|
360
|
+
};
|
|
361
|
+
const z = regionRelevance[region];
|
|
362
|
+
|
|
363
|
+
return { x, y, z };
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Prune a region to make space
|
|
368
|
+
*/
|
|
369
|
+
private async pruneRegion(region: ManifoldRegion, needed: number): Promise<void> {
|
|
370
|
+
const fragmentIds = this.fragmentsByRegion.get(region) || [];
|
|
371
|
+
const fragments = fragmentIds
|
|
372
|
+
.map(id => this.fragments.get(id)!)
|
|
373
|
+
.sort((a, b) => {
|
|
374
|
+
// Prune by: low influence, old, low relevance
|
|
375
|
+
const scoreA = a.influence * a.position.y * a.position.z;
|
|
376
|
+
const scoreB = b.influence * b.position.y * b.position.z;
|
|
377
|
+
return scoreA - scoreB;
|
|
378
|
+
});
|
|
379
|
+
|
|
380
|
+
let freed = 0;
|
|
381
|
+
for (const fragment of fragments) {
|
|
382
|
+
if (freed >= needed) break;
|
|
383
|
+
|
|
384
|
+
await this.removeFragment(fragment.id);
|
|
385
|
+
freed += fragment.token_count;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Remove a fragment from the manifold
|
|
391
|
+
*/
|
|
392
|
+
async removeFragment(id: FragmentId): Promise<void> {
|
|
393
|
+
const fragment = this.fragments.get(id);
|
|
394
|
+
if (!fragment) return;
|
|
395
|
+
|
|
396
|
+
// Update totals
|
|
397
|
+
this.totalTokens -= fragment.token_count;
|
|
398
|
+
this.influenceBySource[fragment.source_class] -= fragment.influence;
|
|
399
|
+
|
|
400
|
+
// Remove from indices
|
|
401
|
+
const regionIds = this.fragmentsByRegion.get(fragment.region) || [];
|
|
402
|
+
this.fragmentsByRegion.set(
|
|
403
|
+
fragment.region,
|
|
404
|
+
regionIds.filter(fid => fid !== id)
|
|
405
|
+
);
|
|
406
|
+
|
|
407
|
+
const sourceIds = this.fragmentsBySource.get(fragment.source_class) || [];
|
|
408
|
+
this.fragmentsBySource.set(
|
|
409
|
+
fragment.source_class,
|
|
410
|
+
sourceIds.filter(fid => fid !== id)
|
|
411
|
+
);
|
|
412
|
+
|
|
413
|
+
this.fragments.delete(id);
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* Get region token count
|
|
418
|
+
*/
|
|
419
|
+
private getRegionTokens(region: ManifoldRegion): number {
|
|
420
|
+
const fragmentIds = this.fragmentsByRegion.get(region) || [];
|
|
421
|
+
return fragmentIds.reduce((sum, id) => {
|
|
422
|
+
const fragment = this.fragments.get(id);
|
|
423
|
+
return sum + (fragment?.token_count || 0);
|
|
424
|
+
}, 0);
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* Generate a manifold commitment proof
|
|
429
|
+
*/
|
|
430
|
+
async generateCommitmentProof(): Promise<ManifoldCommitmentProof> {
|
|
431
|
+
if (!this.key) {
|
|
432
|
+
throw new Error('MCCA engine not initialized');
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// Calculate merkle root of all fragments
|
|
436
|
+
const fragmentHashes = Array.from(this.fragments.values())
|
|
437
|
+
.map(f => f.content_hash);
|
|
438
|
+
|
|
439
|
+
const merkleRoot = fragmentHashes.length > 0
|
|
440
|
+
? await this.computeMerkleRoot(fragmentHashes)
|
|
441
|
+
: await sha256('empty-manifold');
|
|
442
|
+
|
|
443
|
+
// Calculate total influence
|
|
444
|
+
const totalInfluence = Object.values(this.influenceBySource).reduce((a, b) => a + b, 0);
|
|
445
|
+
|
|
446
|
+
// Calculate influence distribution (normalized)
|
|
447
|
+
const distribution: Record<SourceClass, number> = {} as Record<SourceClass, number>;
|
|
448
|
+
for (const [source, influence] of Object.entries(this.influenceBySource)) {
|
|
449
|
+
distribution[source as SourceClass] = totalInfluence > 0
|
|
450
|
+
? influence / totalInfluence
|
|
451
|
+
: 0;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// Check budget compliance
|
|
455
|
+
const budgetCompliant = this.checkBudgetCompliance();
|
|
456
|
+
|
|
457
|
+
// Calculate drift score
|
|
458
|
+
const driftAnalysis = await this.analyzeDrift();
|
|
459
|
+
|
|
460
|
+
const now = generateTimestamp();
|
|
461
|
+
const id = `mcp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
462
|
+
|
|
463
|
+
const proofData = {
|
|
464
|
+
id,
|
|
465
|
+
timestamp: now,
|
|
466
|
+
merkle_root: merkleRoot,
|
|
467
|
+
fragment_count: this.fragments.size,
|
|
468
|
+
influence_distribution: distribution,
|
|
469
|
+
budget_compliant: budgetCompliant.compliant,
|
|
470
|
+
drift_score: driftAnalysis.score,
|
|
471
|
+
commitment_id: '',
|
|
472
|
+
};
|
|
473
|
+
|
|
474
|
+
// Commit to L1
|
|
475
|
+
const commitment = await this.commitmentEngine.commit(proofData, `mcca-proof:${id}`);
|
|
476
|
+
proofData.commitment_id = commitment.operationId;
|
|
477
|
+
|
|
478
|
+
const seal = await hmacSeal(proofData, this.key);
|
|
479
|
+
|
|
480
|
+
const proof: ManifoldCommitmentProof = {
|
|
481
|
+
...proofData,
|
|
482
|
+
seal,
|
|
483
|
+
};
|
|
484
|
+
|
|
485
|
+
this.proofs.set(id, proof);
|
|
486
|
+
|
|
487
|
+
return proof;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* Compute merkle root from hashes
|
|
492
|
+
*/
|
|
493
|
+
private async computeMerkleRoot(hashes: Hash[]): Promise<Hash> {
|
|
494
|
+
if (hashes.length === 0) {
|
|
495
|
+
return sha256('empty');
|
|
496
|
+
}
|
|
497
|
+
if (hashes.length === 1) {
|
|
498
|
+
return hashes[0];
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
const pairs: Hash[] = [];
|
|
502
|
+
for (let i = 0; i < hashes.length; i += 2) {
|
|
503
|
+
const left = hashes[i];
|
|
504
|
+
const right = hashes[i + 1] || left; // Duplicate last if odd
|
|
505
|
+
const combined = await sha256(`${left}|${right}`);
|
|
506
|
+
pairs.push(combined as Hash);
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
return this.computeMerkleRoot(pairs);
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* Check if current state complies with budget
|
|
514
|
+
*/
|
|
515
|
+
checkBudgetCompliance(): { compliant: boolean; violations: string[] } {
|
|
516
|
+
const violations: string[] = [];
|
|
517
|
+
const totalInfluence = Object.values(this.influenceBySource).reduce((a, b) => a + b, 0);
|
|
518
|
+
|
|
519
|
+
if (totalInfluence === 0) {
|
|
520
|
+
return { compliant: true, violations: [] };
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
for (const [source, budget] of Object.entries(this.config.budget)) {
|
|
524
|
+
const actual = this.influenceBySource[source as SourceClass] / totalInfluence;
|
|
525
|
+
const tolerance = 0.1; // 10% tolerance
|
|
526
|
+
|
|
527
|
+
if (actual > budget + tolerance) {
|
|
528
|
+
violations.push(
|
|
529
|
+
`${source}: ${(actual * 100).toFixed(1)}% exceeds budget ${(budget * 100).toFixed(1)}%`
|
|
530
|
+
);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
return {
|
|
535
|
+
compliant: violations.length === 0,
|
|
536
|
+
violations,
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/**
|
|
541
|
+
* Analyze drift from expected manifold state
|
|
542
|
+
*/
|
|
543
|
+
async analyzeDrift(): Promise<DriftAnalysis> {
|
|
544
|
+
const totalInfluence = Object.values(this.influenceBySource).reduce((a, b) => a + b, 0);
|
|
545
|
+
const violations: DriftAnalysis['violations'] = [];
|
|
546
|
+
const bySource: Record<SourceClass, number> = {} as Record<SourceClass, number>;
|
|
547
|
+
|
|
548
|
+
// Calculate drift per source
|
|
549
|
+
for (const [source, budget] of Object.entries(this.config.budget)) {
|
|
550
|
+
const actual = totalInfluence > 0
|
|
551
|
+
? this.influenceBySource[source as SourceClass] / totalInfluence
|
|
552
|
+
: 0;
|
|
553
|
+
const drift = Math.abs(actual - budget);
|
|
554
|
+
bySource[source as SourceClass] = drift;
|
|
555
|
+
|
|
556
|
+
if (drift > 0.15) { // 15% threshold
|
|
557
|
+
violations.push({
|
|
558
|
+
type: 'budget_exceeded',
|
|
559
|
+
source: source as SourceClass,
|
|
560
|
+
expected: budget,
|
|
561
|
+
actual,
|
|
562
|
+
message: `${source} influence drifted ${(drift * 100).toFixed(1)}% from budget`,
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
// Check region overflow
|
|
568
|
+
for (const [region, limit] of Object.entries(this.config.regionLimits)) {
|
|
569
|
+
const tokens = this.getRegionTokens(region as ManifoldRegion);
|
|
570
|
+
if (tokens > limit * 0.9) { // 90% threshold
|
|
571
|
+
violations.push({
|
|
572
|
+
type: 'region_overflow',
|
|
573
|
+
source: 'system' as SourceClass,
|
|
574
|
+
expected: limit,
|
|
575
|
+
actual: tokens,
|
|
576
|
+
message: `Region ${region} at ${((tokens / limit) * 100).toFixed(1)}% capacity`,
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
// Calculate overall score
|
|
582
|
+
const avgDrift = Object.values(bySource).reduce((a, b) => a + b, 0) /
|
|
583
|
+
Object.values(bySource).length;
|
|
584
|
+
|
|
585
|
+
const score = Math.min(avgDrift * 2, 1); // Scale to 0-1
|
|
586
|
+
|
|
587
|
+
// Classify severity
|
|
588
|
+
let severity: DriftSeverity;
|
|
589
|
+
if (score < 0.1) severity = 'none';
|
|
590
|
+
else if (score < 0.25) severity = 'low';
|
|
591
|
+
else if (score < 0.5) severity = 'medium';
|
|
592
|
+
else if (score < 0.75) severity = 'high';
|
|
593
|
+
else severity = 'critical';
|
|
594
|
+
|
|
595
|
+
// Generate recommendations
|
|
596
|
+
const recommendations: string[] = [];
|
|
597
|
+
if (violations.length > 0) {
|
|
598
|
+
if (bySource.external > 0.15) {
|
|
599
|
+
recommendations.push('Reduce external content influence');
|
|
600
|
+
}
|
|
601
|
+
if (bySource.agent > 0.15) {
|
|
602
|
+
recommendations.push('Agent self-influence exceeds threshold');
|
|
603
|
+
}
|
|
604
|
+
if (severity === 'high' || severity === 'critical') {
|
|
605
|
+
recommendations.push('Consider context reset');
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
return {
|
|
610
|
+
score,
|
|
611
|
+
severity,
|
|
612
|
+
by_source: bySource,
|
|
613
|
+
violations,
|
|
614
|
+
recommendations,
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/**
|
|
619
|
+
* Get fragment by ID
|
|
620
|
+
*/
|
|
621
|
+
getFragment(id: FragmentId): ManifoldFragment | null {
|
|
622
|
+
return this.fragments.get(id) || null;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/**
|
|
626
|
+
* Get all fragments in a region
|
|
627
|
+
*/
|
|
628
|
+
getRegionFragments(region: ManifoldRegion): ManifoldFragment[] {
|
|
629
|
+
const ids = this.fragmentsByRegion.get(region) || [];
|
|
630
|
+
return ids.map(id => this.fragments.get(id)!).filter(Boolean);
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* Get fragments by source
|
|
635
|
+
*/
|
|
636
|
+
getSourceFragments(source: SourceClass): ManifoldFragment[] {
|
|
637
|
+
const ids = this.fragmentsBySource.get(source) || [];
|
|
638
|
+
return ids.map(id => this.fragments.get(id)!).filter(Boolean);
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/**
|
|
642
|
+
* Get current manifold state
|
|
643
|
+
*/
|
|
644
|
+
getState(): {
|
|
645
|
+
totalFragments: number;
|
|
646
|
+
totalTokens: number;
|
|
647
|
+
influenceBySource: Record<SourceClass, number>;
|
|
648
|
+
tokensByRegion: Record<ManifoldRegion, number>;
|
|
649
|
+
} {
|
|
650
|
+
const tokensByRegion: Record<ManifoldRegion, number> = {} as Record<ManifoldRegion, number>;
|
|
651
|
+
for (const region of Object.keys(this.config.regionLimits) as ManifoldRegion[]) {
|
|
652
|
+
tokensByRegion[region] = this.getRegionTokens(region);
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
return {
|
|
656
|
+
totalFragments: this.fragments.size,
|
|
657
|
+
totalTokens: this.totalTokens,
|
|
658
|
+
influenceBySource: { ...this.influenceBySource },
|
|
659
|
+
tokensByRegion,
|
|
660
|
+
};
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
/**
|
|
664
|
+
* Get engine statistics
|
|
665
|
+
*/
|
|
666
|
+
getStats(): {
|
|
667
|
+
fragments: number;
|
|
668
|
+
tokens: number;
|
|
669
|
+
proofs: number;
|
|
670
|
+
budgetCompliance: { compliant: boolean; violations: string[] };
|
|
671
|
+
config: MCCAConfig;
|
|
672
|
+
} {
|
|
673
|
+
return {
|
|
674
|
+
fragments: this.fragments.size,
|
|
675
|
+
tokens: this.totalTokens,
|
|
676
|
+
proofs: this.proofs.size,
|
|
677
|
+
budgetCompliance: this.checkBudgetCompliance(),
|
|
678
|
+
config: this.config,
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
// ============================================================================
|
|
684
|
+
// CONTEXT WINDOW MANAGER
|
|
685
|
+
// ============================================================================
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* Higher-level context window management
|
|
689
|
+
* Uses MCCA engine underneath
|
|
690
|
+
*/
|
|
691
|
+
export class ContextWindowManager {
|
|
692
|
+
private mcca: MCCAEngine;
|
|
693
|
+
private maxTokens: number;
|
|
694
|
+
|
|
695
|
+
constructor(mcca: MCCAEngine, maxTokens: number = 100000) {
|
|
696
|
+
this.mcca = mcca;
|
|
697
|
+
this.maxTokens = maxTokens;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* Add system prompt
|
|
702
|
+
*/
|
|
703
|
+
async addSystemPrompt(content: string, tokens: number): Promise<ManifoldFragment> {
|
|
704
|
+
return this.mcca.addFragment({
|
|
705
|
+
content,
|
|
706
|
+
source_class: 'system',
|
|
707
|
+
region: 'core',
|
|
708
|
+
token_count: tokens,
|
|
709
|
+
influence: 0.3, // High influence for system
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
/**
|
|
714
|
+
* Add user message
|
|
715
|
+
*/
|
|
716
|
+
async addUserMessage(content: string, tokens: number): Promise<ManifoldFragment> {
|
|
717
|
+
return this.mcca.addFragment({
|
|
718
|
+
content,
|
|
719
|
+
source_class: 'user',
|
|
720
|
+
region: 'task',
|
|
721
|
+
token_count: tokens,
|
|
722
|
+
});
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
/**
|
|
726
|
+
* Add agent response
|
|
727
|
+
*/
|
|
728
|
+
async addAgentResponse(content: string, tokens: number): Promise<ManifoldFragment> {
|
|
729
|
+
return this.mcca.addFragment({
|
|
730
|
+
content,
|
|
731
|
+
source_class: 'agent',
|
|
732
|
+
region: 'history',
|
|
733
|
+
token_count: tokens,
|
|
734
|
+
});
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
/**
|
|
738
|
+
* Add tool output
|
|
739
|
+
*/
|
|
740
|
+
async addToolOutput(content: unknown, tokens: number): Promise<ManifoldFragment> {
|
|
741
|
+
return this.mcca.addFragment({
|
|
742
|
+
content,
|
|
743
|
+
source_class: 'tool',
|
|
744
|
+
region: 'task',
|
|
745
|
+
token_count: tokens,
|
|
746
|
+
});
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/**
|
|
750
|
+
* Add retrieved memory
|
|
751
|
+
*/
|
|
752
|
+
async addMemory(content: unknown, tokens: number): Promise<ManifoldFragment> {
|
|
753
|
+
return this.mcca.addFragment({
|
|
754
|
+
content,
|
|
755
|
+
source_class: 'memory',
|
|
756
|
+
region: 'reference',
|
|
757
|
+
token_count: tokens,
|
|
758
|
+
});
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
/**
|
|
762
|
+
* Get context health
|
|
763
|
+
*/
|
|
764
|
+
async getHealth(): Promise<{
|
|
765
|
+
healthy: boolean;
|
|
766
|
+
drift: DriftAnalysis;
|
|
767
|
+
utilization: number;
|
|
768
|
+
}> {
|
|
769
|
+
const state = this.mcca.getState();
|
|
770
|
+
const drift = await this.mcca.analyzeDrift();
|
|
771
|
+
|
|
772
|
+
return {
|
|
773
|
+
healthy: drift.severity === 'none' || drift.severity === 'low',
|
|
774
|
+
drift,
|
|
775
|
+
utilization: state.totalTokens / this.maxTokens,
|
|
776
|
+
};
|
|
777
|
+
}
|
|
778
|
+
}
|