@llblab/pi-state-flow 0.12.1 → 0.13.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/AGENTS.md +5 -5
- package/BACKLOG.md +8 -9
- package/CHANGELOG.md +8 -0
- package/README.md +0 -2
- package/dist/index.d.ts +21 -0
- package/dist/index.js +20 -0
- package/dist/lib/acquisition.d.ts +39 -0
- package/dist/lib/acquisition.js +78 -0
- package/dist/lib/artifact.d.ts +110 -0
- package/dist/lib/artifact.js +334 -0
- package/dist/lib/compaction.d.ts +42 -0
- package/dist/lib/compaction.js +50 -0
- package/dist/lib/config.d.ts +11 -0
- package/dist/lib/config.js +53 -0
- package/dist/lib/context.d.ts +23 -0
- package/dist/lib/context.js +109 -0
- package/dist/lib/continuation.d.ts +111 -0
- package/dist/lib/continuation.js +189 -0
- package/dist/lib/discovery.d.ts +21 -0
- package/dist/lib/discovery.js +125 -0
- package/dist/lib/durable.d.ts +102 -0
- package/dist/lib/durable.js +507 -0
- package/dist/lib/episode.d.ts +8 -0
- package/dist/lib/episode.js +27 -0
- package/dist/lib/extension.d.ts +22 -0
- package/dist/lib/extension.js +1260 -0
- package/dist/lib/git.d.ts +72 -0
- package/dist/lib/git.js +565 -0
- package/dist/lib/history.d.ts +22 -0
- package/dist/lib/history.js +79 -0
- package/dist/lib/json.d.ts +12 -0
- package/dist/lib/json.js +109 -0
- package/dist/lib/logging.d.ts +25 -0
- package/dist/lib/logging.js +24 -0
- package/dist/lib/maintenance.d.ts +36 -0
- package/dist/lib/maintenance.js +98 -0
- package/dist/lib/memory.d.ts +15 -0
- package/dist/lib/memory.js +42 -0
- package/dist/lib/migration.d.ts +13 -0
- package/dist/lib/migration.js +133 -0
- package/dist/lib/protocol.d.ts +7 -0
- package/dist/lib/protocol.js +59 -0
- package/dist/lib/publication.d.ts +69 -0
- package/dist/lib/publication.js +335 -0
- package/dist/lib/query.d.ts +27 -0
- package/dist/lib/query.js +35 -0
- package/dist/lib/recovery.d.ts +8 -0
- package/dist/lib/recovery.js +27 -0
- package/dist/lib/rehydration.d.ts +36 -0
- package/dist/lib/rehydration.js +38 -0
- package/dist/lib/runtime.d.ts +142 -0
- package/dist/lib/runtime.js +529 -0
- package/dist/lib/session.d.ts +21 -0
- package/dist/lib/session.js +44 -0
- package/dist/lib/skills.d.ts +25 -0
- package/dist/lib/skills.js +131 -0
- package/dist/lib/snapshot.d.ts +88 -0
- package/dist/lib/snapshot.js +255 -0
- package/dist/lib/state.d.ts +55 -0
- package/dist/lib/state.js +31 -0
- package/dist/lib/status.d.ts +38 -0
- package/dist/lib/status.js +79 -0
- package/dist/lib/storage.d.ts +46 -0
- package/dist/lib/storage.js +217 -0
- package/dist/lib/telegram.d.ts +98 -0
- package/dist/lib/telegram.js +231 -0
- package/dist/lib/temporal.d.ts +39 -0
- package/dist/lib/temporal.js +203 -0
- package/dist/lib/transition.d.ts +25 -0
- package/dist/lib/transition.js +204 -0
- package/dist/package.json +79 -0
- package/dist/pi-state-flow/index.js +1 -0
- package/dist/skills/state-flow-memory/SKILL.md +138 -0
- package/docs/architecture.md +3 -3
- package/docs/filesystem-recovery.md +3 -3
- package/docs/usage.md +4 -4
- package/lib/durable.ts +88 -96
- package/lib/extension.ts +24 -10
- package/lib/git.ts +32 -188
- package/lib/migration.ts +84 -48
- package/lib/recovery.ts +7 -30
- package/lib/runtime.ts +48 -50
- package/lib/snapshot.ts +41 -97
- package/lib/storage.ts +17 -12
- package/lib/telegram.ts +4 -4
- package/package.json +20 -5
package/lib/durable.ts
CHANGED
|
@@ -18,22 +18,26 @@ import {
|
|
|
18
18
|
serializeArtifactProvenanceRegistry,
|
|
19
19
|
type ArtifactProvenanceRegistry,
|
|
20
20
|
} from "./artifact.ts";
|
|
21
|
-
import { canonicalJson,
|
|
21
|
+
import { canonicalJson, isJsonValue, isObject } from "./json.ts";
|
|
22
22
|
import { validateScopeStream, validateTemporalState, type ScopeStream, type TemporalState } from "./temporal.ts";
|
|
23
|
-
import
|
|
23
|
+
import type { StateScope } from "./state.ts";
|
|
24
24
|
|
|
25
|
-
const LEGACY_MAX_SCOPE_SLUG_LENGTH = 80;
|
|
26
|
-
const LEGACY_SCOPE_KEY_PATTERN = /^[A-Za-z0-9._-]{1,80}-[a-f0-9]{64}$/;
|
|
27
25
|
const SESSION_KEY_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
|
|
28
26
|
const STATE_FILE = "state.json";
|
|
29
27
|
const CHECKPOINT_FILE = "checkpoint.json";
|
|
30
28
|
const PATCHES_FILE = "patches.jsonl";
|
|
31
29
|
const META_FILE = "meta.json";
|
|
32
30
|
|
|
33
|
-
/** Canonical
|
|
31
|
+
/** Canonical semantic sources plus runtime-owned temporal metadata. */
|
|
34
32
|
export interface ScopeStreamSources {
|
|
35
33
|
checkpoint: string;
|
|
36
34
|
patches: string;
|
|
35
|
+
temporal: ScopeTemporalMetadata;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface ScopeTemporalMetadata {
|
|
39
|
+
checkpoint: ScopeStream["checkpoint"]["through"];
|
|
40
|
+
patches: ScopeStream["patches"][number]["transition"][];
|
|
37
41
|
}
|
|
38
42
|
|
|
39
43
|
export interface SessionAddress {
|
|
@@ -41,17 +45,18 @@ export interface SessionAddress {
|
|
|
41
45
|
readonly key: string;
|
|
42
46
|
}
|
|
43
47
|
|
|
44
|
-
/**
|
|
48
|
+
/** Semantic files contain no runtime envelope; temporal boundaries and CWD ownership live in meta.json. */
|
|
45
49
|
export function serializeScopeStream(stream: ScopeStream, scope: StateScope, cwdIdentity?: string): ScopeStreamSources {
|
|
46
50
|
validateScopeStream(stream, scope);
|
|
47
51
|
if (scope === "cwd" && cwdIdentity === undefined) throw new Error("State Flow CWD scope serialization requires its canonical identity");
|
|
48
52
|
if (scope !== "cwd" && cwdIdentity !== undefined) throw new Error("Only State Flow CWD scope serialization accepts a CWD identity");
|
|
49
|
-
const checkpoint = scope === "cwd"
|
|
50
|
-
? { ...stream.checkpoint, owner: { cwd: resolve(cwdIdentity!) } }
|
|
51
|
-
: stream.checkpoint;
|
|
52
53
|
return {
|
|
53
|
-
checkpoint: `${canonicalJson(checkpoint)}\n`,
|
|
54
|
-
patches: stream.patches.map((record) => `${canonicalJson(record)}\n`).join(""),
|
|
54
|
+
checkpoint: `${canonicalJson(stream.checkpoint.state)}\n`,
|
|
55
|
+
patches: stream.patches.map((record) => `${canonicalJson(record.patch)}\n`).join(""),
|
|
56
|
+
temporal: {
|
|
57
|
+
checkpoint: structuredClone(stream.checkpoint.through),
|
|
58
|
+
patches: stream.patches.map((record) => structuredClone(record.transition)),
|
|
59
|
+
},
|
|
55
60
|
};
|
|
56
61
|
}
|
|
57
62
|
|
|
@@ -65,6 +70,7 @@ export function classifyScopeStream(
|
|
|
65
70
|
patchesSource: string | undefined,
|
|
66
71
|
scope: StateScope,
|
|
67
72
|
expectedCwd?: string,
|
|
73
|
+
metaSource?: string,
|
|
68
74
|
): ScopeStreamPresence {
|
|
69
75
|
if (checkpointSource === undefined && patchesSource === undefined) return { kind: "absent" };
|
|
70
76
|
if (checkpointSource === undefined || patchesSource === undefined) {
|
|
@@ -76,16 +82,11 @@ export function classifyScopeStream(
|
|
|
76
82
|
} catch {
|
|
77
83
|
throw new Error(`State Flow ${scope} checkpoint contains invalid JSON`);
|
|
78
84
|
}
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
}
|
|
85
|
-
if (expectedCwd !== undefined && (owner as { cwd: string }).cwd !== resolve(expectedCwd)) throw new Error("State Flow CWD scope identity mismatch");
|
|
86
|
-
checkpoint = semantic;
|
|
87
|
-
} else if (scope === "cwd" && expectedCwd !== undefined) {
|
|
88
|
-
throw new Error("State Flow CWD scope identity is missing");
|
|
85
|
+
let meta: Record<string, unknown> | undefined;
|
|
86
|
+
if (metaSource !== undefined) {
|
|
87
|
+
try { meta = JSON.parse(metaSource) as Record<string, unknown>; }
|
|
88
|
+
catch { throw new Error(`State Flow ${scope} metadata contains invalid JSON`); }
|
|
89
|
+
if (!isObject(meta)) throw new Error(`Invalid State Flow ${scope} metadata`);
|
|
89
90
|
}
|
|
90
91
|
const patches: unknown[] = [];
|
|
91
92
|
for (const [index, line] of patchesSource.split(/\r?\n/).entries()) {
|
|
@@ -96,7 +97,35 @@ export function classifyScopeStream(
|
|
|
96
97
|
throw new Error(`State Flow ${scope} tail contains invalid JSON at line ${index + 1}`);
|
|
97
98
|
}
|
|
98
99
|
}
|
|
99
|
-
const
|
|
100
|
+
const temporal = meta?.temporal;
|
|
101
|
+
if (isObject(temporal) && Object.hasOwn(temporal, "checkpoint") && Array.isArray(temporal.patches)) {
|
|
102
|
+
const owner = meta?.owner;
|
|
103
|
+
if (scope === "cwd" && expectedCwd !== undefined
|
|
104
|
+
&& (!isObject(owner) || Object.keys(owner).join(",") !== "cwd" || owner.cwd !== resolve(expectedCwd))) {
|
|
105
|
+
throw new Error(owner === undefined ? "State Flow CWD scope identity is missing" : "State Flow CWD scope identity mismatch");
|
|
106
|
+
}
|
|
107
|
+
const boundaries = temporal.patches;
|
|
108
|
+
if (boundaries.length !== patches.length) throw new Error(`State Flow ${scope} temporal metadata does not match its semantic tail`);
|
|
109
|
+
const stream = {
|
|
110
|
+
checkpoint: { through: temporal.checkpoint, state: checkpoint },
|
|
111
|
+
patches: patches.map((patch, index) => ({ transition: boundaries[index], patch })),
|
|
112
|
+
};
|
|
113
|
+
validateScopeStream(stream, scope);
|
|
114
|
+
return { kind: "present", stream };
|
|
115
|
+
}
|
|
116
|
+
// Complete predecessor envelopes are the only no-meta form that may be unwrapped.
|
|
117
|
+
let legacyCheckpoint = checkpoint;
|
|
118
|
+
if (isObject(checkpoint) && Object.hasOwn(checkpoint, "owner")) {
|
|
119
|
+
const { owner, ...semantic } = checkpoint;
|
|
120
|
+
if (scope !== "cwd" || !isObject(owner) || Object.keys(owner).join(",") !== "cwd" || typeof owner.cwd !== "string") {
|
|
121
|
+
throw new Error("Invalid State Flow CWD scope identity");
|
|
122
|
+
}
|
|
123
|
+
if (expectedCwd !== undefined && owner.cwd !== resolve(expectedCwd)) throw new Error("State Flow CWD scope identity mismatch");
|
|
124
|
+
legacyCheckpoint = semantic;
|
|
125
|
+
} else if (scope === "cwd" && expectedCwd !== undefined) {
|
|
126
|
+
throw new Error("State Flow CWD scope identity is missing");
|
|
127
|
+
}
|
|
128
|
+
const stream = { checkpoint: legacyCheckpoint, patches };
|
|
100
129
|
validateScopeStream(stream, scope);
|
|
101
130
|
return { kind: "present", stream };
|
|
102
131
|
}
|
|
@@ -107,8 +136,9 @@ export function parseScopeStream(
|
|
|
107
136
|
patchesSource: string | undefined,
|
|
108
137
|
scope: StateScope,
|
|
109
138
|
expectedCwd?: string,
|
|
139
|
+
metaSource?: string,
|
|
110
140
|
): ScopeStream | undefined {
|
|
111
|
-
const presence = classifyScopeStream(checkpointSource, patchesSource, scope, expectedCwd);
|
|
141
|
+
const presence = classifyScopeStream(checkpointSource, patchesSource, scope, expectedCwd, metaSource);
|
|
112
142
|
return presence.kind === "present" ? presence.stream : undefined;
|
|
113
143
|
}
|
|
114
144
|
|
|
@@ -134,13 +164,13 @@ export function sessionRuntimePaths(cwd: string, sessionId: string, repositoryRo
|
|
|
134
164
|
return { config: join(directory, "config.json"), meta: join(directory, META_FILE) };
|
|
135
165
|
}
|
|
136
166
|
|
|
137
|
-
/**
|
|
167
|
+
/** Unsupported state.json presence never becomes an anchored checkpoint. */
|
|
138
168
|
export function loadScopeStream(cwd: string, sessionId: string, scope: StateScope, repositoryRoot: string, sessionKey = sessionId): ScopeStream | undefined {
|
|
139
169
|
const paths = temporalScopePaths(cwd, sessionId, scope, repositoryRoot, sessionKey);
|
|
140
170
|
if (readRegularBytes(join(paths.directory, STATE_FILE), repositoryRoot) !== undefined) {
|
|
141
171
|
throw new Error(`Legacy State Flow storage requires explicit migration: ${paths.directory}`);
|
|
142
172
|
}
|
|
143
|
-
return parseScopeStream(readRegularFile(paths.checkpoint, repositoryRoot), readRegularFile(paths.patches, repositoryRoot), scope, scope === "cwd" ? cwd : undefined);
|
|
173
|
+
return parseScopeStream(readRegularFile(paths.checkpoint, repositoryRoot), readRegularFile(paths.patches, repositoryRoot), scope, scope === "cwd" ? cwd : undefined, readRegularFile(paths.meta, repositoryRoot));
|
|
144
174
|
}
|
|
145
175
|
|
|
146
176
|
/** Include legacy names in the CAS basis solely to prevent format races during cutover. */
|
|
@@ -182,24 +212,43 @@ export interface DurablePaths {
|
|
|
182
212
|
globalPatches: string;
|
|
183
213
|
}
|
|
184
214
|
|
|
185
|
-
/**
|
|
215
|
+
/** Merge authoritative owned leaves while preserving forward-compatible metadata siblings. */
|
|
216
|
+
export function serializeScopeMetadata(
|
|
217
|
+
registry: Readonly<ArtifactProvenanceRegistry> | undefined, stream: ScopeStream, scope: StateScope,
|
|
218
|
+
cwdIdentity?: string, existingSource?: string,
|
|
219
|
+
): string {
|
|
220
|
+
const existing = parseMetadataDocument(existingSource, `State Flow metadata`);
|
|
221
|
+
const sources = serializeScopeStream(stream, scope, cwdIdentity);
|
|
222
|
+
const value = {
|
|
223
|
+
...existing,
|
|
224
|
+
version: 1,
|
|
225
|
+
...(registry === undefined ? {} : { artifacts: serializeArtifactProvenanceRegistry(registry) }),
|
|
226
|
+
temporal: sources.temporal,
|
|
227
|
+
...(scope === "cwd" ? { owner: { cwd: resolve(cwdIdentity!) } } : {}),
|
|
228
|
+
};
|
|
229
|
+
return `${canonicalJson(value)}\n`;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Compatibility serializer retained for metadata-only callers. */
|
|
186
233
|
export function serializeScopeProvenance(registry: Readonly<ArtifactProvenanceRegistry>): string {
|
|
187
234
|
return `${canonicalJson({ version: 1, artifacts: serializeArtifactProvenanceRegistry(registry) })}\n`;
|
|
188
235
|
}
|
|
189
236
|
|
|
190
|
-
|
|
191
|
-
export function parseScopeProvenance(source: string | undefined, path: string): ArtifactProvenanceRegistry {
|
|
237
|
+
function parseMetadataDocument(source: string | undefined, label: string): Record<string, unknown> {
|
|
192
238
|
if (source === undefined) return {};
|
|
193
239
|
let value: unknown;
|
|
194
|
-
try {
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
}
|
|
240
|
+
try { value = JSON.parse(source); }
|
|
241
|
+
catch { throw new Error(`${label} contains invalid JSON`); }
|
|
242
|
+
if (!isObject(value) || !isJsonValue(value)) throw new Error(`Invalid ${label}`);
|
|
243
|
+
return value;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Missing provenance is unavailable evidence, never corrupt state. Unknown metadata is preserved by writers. */
|
|
247
|
+
export function parseScopeProvenance(source: string | undefined, path: string): ArtifactProvenanceRegistry {
|
|
248
|
+
const value = parseMetadataDocument(source, `State Flow provenance file: ${path}`);
|
|
249
|
+
if (Object.keys(value).length === 0) return {};
|
|
250
|
+
if (value.version !== 1) throw new Error(`Invalid State Flow provenance document: ${path}`);
|
|
251
|
+
if (!Object.hasOwn(value, "artifacts")) return {};
|
|
203
252
|
return parseArtifactProvenanceRegistry(value.artifacts, `State Flow provenance at ${path}`);
|
|
204
253
|
}
|
|
205
254
|
|
|
@@ -232,12 +281,6 @@ export function durablePaths(repositoryRoot = getDurableRepositoryRoot()): Durab
|
|
|
232
281
|
};
|
|
233
282
|
}
|
|
234
283
|
|
|
235
|
-
function legacyReadableScopeKey(identity: string, readable: string): string {
|
|
236
|
-
if (identity.length === 0) throw new Error("State Flow scope identity must be non-empty");
|
|
237
|
-
const slug = readable.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, LEGACY_MAX_SCOPE_SLUG_LENGTH) || "scope";
|
|
238
|
-
return `${slug}-${createHash("sha256").update(identity).digest("hex")}`;
|
|
239
|
-
}
|
|
240
|
-
|
|
241
284
|
/** Match Pi's native project-session directory convention exactly. */
|
|
242
285
|
export function cwdScopeKey(cwd: string): string {
|
|
243
286
|
const canonical = resolve(cwd);
|
|
@@ -266,16 +309,6 @@ export function resolveSessionAddress(sessionFile: string | undefined, sessionId
|
|
|
266
309
|
return Object.freeze({ id: sessionId, key: sessionStorageKey(sessionFile, sessionId, timestamp) });
|
|
267
310
|
}
|
|
268
311
|
|
|
269
|
-
/** Read-only migration input for the untagged hashed-layout draft. */
|
|
270
|
-
export function legacyCwdScopeKey(cwd: string): string {
|
|
271
|
-
const canonical = resolve(cwd);
|
|
272
|
-
return legacyReadableScopeKey(canonical, `--${canonical.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`);
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
export function legacySessionScopeKey(sessionId: string): string {
|
|
276
|
-
return legacyReadableScopeKey(sessionScopeKey(sessionId), sessionId);
|
|
277
|
-
}
|
|
278
|
-
|
|
279
312
|
export function cwdScopePaths(cwd: string, repositoryRoot = getDurableRepositoryRoot()): ScopePaths {
|
|
280
313
|
const directory = join(resolve(repositoryRoot), cwdScopeKey(cwd));
|
|
281
314
|
return { directory, state: join(directory, STATE_FILE), patches: join(directory, PATCHES_FILE) };
|
|
@@ -299,28 +332,6 @@ export function cwdPatchesPath(cwd: string, repositoryRoot = getDurableRepositor
|
|
|
299
332
|
return cwdScopePaths(cwd, repositoryRoot).patches;
|
|
300
333
|
}
|
|
301
334
|
|
|
302
|
-
/** Historical paths from the pre-0.4 hashed-layout draft; never selected for new writes. */
|
|
303
|
-
export function legacyTemporalScopePaths(cwd: string, sessionId: string, scope: StateScope, repositoryRoot: string): TemporalScopePaths {
|
|
304
|
-
const root = resolve(repositoryRoot);
|
|
305
|
-
const cwdDirectory = join(root, legacyCwdScopeKey(cwd));
|
|
306
|
-
const directory = scope === "global" ? root : scope === "cwd" ? cwdDirectory : join(cwdDirectory, legacySessionScopeKey(sessionId));
|
|
307
|
-
return { directory, checkpoint: join(directory, CHECKPOINT_FILE), patches: join(directory, PATCHES_FILE), meta: join(directory, META_FILE) };
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
export function legacySessionRuntimePaths(cwd: string, sessionId: string, repositoryRoot: string): { config: string; meta: string } {
|
|
311
|
-
const directory = legacyTemporalScopePaths(cwd, sessionId, "session", repositoryRoot).directory;
|
|
312
|
-
return { config: join(directory, "config.json"), meta: join(directory, "meta.json") };
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
export function captureLegacyTemporalFileBases(cwd: string, sessionId: string, repositoryRoot: string): DurableFileBase[] {
|
|
316
|
-
const paths = (["global", "cwd", "session"] as const).flatMap((scope) => {
|
|
317
|
-
const pair = legacyTemporalScopePaths(cwd, sessionId, scope, repositoryRoot);
|
|
318
|
-
const runtime = scope === "session" ? legacySessionRuntimePaths(cwd, sessionId, repositoryRoot) : undefined;
|
|
319
|
-
return [pair.checkpoint, pair.patches, join(pair.directory, STATE_FILE), ...(runtime === undefined ? [] : [runtime.config, runtime.meta])];
|
|
320
|
-
});
|
|
321
|
-
return captureOwnedFileBases(paths, repositoryRoot);
|
|
322
|
-
}
|
|
323
|
-
|
|
324
335
|
export function sessionStatePath(cwd: string, sessionId: string, repositoryRoot = getDurableRepositoryRoot(), sessionKey = sessionId): string {
|
|
325
336
|
return sessionScopePaths(cwd, sessionId, repositoryRoot, sessionKey).state;
|
|
326
337
|
}
|
|
@@ -337,7 +348,7 @@ export function isStateFlowOwnedPath(candidate: string, repositoryRoot = getDura
|
|
|
337
348
|
if (absolute === global.globalState || absolute === global.globalPatches
|
|
338
349
|
|| absolute === join(root, CHECKPOINT_FILE) || absolute === join(root, META_FILE)) return true;
|
|
339
350
|
const segments = relative(root, absolute).split(sep);
|
|
340
|
-
const cwdKey = (value: string) =>
|
|
351
|
+
const cwdKey = (value: string) => value.startsWith("--") && value.endsWith("--");
|
|
341
352
|
const sessionKey = (value: string) => {
|
|
342
353
|
try { return sessionScopeKey(value) === value; } catch { return false; }
|
|
343
354
|
};
|
|
@@ -346,7 +357,7 @@ export function isStateFlowOwnedPath(candidate: string, repositoryRoot = getDura
|
|
|
346
357
|
}
|
|
347
358
|
if (segments.length === 3) {
|
|
348
359
|
return cwdKey(segments[0]!)
|
|
349
|
-
&&
|
|
360
|
+
&& sessionKey(segments[1]!)
|
|
350
361
|
&& (segments[2] === STATE_FILE || segments[2] === CHECKPOINT_FILE || segments[2] === PATCHES_FILE
|
|
351
362
|
|| segments[2] === "config.json" || segments[2] === META_FILE);
|
|
352
363
|
}
|
|
@@ -446,25 +457,6 @@ export function captureOwnedFileBases(paths: readonly string[], repositoryRoot:
|
|
|
446
457
|
});
|
|
447
458
|
}
|
|
448
459
|
|
|
449
|
-
function validateState(value: unknown, path: string): asserts value is MaterializedState {
|
|
450
|
-
if (!isMaterializedState(value) || !isJsonValue(value) || containsNull(value)) {
|
|
451
|
-
throw new Error(`Durable State Flow file has invalid materialized state: ${path}`);
|
|
452
|
-
}
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
/** One-way legacy current-state interpretation; explanatory journals are not recovery input. */
|
|
456
|
-
export function parseStateSource(source: string | undefined, path: string): MaterializedState | undefined {
|
|
457
|
-
if (source === undefined) return undefined;
|
|
458
|
-
let value: unknown;
|
|
459
|
-
try {
|
|
460
|
-
value = JSON.parse(source);
|
|
461
|
-
} catch {
|
|
462
|
-
throw new Error(`Durable State Flow file contains invalid JSON: ${path}`);
|
|
463
|
-
}
|
|
464
|
-
validateState(value, path);
|
|
465
|
-
return structuredClone(value);
|
|
466
|
-
}
|
|
467
|
-
|
|
468
460
|
interface PreparedFile {
|
|
469
461
|
path: string;
|
|
470
462
|
repositoryRoot: string;
|
package/lib/extension.ts
CHANGED
|
@@ -57,15 +57,24 @@ export const READ_STATE_TOOL_NAME = "read_state";
|
|
|
57
57
|
export const MAX_FALLBACK_ATTEMPTS: number = 2;
|
|
58
58
|
const PASSIVE_STOP_ENTRY_TYPE = "state-flow-passive-stop";
|
|
59
59
|
const PUBLICATION_SHUTDOWN_WAIT_MS = 2_000;
|
|
60
|
-
const
|
|
60
|
+
const PATCH_DISPLAY_SECTION_KEYS = new Set([
|
|
61
|
+
"global",
|
|
62
|
+
"cwd",
|
|
63
|
+
"session",
|
|
64
|
+
"artifacts",
|
|
65
|
+
"contract",
|
|
66
|
+
"working",
|
|
67
|
+
"response",
|
|
68
|
+
"final",
|
|
69
|
+
]);
|
|
61
70
|
|
|
62
|
-
/** Keep successful patch JSON valid while separating adjacent memory sections visually. */
|
|
71
|
+
/** Keep successful patch JSON valid while separating adjacent scopes and memory sections visually. */
|
|
63
72
|
export function formatPatchStateArguments(args: unknown): string {
|
|
64
73
|
const seenAtIndent = new Set<number>();
|
|
65
74
|
return JSON.stringify(args, null, 2).split("\n").flatMap((line) => {
|
|
66
75
|
const indent = line.length - line.trimStart().length;
|
|
67
76
|
const match = /^(\s+)"([^"]+)":/.exec(line);
|
|
68
|
-
if (match === null || !
|
|
77
|
+
if (match === null || !PATCH_DISPLAY_SECTION_KEYS.has(match[2])) {
|
|
69
78
|
for (const seenIndent of seenAtIndent) {
|
|
70
79
|
if (seenIndent > indent) seenAtIndent.delete(seenIndent);
|
|
71
80
|
}
|
|
@@ -91,10 +100,15 @@ export function normalizePatchStateArguments(args: unknown): any {
|
|
|
91
100
|
return { ...args, final };
|
|
92
101
|
}
|
|
93
102
|
|
|
103
|
+
/** Keep tool output visually separated from its heading with exactly one leading newline. */
|
|
104
|
+
function separatedOutput(text: string): string {
|
|
105
|
+
return `\n${text.replace(/^\n+/, "")}`;
|
|
106
|
+
}
|
|
107
|
+
|
|
94
108
|
/** Keep a failed tool invocation visually separated from its rendered error without changing error semantics. */
|
|
95
109
|
function separatedFailure(error: unknown): Error {
|
|
96
110
|
const message = error instanceof Error ? error.message : String(error);
|
|
97
|
-
return new Error(
|
|
111
|
+
return new Error(separatedOutput(message), error instanceof Error ? { cause: error } : undefined);
|
|
98
112
|
}
|
|
99
113
|
|
|
100
114
|
export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowExtensionOptions = {}): void {
|
|
@@ -581,9 +595,9 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
581
595
|
const branch = ctx.sessionManager.getBranch();
|
|
582
596
|
const discovery = discoverSnapshotData(branch);
|
|
583
597
|
let restoreSelected: (() => Snapshot) | undefined;
|
|
584
|
-
const recovery = recoverSnapshot(discovery.candidates, (revision
|
|
598
|
+
const recovery = recoverSnapshot(discovery.candidates, (revision) => {
|
|
585
599
|
try {
|
|
586
|
-
const prepared = prepareBranchRestore(ctx, revision
|
|
600
|
+
const prepared = prepareBranchRestore(ctx, revision);
|
|
587
601
|
restoreSelected = prepared.restore;
|
|
588
602
|
return prepared.snapshot;
|
|
589
603
|
} catch (error) {
|
|
@@ -607,7 +621,6 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
607
621
|
} else if (branchHasSnapshot && snapshot.config.enabled) {
|
|
608
622
|
const publication = runtime.initialize(snapshot, true);
|
|
609
623
|
recordPolicyPublication(publication, ctx);
|
|
610
|
-
delete snapshot.legacySession;
|
|
611
624
|
}
|
|
612
625
|
installScopeStates();
|
|
613
626
|
} else if (config.autoStart && isNewSession(sessionStartReason, branch)) {
|
|
@@ -837,8 +850,9 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
837
850
|
prepareArguments: normalizePatchStateArguments,
|
|
838
851
|
renderResult(result, { isPartial }, theme, context) {
|
|
839
852
|
const text = result.content.find((block) => block.type === "text")?.text ?? "";
|
|
840
|
-
if (
|
|
841
|
-
return new Text(
|
|
853
|
+
if (context.isError) return new Text(separatedOutput(text), 0, 0);
|
|
854
|
+
if (isPartial || !config.showSuccessfulPatches) return new Text(text, 0, 0);
|
|
855
|
+
return new Text(separatedOutput(theme.fg("dim", formatPatchStateArguments(context.args))), 0, 0);
|
|
842
856
|
},
|
|
843
857
|
async execute(toolCallId, params, signal, _onUpdate, ctx) {
|
|
844
858
|
try {
|
|
@@ -910,6 +924,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
910
924
|
activeContext = ctx;
|
|
911
925
|
runtime ??= createRuntime(ctx);
|
|
912
926
|
if (branchStartsWithoutRuntime) runtime.prepare();
|
|
927
|
+
runtime.migrateLegacyStorage();
|
|
913
928
|
const bootstrap = (!branchHasSnapshot || !snapshot.config.enabled)
|
|
914
929
|
&& (hasPriorConversation(branch) || previousPassiveContinuation !== undefined);
|
|
915
930
|
if (!runtime.view && snapshot.meta.durableBase) {
|
|
@@ -932,7 +947,6 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
932
947
|
: runtime.initialize(snapshot, true, undefined, branchStartsWithoutRuntime);
|
|
933
948
|
recordPolicyPublication(publication, ctx);
|
|
934
949
|
installScopeStates();
|
|
935
|
-
delete snapshot.legacySession;
|
|
936
950
|
clearRunTransient();
|
|
937
951
|
passiveContinuation = undefined;
|
|
938
952
|
bootstrapContinuation = snapshot.meta.bootstrap
|