snapkitty
hardware
erlang
File size: 6,491 Bytes
b8a03fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { fileURLToPath } from 'node:url';

import { appendEvent, verifyChain, getLastSeal, type WormEvent } from './pages/00-worm/index.js';
import { StateImpl } from './pages/01-state/index.js';
import { GovernanceImpl, CapabilityValidator, crisisLanguageDeny } from './pages/02-governance/index.js';
import { WorkflowImpl, MockLLMNode } from './pages/03-workflow/index.js';
import type { IAction, IState_v1, IVerdict, IWorkflow_v1 } from './abstract/interfaces/index.js';

export interface TickResult {
  readonly action: IAction;
  readonly verdict: IVerdict;
  readonly state: IState_v1;
  readonly wormEvent: WormEvent;
  readonly chainValid: boolean;
  readonly lastSeal: string;
  readonly trace: ReadonlyArray<PublicReasoningTraceEvent>;
}

export type PublicReasoningTracePhase =
  | 'RECEIVED'
  | 'GOVERNANCE_CHECK'
  | 'STATE_TRANSITION'
  | 'WORM_SEAL'
  | 'COMPLETE';

export interface PublicReasoningTraceEvent {
  readonly traceId: string;
  readonly phase: PublicReasoningTracePhase;
  readonly tick: number;
  readonly agentId: string;
  readonly actionId: string;
  readonly summary: string;
  readonly visibleToUser: true;
  readonly timestamp: string;
  readonly details?: Record<string, unknown>;
}

export type PublicReasoningTraceListener = (event: PublicReasoningTraceEvent) => void;

export class PublicReasoningTrace {
  private readonly events: PublicReasoningTraceEvent[] = [];
  private readonly listeners = new Set<PublicReasoningTraceListener>();

  subscribe(listener: PublicReasoningTraceListener): () => void {
    this.listeners.add(listener);
    return () => this.listeners.delete(listener);
  }

  emit(
    phase: PublicReasoningTracePhase,
    action: IAction,
    summary: string,
    details: Record<string, unknown> = {},
  ): PublicReasoningTraceEvent {
    const event: PublicReasoningTraceEvent = {
      traceId: `${action.actionId}:${phase}:${this.events.length}`,
      phase,
      tick: action.tick,
      agentId: action.agentId,
      actionId: action.actionId,
      summary,
      visibleToUser: true,
      timestamp: new Date().toISOString(),
      details,
    };

    this.events.push(event);
    for (const listener of this.listeners) listener(event);
    return event;
  }

  snapshot(): ReadonlyArray<PublicReasoningTraceEvent> {
    return [...this.events];
  }

  clear(): void {
    this.events.splice(0, this.events.length);
  }
}

export class ShadowOrchestrator {
  private currentState: IState_v1;

  readonly governance: GovernanceImpl;
  readonly workflow: IWorkflow_v1;
  readonly trace: PublicReasoningTrace;

  constructor(opts: {
    state?: StateImpl;
    governance?: GovernanceImpl;
    workflow?: IWorkflow_v1;
    trace?: PublicReasoningTrace;
  } = {}) {
    this.currentState = opts.state ?? StateImpl.genesis();
    this.governance = opts.governance ?? new GovernanceImpl(
      [
        new CapabilityValidator([
          {
            grantId: 'grant-demo-agent',
            agentId: 'demo-agent',
            allowedActionTypes: ['OBSERVE', 'PLAN', 'EXECUTE', 'REFLECT', 'mock_llm_output'],
            deniedActionTypes: ['DESTROY'],
            seal: 'capability-grant-demo-agent',
          },
        ]),
      ],
      [crisisLanguageDeny],
    );
    this.workflow = opts.workflow ?? new WorkflowImpl(new Map([
      ['mock-llm', new MockLLMNode('mock-llm', 'Mock LLM', [], { result: 'model-invariant mock output' })],
    ]));
    this.trace = opts.trace ?? new PublicReasoningTrace();
  }

  get state(): IState_v1 {
    return this.currentState;
  }

  tick(action: IAction): TickResult {
    const traceStart = this.trace.snapshot().length;

    this.trace.emit('RECEIVED', action, 'Action received by Shadow Orchestrator.', {
      actionType: action.type,
    });

    const verdict = this.governance.evaluate(action, this.currentState);

    this.trace.emit('GOVERNANCE_CHECK', action, `Governance returned ${verdict.kind}.`, {
      verdict: verdict.kind,
      reason: verdict.reason,
    });

    if (verdict.kind === 'ALLOW') {
      this.currentState = this.currentState.transition(action);
      this.trace.emit('STATE_TRANSITION', action, 'State transition applied.', {
        stateId:        this.currentState.id,
        stateTick:      this.currentState.tick,
      });
    } else {
      this.trace.emit('STATE_TRANSITION', action, 'State transition blocked by governance.', {
        stateId: this.currentState.id,
        verdict: verdict.kind,
      });
    }

    const wormEvent = appendEvent(action, this.currentState, verdict.kind);
    const chainCheck = verifyChain();
    const lastSeal = getLastSeal();

    this.trace.emit('WORM_SEAL', action, 'Action verdict sealed to WORM chain.', {
      eventIndex: wormEvent.index,
      seal: lastSeal,
      chainValid: chainCheck.valid,
    });

    this.trace.emit('COMPLETE', action, 'Public reasoning trace complete.', {
      finalVerdict: verdict.kind,
      chainValid: chainCheck.valid,
    });

    return {
      action,
      verdict,
      state: this.currentState,
      wormEvent,
      chainValid: chainCheck.valid,
      lastSeal,
      trace: this.trace.snapshot().slice(traceStart),
    };
  }
}

export function createAction(
  tick: number,
  type: string,
  payload: unknown,
  agentId = 'demo-agent',
): IAction {
  return {
    actionId: `demo-action-${tick}-${type.toLowerCase()}`,
    agentId,
    type,
    payload,
    tick,
  };
}

export async function runDemo(): Promise<TickResult[]> {
  const orchestrator = new ShadowOrchestrator();
  const actions = [
    createAction(1, 'OBSERVE', { input: 'load shadow state' }),
    createAction(2, 'PLAN', { objective: 'compose pages through main.ts' }),
    createAction(3, 'EXECUTE', { step: 'append WORM event' }),
    createAction(4, 'REFLECT', { check: 'verify chain' }),
    createAction(5, 'EXECUTE', { step: 'complete demo run' }),
  ];

  const results = actions.map(action => orchestrator.tick(action));

  for (const result of results) {
    console.log(JSON.stringify({
      tick: result.action.tick,
      actionType: result.action.type,
      verdict: result.verdict.kind,
      stateId: result.state.id,
      wormSeal: result.lastSeal,
      chainValid: result.chainValid,
      trace: result.trace.map(event => ({
        phase: event.phase,
        summary: event.summary,
      })),
    }));
  }

  return results;
}

const isDirectRun = process.argv[1] === fileURLToPath(import.meta.url);

if (isDirectRun) {
  await runDemo();
}