File size: 7,189 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
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
import fs from "node:fs/promises";
import path from "node:path";
import type { SkynetContinuityState } from "./continuity-tracker.js";
import type { SkynetExperimentPlan } from "./experiment-cycle.js";
import type { SkynetNucleusState } from "./nucleus.js";
import type { SkynetStudyProgram } from "./study-program.js";

export type SkynetCommitmentKind = "artifact" | "reframe" | "stabilize";
export type SkynetArtifactKind = "module" | "benchmark" | "note";

export type SkynetCommitmentDecision = {
  sessionKey: string;
  updatedAt: number;
  projectName: string;
  kind: SkynetCommitmentKind;
  artifactKind: SkynetArtifactKind;
  targetFocusKey: string;
  chosenWorkItemId?: string;
  chosenWorkItemTitle?: string;
  rationale: string;
  executableTask: string;
  confidence: number;
};

function clamp01(value: number): number {
  return Math.max(0, Math.min(1, value));
}

function sanitizeSessionKey(sessionKey: string): string {
  return (sessionKey.trim() || "main").replace(/[^a-zA-Z0-9._-]+/g, "_").slice(0, 64) || "main";
}

function resolveCommitmentJsonPath(params: { workspaceRoot: string; sessionKey: string }): string {
  return path.join(
    params.workspaceRoot,
    ".openskynet",
    "skynet-commitment",
    `${sanitizeSessionKey(params.sessionKey)}.json`,
  );
}

function resolveCommitmentMarkdownPath(workspaceRoot: string): string {
  return path.join(workspaceRoot, "memory", "SKYNET_COMMITMENT.md");
}

function buildArtifactTask(params: {
  projectName: string;
  focusKey: string;
  itemTitle?: string;
  experiment: SkynetExperimentPlan;
}): string {
  if (params.focusKey === "endogenous_science_agenda") {
    return `Implement one executable ${params.projectName} study artifact that can be validated in the next cycle.`;
  }
  return params.itemTitle
    ? `Implement or update the artifact implied by: ${params.itemTitle}.`
    : `Implement the active experiment deliverable: ${params.experiment.deliverable}`;
}

function buildReframeTask(params: {
  itemTitle?: string;
  experiment: SkynetExperimentPlan;
}): string {
  return params.itemTitle
    ? `Produce a new framing for ${params.itemTitle} that changes the next cycle's target or execution route.`
    : `Produce a new framing for the active experiment: ${params.experiment.hypothesis}`;
}

function buildStabilityTask(params: {
  continuity?: SkynetContinuityState;
  experiment: SkynetExperimentPlan;
}): string {
  return `Stabilize continuity before expansion; preserve focus and artifact carry-over above ${
    typeof params.continuity?.continuityScore === "number"
      ? params.continuity.continuityScore.toFixed(2)
      : "current"
  } while preparing the active experiment.`;
}

export function deriveSkynetCommitmentDecision(params: {
  sessionKey: string;
  nucleus: SkynetNucleusState;
  program: SkynetStudyProgram;
  experiment: SkynetExperimentPlan;
  continuity?: SkynetContinuityState;
}): SkynetCommitmentDecision {
  const topItem = params.program.items[0];
  const lowContinuity = (params.continuity?.continuityScore ?? 1) < 0.55;
  const mode = params.nucleus.mode;

  if (lowContinuity || mode === "stabilize") {
    return {
      sessionKey: params.sessionKey,
      updatedAt: Date.now(),
      projectName: params.nucleus.name,
      kind: "stabilize",
      artifactKind: "benchmark",
      targetFocusKey: params.program.focusKey,
      chosenWorkItemId: topItem?.id,
      chosenWorkItemTitle: topItem?.title,
      rationale:
        "Continuity is too weak for aggressive expansion; the next cycle should preserve structure and measure carry-over first.",
      executableTask: buildStabilityTask({
        continuity: params.continuity,
        experiment: params.experiment,
      }),
      confidence: clamp01(0.66 + (0.55 - (params.continuity?.continuityScore ?? 0.55)) * 0.4),
    };
  }

  if (mode === "reframe") {
    return {
      sessionKey: params.sessionKey,
      updatedAt: Date.now(),
      projectName: params.nucleus.name,
      kind: "reframe",
      artifactKind: "note",
      targetFocusKey: params.program.focusKey,
      chosenWorkItemId: topItem?.id,
      chosenWorkItemTitle: topItem?.title,
      rationale:
        "The nucleus is signaling reframe pressure; the next concrete artifact should change plan shape before more execution.",
      executableTask: buildReframeTask({
        itemTitle: topItem?.title,
        experiment: params.experiment,
      }),
      confidence: clamp01(params.nucleus.executive.commitment * 0.95),
    };
  }

  return {
    sessionKey: params.sessionKey,
    updatedAt: Date.now(),
    projectName: params.nucleus.name,
    kind: "artifact",
    artifactKind: params.program.focusKey === "endogenous_science_agenda" ? "module" : "benchmark",
    targetFocusKey: params.program.focusKey,
    chosenWorkItemId: topItem?.id,
    chosenWorkItemTitle: topItem?.title,
    rationale:
      "Continuity is strong enough to commit to a concrete artifact instead of another planning-only cycle.",
    executableTask: buildArtifactTask({
      projectName: params.nucleus.name,
      focusKey: params.program.focusKey,
      itemTitle: topItem?.title,
      experiment: params.experiment,
    }),
    confidence: clamp01(
      params.nucleus.executive.commitment * 0.72 +
        (params.continuity?.continuityScore ?? 0.7) * 0.28,
    ),
  };
}

function buildCommitmentMarkdown(decision: SkynetCommitmentDecision): string {
  return [
    `# ${decision.projectName.toUpperCase()} Commitment`,
    "",
    `Updated: ${new Date(decision.updatedAt).toISOString()}`,
    `Session: ${decision.sessionKey}`,
    `Kind: ${decision.kind}`,
    `Artifact kind: ${decision.artifactKind}`,
    `Focus: ${decision.targetFocusKey}`,
    `Confidence: ${decision.confidence.toFixed(2)}`,
    "",
    "## Rationale",
    "",
    decision.rationale,
    "",
    "## Executable Task",
    "",
    decision.executableTask,
    "",
  ].join("\n");
}

export async function syncSkynetCommitmentDecision(params: {
  workspaceRoot: string;
  sessionKey: string;
  nucleus: SkynetNucleusState;
  program: SkynetStudyProgram;
  experiment: SkynetExperimentPlan;
  continuity?: SkynetContinuityState;
}): Promise<SkynetCommitmentDecision> {
  const decision = deriveSkynetCommitmentDecision(params);
  const jsonPath = resolveCommitmentJsonPath({
    workspaceRoot: params.workspaceRoot,
    sessionKey: params.sessionKey,
  });
  const markdownPath = resolveCommitmentMarkdownPath(params.workspaceRoot);
  await fs.mkdir(path.dirname(jsonPath), { recursive: true });
  await fs.mkdir(path.dirname(markdownPath), { recursive: true });
  await fs.writeFile(jsonPath, JSON.stringify(decision, null, 2) + "\n", "utf-8");
  await fs.writeFile(markdownPath, buildCommitmentMarkdown(decision), "utf-8");
  return decision;
}

export function formatSkynetCommitmentBlock(decision?: SkynetCommitmentDecision): string[] {
  if (!decision) {
    return [];
  }
  return [
    "",
    `[${decision.projectName} Commitment]`,
    `Kind: ${decision.kind} | artifact ${decision.artifactKind} | confidence ${decision.confidence.toFixed(2)}`,
    `Rationale: ${decision.rationale}`,
    `Executable task: ${decision.executableTask}`,
  ];
}