@llblab/pi-state-flow 0.4.0 → 0.6.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.
@@ -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);
package/lib/extension.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { execFile } from "node:child_process";
1
2
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
3
  import { StringEnum, Type } from "@earendil-works/pi-ai";
3
4
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
@@ -16,14 +17,20 @@ import { discoverSnapshotData, hasPriorConversation, isNewSession, SNAPSHOT_ENTR
16
17
  import { compactStatus, detailedStatus, STATUS_KEY, type PendingPublicationDiagnostic, type StatusDiagnostics } from "./status.ts";
17
18
  import { abandonValidation, prepareRun, resumeEpisode, startEpisode, stopEpisode } from "./episode.ts";
18
19
  import { recoverSnapshot } from "./recovery.ts";
20
+ import type { RehydrationPhase } from "./rehydration.ts";
21
+ import { resolveRemotePublicationPolicy, serializeRemotePublicationPolicyDocument } from "./publication.ts";
22
+ import { coalescePublicationTarget, createPublicationQueue, type PublicationQueueState } from "./publication.ts";
23
+ import { acquirePublicationWorkerLease, loadPublicationQueue, publicationQueuePath, removePublicationQueue, savePublicationQueue } from "./publication.ts";
24
+ import { runPublicationWorker } from "./publication.ts";
19
25
  import { getKnowledgeRoot, GlobalMarkdownDiscovery } from "./discovery.ts";
20
26
  import {
21
27
  cwdScopeKey,
28
+ resolveSessionAddress,
22
29
  sessionScopeKey,
23
- sessionStorageKey,
30
+ type SessionAddress,
24
31
  } from "./durable.ts";
25
32
  import { projectRecentTransitionsWithLimit } from "./history.ts";
26
- import { pushGitCommit } from "./git.ts";
33
+ import { isGitCommitAncestor, pushGitCommit, resolveGitPushDestination } from "./git.ts";
27
34
  import {
28
35
  ORDINARY_ARTIFACT_COMPILER,
29
36
  planArtifactInvalidation,
@@ -52,15 +59,21 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
52
59
  let runtime: TemporalRuntime | undefined;
53
60
  let activeContext: ExtensionContext | undefined;
54
61
  let pendingPublication: PendingPublicationDiagnostic | undefined;
62
+ let rehydrationPhase: RehydrationPhase | undefined;
63
+ let turnPublicationTarget: string | undefined;
64
+ const activePublicationWorkers = new Set<string>();
55
65
  const repositoryRoot = resolve(options.repositoryRoot ?? config.directory);
56
66
  const skillReads = new SkillReadTracker();
57
67
  const artifactReads = new ArtifactReadTracker();
58
68
  const globalMarkdown = new GlobalMarkdownDiscovery(options.knowledgeRoot ?? getKnowledgeRoot(options.agentDir));
59
69
  let artifactInvalidations: ArtifactInvalidationRequest[] = [];
60
70
 
61
- function sessionIdentity(ctx: ExtensionContext): { id: string; key: string } {
62
- const id = ctx.sessionManager.getSessionId();
63
- return { id, key: sessionStorageKey(ctx.sessionManager.getSessionFile(), id, ctx.sessionManager.getHeader()?.timestamp) };
71
+ function sessionAddress(ctx: ExtensionContext): SessionAddress {
72
+ return resolveSessionAddress(ctx.sessionManager.getSessionFile(), ctx.sessionManager.getSessionId(), ctx.sessionManager.getHeader()?.timestamp);
73
+ }
74
+
75
+ function createRuntime(ctx: ExtensionContext): TemporalRuntime {
76
+ return new TemporalRuntime(ctx.cwd, sessionAddress(ctx), repositoryRoot);
64
77
  }
65
78
 
66
79
  options.onRuntime?.({ read: (offset, scope) => {
@@ -69,7 +82,9 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
69
82
  } });
70
83
 
71
84
  function persist(): void {
72
- const publication = runtime?.view ? runtime.publish(snapshot) : undefined;
85
+ const mode = snapshot.meta.remotePublication?.mode ?? "transition";
86
+ const publication = runtime?.view ? runtime.publish(snapshot, false, undefined, { pushRemote: mode === "transition" }) : undefined;
87
+ if (publication?.commit && mode === "turn-end") turnPublicationTarget = publication.commit;
73
88
  if (publication && activeContext) recordPublication(publication, activeContext);
74
89
  const checkpoint = persistableSnapshot(snapshot);
75
90
  if ("disabled" in checkpoint && !branchStartsWithoutRuntime) {
@@ -182,7 +197,9 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
182
197
  const acquiredArtifactPaths = new Set(artifactReads.successful.keys());
183
198
  const committed = commitScopedTransition(snapshot, scopeStates, stage, (accepted, nextSnapshot) => {
184
199
  if (!runtime?.view) throw new Error("Temporal State Flow runtime is unavailable; reload before publishing");
185
- const publication = runtime.publish(nextSnapshot, accepted !== undefined, accepted);
200
+ const mode = nextSnapshot.meta.remotePublication?.mode ?? "transition";
201
+ const publication = runtime.publish(nextSnapshot, accepted !== undefined, accepted, { pushRemote: mode === "transition" });
202
+ if (publication?.commit && mode === "turn-end") turnPublicationTarget = publication.commit;
186
203
  if (publication) recordPublication(publication, ctx);
187
204
  }, runtime!.causalBasis(), { finalizeRun });
188
205
  if (!committed) return false;
@@ -195,6 +212,70 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
195
212
  return true;
196
213
  }
197
214
 
215
+ function enqueueTurnPublication(): void {
216
+ const target = turnPublicationTarget;
217
+ turnPublicationTarget = undefined;
218
+ if (!target) return;
219
+ const destination = resolveGitPushDestination(repositoryRoot);
220
+ if (!destination) return;
221
+ const path = publicationQueuePath(destination);
222
+ const previous = loadPublicationQueue(path);
223
+ const next = previous
224
+ ? coalescePublicationTarget(previous, destination, target, (ancestor, descendant) => isGitCommitAncestor(repositoryRoot, ancestor, descendant))
225
+ : createPublicationQueue(destination, target);
226
+ savePublicationQueue(path, next, previous);
227
+ }
228
+
229
+ function launchPublicationWorker(): void {
230
+ let destination: ReturnType<typeof resolveGitPushDestination>;
231
+ try {
232
+ destination = resolveGitPushDestination(repositoryRoot);
233
+ } catch (error) {
234
+ if (error instanceof Error && /ENOENT/.test(error.message)) return;
235
+ throw error;
236
+ }
237
+ if (!destination) return;
238
+ const path = publicationQueuePath(destination);
239
+ if (activePublicationWorkers.has(path)) return;
240
+ let queued: PublicationQueueState | undefined;
241
+ let lease: ReturnType<typeof acquirePublicationWorkerLease>;
242
+ try {
243
+ queued = loadPublicationQueue(path);
244
+ if (!queued) return;
245
+ lease = acquirePublicationWorkerLease(path);
246
+ } catch {
247
+ return;
248
+ }
249
+ if (!lease) return;
250
+ activePublicationWorkers.add(path);
251
+ void runPublicationWorker(
252
+ queued,
253
+ ({ target }) => new Promise<void>((resolve, reject) => {
254
+ execFile("git", ["-C", repositoryRoot, "push", destination.remote, `${target}:${destination.ref}`], {
255
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" },
256
+ }, (error) => error ? reject(error) : resolve());
257
+ }),
258
+ () => loadPublicationQueue(path) ?? queued,
259
+ (ancestor, descendant) => isGitCommitAncestor(repositoryRoot, ancestor, descendant),
260
+ ).then((result) => {
261
+ const current = loadPublicationQueue(path);
262
+ if (!current) return;
263
+ if (result.next === undefined) {
264
+ if (current.target === result.attempted.target) removePublicationQueue(path, current);
265
+ return;
266
+ }
267
+ if (current.target === result.attempted.target || result.next.target === current.target) {
268
+ savePublicationQueue(path, result.next, current);
269
+ }
270
+ }).catch(() => {
271
+ // Queue/CAS truth remains durable; status and a later activation expose retry.
272
+ }).finally(() => {
273
+ activePublicationWorkers.delete(path);
274
+ lease.release();
275
+ if (loadPublicationQueue(path)?.status === "pending") launchPublicationWorker();
276
+ });
277
+ }
278
+
198
279
  function retryPendingPush(ctx: ExtensionContext): void {
199
280
  if (pendingPublication === undefined || !runtime?.view) return;
200
281
  const result = pushGitCommit(repositoryRoot, pendingPublication.commit);
@@ -210,6 +291,10 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
210
291
  }
211
292
  }
212
293
 
294
+ function currentRehydrationPhase(): RehydrationPhase | undefined {
295
+ return rehydrationPhase;
296
+ }
297
+
213
298
  function statusDiagnostics(ctx: ExtensionContext): StatusDiagnostics {
214
299
  const cwd = ctx.cwd;
215
300
  const diagnosticStates = scopeStates;
@@ -239,7 +324,16 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
239
324
  }
240
325
  }
241
326
 
242
- const session = sessionIdentity(ctx);
327
+ const session = sessionAddress(ctx);
328
+ let publicationQueue: PublicationQueueState | undefined;
329
+ let publicationQueueError: string | undefined;
330
+ try {
331
+ const destination = resolveGitPushDestination(repositoryRoot);
332
+ publicationQueue = destination ? loadPublicationQueue(publicationQueuePath(destination)) : undefined;
333
+ } catch (error) {
334
+ publicationQueue = undefined;
335
+ publicationQueueError = error instanceof Error ? error.message : String(error);
336
+ }
243
337
  return {
244
338
  repositoryRoot,
245
339
  cwdScopeKey: cwdScopeKey(cwd),
@@ -256,14 +350,16 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
256
350
  ...(durableStateError === undefined ? {} : { durableStateError }),
257
351
  ...(pendingPublication === undefined ? {} : { pendingPublication }),
258
352
  retryQueued,
353
+ ...(publicationQueue === undefined ? {} : { publicationQueue }),
354
+ ...(publicationQueueError === undefined ? {} : { publicationQueueError }),
259
355
  };
260
356
  }
261
357
 
262
358
  function restoreActiveBranch(ctx: ExtensionContext, sessionStartReason?: unknown): void {
263
359
  clearRunTransient();
264
360
  activeContext = ctx;
265
- const session = sessionIdentity(ctx);
266
- runtime = new TemporalRuntime(ctx.cwd, session.id, repositoryRoot, session.key);
361
+ const session = sessionAddress(ctx);
362
+ runtime = new TemporalRuntime(ctx.cwd, session, repositoryRoot);
267
363
  installScopeStates();
268
364
  pendingPublication = undefined;
269
365
  branchHasSnapshot = false;
@@ -293,6 +389,9 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
293
389
  installScopeStates();
294
390
  } else if (config.autoStart && isNewSession(sessionStartReason, branch)) {
295
391
  snapshot = startEpisode(hasPriorConversation(branch));
392
+ snapshot.meta.remotePublication = serializeRemotePublicationPolicyDocument(
393
+ resolveRemotePublicationPolicy(config.remotePublication, { legacyRuntime: false }),
394
+ );
296
395
  runtime.prepare();
297
396
  const initialization = runtime.initialize(snapshot, true);
298
397
  if (initialization) recordPublication(initialization, ctx);
@@ -317,6 +416,16 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
317
416
  meta: { ...snapshot.meta, validation: failure.meta.validation },
318
417
  };
319
418
  }
419
+ if (branchHasSnapshot && snapshot.meta.remotePublication === undefined) {
420
+ snapshot.meta.remotePublication = serializeRemotePublicationPolicyDocument(
421
+ resolveRemotePublicationPolicy(undefined, { legacyRuntime: true }),
422
+ );
423
+ }
424
+ if (snapshot.config.enabled && snapshot.meta.remotePublication === undefined) {
425
+ snapshot.meta.remotePublication = serializeRemotePublicationPolicyDocument(
426
+ resolveRemotePublicationPolicy(undefined, { legacyRuntime: true }),
427
+ );
428
+ }
320
429
  pendingPublication = snapshot.meta.pendingPublication === undefined
321
430
  ? undefined
322
431
  : structuredClone(snapshot.meta.pendingPublication);
@@ -392,10 +501,10 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
392
501
  pi.registerTool({
393
502
  name: PATCH_STATE_TOOL_NAME,
394
503
  label: "Patch State",
395
- description: "Materialize established future-relevant semantic state at a session, CWD, or global barrier. Do not use for scratchpad, narration, routine progress, or speculative churn. This call must be the only State Flow barrier in its assistant response; sibling tool calls are blocked and reconsidered after rematerialization.",
504
+ description: "Materialize established future-relevant semantic state at a session, CWD, or global barrier, including a necessary write-and-verify step during explicitly requested curation. Do not use for scratchpad, narration, routine progress, or speculative churn. This call must be the only State Flow barrier in its assistant response; sibling tool calls are blocked and reconsidered after rematerialization.",
396
505
  promptSnippet: "Materialize established future-relevant state as an immediate inference barrier",
397
506
  promptGuidelines: [
398
- "Use patch_state only when established future-relevant information would face meaningful loss or recovery risk if delayed until terminal reconciliation.",
507
+ "Use patch_state when established future-relevant information would face meaningful loss or recovery risk if delayed until terminal reconciliation, or for a necessary write-and-verify step in explicitly requested curation.",
399
508
  "Call patch_state alone in an assistant response; choose subsequent actions only after its compact acknowledgement and rematerialized State Flow context.",
400
509
  ],
401
510
  executionMode: "sequential",
@@ -406,9 +515,10 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
406
515
  async execute(_toolCallId, params, signal, _onUpdate, ctx) {
407
516
  if (!snapshot.config.enabled) throw new Error("State Flow is disabled on this session branch");
408
517
  if (signal?.aborted) throw new Error("State Flow patch was aborted before materialization");
518
+ const transition = { scope: params.scope as StateScope, patch: params.patch as ScopePatch };
409
519
  const stage = stageScopedPatch(
410
520
  scopeStates,
411
- { scope: params.scope as StateScope, patch: params.patch as ScopePatch },
521
+ transition,
412
522
  skillReads.successful.values(),
413
523
  runtime!.causalBasis(),
414
524
  artifactReads.successful.values(),
@@ -417,7 +527,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
417
527
  updateUi(ctx);
418
528
  const publication = pendingPublication === undefined ? "" : "; durable publication pending";
419
529
  return {
420
- content: [{ type: "text", text: `State materialized at ${params.scope} scope${publication}.` }],
530
+ content: [{ type: "text", text: `\nState materialized at ${params.scope} scope${publication}.` }],
421
531
  details: { scope: params.scope, step: snapshot.meta.step },
422
532
  };
423
533
  },
@@ -434,8 +544,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
434
544
  }
435
545
  const branch = ctx.sessionManager.getBranch();
436
546
  activeContext = ctx;
437
- const session = sessionIdentity(ctx);
438
- runtime ??= new TemporalRuntime(ctx.cwd, session.id, repositoryRoot, session.key);
547
+ runtime ??= createRuntime(ctx);
439
548
  if (branchStartsWithoutRuntime) runtime.prepare();
440
549
  const bootstrap = (!branchHasSnapshot || !snapshot.config.enabled)
441
550
  && hasPriorConversation(branch);
@@ -444,9 +553,15 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
444
553
  setPendingPublication(snapshot.meta.pendingPublication);
445
554
  branchHasSnapshot = true;
446
555
  }
447
- snapshot = branchHasSnapshot
556
+ const existingBranch = branchHasSnapshot;
557
+ snapshot = existingBranch
448
558
  ? resumeEpisode(snapshot, bootstrap)
449
559
  : startEpisode(bootstrap);
560
+ if (snapshot.meta.remotePublication === undefined) {
561
+ snapshot.meta.remotePublication = serializeRemotePublicationPolicyDocument(
562
+ resolveRemotePublicationPolicy(existingBranch ? undefined : config.remotePublication, { legacyRuntime: existingBranch }),
563
+ );
564
+ }
450
565
  branchHasSnapshot = true;
451
566
  const publication = runtime.view
452
567
  ? runtime.promote(snapshot) ?? runtime.publish(snapshot)
@@ -490,8 +605,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
490
605
  let selected = runtime;
491
606
  let current = snapshot;
492
607
  if (!selected?.view && snapshot.meta.durableBase) {
493
- const session = sessionIdentity(ctx);
494
- selected = new TemporalRuntime(ctx.cwd, session.id, repositoryRoot, session.key);
608
+ selected = createRuntime(ctx);
495
609
  current = selected.restore(snapshot.meta.durableBase, snapshot);
496
610
  }
497
611
  const stopped = stopEpisode(current);
@@ -517,6 +631,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
517
631
  artifactReads.clear();
518
632
  }
519
633
  const rotatesRun = snapshot.meta.specification !== undefined && !retryQueued;
634
+ if (rotatesRun) rehydrationPhase = "step";
520
635
  if (prepareRun(snapshot, event.prompt, retryQueued)) {
521
636
  if (rotatesRun) runAnchorTimestamp = undefined;
522
637
  persist();
@@ -533,9 +648,10 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
533
648
  snapshot.config.transitionWindow,
534
649
  runtime?.recent() ?? [],
535
650
  );
651
+ const activeRehydrationPhase = currentRehydrationPhase();
536
652
  if (snapshot.meta.bootstrap) {
537
653
  const messages = withoutPrivateValidation(event.messages as AgentMessage[]);
538
- return { messages: [runtimeContextMessage(snapshot, effectiveState, recentTransitions, artifactInvalidations), ...messages] };
654
+ return { messages: [runtimeContextMessage(snapshot, effectiveState, recentTransitions, artifactInvalidations, activeRehydrationPhase), ...messages] };
539
655
  }
540
656
  const trajectory = currentRunTrajectory(
541
657
  event.messages as AgentMessage[],
@@ -545,7 +661,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
545
661
  runAnchorTimestamp = trajectory.anchorTimestamp;
546
662
  return {
547
663
  messages: [
548
- runtimeContextMessage(snapshot, effectiveState, recentTransitions, artifactInvalidations),
664
+ runtimeContextMessage(snapshot, effectiveState, recentTransitions, artifactInvalidations, activeRehydrationPhase),
549
665
  ...trajectory.messages,
550
666
  ],
551
667
  };
@@ -629,6 +745,8 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
629
745
  try {
630
746
  stagedFinal.nextStates.session.response = finalizedAssistantResponse(event.message);
631
747
  commitStage(stagedFinal, ctx, true);
748
+ enqueueTurnPublication();
749
+ if (snapshot.meta.remotePublication?.mode === "turn-end") launchPublicationWorker();
632
750
  } catch (error) {
633
751
  queueTerminalRegeneration(error instanceof Error ? error.message : String(error), ctx);
634
752
  }
@@ -638,12 +756,15 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
638
756
 
639
757
  pi.on("agent_settled", (_event, ctx) => {
640
758
  if (snapshot.config.enabled && retryQueued) abandonRun(ctx);
759
+ if (snapshot.meta.remotePublication?.mode === "turn-end") launchPublicationWorker();
641
760
  });
642
761
 
643
762
  pi.on("session_start", (event, ctx) => {
763
+ rehydrationPhase = event.reason === "resume" ? "resume-bootstrap" : "new-bootstrap";
644
764
  restoreActiveBranch(ctx, event.reason);
645
765
  refreshArtifactInvalidations(ctx);
646
766
  retryPendingPush(ctx);
767
+ if (snapshot.meta.remotePublication?.mode === "turn-end") launchPublicationWorker();
647
768
  updateUi(ctx);
648
769
  });
649
770
  pi.on("session_tree", (_event, ctx) => {