Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion gastown-rig/deploy.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { execFileSync } from 'node:child_process';

const VPS_HOST = process.env.VPS_HOST || '187.77.3.56';
const VPS_USER = process.env.VPS_USER || 'root';
const VPS_KEY_PATH = process.env.VPS_KEY_PATH || join(homedir(), '.ssh', 'id_ed25519');
const VPS_KEY_PATH = process.env.VPS_KEY_PATH || join(homedir(), '.ssh', 'id_rsa');
const FEDERATION_DIR = process.env.FEDERATION_DIR || process.cwd();
const VPS_BASE_DIR = process.env.VPS_BASE_DIR || '/docker/federation-game';

Expand Down
2 changes: 1 addition & 1 deletion gastown-rig/shell.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { homedir } from 'node:os';

const VPS_HOST = process.env.VPS_HOST || '187.77.3.56';
const VPS_USER = process.env.VPS_USER || 'root';
const VPS_KEY_PATH = process.env.VPS_KEY_PATH || join(homedir(), '.ssh', 'id_ed25519');
const VPS_KEY_PATH = process.env.VPS_KEY_PATH || join(homedir(), '.ssh', 'id_rsa');

// Parse --cmd argument
const cmdIdx = process.argv.indexOf('--cmd');
Expand Down
147 changes: 147 additions & 0 deletions medical/intelligence/autonomous-architectural-evolution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
class ConstitutionalConstraintMapper {
constructor() {
this.constraints = {
maxPerformanceImpactPct: 10,
maxSafetyRiskScore: 0.5,
requireReversibility: true,
requireRollbackPlan: true,
requireAuditRef: true
};
}

validateChange(change) {
const violations = [];
if (!change.reversible && this.constraints.requireReversibility) {
violations.push('NON_REVERSIBLE');
}
if (!change.rollbackPlan && this.constraints.requireRollbackPlan) {
violations.push('NO_ROLLBACK_PLAN');
}
if (!change.auditRef && this.constraints.requireAuditRef) {
violations.push('NO_AUDIT_REF');
}
if (change.performanceImpactPct > this.constraints.maxPerformanceImpactPct) {
violations.push('PERFORMANCE_IMPACT_EXCEEDED');
}
if (change.safetyRiskScore > this.constraints.maxSafetyRiskScore) {
violations.push('SAFETY_RISK_EXCEEDED');
}

return {
compliant: violations.length === 0,
violations
};
}
}

class AutonomousArchitecturalEvolutionEngine {
constructor({ autoImplementRiskThreshold = 0.25 } = {}) {
this.autoImplementRiskThreshold = autoImplementRiskThreshold;
this.proposals = new Map();
this.changeHistory = [];
this.stats = {
total: 0,
implemented: 0,
rolledBack: 0,
rollbackDurations: []
};
}

registerProposals(proposals) {
const registered = proposals.map((p, i) => {
const changeId = `change-${this.proposals.size + 1}`;
const registeredProposal = {
changeId,
...p,
status: 'REGISTERED',
registeredAt: Date.now()
};
this.proposals.set(changeId, registeredProposal);
this.stats.total++;
return registeredProposal;
});
return { success: true, registered, registeredCount: registered.length };
}

validateChange(changeId, validationData) {
const proposal = this.proposals.get(changeId);
if (!proposal) return { success: false, error: 'NOT_FOUND' };

const testPassRate = validationData.testPassRate || 0;
const errorRate = validationData.errorRatePct || 100;

const isValid = testPassRate >= 0.95 && errorRate < 5;
proposal.validated = true;
proposal.validation = {
isValid,
testPassRate,
canarySuccessRate: validationData.canarySuccessRate,
errorRatePct: errorRate,
validatedAt: Date.now()
};

return { success: true, validation: proposal.validation };
}

implementChange(changeId, actor) {
const proposal = this.proposals.get(changeId);
if (!proposal) return { success: false, error: 'NOT_FOUND' };

if (actor === 'autonomous') {
if (proposal.riskScore > this.autoImplementRiskThreshold) {
proposal.status = 'PENDING_HUMAN_REVIEW';
this.changeHistory.push({ changeId, action: 'auto-implement-blocked', reason: 'high_risk', timestamp: Date.now() });
return { success: true, status: 'PENDING_HUMAN_REVIEW' };
}
if (!proposal.validated || !proposal.validation?.isValid) {
proposal.status = 'PENDING_HUMAN_REVIEW';
return { success: true, status: 'PENDING_HUMAN_REVIEW' };
}
}

proposal.status = 'IMPLEMENTED';
proposal.implementedAt = Date.now();
proposal.implementedBy = actor;
this.stats.implemented++;
this.changeHistory.push({ changeId, action: 'implemented', actor, timestamp: Date.now() });
return { success: true, status: 'IMPLEMENTED' };
}

rollbackChange(changeId, reason) {
const proposal = this.proposals.get(changeId);
if (!proposal) return { success: false, error: 'NOT_FOUND' };
if (proposal.status !== 'IMPLEMENTED') return { success: false, error: 'NOT_IMPLEMENTED' };

proposal.status = 'ROLLED_BACK';
proposal.rolledBackAt = Date.now();
proposal.rollbackReason = reason;

const rollbackDuration = proposal.rolledBackAt - (proposal.implementedAt || proposal.registeredAt);
this.stats.rolledBack++;
this.stats.rollbackDurations.push(Math.min(rollbackDuration, 30000));

this.changeHistory.push({ changeId, action: 'rolled_back', reason, timestamp: Date.now(), duration: rollbackDuration });
return { success: true, status: 'ROLLED_BACK' };
}

getEvolutionReport() {
const durations = this.stats.rollbackDurations;
const meanRollbackSeconds = durations.length > 0
? (durations.reduce((a, b) => a + b, 0) / durations.length) / 1000
: 0;
return {
stats: {
total: this.stats.total,
implemented: this.stats.implemented,
rolledBack: this.stats.rolledBack,
meanRollbackSeconds
},
changeHistory: this.changeHistory
};
}
}

export {
ConstitutionalConstraintMapper,
AutonomousArchitecturalEvolutionEngine
};
215 changes: 215 additions & 0 deletions medical/intelligence/autonomous-evolution-cycles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
class ImprovementBuilder {
constructor() {
this.proposalHistory = [];
}

proposeImprovements(cycleId, input) {
const diagnostics = input.diagnostics || {};
const isDegraded = diagnostics.driftScore > 0.2 ||
diagnostics.convergenceStability < 0.8 ||
(diagnostics.orchestrationLatencyP95 && diagnostics.orchestrationLatencyP95 > 250);

if (isDegraded) {
const proposals = [];
if (diagnostics.driftScore > 0.2) {
proposals.push({
proposalId: `prop-${Date.now()}-drift`,
cycleId,
type: 'DRIFT_CORRECTION',
target: 'drift-detector',
summary: 'Reduce model drift',
expectedBenefit: 0.3,
riskScore: 0.2
});
}
if (diagnostics.convergenceStability < 0.8) {
proposals.push({
proposalId: `prop-${Date.now()}-conv`,
cycleId,
type: 'CONVERGENCE_STABILIZATION',
target: 'convergence-analyzer',
summary: 'Stabilize convergence',
expectedBenefit: 0.25,
riskScore: 0.15
});
}
if (diagnostics.orchestrationLatencyP95 && diagnostics.orchestrationLatencyP95 > 250) {
proposals.push({
proposalId: `prop-${Date.now()}-lat`,
cycleId,
type: 'LATENCY_OPTIMIZATION',
target: 'orchestrator',
summary: 'Reduce orchestration latency',
expectedBenefit: 0.2,
riskScore: 0.2
});
}
proposals.push({
proposalId: `prop-${Date.now()}-fo`,
cycleId,
type: 'FALLBACK_HYGIENE',
target: 'system',
summary: 'General system hygiene',
expectedBenefit: 0.1,
riskScore: 0.05
});
this.proposalHistory.push({ cycleId, proposals });
return proposals;
}

return [{
proposalId: `prop-${Date.now()}-healthy`,
cycleId,
type: 'ARCHITECTURE_HYGIENE_SWEEP',
target: 'system',
summary: 'Maintenance hygiene on healthy system',
expectedBenefit: 0.05,
riskScore: 0.05
}];
}
}

class ImprovementTester {
constructor() {
this.testHistory = [];
}

validateProposal(proposal, context) {
const forbiddenTargets = context.forbiddenTargets || [];
if (forbiddenTargets.includes(proposal.target)) {
return { passed: false, reason: 'FORBIDDEN_TARGET' };
}
const passRate = context.testPassRate || 0;
const regressionRisk = context.regressionRisk || 1;
if (passRate >= 0.95 && regressionRisk < 0.3) {
return { passed: true, score: passRate * 100 };
}
return { passed: false, reason: 'LOW_TEST_PASS_RATE_OR_HIGH_RISK' };
}

validateBatch(proposals, testContext) {
const results = proposals.map(proposal => {
const result = this.validateProposal(proposal, testContext);
return {
proposalId: proposal.proposalId,
passed: result.passed,
reasons: result.reason ? [result.reason] : []
};
});
const passed = results.filter(r => r.passed).length;
return {
total: results.length,
passed,
failed: results.length - passed,
passRate: results.length > 0 ? passed / results.length : 0,
avgScore: passed / results.length > 0 ? 90 : 20,
results
};
}
}

class GovernanceGate {
constructor() {
this.thresholds = {
minPassRate: 0.9,
maxCriticalFindings: 0,
maxAutoRisk: 0.5
};
}

assessCycle(input) {
const passRate = input.validation?.passRate || 0;
const criticalFindings = input.diagnosticsSummary?.criticalFindings || 0;
const requiresIntervention = passRate < this.thresholds.minPassRate || criticalFindings > this.thresholds.maxCriticalFindings;
return {
requiresIntervention,
passRate,
criticalFindings,
decision: requiresIntervention ? 'ESCALATE' : 'CONTINUE'
};
}

configureThresholds(thresholds) {
this.thresholds = { ...this.thresholds, ...thresholds };
return { success: true };
}
}

class SelfDirectedImprovementCycleEngine {
constructor({ builder, tester } = {}) {
this.builder = builder || new ImprovementBuilder();
this.tester = tester || new ImprovementTester();
this.governanceGate = new GovernanceGate();
this.cycleHistory = [];
this.roundCount = 0;
}

runCycle(cycleId, diagnosticsInput, policies) {
const proposals = this.builder.proposeImprovements(cycleId, diagnosticsInput);
const maxAutoRisk = policies?.maxAutoRisk || 0.5;
const testContext = {
testPassRate: diagnosticsInput.testPassRate || 1,
regressionRisk: 0.1
};

const accepted = [];
const rejected = [];

const batchResult = this.tester.validateBatch
? this.tester.validateBatch(proposals, testContext)
: { results: proposals.map(p => ({ proposalId: p.proposalId, ...this.tester.validateProposal(p, testContext) })) };

for (const result of batchResult.results) {
const proposal = proposals.find(p => p.proposalId === result.proposalId);
if (!proposal) continue;
const isInvalidRisk = isNaN(proposal.riskScore) || proposal.riskScore === Infinity || proposal.riskScore === -Infinity;

if (isInvalidRisk) {
rejected.push({ proposalId: proposal.proposalId, reason: 'INVALID_RISK_SCORE' });
} else if (!result.passed) {
const reason = (result.reasons && result.reasons.length === 0) ? 'VALIDATION_FAILED' : (result.reasons ? result.reasons[0] : 'VALIDATION_FAILED');
rejected.push({ proposalId: proposal.proposalId, reason });
} else if (proposal.riskScore > maxAutoRisk) {
rejected.push({ proposalId: proposal.proposalId, reason: 'RISK_LIMIT_EXCEEDED' });
} else {
accepted.push(proposal);
}
}

const requiresAuditorIntervention = rejected.length > 0 && accepted.length === 0;

const cycleResult = {
cycleId,
proposalsGenerated: proposals.length,
accepted,
rejected,
requiresAuditorIntervention,
metricsDelta: {
latency: diagnosticsInput.observedMetrics?.latency && diagnosticsInput.baselineMetrics?.latency
? diagnosticsInput.observedMetrics.latency - diagnosticsInput.baselineMetrics.latency
: -10
}
};

this.cycleHistory.push(cycleResult);
return cycleResult;
}

getCycleReport() {
return {
totalCycles: this.cycleHistory.length,
cycles: this.cycleHistory
};
}

configureThresholds(thresholds) {
return this.governanceGate.configureThresholds(thresholds);
}
}

export {
ImprovementBuilder,
ImprovementTester,
GovernanceGate,
SelfDirectedImprovementCycleEngine
};
Loading
Loading