@llblab/pi-state-flow 0.4.0 → 0.5.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 +3 -3
- package/BACKLOG.md +7 -3
- package/CHANGELOG.md +10 -1
- package/README.md +11 -3
- package/docs/README.md +1 -3
- package/docs/architecture.md +188 -0
- package/index.ts +148 -93
- package/lib/artifact.ts +28 -0
- package/lib/config.ts +16 -4
- package/lib/context.ts +3 -0
- package/lib/continuation.ts +268 -0
- package/lib/durable.ts +10 -0
- package/lib/extension.ts +140 -19
- package/lib/git.ts +25 -5
- package/lib/history.ts +2 -2
- package/lib/json.ts +24 -0
- package/lib/memory.ts +52 -0
- package/lib/publication.ts +296 -0
- package/lib/rehydration.ts +79 -0
- package/lib/runtime.ts +19 -14
- package/lib/snapshot.ts +12 -1
- package/lib/status.ts +23 -0
- package/lib/storage.ts +4 -4
- package/lib/temporal.ts +3 -3
- package/lib/terminal.ts +6 -0
- package/package.json +5 -1
- package/skills/state-flow-memory/SKILL.md +73 -0
package/lib/artifact.ts
CHANGED
|
@@ -14,6 +14,7 @@ export type ArtifactMetadata = JsonObject & {
|
|
|
14
14
|
compiled_at?: string;
|
|
15
15
|
compilation?: JsonObject;
|
|
16
16
|
kind?: string;
|
|
17
|
+
tags?: string[];
|
|
17
18
|
};
|
|
18
19
|
|
|
19
20
|
/** Artifact source paths are the canonical registry keys. */
|
|
@@ -57,6 +58,7 @@ export type ArtifactCompilerOutput = JsonObject & {
|
|
|
57
58
|
compiled_at?: string;
|
|
58
59
|
compilation?: JsonObject;
|
|
59
60
|
kind?: string;
|
|
61
|
+
tags?: string[];
|
|
60
62
|
};
|
|
61
63
|
|
|
62
64
|
export interface ArtifactCompilationUpdate {
|
|
@@ -97,6 +99,11 @@ export function validateArtifactMetadata(value: unknown, path = "<unknown>"): as
|
|
|
97
99
|
&& (typeof value.kind !== "string" || value.kind.trim().length === 0)) {
|
|
98
100
|
throw new Error(`Artifact metadata at ${path} kind must be a non-empty string`);
|
|
99
101
|
}
|
|
102
|
+
if (Object.hasOwn(value, "tags") && (!Array.isArray(value.tags)
|
|
103
|
+
|| value.tags.some((tag) => typeof tag !== "string" || tag.trim().length === 0 || tag !== tag.trim())
|
|
104
|
+
|| new Set(value.tags).size !== value.tags.length)) {
|
|
105
|
+
throw new Error(`Artifact metadata at ${path} tags must be unique non-empty trimmed strings`);
|
|
106
|
+
}
|
|
100
107
|
}
|
|
101
108
|
|
|
102
109
|
export function isArtifactMetadata(value: unknown): value is ArtifactMetadata {
|
|
@@ -116,6 +123,27 @@ export function validateArtifactRegistry(value: unknown): asserts value is Artif
|
|
|
116
123
|
}
|
|
117
124
|
}
|
|
118
125
|
|
|
126
|
+
export function selectArtifactsByTags(
|
|
127
|
+
registry: ArtifactRegistry,
|
|
128
|
+
tags: readonly string[],
|
|
129
|
+
match: "all" | "any" = "all",
|
|
130
|
+
): string[] {
|
|
131
|
+
validateArtifactRegistry(registry);
|
|
132
|
+
if (tags.length === 0 || tags.some((tag) => typeof tag !== "string" || tag.trim().length === 0 || tag !== tag.trim())) {
|
|
133
|
+
throw new Error("Artifact tag query requires one or more non-empty trimmed strings");
|
|
134
|
+
}
|
|
135
|
+
const requested = new Set(tags);
|
|
136
|
+
return Object.entries(registry)
|
|
137
|
+
.filter(([, metadata]) => {
|
|
138
|
+
const available = new Set(metadata.tags ?? []);
|
|
139
|
+
return match === "all"
|
|
140
|
+
? [...requested].every((tag) => available.has(tag))
|
|
141
|
+
: [...requested].some((tag) => available.has(tag));
|
|
142
|
+
})
|
|
143
|
+
.map(([path]) => path)
|
|
144
|
+
.sort();
|
|
145
|
+
}
|
|
146
|
+
|
|
119
147
|
export function isArtifactRegistry(value: unknown): value is ArtifactRegistry {
|
|
120
148
|
try {
|
|
121
149
|
validateArtifactRegistry(value);
|
package/lib/config.ts
CHANGED
|
@@ -9,12 +9,16 @@ import { isObject } from "./json.ts";
|
|
|
9
9
|
export interface StateFlowConfig {
|
|
10
10
|
directory: string;
|
|
11
11
|
autoStart: boolean;
|
|
12
|
+
remotePublication?: "off" | "turn-end" | "transition";
|
|
12
13
|
}
|
|
13
14
|
|
|
14
15
|
/** Read once at extension load/reload. Missing config uses defaults; invalid config never falls back. */
|
|
15
16
|
export function loadStateFlowConfig(agentDir = getAgentDir()): StateFlowConfig {
|
|
16
17
|
const path = resolve(agentDir, "state-flow.json");
|
|
17
|
-
const defaults = {
|
|
18
|
+
const defaults: StateFlowConfig = {
|
|
19
|
+
directory: getDurableRepositoryRoot(agentDir),
|
|
20
|
+
autoStart: false,
|
|
21
|
+
};
|
|
18
22
|
let value: unknown;
|
|
19
23
|
try {
|
|
20
24
|
if (!lstatSync(path, { throwIfNoEntry: false })) return defaults;
|
|
@@ -22,15 +26,23 @@ export function loadStateFlowConfig(agentDir = getAgentDir()): StateFlowConfig {
|
|
|
22
26
|
} catch (error) {
|
|
23
27
|
throw new Error(`Cannot read State Flow configuration: ${path}`, { cause: error });
|
|
24
28
|
}
|
|
25
|
-
|
|
26
|
-
|
|
29
|
+
const allowed = new Set(["directory", "autoStart", "remotePublication"]);
|
|
30
|
+
if (!isObject(value) || Object.keys(value).some((key) => !allowed.has(key))) {
|
|
31
|
+
throw new Error(`State Flow configuration contains unknown settings: ${path}`);
|
|
27
32
|
}
|
|
28
33
|
if (Object.hasOwn(value, "autoStart") && typeof value.autoStart !== "boolean") throw new Error(`State Flow autoStart must be a boolean: ${path}`);
|
|
34
|
+
if (Object.hasOwn(value, "remotePublication") && value.remotePublication !== "off" && value.remotePublication !== "turn-end" && value.remotePublication !== "transition") {
|
|
35
|
+
throw new Error(`State Flow remotePublication must be off, turn-end, or transition: ${path}`);
|
|
36
|
+
}
|
|
29
37
|
if (Object.hasOwn(value, "directory") && (typeof value.directory !== "string" || !value.directory.trim() || value.directory.includes("\0"))) {
|
|
30
38
|
throw new Error(`State Flow directory must be a non-empty path: ${path}`);
|
|
31
39
|
}
|
|
32
40
|
const directory = value.directory as string | undefined;
|
|
33
41
|
if (directory?.startsWith("~") && directory !== "~" && !directory.startsWith("~/")) throw new Error(`State Flow directory supports ~ or ~/ paths, not named-user expansion: ${path}`);
|
|
34
42
|
const expanded = directory === "~" ? homedir() : directory?.startsWith("~/") ? resolve(homedir(), directory.slice(2)) : directory;
|
|
35
|
-
return {
|
|
43
|
+
return {
|
|
44
|
+
directory: expanded === undefined ? defaults.directory : resolve(dirname(path), expanded),
|
|
45
|
+
autoStart: value.autoStart === true,
|
|
46
|
+
...(value.remotePublication === undefined ? {} : { remotePublication: value.remotePublication as "off" | "turn-end" | "transition" }),
|
|
47
|
+
};
|
|
36
48
|
}
|
package/lib/context.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type { ArtifactInvalidationRequest } from "./artifact.ts";
|
|
|
3
3
|
import type { RecentTransitionWindow } from "./history.ts";
|
|
4
4
|
import { canonicalJson } from "./json.ts";
|
|
5
5
|
import type { Snapshot } from "./snapshot.ts";
|
|
6
|
+
import type { RehydrationPhase } from "./rehydration.ts";
|
|
6
7
|
import type { MaterializedState } from "./state.ts";
|
|
7
8
|
|
|
8
9
|
export const VALIDATION_MESSAGE_TYPE = "state-flow-validation";
|
|
@@ -36,6 +37,7 @@ export function runtimeContextMessage(
|
|
|
36
37
|
state: MaterializedState,
|
|
37
38
|
recentTransitions: RecentTransitionWindow = [],
|
|
38
39
|
artifactInvalidations: readonly ArtifactInvalidationRequest[] = [],
|
|
40
|
+
rehydrationPhase?: RehydrationPhase,
|
|
39
41
|
): AgentMessage {
|
|
40
42
|
if (snapshot.meta.specification === undefined) {
|
|
41
43
|
throw new Error("State Flow runtime context requires an active specification");
|
|
@@ -43,6 +45,7 @@ export function runtimeContextMessage(
|
|
|
43
45
|
const context = {
|
|
44
46
|
specification: snapshot.meta.specification,
|
|
45
47
|
state,
|
|
48
|
+
...(rehydrationPhase === undefined ? {} : { knowledge_rehydration: { phase: rehydrationPhase } }),
|
|
46
49
|
...(artifactInvalidations.length === 0 ? {} : { artifact_invalidations: artifactInvalidations }),
|
|
47
50
|
...(recentTransitions.length === 0 ? {} : { recent_transitions: recentTransitions }),
|
|
48
51
|
...(snapshot.meta.validation === undefined ? {} : { validation_feedback: snapshot.meta.validation }),
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { closeSync, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync, statSync } from "node:fs";
|
|
3
|
+
import { join, relative, resolve } from "node:path";
|
|
4
|
+
import { loadScopeStream, resolveSessionAddress, sessionRuntimePaths } from "./durable.ts";
|
|
5
|
+
import { loadTemporalRevision } from "./git.ts";
|
|
6
|
+
import { parseSessionRuntime } from "./snapshot.ts";
|
|
7
|
+
import { validateTemporalState } from "./temporal.ts";
|
|
8
|
+
|
|
9
|
+
export type ContinuationTransport = "local" | "sdk" | "telegram" | string;
|
|
10
|
+
|
|
11
|
+
export interface ContinuationHostContext {
|
|
12
|
+
cwd: string;
|
|
13
|
+
agentDir: string;
|
|
14
|
+
sessionDir: string;
|
|
15
|
+
transport: ContinuationTransport;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export type ContinuationHostIntent =
|
|
19
|
+
| { kind: "default" }
|
|
20
|
+
| { kind: "new" }
|
|
21
|
+
| { kind: "resume-exact"; sessionFile: string; sessionId: string }
|
|
22
|
+
| { kind: "native-picker" }
|
|
23
|
+
| { kind: "continue-recent" }
|
|
24
|
+
| { kind: "no-session" };
|
|
25
|
+
|
|
26
|
+
export interface ContinuationCandidateSummary {
|
|
27
|
+
sessionFile: string;
|
|
28
|
+
sessionId: string;
|
|
29
|
+
lastActivity: string;
|
|
30
|
+
reason: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type ContinuationRecommendation =
|
|
34
|
+
| { action: "resume"; sessionFile: string; sessionId: string; reason: "latest-enabled-state-flow" }
|
|
35
|
+
| { action: "choose"; candidates: ContinuationCandidateSummary[]; reason: "ambiguous" }
|
|
36
|
+
| { action: "new"; reason: "none" | "last-not-state-flow" | "ineligible" };
|
|
37
|
+
|
|
38
|
+
export type ContinuationStartupDecision =
|
|
39
|
+
| ContinuationRecommendation
|
|
40
|
+
| { action: "new"; reason: "explicit-new" }
|
|
41
|
+
| { action: "resume"; sessionFile: string; sessionId: string; reason: "explicit-resume" }
|
|
42
|
+
| { action: "native"; mode: "picker" | "continue-recent" | "no-session" };
|
|
43
|
+
|
|
44
|
+
export interface ContinuationProjectIdentity {
|
|
45
|
+
profile: string;
|
|
46
|
+
cwd: string;
|
|
47
|
+
gitCommonDir?: string;
|
|
48
|
+
worktree?: string;
|
|
49
|
+
branch?: string;
|
|
50
|
+
transport: ContinuationTransport;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface ContinuationSessionCandidate extends ContinuationCandidateSummary {
|
|
54
|
+
profile: string;
|
|
55
|
+
cwd: string;
|
|
56
|
+
gitCommonDir?: string;
|
|
57
|
+
worktree?: string;
|
|
58
|
+
branch?: string;
|
|
59
|
+
transport: ContinuationTransport;
|
|
60
|
+
lifecycle: "open" | "closed" | "archived";
|
|
61
|
+
doNotAutoResume?: boolean;
|
|
62
|
+
stateFlow: { enabled: boolean; restorable: boolean };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export type ContinuationRecommender = (
|
|
66
|
+
context: Readonly<ContinuationHostContext>,
|
|
67
|
+
) => ContinuationRecommendation | Promise<ContinuationRecommendation>;
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Preserve host-owned explicit session intent and consult State Flow only for
|
|
71
|
+
* an ordinary default launch. The recommender is a read-only advisory port;
|
|
72
|
+
* opening or claiming a native session remains the host's responsibility.
|
|
73
|
+
*/
|
|
74
|
+
function sameOptionalIdentity(current: string | undefined, candidate: string | undefined): boolean {
|
|
75
|
+
return current === undefined ? candidate === undefined : candidate === current;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function structurallyRelevant(identity: ContinuationProjectIdentity, candidate: ContinuationSessionCandidate): boolean {
|
|
79
|
+
return candidate.profile === identity.profile
|
|
80
|
+
&& candidate.cwd === identity.cwd
|
|
81
|
+
&& candidate.transport === identity.transport
|
|
82
|
+
&& candidate.lifecycle === "open"
|
|
83
|
+
&& candidate.doNotAutoResume !== true
|
|
84
|
+
&& sameOptionalIdentity(identity.gitCommonDir, candidate.gitCommonDir)
|
|
85
|
+
&& sameOptionalIdentity(identity.worktree, candidate.worktree)
|
|
86
|
+
&& sameOptionalIdentity(identity.branch, candidate.branch)
|
|
87
|
+
&& Number.isFinite(Date.parse(candidate.lastActivity));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Rank already header/provenance-only candidates without transcript content or I/O. */
|
|
91
|
+
export function recommendContinuationFromProvenance(
|
|
92
|
+
identity: ContinuationProjectIdentity,
|
|
93
|
+
candidates: readonly ContinuationSessionCandidate[],
|
|
94
|
+
): ContinuationRecommendation {
|
|
95
|
+
const relevant = candidates.filter((candidate) => structurallyRelevant(identity, candidate));
|
|
96
|
+
if (relevant.length === 0) return { action: "new", reason: "none" };
|
|
97
|
+
const latestTime = Math.max(...relevant.map(({ lastActivity }) => Date.parse(lastActivity)));
|
|
98
|
+
const latest = relevant.filter(({ lastActivity }) => Date.parse(lastActivity) === latestTime)
|
|
99
|
+
.sort((left, right) => left.sessionFile.localeCompare(right.sessionFile));
|
|
100
|
+
if (latest.length > 1) {
|
|
101
|
+
const resumable = latest.filter(({ stateFlow }) => stateFlow.enabled && stateFlow.restorable);
|
|
102
|
+
if (resumable.length > 1) return { action: "choose", reason: "ambiguous", candidates: resumable.map(({ sessionFile, sessionId, lastActivity }) => ({ sessionFile, sessionId, lastActivity, reason: "equally recent enabled State Flow session" })) };
|
|
103
|
+
if (resumable.length === 1 && latest.every(({ stateFlow }) => stateFlow.enabled && stateFlow.restorable)) {
|
|
104
|
+
const candidate = resumable[0];
|
|
105
|
+
return { action: "resume", sessionFile: candidate.sessionFile, sessionId: candidate.sessionId, reason: "latest-enabled-state-flow" };
|
|
106
|
+
}
|
|
107
|
+
return { action: "new", reason: "ineligible" };
|
|
108
|
+
}
|
|
109
|
+
const candidate = latest[0];
|
|
110
|
+
if (!candidate.stateFlow.enabled) return { action: "new", reason: "last-not-state-flow" };
|
|
111
|
+
if (!candidate.stateFlow.restorable) return { action: "new", reason: "ineligible" };
|
|
112
|
+
return { action: "resume", sessionFile: candidate.sessionFile, sessionId: candidate.sessionId, reason: "latest-enabled-state-flow" };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export async function resolveContinuationStartup(
|
|
116
|
+
context: ContinuationHostContext,
|
|
117
|
+
intent: ContinuationHostIntent,
|
|
118
|
+
recommend: ContinuationRecommender,
|
|
119
|
+
): Promise<ContinuationStartupDecision> {
|
|
120
|
+
switch (intent.kind) {
|
|
121
|
+
case "new":
|
|
122
|
+
return { action: "new", reason: "explicit-new" };
|
|
123
|
+
case "resume-exact":
|
|
124
|
+
return { action: "resume", sessionFile: intent.sessionFile, sessionId: intent.sessionId, reason: "explicit-resume" };
|
|
125
|
+
case "native-picker":
|
|
126
|
+
return { action: "native", mode: "picker" };
|
|
127
|
+
case "continue-recent":
|
|
128
|
+
return { action: "native", mode: "continue-recent" };
|
|
129
|
+
case "no-session":
|
|
130
|
+
return { action: "native", mode: "no-session" };
|
|
131
|
+
case "default":
|
|
132
|
+
return recommend(Object.freeze({ ...context }));
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const MAX_SESSION_HEADER_BYTES = 64 * 1024;
|
|
137
|
+
|
|
138
|
+
export interface NativeSessionHeader {
|
|
139
|
+
file: string;
|
|
140
|
+
id: string;
|
|
141
|
+
cwd: string;
|
|
142
|
+
timestamp: string;
|
|
143
|
+
lastActivity: string;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export interface ContinuationCandidateProvenance {
|
|
147
|
+
profile: string;
|
|
148
|
+
gitCommonDir?: string;
|
|
149
|
+
worktree?: string;
|
|
150
|
+
branch?: string;
|
|
151
|
+
transport: ContinuationTransport;
|
|
152
|
+
lifecycle: "open" | "closed" | "archived";
|
|
153
|
+
doNotAutoResume?: boolean;
|
|
154
|
+
stateFlow: { enabled: boolean; restorable: boolean };
|
|
155
|
+
reason: string;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function readFirstLine(path: string): string {
|
|
159
|
+
const fd = openSync(path, "r");
|
|
160
|
+
try {
|
|
161
|
+
const bytes: number[] = [];
|
|
162
|
+
const byte = Buffer.allocUnsafe(1);
|
|
163
|
+
while (bytes.length <= MAX_SESSION_HEADER_BYTES) {
|
|
164
|
+
const count = readSync(fd, byte, 0, 1, null);
|
|
165
|
+
if (count === 0 || byte[0] === 0x0a) break;
|
|
166
|
+
bytes.push(byte[0]);
|
|
167
|
+
}
|
|
168
|
+
if (bytes.length > MAX_SESSION_HEADER_BYTES) throw new Error("Native Pi session header exceeds the safe discovery limit");
|
|
169
|
+
return Buffer.from(bytes).toString("utf8").replace(/\r$/, "");
|
|
170
|
+
} finally {
|
|
171
|
+
closeSync(fd);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export function readNativeSessionHeader(path: string): NativeSessionHeader {
|
|
176
|
+
const file = resolve(path);
|
|
177
|
+
let value: unknown;
|
|
178
|
+
try {
|
|
179
|
+
value = JSON.parse(readFirstLine(file));
|
|
180
|
+
} catch (error) {
|
|
181
|
+
throw new Error(`Cannot read native Pi session header: ${error instanceof Error ? error.message : String(error)}`);
|
|
182
|
+
}
|
|
183
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("Invalid native Pi session header");
|
|
184
|
+
const header = value as Record<string, unknown>;
|
|
185
|
+
if (header.type !== "session" || typeof header.id !== "string" || header.id.trim().length === 0
|
|
186
|
+
|| typeof header.cwd !== "string" || header.cwd.trim().length === 0
|
|
187
|
+
|| typeof header.timestamp !== "string" || !Number.isFinite(Date.parse(header.timestamp))) {
|
|
188
|
+
throw new Error("Invalid native Pi session header");
|
|
189
|
+
}
|
|
190
|
+
const stats = statSync(file);
|
|
191
|
+
return { file, id: header.id, cwd: resolve(header.cwd), timestamp: header.timestamp, lastActivity: stats.mtime.toISOString() };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export function discoverNativeSessionHeaders(sessionDir: string): { headers: NativeSessionHeader[]; invalid: Array<{ file: string; error: string }> } {
|
|
195
|
+
const headers: NativeSessionHeader[] = [];
|
|
196
|
+
const invalid: Array<{ file: string; error: string }> = [];
|
|
197
|
+
for (const entry of readdirSync(sessionDir, { withFileTypes: true }).sort((left, right) => left.name.localeCompare(right.name))) {
|
|
198
|
+
if (!entry.isFile() || !entry.name.endsWith(".jsonl")) continue;
|
|
199
|
+
const file = join(sessionDir, entry.name);
|
|
200
|
+
try {
|
|
201
|
+
headers.push(readNativeSessionHeader(file));
|
|
202
|
+
} catch (error) {
|
|
203
|
+
invalid.push({ file: resolve(file), error: error instanceof Error ? error.message : String(error) });
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return { headers, invalid };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function readRegular(path: string): string | undefined {
|
|
210
|
+
if (!existsSync(path)) return undefined;
|
|
211
|
+
if (!lstatSync(path).isFile()) throw new Error("State Flow continuation provenance must be a regular file");
|
|
212
|
+
return readFileSync(path, "utf8");
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Inspect only exact current runtime provenance; never initialize, migrate, lock, checkout, or publish. */
|
|
216
|
+
export function inspectStateFlowContinuationProvenance(
|
|
217
|
+
header: NativeSessionHeader,
|
|
218
|
+
repositoryRoot: string,
|
|
219
|
+
): Pick<ContinuationCandidateProvenance, "stateFlow" | "reason"> {
|
|
220
|
+
const sessionKey = resolveSessionAddress(header.file, header.id, header.timestamp).key;
|
|
221
|
+
const paths = sessionRuntimePaths(header.cwd, header.id, repositoryRoot, sessionKey);
|
|
222
|
+
try {
|
|
223
|
+
const config = readRegular(paths.config);
|
|
224
|
+
const meta = readRegular(paths.meta);
|
|
225
|
+
if (config === undefined && meta === undefined) {
|
|
226
|
+
return { stateFlow: { enabled: false, restorable: true }, reason: "no State Flow session runtime" };
|
|
227
|
+
}
|
|
228
|
+
const runtime = parseSessionRuntime(config, meta, header.cwd, header.id);
|
|
229
|
+
if (!runtime) return { stateFlow: { enabled: false, restorable: true }, reason: "no State Flow session runtime" };
|
|
230
|
+
if (!runtime.config.enabled) return { stateFlow: { enabled: false, restorable: true }, reason: "State Flow stopped on selected runtime" };
|
|
231
|
+
if (runtime.meta.publication === "files") {
|
|
232
|
+
const global = loadScopeStream(header.cwd, header.id, "global", repositoryRoot, sessionKey);
|
|
233
|
+
const cwd = loadScopeStream(header.cwd, header.id, "cwd", repositoryRoot, sessionKey);
|
|
234
|
+
const session = loadScopeStream(header.cwd, header.id, "session", repositoryRoot, sessionKey);
|
|
235
|
+
if (!global || !cwd || !session) throw new Error("incomplete file-only temporal cohort");
|
|
236
|
+
validateTemporalState({ lineage: runtime.meta.lineage, scopes: { global, cwd, session } });
|
|
237
|
+
return { stateFlow: { enabled: true, restorable: true }, reason: "exact file-only runtime cohort is restorable" };
|
|
238
|
+
}
|
|
239
|
+
const runtimePath = relative(resolve(repositoryRoot), paths.meta);
|
|
240
|
+
if (runtimePath.startsWith("..")) throw new Error("runtime provenance escapes repository");
|
|
241
|
+
const owner = execFileSync("git", ["-C", repositoryRoot, "log", "-1", "--format=%H", "--", runtimePath], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
|
|
242
|
+
if (!owner) throw new Error("runtime owner commit is unavailable");
|
|
243
|
+
const restored = loadTemporalRevision(header.cwd, header.id, repositoryRoot, owner, sessionKey);
|
|
244
|
+
if (!restored.runtime || !restored.runtime.document.config.enabled) throw new Error("selected Git runtime is not enabled");
|
|
245
|
+
return { stateFlow: { enabled: true, restorable: true }, reason: `exact Git runtime ${owner.slice(0, 12)} is restorable` };
|
|
246
|
+
} catch (error) {
|
|
247
|
+
return { stateFlow: { enabled: true, restorable: false }, reason: `State Flow runtime is ineligible: ${error instanceof Error ? error.message : String(error)}` };
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
export function buildContinuationCandidates(
|
|
252
|
+
headers: readonly NativeSessionHeader[],
|
|
253
|
+
inspect: (header: Readonly<NativeSessionHeader>) => ContinuationCandidateProvenance | undefined,
|
|
254
|
+
): ContinuationSessionCandidate[] {
|
|
255
|
+
const candidates: ContinuationSessionCandidate[] = [];
|
|
256
|
+
for (const header of headers) {
|
|
257
|
+
const provenance = inspect(Object.freeze({ ...header }));
|
|
258
|
+
if (!provenance) continue;
|
|
259
|
+
candidates.push({
|
|
260
|
+
sessionFile: header.file,
|
|
261
|
+
sessionId: header.id,
|
|
262
|
+
lastActivity: header.lastActivity,
|
|
263
|
+
cwd: header.cwd,
|
|
264
|
+
...provenance,
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
return candidates;
|
|
268
|
+
}
|
package/lib/durable.ts
CHANGED
|
@@ -30,6 +30,11 @@ export interface ScopeStreamSources {
|
|
|
30
30
|
patches: string;
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
+
export interface SessionAddress {
|
|
34
|
+
readonly id: string;
|
|
35
|
+
readonly key: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
33
38
|
/** CWD storage requires its canonical owner; legacy ownerless sources are read-only. */
|
|
34
39
|
export function serializeScopeStream(stream: ScopeStream, scope: StateScope, cwdIdentity?: string): ScopeStreamSources {
|
|
35
40
|
validateScopeStream(stream, scope);
|
|
@@ -212,6 +217,11 @@ export function sessionStorageKey(sessionFile: string | undefined, sessionId: st
|
|
|
212
217
|
return sessionScopeKey(sessionId);
|
|
213
218
|
}
|
|
214
219
|
|
|
220
|
+
export function resolveSessionAddress(sessionFile: string | undefined, sessionId: string, timestamp?: string): SessionAddress {
|
|
221
|
+
if (sessionId.trim().length === 0 || sessionId !== sessionId.trim()) throw new Error("State Flow session identity must be non-empty and trimmed");
|
|
222
|
+
return Object.freeze({ id: sessionId, key: sessionStorageKey(sessionFile, sessionId, timestamp) });
|
|
223
|
+
}
|
|
224
|
+
|
|
215
225
|
/** Read-only migration input for the untagged hashed-layout draft. */
|
|
216
226
|
export function legacyCwdScopeKey(cwd: string): string {
|
|
217
227
|
const canonical = resolve(cwd);
|