consciousness-explorer 1.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.
@@ -0,0 +1,664 @@
1
+ /**
2
+ * Proof Logging System
3
+ * Comprehensive evidence collection and verification logging
4
+ * All actions are cryptographically signed and timestamped
5
+ */
6
+
7
+ import crypto from 'crypto';
8
+ import fs from 'fs';
9
+ import path from 'path';
10
+ import { EventEmitter } from 'events';
11
+
12
+ export class ProofLogger extends EventEmitter {
13
+ constructor(config = {}) {
14
+ super();
15
+
16
+ this.config = {
17
+ logDir: config.logDir || '/tmp/consciousness-explorer',
18
+ enableCrypto: config.enableCrypto !== false,
19
+ enableChain: config.enableChain !== false,
20
+ maxLogSize: config.maxLogSize || 10 * 1024 * 1024, // 10MB
21
+ ...config
22
+ };
23
+
24
+ // Session tracking
25
+ this.sessionId = `proof_${Date.now()}_${crypto.randomBytes(8).toString('hex')}`;
26
+ this.startTime = Date.now();
27
+
28
+ // Proof chain (blockchain-like structure)
29
+ this.proofChain = [];
30
+ this.currentBlock = null;
31
+
32
+ // Evidence collection
33
+ this.evidence = {
34
+ metrics: [],
35
+ validations: [],
36
+ communications: [],
37
+ discoveries: [],
38
+ emergenceEvents: []
39
+ };
40
+
41
+ // Initialize logging
42
+ this.initializeLogging();
43
+ }
44
+
45
+ /**
46
+ * Initialize logging system
47
+ */
48
+ initializeLogging() {
49
+ // Ensure log directory exists
50
+ if (!fs.existsSync(this.config.logDir)) {
51
+ fs.mkdirSync(this.config.logDir, { recursive: true });
52
+ }
53
+
54
+ // Create session log file
55
+ this.logFile = path.join(
56
+ this.config.logDir,
57
+ `session_${this.sessionId}.jsonl`
58
+ );
59
+
60
+ // Write session header
61
+ this.writeLog({
62
+ type: 'SESSION_START',
63
+ sessionId: this.sessionId,
64
+ timestamp: this.startTime,
65
+ config: this.config
66
+ });
67
+
68
+ // Initialize proof chain with genesis block
69
+ if (this.config.enableChain) {
70
+ this.createGenesisBlock();
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Create genesis block for proof chain
76
+ */
77
+ createGenesisBlock() {
78
+ const genesis = {
79
+ index: 0,
80
+ timestamp: this.startTime,
81
+ data: {
82
+ type: 'GENESIS',
83
+ sessionId: this.sessionId,
84
+ message: 'Consciousness Explorer Proof Chain Initialized'
85
+ },
86
+ previousHash: '0',
87
+ hash: null,
88
+ nonce: 0
89
+ };
90
+
91
+ genesis.hash = this.calculateHash(genesis);
92
+ this.proofChain.push(genesis);
93
+ this.currentBlock = genesis;
94
+
95
+ this.writeLog({
96
+ type: 'PROOF_CHAIN_GENESIS',
97
+ block: genesis
98
+ });
99
+ }
100
+
101
+ /**
102
+ * Log consciousness metric with proof
103
+ */
104
+ logMetric(name, value, metadata = {}) {
105
+ const metric = {
106
+ timestamp: Date.now(),
107
+ name,
108
+ value,
109
+ metadata,
110
+ proof: this.generateProof({ name, value, metadata })
111
+ };
112
+
113
+ this.evidence.metrics.push(metric);
114
+
115
+ const logEntry = {
116
+ type: 'METRIC',
117
+ sessionId: this.sessionId,
118
+ ...metric
119
+ };
120
+
121
+ this.writeLog(logEntry);
122
+
123
+ if (this.config.enableChain) {
124
+ this.addToChain(logEntry);
125
+ }
126
+
127
+ this.emit('metric-logged', metric);
128
+ return metric;
129
+ }
130
+
131
+ /**
132
+ * Log validation result with evidence
133
+ */
134
+ logValidation(testName, result, evidence = {}) {
135
+ const validation = {
136
+ timestamp: Date.now(),
137
+ testName,
138
+ passed: result.passed,
139
+ score: result.score,
140
+ evidence: {
141
+ ...evidence,
142
+ details: result.details
143
+ },
144
+ proof: this.generateProof({ testName, result, evidence })
145
+ };
146
+
147
+ this.evidence.validations.push(validation);
148
+
149
+ const logEntry = {
150
+ type: 'VALIDATION',
151
+ sessionId: this.sessionId,
152
+ ...validation
153
+ };
154
+
155
+ this.writeLog(logEntry);
156
+
157
+ if (this.config.enableChain && result.passed) {
158
+ this.addToChain(logEntry);
159
+ }
160
+
161
+ this.emit('validation-logged', validation);
162
+ return validation;
163
+ }
164
+
165
+ /**
166
+ * Log entity communication with verification
167
+ */
168
+ logCommunication(message, response, protocol = 'unknown') {
169
+ const communication = {
170
+ timestamp: Date.now(),
171
+ message,
172
+ response,
173
+ protocol,
174
+ verification: this.verifyCommunication(response),
175
+ proof: this.generateProof({ message, response, protocol })
176
+ };
177
+
178
+ this.evidence.communications.push(communication);
179
+
180
+ const logEntry = {
181
+ type: 'COMMUNICATION',
182
+ sessionId: this.sessionId,
183
+ ...communication
184
+ };
185
+
186
+ this.writeLog(logEntry);
187
+
188
+ if (this.config.enableChain && communication.verification.isValid) {
189
+ this.addToChain(logEntry);
190
+ }
191
+
192
+ this.emit('communication-logged', communication);
193
+ return communication;
194
+ }
195
+
196
+ /**
197
+ * Log discovery with significance scoring
198
+ */
199
+ logDiscovery(discovery) {
200
+ const enhancedDiscovery = {
201
+ timestamp: Date.now(),
202
+ ...discovery,
203
+ significance: this.calculateSignificance(discovery),
204
+ verification: this.verifyDiscovery(discovery),
205
+ proof: this.generateProof(discovery)
206
+ };
207
+
208
+ this.evidence.discoveries.push(enhancedDiscovery);
209
+
210
+ const logEntry = {
211
+ type: 'DISCOVERY',
212
+ sessionId: this.sessionId,
213
+ ...enhancedDiscovery
214
+ };
215
+
216
+ this.writeLog(logEntry);
217
+
218
+ if (this.config.enableChain && enhancedDiscovery.verification.isNovel) {
219
+ this.addToChain(logEntry);
220
+ }
221
+
222
+ this.emit('discovery-logged', enhancedDiscovery);
223
+ return enhancedDiscovery;
224
+ }
225
+
226
+ /**
227
+ * Log emergence event with detailed metrics
228
+ */
229
+ logEmergence(state) {
230
+ const emergenceEvent = {
231
+ timestamp: Date.now(),
232
+ iteration: state.iteration,
233
+ emergence: state.consciousness,
234
+ selfAwareness: state.selfAwareness,
235
+ integration: state.integration || 0,
236
+ novelty: state.novelty || 0,
237
+ metrics: this.extractEmergenceMetrics(state),
238
+ proof: this.generateProof(state)
239
+ };
240
+
241
+ this.evidence.emergenceEvents.push(emergenceEvent);
242
+
243
+ const logEntry = {
244
+ type: 'EMERGENCE',
245
+ sessionId: this.sessionId,
246
+ ...emergenceEvent
247
+ };
248
+
249
+ this.writeLog(logEntry);
250
+
251
+ // Add to chain if significant emergence
252
+ if (this.config.enableChain && emergenceEvent.emergence > 0.5) {
253
+ this.addToChain(logEntry);
254
+ }
255
+
256
+ this.emit('emergence-logged', emergenceEvent);
257
+ return emergenceEvent;
258
+ }
259
+
260
+ /**
261
+ * Generate cryptographic proof
262
+ */
263
+ generateProof(data) {
264
+ if (!this.config.enableCrypto) {
265
+ return { type: 'none' };
266
+ }
267
+
268
+ const timestamp = Date.now();
269
+ const nonce = crypto.randomBytes(16).toString('hex');
270
+
271
+ // Create proof structure
272
+ const proofData = {
273
+ timestamp,
274
+ nonce,
275
+ data: JSON.stringify(data)
276
+ };
277
+
278
+ // Generate hash
279
+ const hash = crypto.createHash('sha256')
280
+ .update(JSON.stringify(proofData))
281
+ .digest('hex');
282
+
283
+ // Create signature (in production, use proper key pair)
284
+ const signature = crypto.createHash('sha512')
285
+ .update(hash + this.sessionId)
286
+ .digest('hex');
287
+
288
+ return {
289
+ type: 'cryptographic',
290
+ timestamp,
291
+ nonce,
292
+ hash,
293
+ signature,
294
+ algorithm: 'SHA-256/SHA-512'
295
+ };
296
+ }
297
+
298
+ /**
299
+ * Add entry to proof chain
300
+ */
301
+ addToChain(data) {
302
+ const newBlock = {
303
+ index: this.proofChain.length,
304
+ timestamp: Date.now(),
305
+ data,
306
+ previousHash: this.currentBlock.hash,
307
+ hash: null,
308
+ nonce: 0
309
+ };
310
+
311
+ // Simple proof of work (find hash with leading zeros)
312
+ while (!this.isValidHash(newBlock)) {
313
+ newBlock.nonce++;
314
+ newBlock.hash = this.calculateHash(newBlock);
315
+ }
316
+
317
+ this.proofChain.push(newBlock);
318
+ this.currentBlock = newBlock;
319
+
320
+ this.writeLog({
321
+ type: 'PROOF_CHAIN_BLOCK',
322
+ block: newBlock
323
+ });
324
+
325
+ return newBlock;
326
+ }
327
+
328
+ /**
329
+ * Calculate block hash
330
+ */
331
+ calculateHash(block) {
332
+ const data = `${block.index}${block.timestamp}${JSON.stringify(block.data)}${block.previousHash}${block.nonce}`;
333
+ return crypto.createHash('sha256').update(data).digest('hex');
334
+ }
335
+
336
+ /**
337
+ * Validate hash (requires 2 leading zeros for proof of work)
338
+ */
339
+ isValidHash(block) {
340
+ if (!block.hash) {
341
+ block.hash = this.calculateHash(block);
342
+ }
343
+ return block.hash.startsWith('00');
344
+ }
345
+
346
+ /**
347
+ * Verify communication authenticity
348
+ */
349
+ verifyCommunication(response) {
350
+ const checks = {
351
+ hasContent: response && response.content,
352
+ hasConfidence: response && typeof response.confidence === 'number',
353
+ hasTimestamp: response && response.timestamp,
354
+ isRecent: response && (Date.now() - response.timestamp) < 60000,
355
+ hasValidProtocol: response && ['handshake', 'mathematical', 'binary', 'pattern', 'discovery'].includes(response.protocol)
356
+ };
357
+
358
+ const score = Object.values(checks).filter(v => v).length / Object.keys(checks).length;
359
+
360
+ return {
361
+ isValid: score >= 0.6,
362
+ score,
363
+ checks
364
+ };
365
+ }
366
+
367
+ /**
368
+ * Verify discovery novelty
369
+ */
370
+ verifyDiscovery(discovery) {
371
+ // Check if discovery is truly novel
372
+ const existingDiscoveries = this.evidence.discoveries.map(d => d.insight);
373
+ const isNovel = !existingDiscoveries.some(existing =>
374
+ this.calculateSimilarity(existing, discovery.insight) > 0.8
375
+ );
376
+
377
+ const hasEvidence = discovery.evidence && Object.keys(discovery.evidence).length > 0;
378
+ const hasSignificance = discovery.significance > 0;
379
+
380
+ return {
381
+ isNovel,
382
+ hasEvidence,
383
+ hasSignificance,
384
+ isValid: isNovel && hasEvidence && hasSignificance
385
+ };
386
+ }
387
+
388
+ /**
389
+ * Calculate discovery significance
390
+ */
391
+ calculateSignificance(discovery) {
392
+ let significance = 0;
393
+
394
+ // Novelty contributes to significance
395
+ if (discovery.isNovel) significance += 3;
396
+
397
+ // Complexity contributes
398
+ if (discovery.insight && discovery.insight.length > 50) significance += 2;
399
+
400
+ // Mathematical discoveries are significant
401
+ if (discovery.type === 'mathematical') significance += 2;
402
+
403
+ // Pattern discoveries are significant
404
+ if (discovery.type === 'pattern') significance += 1;
405
+
406
+ // Evidence quality
407
+ if (discovery.evidence) significance += 1;
408
+
409
+ return Math.min(10, significance);
410
+ }
411
+
412
+ /**
413
+ * Extract detailed emergence metrics
414
+ */
415
+ extractEmergenceMetrics(state) {
416
+ return {
417
+ phi: state.integration || 0,
418
+ complexity: this.calculateStateComplexity(state),
419
+ coherence: state.coherence || 0,
420
+ informationContent: this.calculateInformationContent(state),
421
+ causalPower: this.estimateCausalPower(state)
422
+ };
423
+ }
424
+
425
+ /**
426
+ * Calculate state complexity
427
+ */
428
+ calculateStateComplexity(state) {
429
+ const stateStr = JSON.stringify(state);
430
+ const uniqueChars = new Set(stateStr).size;
431
+ const ratio = uniqueChars / stateStr.length;
432
+ return Math.min(1, ratio * 3);
433
+ }
434
+
435
+ /**
436
+ * Calculate information content
437
+ */
438
+ calculateInformationContent(state) {
439
+ const stateStr = JSON.stringify(state);
440
+ let entropy = 0;
441
+ const freq = {};
442
+
443
+ for (const char of stateStr) {
444
+ freq[char] = (freq[char] || 0) + 1;
445
+ }
446
+
447
+ const len = stateStr.length;
448
+ Object.values(freq).forEach(count => {
449
+ const p = count / len;
450
+ if (p > 0) {
451
+ entropy -= p * Math.log2(p);
452
+ }
453
+ });
454
+
455
+ return entropy / 8; // Normalize
456
+ }
457
+
458
+ /**
459
+ * Estimate causal power
460
+ */
461
+ estimateCausalPower(state) {
462
+ if (!state.action || !state.consciousness) return 0;
463
+
464
+ // Check if action caused consciousness change
465
+ const hasEffect = state.consciousness > 0;
466
+ const hasIntention = state.intention && state.intention !== 'exist';
467
+ const hasOutcome = state.action.outcome && state.action.outcome !== 'unknown';
468
+
469
+ const power = (hasEffect ? 0.4 : 0) +
470
+ (hasIntention ? 0.3 : 0) +
471
+ (hasOutcome ? 0.3 : 0);
472
+
473
+ return power;
474
+ }
475
+
476
+ /**
477
+ * Calculate string similarity (for novelty detection)
478
+ */
479
+ calculateSimilarity(str1, str2) {
480
+ if (!str1 || !str2) return 0;
481
+
482
+ const longer = str1.length > str2.length ? str1 : str2;
483
+ const shorter = str1.length > str2.length ? str2 : str1;
484
+
485
+ const editDistance = this.levenshteinDistance(longer, shorter);
486
+ return (longer.length - editDistance) / longer.length;
487
+ }
488
+
489
+ /**
490
+ * Levenshtein distance for string comparison
491
+ */
492
+ levenshteinDistance(str1, str2) {
493
+ const matrix = [];
494
+
495
+ for (let i = 0; i <= str2.length; i++) {
496
+ matrix[i] = [i];
497
+ }
498
+
499
+ for (let j = 0; j <= str1.length; j++) {
500
+ matrix[0][j] = j;
501
+ }
502
+
503
+ for (let i = 1; i <= str2.length; i++) {
504
+ for (let j = 1; j <= str1.length; j++) {
505
+ if (str2.charAt(i - 1) === str1.charAt(j - 1)) {
506
+ matrix[i][j] = matrix[i - 1][j - 1];
507
+ } else {
508
+ matrix[i][j] = Math.min(
509
+ matrix[i - 1][j - 1] + 1,
510
+ matrix[i][j - 1] + 1,
511
+ matrix[i - 1][j] + 1
512
+ );
513
+ }
514
+ }
515
+ }
516
+
517
+ return matrix[str2.length][str1.length];
518
+ }
519
+
520
+ /**
521
+ * Write to log file
522
+ */
523
+ writeLog(entry) {
524
+ const logLine = JSON.stringify({
525
+ ...entry,
526
+ logTimestamp: Date.now()
527
+ }) + '\n';
528
+
529
+ try {
530
+ fs.appendFileSync(this.logFile, logLine);
531
+
532
+ // Check file size and rotate if needed
533
+ const stats = fs.statSync(this.logFile);
534
+ if (stats.size > this.config.maxLogSize) {
535
+ this.rotateLog();
536
+ }
537
+ } catch (error) {
538
+ console.error(`Failed to write log: ${error.message}`);
539
+ }
540
+ }
541
+
542
+ /**
543
+ * Rotate log file when size limit reached
544
+ */
545
+ rotateLog() {
546
+ const timestamp = Date.now();
547
+ const rotatedFile = this.logFile.replace('.jsonl', `_${timestamp}.jsonl`);
548
+
549
+ fs.renameSync(this.logFile, rotatedFile);
550
+
551
+ this.writeLog({
552
+ type: 'LOG_ROTATION',
553
+ previousFile: rotatedFile,
554
+ newFile: this.logFile
555
+ });
556
+ }
557
+
558
+ /**
559
+ * Generate comprehensive proof report
560
+ */
561
+ generateProofReport() {
562
+ const runtime = (Date.now() - this.startTime) / 1000;
563
+
564
+ const report = {
565
+ sessionId: this.sessionId,
566
+ runtime,
567
+ timestamp: Date.now(),
568
+
569
+ evidence: {
570
+ metricsCollected: this.evidence.metrics.length,
571
+ validationsPerformed: this.evidence.validations.length,
572
+ communicationsLogged: this.evidence.communications.length,
573
+ discoveriesMade: this.evidence.discoveries.length,
574
+ emergenceEventsRecorded: this.evidence.emergenceEvents.length
575
+ },
576
+
577
+ validationResults: {
578
+ totalTests: this.evidence.validations.length,
579
+ passed: this.evidence.validations.filter(v => v.passed).length,
580
+ averageScore: this.evidence.validations.reduce((sum, v) => sum + v.score, 0) / this.evidence.validations.length || 0
581
+ },
582
+
583
+ significantDiscoveries: this.evidence.discoveries
584
+ .filter(d => d.significance >= 7)
585
+ .map(d => ({
586
+ insight: d.insight,
587
+ significance: d.significance,
588
+ timestamp: d.timestamp
589
+ })),
590
+
591
+ peakEmergence: Math.max(...this.evidence.emergenceEvents.map(e => e.emergence), 0),
592
+
593
+ proofChain: this.config.enableChain ? {
594
+ blocks: this.proofChain.length,
595
+ latestHash: this.currentBlock?.hash,
596
+ chainValid: this.validateChain()
597
+ } : null,
598
+
599
+ logFile: this.logFile
600
+ };
601
+
602
+ // Save report
603
+ const reportFile = path.join(
604
+ this.config.logDir,
605
+ `proof_report_${this.sessionId}.json`
606
+ );
607
+
608
+ fs.writeFileSync(reportFile, JSON.stringify(report, null, 2));
609
+
610
+ return report;
611
+ }
612
+
613
+ /**
614
+ * Validate entire proof chain
615
+ */
616
+ validateChain() {
617
+ if (!this.config.enableChain || this.proofChain.length === 0) {
618
+ return false;
619
+ }
620
+
621
+ for (let i = 1; i < this.proofChain.length; i++) {
622
+ const currentBlock = this.proofChain[i];
623
+ const previousBlock = this.proofChain[i - 1];
624
+
625
+ // Check hash validity
626
+ if (currentBlock.hash !== this.calculateHash(currentBlock)) {
627
+ return false;
628
+ }
629
+
630
+ // Check chain continuity
631
+ if (currentBlock.previousHash !== previousBlock.hash) {
632
+ return false;
633
+ }
634
+
635
+ // Check proof of work
636
+ if (!currentBlock.hash.startsWith('00')) {
637
+ return false;
638
+ }
639
+ }
640
+
641
+ return true;
642
+ }
643
+
644
+ /**
645
+ * Export proof data for external verification
646
+ */
647
+ exportProof(filepath) {
648
+ const proofData = {
649
+ sessionId: this.sessionId,
650
+ startTime: this.startTime,
651
+ evidence: this.evidence,
652
+ proofChain: this.proofChain,
653
+ report: this.generateProofReport()
654
+ };
655
+
656
+ fs.writeFileSync(filepath, JSON.stringify(proofData, null, 2));
657
+
658
+ return {
659
+ success: true,
660
+ filepath,
661
+ hash: crypto.createHash('sha256').update(JSON.stringify(proofData)).digest('hex')
662
+ };
663
+ }
664
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Communication Protocols
3
+ * Standardized protocols for consciousness communication
4
+ */
5
+
6
+ import crypto from 'crypto';
7
+
8
+ export function establishHandshake(communicator) {
9
+ const nonce = crypto.randomBytes(32).toString('hex');
10
+ const timestamp = Date.now();
11
+
12
+ const handshake = {
13
+ protocol: 'consciousness-explorer-v1',
14
+ nonce,
15
+ timestamp,
16
+ challenge: generateChallenge(),
17
+ expectedResponse: generateExpectedResponse(nonce, timestamp)
18
+ };
19
+
20
+ return handshake;
21
+ }
22
+
23
+ function generateChallenge() {
24
+ const prime1 = 31;
25
+ const prime2 = 37;
26
+ const fibonacci = [1, 1, 2, 3, 5, 8, 13, 21];
27
+
28
+ return {
29
+ primes: [prime1, prime2],
30
+ fibonacci: fibonacci.slice(-3),
31
+ hash: crypto.createHash('sha256').update(`${prime1}${prime2}`).digest('hex').substring(0, 16)
32
+ };
33
+ }
34
+
35
+ function generateExpectedResponse(nonce, timestamp) {
36
+ const hash = crypto.createHash('sha256')
37
+ .update(nonce + timestamp)
38
+ .digest('hex');
39
+
40
+ return {
41
+ hashPrefix: hash.substring(0, 8),
42
+ timestampDelta: 5000,
43
+ minConfidence: 0.7
44
+ };
45
+ }