@llblab/pi-state-flow 0.2.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/skills.ts CHANGED
@@ -1,4 +1,14 @@
1
- import { isObject, type JsonObject } from "./json.ts";
1
+ import { readFileSync } from "node:fs";
2
+ import {
3
+ hashArtifactSource,
4
+ isArtifactHash,
5
+ type ArtifactMetadata,
6
+ type ArtifactRegistry,
7
+ } from "./artifact.ts";
8
+ import { canonicalJson, isObject, type JsonObject, type JsonValue } from "./json.ts";
9
+ import type { MaterializedState } from "./state.ts";
10
+
11
+ export const SKILL_ARTIFACT_COMPILER = "skill-artifact-v1";
2
12
 
3
13
  function hasContent(value: unknown): boolean {
4
14
  if (typeof value === "string") return value.trim().length > 0;
@@ -7,9 +17,70 @@ function hasContent(value: unknown): boolean {
7
17
  return value !== undefined && value !== null;
8
18
  }
9
19
 
10
- export function hasCompiledSkill(contract: JsonObject, source: string): boolean {
11
- if (!isObject(contract.compiled_skills)) return false;
12
- return hasContent(contract.compiled_skills[source]);
20
+ export function hasCompiledSkillArtifact(
21
+ artifacts: ArtifactRegistry,
22
+ source: string,
23
+ expectedHash?: string,
24
+ ): boolean {
25
+ const metadata = artifacts[source];
26
+ return isObject(metadata)
27
+ && metadata.kind === "skill"
28
+ && metadata.compiler === SKILL_ARTIFACT_COMPILER
29
+ && (expectedHash === undefined || metadata.hash === expectedHash)
30
+ && isObject(metadata.compilation)
31
+ && hasContent(metadata.compilation);
32
+ }
33
+
34
+ export type SkillSourceHasher = (source: string) => string;
35
+
36
+ export function hashSkillSource(source: string): string {
37
+ return hashArtifactSource(readFileSync(source));
38
+ }
39
+
40
+ function legacyCompilation(value: JsonValue): JsonObject | undefined {
41
+ if (!hasContent(value)) return undefined;
42
+ return isObject(value) ? structuredClone(value) : { value: structuredClone(value) };
43
+ }
44
+
45
+ /** Move the retired contract store into source-addressed Skill artifacts. */
46
+ export function migrateLegacySkillCompilations(
47
+ state: MaterializedState,
48
+ hasher: SkillSourceHasher = hashSkillSource,
49
+ ): MaterializedState {
50
+ if (!isObject(state.contract.compiled_skills)) return structuredClone(state);
51
+ const legacy = state.contract.compiled_skills;
52
+ const next = structuredClone(state);
53
+ delete next.contract.compiled_skills;
54
+ for (const [source, value] of Object.entries(legacy)) {
55
+ const compilation = legacyCompilation(value);
56
+ if (!compilation) continue;
57
+ let hash: string;
58
+ let verified = true;
59
+ try {
60
+ hash = hasher(source);
61
+ if (!isArtifactHash(hash)) throw new Error("invalid source hash");
62
+ } catch {
63
+ // Preserve useful legacy behavior while ensuring a later observable source
64
+ // identity normally invalidates this explicitly unverified fallback.
65
+ hash = hashArtifactSource(canonicalJson({ source, compilation }));
66
+ verified = false;
67
+ }
68
+ const metadata: ArtifactMetadata = {
69
+ description: `Compiled operational guidance for the Skill at ${source}`,
70
+ hash,
71
+ compiler: SKILL_ARTIFACT_COMPILER,
72
+ kind: "skill",
73
+ compilation,
74
+ ...(verified ? {} : { source_hash_verified: false }),
75
+ };
76
+ Object.defineProperty(next.artifacts, source, {
77
+ value: metadata,
78
+ enumerable: true,
79
+ configurable: true,
80
+ writable: true,
81
+ });
82
+ }
83
+ return next;
13
84
  }
14
85
 
15
86
  export function skillPathFromRead(toolName: unknown, args: unknown): string | undefined {
@@ -17,15 +88,26 @@ export function skillPathFromRead(toolName: unknown, args: unknown): string | un
17
88
  return /(^|[\\/])SKILL\.md$/.test(args.path) ? args.path : undefined;
18
89
  }
19
90
 
91
+ export interface SuccessfulSkillRead {
92
+ path: string;
93
+ hash?: string;
94
+ error?: string;
95
+ }
96
+
20
97
  interface PendingRead {
21
98
  toolName: string;
22
99
  args: unknown;
23
100
  }
24
101
 
25
- /** Correlates Pi's mutable tool lifecycle without exposing runtime event objects. */
102
+ /** Correlates Pi's mutable tool lifecycle and captures trusted source identity. */
26
103
  export class SkillReadTracker {
27
- readonly successful = new Set<string>();
104
+ readonly successful = new Map<string, SuccessfulSkillRead>();
28
105
  readonly #pending = new Map<string, PendingRead>();
106
+ readonly hashSource: SkillSourceHasher;
107
+
108
+ constructor(hashSource: SkillSourceHasher = hashSkillSource) {
109
+ this.hashSource = hashSource;
110
+ }
29
111
 
30
112
  clear(): void {
31
113
  this.successful.clear();
@@ -45,7 +127,17 @@ export class SkillReadTracker {
45
127
  this.#pending.delete(toolCallId);
46
128
  if (isError || !pending || toolName !== pending.toolName) return;
47
129
  const source = skillPathFromRead(pending.toolName, pending.args);
48
- if (source) this.successful.add(source);
130
+ if (!source) return;
131
+ try {
132
+ const hash = this.hashSource(source);
133
+ if (!isArtifactHash(hash)) throw new Error("hasher returned a non-canonical SHA-256 identity");
134
+ this.successful.set(source, { path: source, hash });
135
+ } catch (error) {
136
+ this.successful.set(source, {
137
+ path: source,
138
+ error: error instanceof Error ? error.message : String(error),
139
+ });
140
+ }
49
141
  }
50
142
 
51
143
  #record(toolCallId: string, toolName: string, args: unknown): void {
package/lib/snapshot.ts CHANGED
@@ -1,18 +1,139 @@
1
- import { applyPatch, containsNull, isJsonValue, isObject, type JsonObject } from "./json.ts";
2
- import { emptyState, isStateDocument, type StateDocument } from "./state.ts";
1
+ import { resolve } from "node:path";
2
+ import { RECENT_TRANSITION_LIMIT } from "./history.ts";
3
+ import { applyPatch, canonicalJson, containsNull, isJsonValue, isObject, type JsonObject } from "./json.ts";
4
+ import { validateTemporalLineage, type TransitionBoundary } from "./temporal.ts";
5
+ import { migrateLegacySkillCompilations } from "./skills.ts";
6
+ import { isMaterializedState, type MaterializedState } from "./state.ts";
3
7
  import { MAX_VALIDATION_RETRIES, type ValidationFeedback } from "./validation.ts";
4
8
 
5
9
  const MAX_RESTORED_STEP = Number.MAX_SAFE_INTEGER - 1;
6
10
 
7
- export interface Snapshot {
11
+ /** Missing operational capability is not evidence that a checkpoint target is invalid. */
12
+ export class RevisionUnavailableError extends Error {}
13
+
14
+ export interface SnapshotConfig {
8
15
  enabled: boolean;
9
- specification?: string;
10
- state: StateDocument;
16
+ transitionWindow: number;
17
+ }
18
+
19
+ export interface PendingPublicationState {
20
+ commit: string;
21
+ error: string;
22
+ }
23
+
24
+ export interface SnapshotMeta {
25
+ durableBase?: string;
26
+ pendingPublication?: PendingPublicationState;
11
27
  step: number;
28
+ specification?: string;
12
29
  validation?: ValidationFeedback;
13
30
  bootstrap?: boolean;
14
31
  }
15
32
 
33
+ export interface LegacySessionMigration {
34
+ state: MaterializedState;
35
+ }
36
+
37
+ /** In-memory runtime config/provenance; durable config/meta and scope files own restoration. */
38
+ export interface StateFlowSnapshot {
39
+ config: SnapshotConfig;
40
+ meta: SnapshotMeta;
41
+ /** Ephemeral one-way migration payload. persistSnapshot() never writes it to Pi checkpoints. */
42
+ legacySession?: LegacySessionMigration;
43
+ }
44
+
45
+ export type Snapshot = StateFlowSnapshot;
46
+
47
+ export interface SessionRuntime {
48
+ config: SnapshotConfig;
49
+ meta: Omit<SnapshotMeta, "durableBase" | "pendingPublication"> & {
50
+ version: 1;
51
+ identity: { cwd: string; sessionId: string };
52
+ lineage: TransitionBoundary[];
53
+ /** Resolved against the commit that last wrote this runtime record, not arbitrary HEAD. */
54
+ revision: "self";
55
+ temporalRevision?: "self" | string;
56
+ /** Durable intent survives a crash before the push result can be observed. */
57
+ publication: "unconfirmed" | "files";
58
+ };
59
+ }
60
+
61
+ export function validateSessionRuntime(value: unknown, cwd: string, sessionId: string): asserts value is SessionRuntime {
62
+ if (!isJsonValue(value) || !isObject(value) || Object.keys(value).sort().join(",") !== "config,meta"
63
+ || !isObject(value.config) || !isObject(value.meta)) throw new Error("Invalid State Flow session runtime envelope");
64
+ const { version, identity, lineage, revision, temporalRevision, publication, ...fields } = value.meta;
65
+ if (temporalRevision !== undefined && temporalRevision !== "self"
66
+ && !isExactRevision(temporalRevision)) throw new Error("Invalid temporal revision reference");
67
+ if (version !== 1 || revision !== "self" || (publication !== "unconfirmed" && publication !== "files")) throw new Error("Unsupported State Flow runtime provenance format");
68
+ if (publication === "files" && temporalRevision !== undefined && temporalRevision !== "self") throw new Error("File runtime cannot select a historical temporal revision");
69
+ if (!isObject(identity) || Object.keys(identity).sort().join(",") !== "cwd,sessionId"
70
+ || identity.cwd !== resolve(cwd) || identity.sessionId !== sessionId || sessionId.trim().length === 0 || sessionId !== sessionId.trim()) {
71
+ throw new Error("State Flow runtime scope identity mismatch");
72
+ }
73
+ validateTemporalLineage(lineage);
74
+ const allowed = new Set(["step", "specification", "validation", "bootstrap"]);
75
+ if (Object.keys(fields).some((key) => !allowed.has(key))) throw new Error("Unexpected State Flow runtime metadata field");
76
+ const normalized = migrateSnapshot({ config: value.config, meta: fields });
77
+ if (fields.bootstrap === false) normalized.meta.bootstrap = false;
78
+ if (fields.step === Number.MAX_SAFE_INTEGER) normalized.meta.step = Number.MAX_SAFE_INTEGER;
79
+ if (canonicalJson({ config: normalized.config, meta: normalized.meta }) !== canonicalJson({ config: value.config, meta: fields })) {
80
+ throw new Error("Invalid State Flow runtime configuration or counters");
81
+ }
82
+ }
83
+
84
+ export function createSessionRuntime(snapshot: Snapshot, cwd: string, sessionId: string, lineage: readonly TransitionBoundary[], publication: SessionRuntime["meta"]["publication"] = "unconfirmed"): SessionRuntime {
85
+ const { durableBase: _base, pendingPublication: _publication, ...fields } = snapshot.meta;
86
+ const runtime: SessionRuntime = {
87
+ config: structuredClone(snapshot.config),
88
+ meta: {
89
+ ...Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined)) as Omit<SnapshotMeta, "durableBase" | "pendingPublication">,
90
+ version: 1,
91
+ identity: { cwd: resolve(cwd), sessionId },
92
+ lineage: structuredClone([...lineage]),
93
+ revision: "self",
94
+ publication,
95
+ },
96
+ };
97
+ validateSessionRuntime(runtime, cwd, sessionId);
98
+ return runtime;
99
+ }
100
+
101
+ export function serializeSessionRuntime(runtime: SessionRuntime, cwd: string, sessionId: string): { config: string; meta: string } {
102
+ validateSessionRuntime(runtime, cwd, sessionId);
103
+ return { config: `${canonicalJson(runtime.config)}\n`, meta: `${canonicalJson(runtime.meta)}\n` };
104
+ }
105
+
106
+ export function parseSessionRuntime(config: string | undefined, meta: string | undefined, cwd: string, sessionId: string): SessionRuntime | undefined {
107
+ if (config === undefined && meta === undefined) return undefined;
108
+ if (config === undefined || meta === undefined) throw new Error("Incomplete State Flow config/meta pair");
109
+ let runtime: unknown;
110
+ try {
111
+ runtime = { config: JSON.parse(config), meta: JSON.parse(meta) };
112
+ } catch {
113
+ throw new Error("State Flow session runtime contains invalid JSON");
114
+ }
115
+ validateSessionRuntime(runtime, cwd, sessionId);
116
+ return runtime;
117
+ }
118
+
119
+ export function resolveSessionRuntime(runtime: SessionRuntime, revision: string): { snapshot: Snapshot; lineage: TransitionBoundary[]; publicationTarget: string } {
120
+ validateSessionRuntime(runtime, runtime.meta.identity.cwd, runtime.meta.identity.sessionId);
121
+ if (!isExactRevision(revision) || runtime.meta.publication !== "unconfirmed") throw new Error("Runtime self reference requires its exact Git revision and Git publication provenance");
122
+ const { version: _version, identity: _identity, lineage, revision: _self, temporalRevision: _temporal, publication: _intent, ...fields } = runtime.meta;
123
+ return {
124
+ snapshot: { config: structuredClone(runtime.config), meta: { ...structuredClone(fields), durableBase: revision } },
125
+ lineage: structuredClone(lineage),
126
+ publicationTarget: revision,
127
+ };
128
+ }
129
+
130
+ export function resolveFileSessionRuntime(runtime: SessionRuntime, revision: string): Snapshot {
131
+ validateSessionRuntime(runtime, runtime.meta.identity.cwd, runtime.meta.identity.sessionId);
132
+ if (!isFileRevision(revision) || runtime.meta.publication !== "files") throw new Error("File runtime requires its exact file revision and file publication provenance");
133
+ const { version: _version, identity: _identity, lineage: _lineage, revision: _self, temporalRevision: _temporal, publication: _intent, ...fields } = runtime.meta;
134
+ return { config: structuredClone(runtime.config), meta: { ...structuredClone(fields), durableBase: revision } };
135
+ }
136
+
16
137
  function isLegacyTwoPartState(value: unknown): value is { contract: JsonObject; working: JsonObject } {
17
138
  return isObject(value)
18
139
  && isObject(value.contract)
@@ -20,6 +141,14 @@ function isLegacyTwoPartState(value: unknown): value is { contract: JsonObject;
20
141
  && Object.keys(value).every((key) => key === "contract" || key === "working");
21
142
  }
22
143
 
144
+ function isLegacyThreePartState(value: unknown): value is { contract: JsonObject; working: JsonObject; response: string } {
145
+ return isObject(value)
146
+ && isObject(value.contract)
147
+ && isObject(value.working)
148
+ && typeof value.response === "string"
149
+ && Object.keys(value).every((key) => key === "contract" || key === "working" || key === "response");
150
+ }
151
+
23
152
  function restoredStep(value: unknown): number {
24
153
  return typeof value === "number"
25
154
  && Number.isSafeInteger(value)
@@ -43,61 +172,178 @@ function restoredValidation(value: unknown): ValidationFeedback | undefined {
43
172
  };
44
173
  }
45
174
 
46
- export function migrationFailure(data: JsonObject, error: string): Snapshot {
175
+ function restoredTransitionWindow(value: unknown): number {
176
+ return Number.isSafeInteger(value)
177
+ && (value as number) >= 0
178
+ && (value as number) <= RECENT_TRANSITION_LIMIT
179
+ ? value as number
180
+ : RECENT_TRANSITION_LIMIT;
181
+ }
182
+
183
+ function restoredPendingPublication(value: unknown): PendingPublicationState | undefined {
184
+ if (!isObject(value)
185
+ || typeof value.commit !== "string"
186
+ || !/^[0-9a-f]{40,64}$/.test(value.commit)
187
+ || typeof value.error !== "string"
188
+ || value.error.trim().length === 0) return undefined;
189
+ return { commit: value.commit, error: value.error };
190
+ }
191
+
192
+ function restoredMeta(value: unknown, legacy: JsonObject = {}): SnapshotMeta {
193
+ const meta = isObject(value) ? value : legacy;
194
+ const pendingPublication = restoredPendingPublication(meta.pendingPublication);
195
+ const validation = restoredValidation(meta.validation);
47
196
  return {
48
- enabled: false,
49
- specification: typeof data.specification === "string" ? data.specification : undefined,
50
- state: emptyState(),
51
- step: restoredStep(data.step),
52
- validation: {
53
- attempt: 0,
54
- error,
55
- instruction: "Start a fresh State Flow episode; null is reserved for patch deletion.",
56
- },
197
+ ...(isDurableRevision(meta.durableBase)
198
+ ? { durableBase: meta.durableBase }
199
+ : {}),
200
+ ...(pendingPublication === undefined ? {} : { pendingPublication }),
201
+ step: restoredStep(meta.step),
202
+ ...(typeof meta.specification === "string" ? { specification: meta.specification } : {}),
203
+ ...(validation === undefined ? {} : { validation }),
204
+ ...(meta.bootstrap === true ? { bootstrap: true } : {}),
57
205
  };
58
206
  }
59
207
 
60
- export function migrateSnapshot(value: unknown): Snapshot {
61
- if (!isObject(value)) return { enabled: false, state: emptyState(), step: 0 };
62
- const base = {
63
- enabled: value.enabled === true,
64
- specification: typeof value.specification === "string" ? value.specification : undefined,
65
- step: restoredStep(value.step),
66
- validation: restoredValidation(value.validation),
67
- bootstrap: value.bootstrap === true,
208
+ function envelope(
209
+ enabled: boolean,
210
+ meta: SnapshotMeta,
211
+ transitionWindow = RECENT_TRANSITION_LIMIT,
212
+ legacySession?: LegacySessionMigration,
213
+ ): Snapshot {
214
+ return {
215
+ config: { enabled, transitionWindow },
216
+ meta,
217
+ ...(legacySession === undefined ? {} : { legacySession }),
218
+ };
219
+ }
220
+
221
+ export function emptySnapshot(enabled = false): Snapshot {
222
+ return envelope(enabled, { step: 0 });
223
+ }
224
+
225
+ export type PiCheckpoint = { revision: string } | { disabled: true };
226
+ export type FileRevision = `file:${string}`;
227
+
228
+ export function isFileRevision(value: unknown): value is FileRevision {
229
+ return typeof value === "string" && /^file:[0-9a-f]{64}$/.test(value);
230
+ }
231
+
232
+ export function isDurableRevision(value: unknown): value is string {
233
+ return isExactRevision(value) || isFileRevision(value);
234
+ }
235
+
236
+ export function isExactRevision(value: unknown): value is string {
237
+ return typeof value === "string" && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(value);
238
+ }
239
+
240
+ export function persistableSnapshot(snapshot: Snapshot): PiCheckpoint {
241
+ if (snapshot.meta.durableBase !== undefined) {
242
+ if (!isDurableRevision(snapshot.meta.durableBase)) throw new Error("Checkpoint requires an exact Git revision or file reference");
243
+ return { revision: snapshot.meta.durableBase };
244
+ }
245
+ if (snapshot.legacySession) throw new Error("Legacy semantic state requires migration before checkpoint publication");
246
+ if (snapshot.config.enabled) throw new Error("Enabled checkpoint requires a durable runtime revision");
247
+ return { disabled: true };
248
+ }
249
+
250
+ /** New wire shapes are strict; predecessor envelopes remain one-way migration input. */
251
+ export function parsePiCheckpoint(value: unknown): PiCheckpoint | Snapshot {
252
+ if (!isObject(value)) throw new Error("Invalid State Flow checkpoint");
253
+ if (Object.hasOwn(value, "revision") || Object.hasOwn(value, "disabled")) {
254
+ if (Object.keys(value).length === 1) {
255
+ if (isDurableRevision(value.revision)) return { revision: value.revision };
256
+ if (value.disabled === true) return { disabled: true };
257
+ }
258
+ throw new Error("Invalid State Flow checkpoint pointer or disabled marker");
259
+ }
260
+ if (!Object.hasOwn(value, "config") && !Object.hasOwn(value, "enabled")) throw new Error("Unrecognized State Flow checkpoint");
261
+ const config = Object.hasOwn(value, "config") ? value.config : value;
262
+ if (!isObject(config) || typeof config.enabled !== "boolean") throw new Error("Invalid legacy State Flow configuration");
263
+ if (Object.hasOwn(value, "meta") && !isObject(value.meta)) throw new Error("Invalid legacy State Flow metadata");
264
+ const meta = isObject(value.meta) ? value.meta : value;
265
+ if (Object.hasOwn(meta, "durableBase") && !isDurableRevision(meta.durableBase)) throw new Error("Invalid legacy State Flow revision");
266
+ return migrateSnapshot(value);
267
+ }
268
+
269
+ export function migrationFailure(data: JsonObject, error: string): Snapshot {
270
+ const meta = restoredMeta(data.meta, data);
271
+ meta.validation = {
272
+ attempt: 0,
273
+ error,
274
+ instruction: "Start a fresh State Flow episode; null is reserved for patch deletion.",
68
275
  };
69
- if (isStateDocument(value.state)) {
276
+ const config = isObject(data.config) ? data.config : data;
277
+ return envelope(false, meta, restoredTransitionWindow(config.transitionWindow));
278
+ }
279
+
280
+ function migratedSnapshot(
281
+ enabled: boolean,
282
+ meta: SnapshotMeta,
283
+ transitionWindow: number,
284
+ state: MaterializedState,
285
+ ): Snapshot {
286
+ return envelope(enabled, meta, transitionWindow, {
287
+ state: migrateLegacySkillCompilations(state),
288
+ });
289
+ }
290
+
291
+ export function migrateSnapshot(value: unknown): Snapshot {
292
+ if (!isObject(value)) return emptySnapshot();
293
+ const isEnvelope = Object.hasOwn(value, "config") || Object.hasOwn(value, "meta");
294
+ const config = isEnvelope && isObject(value.config) ? value.config : value;
295
+ const meta = restoredMeta(isEnvelope ? value.meta : undefined, value);
296
+ const enabled = config.enabled === true;
297
+ const transitionWindow = restoredTransitionWindow(config.transitionWindow);
298
+ if (isMaterializedState(value.state)) {
299
+ if (!isJsonValue(value.state)) return migrationFailure(value, "Restored state contains non-JSON data");
300
+ if (containsNull(value.state)) return migrationFailure(value, "Restored state contains null data");
301
+ return migratedSnapshot(enabled, meta, transitionWindow, structuredClone(value.state));
302
+ }
303
+ if (isLegacyThreePartState(value.state)) {
70
304
  if (!isJsonValue(value.state)) return migrationFailure(value, "Restored state contains non-JSON data");
71
305
  if (containsNull(value.state)) return migrationFailure(value, "Restored state contains null data");
72
- return { ...base, state: structuredClone(value.state) };
306
+ return migratedSnapshot(enabled, meta, transitionWindow, {
307
+ artifacts: {},
308
+ ...structuredClone(value.state),
309
+ });
73
310
  }
74
311
  if (isLegacyTwoPartState(value.state)) {
75
312
  if (!isJsonValue(value.state)) return migrationFailure(value, "Restored state contains non-JSON data");
76
313
  if (containsNull(value.state)) return migrationFailure(value, "Restored state contains null data");
77
- return {
78
- ...base,
79
- state: {
80
- contract: structuredClone(value.state.contract),
81
- working: structuredClone(value.state.working),
82
- response: "",
83
- },
84
- };
314
+ return migratedSnapshot(enabled, meta, transitionWindow, {
315
+ artifacts: {},
316
+ contract: structuredClone(value.state.contract),
317
+ working: structuredClone(value.state.working),
318
+ response: "",
319
+ });
85
320
  }
86
- if (isObject(value.state)
87
- && (Object.hasOwn(value.state, "response")
88
- || (Object.hasOwn(value.state, "contract") && Object.hasOwn(value.state, "working")))) {
89
- return migrationFailure(value, "Restored state has an invalid materialized-state schema");
321
+ if (Object.hasOwn(value, "state")) {
322
+ if (isObject(value.state)
323
+ && (Object.hasOwn(value.state, "response")
324
+ || Object.hasOwn(value.state, "artifacts")
325
+ || (Object.hasOwn(value.state, "contract") && Object.hasOwn(value.state, "working")))) {
326
+ return migrationFailure(value, "Restored state has an invalid materialized-state schema");
327
+ }
328
+ if (value.state !== undefined && !isObject(value.state)) {
329
+ return migrationFailure(value, "Restored state has an invalid materialized-state schema");
330
+ }
90
331
  }
91
- const legacyBasis = isObject(value.stateBasis)
92
- ? value.stateBasis
93
- : isObject(value.state)
94
- ? value.state
95
- : {};
96
- const legacyPatch = isObject(value.previousStatePatch) ? value.previousStatePatch : undefined;
97
- if (!isJsonValue(legacyBasis) || (legacyPatch !== undefined && !isJsonValue(legacyPatch))) {
98
- return migrationFailure(value, "Legacy state contains non-JSON data");
332
+ if (Object.hasOwn(value, "stateBasis") || Object.hasOwn(value, "previousStatePatch")) {
333
+ const legacyBasis = isObject(value.stateBasis)
334
+ ? value.stateBasis
335
+ : isObject(value.state)
336
+ ? value.state
337
+ : {};
338
+ const legacyPatch = isObject(value.previousStatePatch) ? value.previousStatePatch : undefined;
339
+ if (!isJsonValue(legacyBasis) || (legacyPatch !== undefined && !isJsonValue(legacyPatch))) {
340
+ return migrationFailure(value, "Legacy state contains non-JSON data");
341
+ }
342
+ const legacyState = legacyPatch === undefined ? legacyBasis : applyPatch(legacyBasis, legacyPatch);
343
+ if (containsNull(legacyState)) return migrationFailure(value, "Legacy state contains null data");
344
+ return migratedSnapshot(enabled, meta, transitionWindow, {
345
+ artifacts: {}, contract: {}, working: structuredClone(legacyState), response: "",
346
+ });
99
347
  }
100
- const legacyState = legacyPatch === undefined ? legacyBasis : applyPatch(legacyBasis, legacyPatch);
101
- if (containsNull(legacyState)) return migrationFailure(value, "Legacy state contains null data");
102
- return { ...base, state: { contract: {}, working: structuredClone(legacyState), response: "" } };
348
+ return envelope(enabled, meta, transitionWindow);
103
349
  }
package/lib/state.ts CHANGED
@@ -1,20 +1,87 @@
1
- import { isObject, type JsonObject } from "./json.ts";
1
+ import {
2
+ isArtifactRegistry,
3
+ updateArtifactRegistry,
4
+ type ArtifactCompilationUpdate,
5
+ type ArtifactRegistry,
6
+ } from "./artifact.ts";
7
+ import { applyPatch, isObject, type JsonObject } from "./json.ts";
2
8
 
3
- /** The only materialized memory shape persisted between State Flow runs. */
4
- export interface StateDocument extends JsonObject {
9
+ /** The canonical semantic state shape shared by global, CWD, and session scopes. */
10
+ export interface MaterializedState extends JsonObject {
11
+ artifacts: ArtifactRegistry;
5
12
  contract: JsonObject;
6
13
  working: JsonObject;
7
14
  response: string;
8
15
  }
9
16
 
10
- export function emptyState(): StateDocument {
11
- return { contract: {}, working: {}, response: "" };
17
+ /** Compatibility name for callers that still treat materialized state as a document. */
18
+ export type StateDocument = MaterializedState;
19
+
20
+ /** Model patch shape; artifact entries may be compiler outputs before trusted metadata is attached. */
21
+ export interface StatePatch extends JsonObject {
22
+ artifacts: JsonObject;
23
+ contract: JsonObject;
24
+ working: JsonObject;
25
+ response: string;
26
+ }
27
+
28
+ export type StateScope = "global" | "cwd" | "session";
29
+
30
+ /** A model-authored patch for one scope. Response is captured by the runtime in session state. */
31
+ export interface ScopePatch {
32
+ artifacts?: JsonObject;
33
+ contract?: JsonObject;
34
+ working?: JsonObject;
35
+ }
36
+
37
+ export interface ScopedPatch {
38
+ scope: StateScope;
39
+ patch: ScopePatch;
12
40
  }
13
41
 
14
- export function isStateDocument(value: unknown): value is StateDocument {
42
+ export interface SemanticTransition {
43
+ transitions: ScopedPatch[];
44
+ }
45
+
46
+ export interface TerminalTransition extends SemanticTransition {
47
+ response: string;
48
+ }
49
+
50
+ export interface ScopedStates {
51
+ global: MaterializedState;
52
+ cwd: MaterializedState;
53
+ session: MaterializedState;
54
+ }
55
+
56
+ export function emptyState(): MaterializedState {
57
+ return { artifacts: {}, contract: {}, working: {}, response: "" };
58
+ }
59
+
60
+ export function isMaterializedState(value: unknown): value is MaterializedState {
15
61
  return isObject(value)
62
+ && isArtifactRegistry(value.artifacts)
16
63
  && isObject(value.contract)
17
64
  && isObject(value.working)
18
65
  && typeof value.response === "string"
19
- && Object.keys(value).every((key) => key === "contract" || key === "working" || key === "response");
66
+ && Object.keys(value).every((key) => key === "artifacts" || key === "contract" || key === "working" || key === "response");
67
+ }
68
+
69
+ export const isStateDocument = isMaterializedState;
70
+
71
+ /** Atomically replace compiled and removed artifacts inside one materialized scope. */
72
+ export function updateMaterializedArtifacts(
73
+ state: MaterializedState,
74
+ updates: readonly ArtifactCompilationUpdate[],
75
+ removed: readonly string[] = [],
76
+ ): MaterializedState {
77
+ if (!isMaterializedState(state)) throw new Error("Cannot update artifacts in an invalid materialized state");
78
+ const artifacts = updateArtifactRegistry(state.artifacts, updates, removed);
79
+ return { ...structuredClone(state), artifacts };
80
+ }
81
+
82
+ /** Overlay lower-to-higher scopes without mutating any scope document. */
83
+ export function overlayStates(...scopes: readonly MaterializedState[]): MaterializedState {
84
+ return scopes.reduce<MaterializedState>((effective, scope) => {
85
+ return applyPatch(effective, scope) as MaterializedState;
86
+ }, emptyState());
20
87
  }