File size: 6,075 Bytes
fc93158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import crypto from "node:crypto";
import fs from "node:fs/promises";
import path from "node:path";
import { loadOmegaDurableMemory } from "./durable-memory.js";
import {
  observeOmegaExecutiveState,
  type OmegaExecutiveObserverSnapshot,
} from "./executive-arbitration.js";
import {
  deriveOmegaExecutiveDispatchPlan,
  deriveNextOmegaExecutiveDispatchAccounting,
  type OmegaExecutiveDispatchAccounting,
  type OmegaExecutiveDispatchPlan,
} from "./executive-runtime.js";
import {
  summarizeOmegaMemoryOrchestration,
  type OmegaMemoryOrchestratorSummary,
} from "./memory-orchestrator.js";
import { loadOmegaOperationalMemory } from "./operational-memory.js";
import type { OmegaSessionAuthority } from "./session-context.js";
import { withOmegaSessionLock } from "./state-lock.js";
import { loadOmegaWorldModelSnapshot, type OmegaWorldModelSnapshot } from "./world-model.js";

export type OmegaExecutiveState = {
  sessionKey: string;
  revision?: number;
  updatedAt: number;
  syncFingerprint?: string;
  sourceSessionAuthority?: OmegaSessionAuthority;
  sourceWorldSnapshot?: OmegaWorldModelSnapshot;
  observer: OmegaExecutiveObserverSnapshot;
  memory: OmegaMemoryOrchestratorSummary;
  runtime: {
    lastSyncedAt: number;
    dispatchPlan: OmegaExecutiveDispatchPlan;
    dispatchAccounting: OmegaExecutiveDispatchAccounting;
  };
};

function sanitizeSessionKey(sessionKey: string): string {
  const normalized = sessionKey.trim() || "main";
  const readable = normalized.replace(/[^a-zA-Z0-9._-]+/g, "_").slice(0, 48) || "main";
  const digest = crypto.createHash("sha256").update(normalized).digest("hex").slice(0, 12);
  return `${readable}-${digest}.json`;
}

function resolveOmegaExecutiveStateDir(workspaceRoot: string): string {
  return path.join(workspaceRoot, ".openskynet", "omega-executive-state");
}

export function resolveOmegaExecutiveStateFile(params: {
  workspaceRoot: string;
  sessionKey: string;
}): string {
  return path.join(
    resolveOmegaExecutiveStateDir(params.workspaceRoot),
    sanitizeSessionKey(params.sessionKey),
  );
}

async function readOmegaExecutiveStateFile(params: {
  workspaceRoot: string;
  sessionKey: string;
}): Promise<OmegaExecutiveState | undefined> {
  try {
    const raw = await fs.readFile(resolveOmegaExecutiveStateFile(params), "utf-8");
    return JSON.parse(raw) as OmegaExecutiveState;
  } catch {
    return undefined;
  }
}

export async function loadOmegaExecutiveState(params: {
  workspaceRoot: string;
  sessionKey: string;
}): Promise<OmegaExecutiveState | undefined> {
  const existing = await readOmegaExecutiveStateFile(params);
  if (existing) {
    return existing;
  }
  return await syncOmegaExecutiveObserverState(params);
}

function buildExecutiveSyncFingerprint(params: {
  snapshot: Awaited<ReturnType<typeof loadOmegaWorldModelSnapshot>>;
  memory: OmegaMemoryOrchestratorSummary;
}): string {
  return crypto
    .createHash("sha256")
    .update(
      JSON.stringify({
        kernelUpdatedAt: params.snapshot.kernel?.updatedAt ?? 0,
        activeGoalTask: params.snapshot.activeGoalTask,
        timelineLength: params.snapshot.timelineLength,
        selfStateUpdatedAt: params.snapshot.selfState?.updatedAt ?? 0,
        activeRecoveryPreference: params.snapshot.activeRecoveryPreference,
        generalizedRecoveryPreference: params.snapshot.generalizedRecoveryPreference,
        problemAgenda: params.snapshot.problemAgenda.map((item) => ({
          classKey: item.classKey,
          status: item.status,
          priority: item.priority,
          realizedUtility: item.realizedUtility,
          activationCount: item.activationCount,
          successCount: item.successCount,
          failureCount: item.failureCount,
        })),
        memory: params.memory,
      }),
    )
    .digest("hex");
}

export async function syncOmegaExecutiveObserverState(
  params: {
    workspaceRoot: string;
    sessionKey: string;
  },
  skipHeavySync?: boolean,
): Promise<OmegaExecutiveState> {
  const existing = await readOmegaExecutiveStateFile(params);
  if (skipHeavySync && existing) {
    return existing;
  }
  const snapshot = await loadOmegaWorldModelSnapshot(params);
  const durableMemory = await loadOmegaDurableMemory(params);
  const operationalSignals = await loadOmegaOperationalMemory(params);
  const memory = summarizeOmegaMemoryOrchestration({
    durableMemory,
    operationalSignals,
  });
  const syncFingerprint = buildExecutiveSyncFingerprint({ snapshot, memory });

  let nextState: OmegaExecutiveState | undefined;
  await withOmegaSessionLock(params, async () => {
    const existing = await readOmegaExecutiveStateFile(params);
    if (existing?.syncFingerprint === syncFingerprint) {
      nextState = existing;
      return;
    }
    const observer = observeOmegaExecutiveState({
      snapshot,
      memory,
    });
    const dispatchPlan = deriveOmegaExecutiveDispatchPlan({
      observer,
      previousAccounting: existing?.runtime.dispatchAccounting,
    });
    const dispatchAccounting = deriveNextOmegaExecutiveDispatchAccounting({
      previousAccounting: existing?.runtime.dispatchAccounting,
      plan: dispatchPlan,
    });
    const now = Date.now();
    nextState = {
      sessionKey: params.sessionKey,
      revision: (existing?.revision ?? 0) + 1,
      updatedAt: now,
      syncFingerprint,
      sourceSessionAuthority: {
        timeline: snapshot.sessionAuthority.timeline,
        state: snapshot.sessionAuthority.state,
        kernel: snapshot.sessionAuthority.kernel,
        transactions: snapshot.sessionAuthority.transactions,
      },
      sourceWorldSnapshot: snapshot,
      observer,
      memory,
      runtime: {
        lastSyncedAt: now,
        dispatchPlan,
        dispatchAccounting,
      },
    };
    await fs.mkdir(resolveOmegaExecutiveStateDir(params.workspaceRoot), { recursive: true });
    await fs.writeFile(
      resolveOmegaExecutiveStateFile(params),
      `${JSON.stringify(nextState, null, 2)}\n`,
      "utf-8",
    );
  });

  return nextState as OmegaExecutiveState;
}