File size: 7,871 Bytes
ee36b84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
export interface VenusState {
  cycle: number;
  day_in_cycle: number;
  accumulated_drift: number;
  total_rows_emitted: number;
  corrections_applied: number;
}

export interface DresdenSimConfig {
  cycle_days: number;
  drift_per_cycle: number;
  warning_threshold: number;
  hard_threshold: number;
  rows_to_emit: number;
}

export const DRESDEN_DEFAULT_CONFIG: DresdenSimConfig = {
  cycle_days: 584,
  drift_per_cycle: 0,
  warning_threshold: 4,
  hard_threshold: 8,
  rows_to_emit: 8,
};

export const DRESDEN_INITIAL_STATE: VenusState = {
  cycle: 0,
  day_in_cycle: 0,
  accumulated_drift: 0,
  total_rows_emitted: 0,
  corrections_applied: 0,
};

export interface ValidatorResult {
  name: string;
  severity: 'pass' | 'soft_fail' | 'hard_fail';
  summary: string;
}

export interface DecisionReceipt {
  summary: string;
  decision_type: string;
  policy_version: string;
  approval_status: string;
  mocked: boolean;
  assumptions: string[];
  evidence: Array<{ kind: string; ref: string; mocked: boolean }>;
}

export interface TraceEvent {
  step: number;
  pipeline_stage: string;
  state_prev_hash: string;
  state_next_hash: string;
  validator_results: ValidatorResult[];
  decision_receipt: DecisionReceipt | null;
}

export interface KernelRunResult<S> {
  summary: {
    status: string;
    steps_executed: number;
    hard_stop_failures: number;
    soft_failures: number;
    stop_reason: string | null;
    final_state_hash: string;
  };
  trace: TraceEvent[];
  final_state: S;
}

function simpleHash(str: string): string {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    const char = str.charCodeAt(i);
    hash = ((hash << 5) - hash) + char;
    hash = hash & hash;
  }
  return Math.abs(hash).toString(16).padStart(8, '0').slice(0, 8);
}

function fullHash(state: unknown): string {
  const s = JSON.stringify(state);
  const h = simpleHash(s);
  return (h + h + h + h + h + h + h + h).slice(0, 64);
}

interface DresdenStep {
  name: string;
  pipeline_stage: string;
  apply: (state: VenusState, cfg: DresdenSimConfig) => VenusState;
  validators: Array<{
    name: string;
    check: (prev: VenusState, next: VenusState, cfg: DresdenSimConfig) => ValidatorResult;
  }>;
}

export function dresdenSteps(cfg: DresdenSimConfig): DresdenStep[] {
  return [
    {
      name: 'emit_rows',
      pipeline_stage: 'ingest',
      apply: (s) => ({ ...s, total_rows_emitted: s.total_rows_emitted + cfg.rows_to_emit }),
      validators: [
        {
          name: 'row_count',
          check: (_p, n) => ({
            name: 'row_count',
            severity: n.total_rows_emitted > 0 ? 'pass' : 'soft_fail',
            summary: `${n.total_rows_emitted} rows emitted`,
          }),
        },
      ],
    },
    {
      name: 'advance_cycle',
      pipeline_stage: 'transform',
      apply: (s) => ({
        ...s,
        cycle: s.cycle + 1,
        day_in_cycle: (s.day_in_cycle + cfg.cycle_days) % 365,
        accumulated_drift: s.accumulated_drift + cfg.drift_per_cycle,
      }),
      validators: [
        {
          name: 'drift_warn',
          check: (_p, n) => ({
            name: 'drift_warn',
            severity:
              Math.abs(n.accumulated_drift) > cfg.hard_threshold
                ? 'hard_fail'
                : Math.abs(n.accumulated_drift) > cfg.warning_threshold
                  ? 'soft_fail'
                  : 'pass',
            summary: `drift=${n.accumulated_drift.toFixed(1)}d`,
          }),
        },
      ],
    },
    {
      name: 'correct_drift',
      pipeline_stage: 'validate',
      apply: (s) => {
        if (Math.abs(s.accumulated_drift) > cfg.warning_threshold) {
          return { ...s, accumulated_drift: s.accumulated_drift * 0.5, corrections_applied: s.corrections_applied + 1 };
        }
        return s;
      },
      validators: [
        {
          name: 'correction_audit',
          check: (p, n) => ({
            name: 'correction_audit',
            severity: 'pass',
            summary: n.corrections_applied > p.corrections_applied ? 'correction applied' : 'no correction needed',
          }),
        },
      ],
    },
  ];
}

export function runLoop<S extends VenusState>(opts: {
  experiment_id: string;
  initial_state: S;
  policy_version: string;
  budgets: { time_budget_ms: number; step_budget: number; retry_budget: number };
  loop_policy: { max_steps: number; adaptive_depth: { enabled: boolean }; entropy_regularized_exit: { enabled: boolean } };
  governance_enabled: boolean;
  steps: DresdenStep[];
}): KernelRunResult<S> {
  const trace: TraceEvent[] = [];
  let state = { ...opts.initial_state } as S;
  let hardFails = 0;
  let softFails = 0;
  let stopReason: string | null = null;
  const maxCycles = Math.min(opts.loop_policy.max_steps, opts.budgets.step_budget);

  for (let cycle = 0; cycle < maxCycles; cycle++) {
    for (const step of opts.steps) {
      const prevHash = fullHash(state);
      const prev = { ...state } as S;
      const next = step.apply(state, DRESDEN_DEFAULT_CONFIG) as S;
      const nextHash = fullHash(next);

      const vResults = opts.governance_enabled
        ? step.validators.map((v) => v.check(prev, next, DRESDEN_DEFAULT_CONFIG))
        : [{ name: 'governance_off', severity: 'pass' as const, summary: 'governance disabled' }];

      const hasHard = vResults.some((v) => v.severity === 'hard_fail');
      const hasSoft = vResults.some((v) => v.severity === 'soft_fail');

      let receipt: DecisionReceipt | null = null;
      if (opts.governance_enabled) {
        receipt = {
          summary: `${step.name}: ${hasHard ? 'BLOCKED' : hasSoft ? 'WARNING' : 'APPROVED'}`,
          decision_type: step.pipeline_stage,
          policy_version: opts.policy_version,
          approval_status: hasHard ? 'blocked' : 'approved',
          mocked: false,
          assumptions: [`cycle=${prev.cycle}`, `drift=${prev.accumulated_drift.toFixed(1)}`],
          evidence: vResults.map((v) => ({ kind: v.name, ref: v.summary, mocked: false })),
        };
      }

      trace.push({
        step: trace.length + 1,
        pipeline_stage: step.pipeline_stage,
        state_prev_hash: prevHash,
        state_next_hash: hasHard && opts.governance_enabled ? prevHash : nextHash,
        validator_results: vResults,
        decision_receipt: receipt,
      });

      if (hasHard && opts.governance_enabled) {
        hardFails++;
        if (hardFails >= 2) {
          stopReason = 'hard_fail_limit';
          state = prev;
          break;
        }
        state = prev;
      } else {
        if (hasSoft) softFails++;
        state = next;
      }
    }

    if (stopReason) break;
  }

  return {
    summary: {
      status: hardFails > 0 ? 'halted' : 'ok',
      steps_executed: trace.length,
      hard_stop_failures: hardFails,
      soft_failures: softFails,
      stop_reason: stopReason,
      final_state_hash: fullHash(state),
    },
    trace,
    final_state: state,
  };
}

export function serializeTraceJsonl(trace: TraceEvent[]): string {
  return trace.map((e) => JSON.stringify(e)).join('\n');
}

export function shortHash(hash: string): string {
  return hash.slice(0, 8);
}

export function replay(
  initialState: VenusState,
  trace: TraceEvent[],
  expectedFinalHash: string,
): { ok: boolean; steps_replayed: number; failed_step: number | null } {
  if (trace.length === 0) return { ok: true, steps_replayed: 0, failed_step: null };

  let prevHash = fullHash(initialState);
  for (let i = 0; i < trace.length; i++) {
    if (trace[i].state_prev_hash !== prevHash) {
      return { ok: false, steps_replayed: i, failed_step: i + 1 };
    }
    prevHash = trace[i].state_next_hash;
  }

  const finalMatch = prevHash === expectedFinalHash;
  return {
    ok: finalMatch,
    steps_replayed: trace.length,
    failed_step: finalMatch ? null : trace.length,
  };
}