@llblab/pi-state-flow 0.3.0 → 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/extension.ts CHANGED
@@ -1,60 +1,329 @@
1
1
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
+ import { StringEnum, Type } from "@earendil-works/pi-ai";
2
3
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
4
  import { assistantToolCallCount, finalizedAssistantResponse, parseTerminalPatch, stateFlowProtocol, stripStateComments } from "./terminal.ts";
4
5
  import { currentRunTrajectory, runtimeContextMessage, VALIDATION_MESSAGE_TYPE, withoutPrivateValidation } from "./context.ts";
6
+ import { ArtifactReadTracker } from "./acquisition.ts";
7
+ import { loadStateFlowConfig } from "./config.ts";
8
+ import { resolve } from "node:path";
5
9
  import { SkillReadTracker } from "./skills.ts";
6
- import { migrationFailure, type Snapshot } from "./snapshot.ts";
7
- import { emptyState } from "./state.ts";
8
- import { commitTransition, stageTransition, type StagedTransition } from "./transition.ts";
10
+ import { emptySnapshot, migrationFailure, persistableSnapshot, type Snapshot } from "./snapshot.ts";
11
+ import { inspectSnapshotRevision, TemporalRuntime, type RuntimePublication } from "./runtime.ts";
12
+ import { emptyState, overlayStates, type MaterializedState, type ScopePatch, type ScopedStates, type StateScope } from "./state.ts";
13
+ import { commitScopedTransition, stageScopedPatch, stageScopedTransition, type StagedScopedTransition } from "./transition.ts";
9
14
  import { MAX_VALIDATION_RETRIES, nextValidation } from "./validation.ts";
10
- import { discoverSnapshotData, hasPriorConversation, SNAPSHOT_ENTRY_TYPE } from "./session.ts";
11
- import { compactStatus, detailedStatus, STATUS_KEY } from "./status.ts";
12
- import { abandonValidation, prepareRun, startEpisode, stopEpisode } from "./episode.ts";
15
+ import { discoverSnapshotData, hasPriorConversation, isNewSession, SNAPSHOT_ENTRY_TYPE } from "./session.ts";
16
+ import { compactStatus, detailedStatus, STATUS_KEY, type PendingPublicationDiagnostic, type StatusDiagnostics } from "./status.ts";
17
+ import { abandonValidation, prepareRun, resumeEpisode, startEpisode, stopEpisode } from "./episode.ts";
13
18
  import { recoverSnapshot } from "./recovery.ts";
19
+ import { getKnowledgeRoot, GlobalMarkdownDiscovery } from "./discovery.ts";
20
+ import {
21
+ cwdScopeKey,
22
+ sessionScopeKey,
23
+ sessionStorageKey,
24
+ } from "./durable.ts";
25
+ import { projectRecentTransitionsWithLimit } from "./history.ts";
26
+ import { pushGitCommit } from "./git.ts";
27
+ import {
28
+ ORDINARY_ARTIFACT_COMPILER,
29
+ planArtifactInvalidation,
30
+ type ArtifactInvalidationRequest,
31
+ } from "./artifact.ts";
14
32
 
15
- export default function stateFlowExtension(pi: ExtensionAPI): void {
16
- let snapshot: Snapshot = { enabled: false, state: emptyState(), step: 0 };
17
- let stagedFinal: StagedTransition | undefined;
33
+ export interface StateFlowExtensionOptions {
34
+ agentDir?: string;
35
+ repositoryRoot?: string;
36
+ knowledgeRoot?: string;
37
+ onRuntime?: (accessor: { read(offset?: number, scope?: StateScope): MaterializedState }) => void;
38
+ }
39
+
40
+ export const PATCH_STATE_TOOL_NAME = "patch_state";
41
+ export const READ_STATE_TOOL_NAME = "read_state";
42
+
43
+ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowExtensionOptions = {}): void {
44
+ const config = loadStateFlowConfig(options.agentDir);
45
+ let snapshot: Snapshot = emptySnapshot();
46
+ let scopeStates: ScopedStates = { global: emptyState(), cwd: emptyState(), session: emptyState() };
47
+ let branchHasSnapshot = false;
48
+ let branchStartsWithoutRuntime = false;
49
+ let stagedFinal: StagedScopedTransition | undefined;
18
50
  let retryQueued = false;
19
51
  let runAnchorTimestamp: number | undefined;
52
+ let runtime: TemporalRuntime | undefined;
53
+ let activeContext: ExtensionContext | undefined;
54
+ let pendingPublication: PendingPublicationDiagnostic | undefined;
55
+ const repositoryRoot = resolve(options.repositoryRoot ?? config.directory);
20
56
  const skillReads = new SkillReadTracker();
57
+ const artifactReads = new ArtifactReadTracker();
58
+ const globalMarkdown = new GlobalMarkdownDiscovery(options.knowledgeRoot ?? getKnowledgeRoot(options.agentDir));
59
+ let artifactInvalidations: ArtifactInvalidationRequest[] = [];
60
+
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) };
64
+ }
65
+
66
+ options.onRuntime?.({ read: (offset, scope) => {
67
+ if (!runtime) throw new Error("State Flow temporal runtime is unavailable");
68
+ return runtime.read(offset, scope);
69
+ } });
21
70
 
22
71
  function persist(): void {
23
- pi.appendEntry(SNAPSHOT_ENTRY_TYPE, structuredClone(snapshot));
72
+ const publication = runtime?.view ? runtime.publish(snapshot) : undefined;
73
+ if (publication && activeContext) recordPublication(publication, activeContext);
74
+ const checkpoint = persistableSnapshot(snapshot);
75
+ if ("disabled" in checkpoint && !branchStartsWithoutRuntime) {
76
+ throw new Error("State Flow cannot checkpoint an unproven branch as ordinary disabled; restore a valid checkpoint first");
77
+ }
78
+ pi.appendEntry(SNAPSHOT_ENTRY_TYPE, checkpoint);
79
+ if ("revision" in checkpoint) branchStartsWithoutRuntime = false;
24
80
  }
25
81
 
26
82
  function updateUi(ctx: ExtensionContext): void {
27
83
  ctx.ui.setStatus(STATUS_KEY, compactStatus(snapshot, (color, text) => ctx.ui.theme.fg(color, text)));
28
84
  }
29
85
 
86
+ function setPendingPublication(value: PendingPublicationDiagnostic | undefined): void {
87
+ pendingPublication = value === undefined ? undefined : structuredClone(value);
88
+ if (value === undefined) delete snapshot.meta.pendingPublication;
89
+ else snapshot.meta.pendingPublication = structuredClone(value);
90
+ }
91
+
30
92
  function clearRunTransient(): void {
31
93
  stagedFinal = undefined;
32
94
  retryQueued = false;
33
95
  runAnchorTimestamp = undefined;
34
96
  skillReads.clear();
97
+ artifactReads.clear();
98
+ }
99
+
100
+ function refreshArtifactInvalidations(ctx: ExtensionContext): void {
101
+ if (!snapshot.config.enabled) {
102
+ artifactInvalidations = [];
103
+ artifactReads.setCandidates([]);
104
+ return;
105
+ }
106
+ try {
107
+ const discovery = globalMarkdown.refresh();
108
+ const plan = planArtifactInvalidation(
109
+ discovery.sources,
110
+ scopeStates.global.artifacts,
111
+ ORDINARY_ARTIFACT_COMPILER,
112
+ );
113
+ artifactInvalidations = structuredClone(plan.requiresCompilation);
114
+ if (plan.removed.length > 0) {
115
+ const removals = Object.fromEntries(plan.removed.map((path) => [path, null]));
116
+ const stage = stageScopedPatch(
117
+ scopeStates,
118
+ { scope: "global", patch: { artifacts: removals } },
119
+ [],
120
+ runtime!.causalBasis(),
121
+ );
122
+ commitStage(stage, ctx, false);
123
+ }
124
+ artifactReads.setCandidates(artifactInvalidations);
125
+ } catch (error) {
126
+ artifactInvalidations = [];
127
+ artifactReads.setCandidates([]);
128
+ ctx.ui.notify(
129
+ `State Flow could not discover global Markdown sources: ${error instanceof Error ? error.message : String(error)}`,
130
+ "warning",
131
+ );
132
+ }
133
+ }
134
+
135
+ function installScopeStates(): void {
136
+ scopeStates = runtime?.view ? runtime.states() : { global: emptyState(), cwd: emptyState(), session: emptyState() };
137
+ }
138
+
139
+ function syncStateFlowTools(): void {
140
+ const active = pi.getActiveTools();
141
+ const owned = [PATCH_STATE_TOOL_NAME, READ_STATE_TOOL_NAME];
142
+ if (owned.every((name) => active.includes(name) === snapshot.config.enabled)) return;
143
+ pi.setActiveTools(snapshot.config.enabled
144
+ ? [...new Set([...active, ...owned])]
145
+ : active.filter((name) => !owned.includes(name)));
146
+ }
147
+
148
+ function assistantToolBatch(ctx: ExtensionContext, toolCallId: string): string[] | undefined {
149
+ const branch = ctx.sessionManager.getBranch();
150
+ for (let index = branch.length - 1; index >= 0; index--) {
151
+ const entry = branch[index] as { type?: unknown; message?: { role?: unknown; content?: unknown } };
152
+ if (entry.type !== "message" || entry.message?.role !== "assistant" || !Array.isArray(entry.message.content)) continue;
153
+ const calls = entry.message.content.filter((block): block is { type: "toolCall"; id: string; name: string } => {
154
+ return typeof block === "object" && block !== null
155
+ && (block as { type?: unknown }).type === "toolCall"
156
+ && typeof (block as { id?: unknown }).id === "string"
157
+ && typeof (block as { name?: unknown }).name === "string";
158
+ });
159
+ if (calls.some(({ id }) => id === toolCallId)) return calls.map(({ name }) => name);
160
+ }
161
+ return undefined;
162
+ }
163
+
164
+ function recordPublication(publication: RuntimePublication, ctx: ExtensionContext): void {
165
+ const revision = publication.revision ?? publication.commit;
166
+ if (revision !== undefined) snapshot.meta.durableBase = revision;
167
+ if (publication.push?.status === "pending") {
168
+ setPendingPublication({
169
+ commit: publication.push.commit,
170
+ error: publication.push.error ?? "unknown push failure",
171
+ });
172
+ ctx.ui.notify(
173
+ `State Flow accepted durable commit ${publication.push.commit.slice(0, 12)}, but push is pending: ${publication.push.error}`,
174
+ "warning",
175
+ );
176
+ } else if (revision !== undefined) {
177
+ setPendingPublication(undefined);
178
+ }
179
+ }
180
+
181
+ function commitStage(stage: StagedScopedTransition, ctx: ExtensionContext, finalizeRun: boolean): boolean {
182
+ const acquiredArtifactPaths = new Set(artifactReads.successful.keys());
183
+ const committed = commitScopedTransition(snapshot, scopeStates, stage, (accepted, nextSnapshot) => {
184
+ if (!runtime?.view) throw new Error("Temporal State Flow runtime is unavailable; reload before publishing");
185
+ const publication = runtime.publish(nextSnapshot, accepted !== undefined, accepted);
186
+ if (publication) recordPublication(publication, ctx);
187
+ }, runtime!.causalBasis(), { finalizeRun });
188
+ if (!committed) return false;
189
+ installScopeStates();
190
+ artifactInvalidations = artifactInvalidations.filter(({ path }) => !acquiredArtifactPaths.has(path));
191
+ artifactReads.setCandidates(artifactInvalidations);
192
+ skillReads.clear();
193
+ artifactReads.clear();
194
+ persist();
195
+ return true;
196
+ }
197
+
198
+ function retryPendingPush(ctx: ExtensionContext): void {
199
+ if (pendingPublication === undefined || !runtime?.view) return;
200
+ const result = pushGitCommit(repositoryRoot, pendingPublication.commit);
201
+ if (result.status !== "pending") {
202
+ setPendingPublication(undefined);
203
+ persist();
204
+ ctx.ui.notify(result.status === "local"
205
+ ? `State Flow retained local-only durable commit ${result.commit.slice(0, 12)}; no remote configured.`
206
+ : `State Flow pushed pending durable commit ${result.commit.slice(0, 12)}.`, "info");
207
+ } else {
208
+ setPendingPublication({ commit: result.commit, error: result.error ?? "unknown push failure" });
209
+ persist();
210
+ }
35
211
  }
36
212
 
37
- function restoreActiveBranch(ctx: ExtensionContext): void {
213
+ function statusDiagnostics(ctx: ExtensionContext): StatusDiagnostics {
214
+ const cwd = ctx.cwd;
215
+ const diagnosticStates = scopeStates;
216
+ const view = runtime?.view;
217
+ const diagnosticRecent = runtime?.recent() ?? [];
218
+ const durableStateError = view ? undefined
219
+ : snapshot.meta.validation?.attempt === 0 ? snapshot.meta.validation.error : "no temporal runtime is selected on this branch";
220
+
221
+ let staleArtifacts: StatusDiagnostics["staleArtifacts"] = [];
222
+ let artifactFreshnessError: string | undefined;
223
+ if (durableStateError !== undefined) {
224
+ artifactFreshnessError = "durable global artifact registry is unavailable";
225
+ } else {
226
+ try {
227
+ const discovery = globalMarkdown.refresh();
228
+ const plan = planArtifactInvalidation(
229
+ discovery.sources,
230
+ diagnosticStates.global.artifacts,
231
+ ORDINARY_ARTIFACT_COMPILER,
232
+ );
233
+ staleArtifacts = [
234
+ ...plan.requiresCompilation.map(({ path, reason }) => ({ scope: "global" as const, path, reason })),
235
+ ...plan.removed.map((path) => ({ scope: "global" as const, path, reason: "source-removed" as const })),
236
+ ];
237
+ } catch (error) {
238
+ artifactFreshnessError = error instanceof Error ? error.message : String(error);
239
+ }
240
+ }
241
+
242
+ const session = sessionIdentity(ctx);
243
+ return {
244
+ repositoryRoot,
245
+ cwdScopeKey: cwdScopeKey(cwd),
246
+ sessionScopeKey: sessionScopeKey(session.key),
247
+ scopeStates: diagnosticStates,
248
+ recent: diagnosticRecent,
249
+ ...(view === undefined ? {} : { temporal: {
250
+ head: structuredClone(view.lineage.at(-1)!),
251
+ historyDepth: view.lineage.length - 1,
252
+ tailCounts: { global: view.scopes.global.patches.length, cwd: view.scopes.cwd.patches.length, session: view.scopes.session.patches.length },
253
+ } }),
254
+ staleArtifacts,
255
+ ...(artifactFreshnessError === undefined ? {} : { artifactFreshnessError }),
256
+ ...(durableStateError === undefined ? {} : { durableStateError }),
257
+ ...(pendingPublication === undefined ? {} : { pendingPublication }),
258
+ retryQueued,
259
+ };
260
+ }
261
+
262
+ function restoreActiveBranch(ctx: ExtensionContext, sessionStartReason?: unknown): void {
38
263
  clearRunTransient();
264
+ activeContext = ctx;
265
+ const session = sessionIdentity(ctx);
266
+ runtime = new TemporalRuntime(ctx.cwd, session.id, repositoryRoot, session.key);
267
+ installScopeStates();
268
+ pendingPublication = undefined;
269
+ branchHasSnapshot = false;
270
+ branchStartsWithoutRuntime = false;
39
271
  try {
40
- const discovery = discoverSnapshotData(ctx.sessionManager.getBranch());
41
- const recovery = recoverSnapshot(discovery.candidates);
272
+ const branch = ctx.sessionManager.getBranch();
273
+ const discovery = discoverSnapshotData(branch);
274
+ const recovery = recoverSnapshot(discovery.candidates, (revision, legacy) =>
275
+ inspectSnapshotRevision(ctx.cwd, session.id, repositoryRoot, revision, legacy, session.key).snapshot);
276
+ branchStartsWithoutRuntime = recovery.disabledMarker === true
277
+ || (discovery.candidates.length === 0 && discovery.errors.length === 0);
42
278
  const skipped = discovery.errors.length + recovery.skipped.length;
43
- snapshot = discovery.candidates.length === 0 && discovery.errors.length > 0
44
- ? migrationFailure({}, `Snapshot restoration failed: ${discovery.errors[0]}`)
45
- : recovery.snapshot;
46
- if (snapshot.enabled && skipped > 0) {
279
+ branchHasSnapshot = recovery.skipped.length < discovery.candidates.length;
280
+ if (discovery.candidates.length === 0 && discovery.errors.length > 0) {
281
+ snapshot = migrationFailure({}, `Snapshot restoration failed: ${discovery.errors[0]}`);
282
+ } else if (discovery.candidates.length > 0) {
283
+ snapshot = recovery.snapshot;
284
+ if (branchHasSnapshot && snapshot.meta.durableBase) {
285
+ const selectedRevision = snapshot.meta.durableBase;
286
+ snapshot = runtime.restore(selectedRevision, snapshot);
287
+ if (snapshot.meta.durableBase !== selectedRevision) persist();
288
+ } else if (branchHasSnapshot && snapshot.config.enabled) {
289
+ const publication = runtime.initialize(snapshot, true);
290
+ if (publication) recordPublication(publication, ctx);
291
+ delete snapshot.legacySession;
292
+ }
293
+ installScopeStates();
294
+ } else if (config.autoStart && isNewSession(sessionStartReason, branch)) {
295
+ snapshot = startEpisode(hasPriorConversation(branch));
296
+ runtime.prepare();
297
+ const initialization = runtime.initialize(snapshot, true);
298
+ if (initialization) recordPublication(initialization, ctx);
299
+ if (!runtime.view) snapshot = emptySnapshot();
300
+ installScopeStates();
301
+ if (snapshot.config.enabled) {
302
+ branchHasSnapshot = true;
303
+ persist();
304
+ }
305
+ } else {
306
+ snapshot = emptySnapshot();
307
+ installScopeStates();
308
+ }
309
+ if (snapshot.config.enabled && skipped > 0) {
47
310
  ctx.ui.notify(`State Flow recovered the previous valid snapshot after skipping ${skipped} malformed newer snapshot(s).`, "warning");
48
311
  }
49
312
  } catch (error) {
50
- snapshot = migrationFailure(
51
- {},
52
- `Snapshot restoration failed: ${error instanceof Error ? error.message : String(error)}`,
53
- );
313
+ const failure = migrationFailure({}, `Snapshot restoration failed: ${error instanceof Error ? error.message : String(error)}`);
314
+ snapshot = {
315
+ ...snapshot,
316
+ config: { ...snapshot.config, enabled: false },
317
+ meta: { ...snapshot.meta, validation: failure.meta.validation },
318
+ };
54
319
  }
55
- if (!snapshot.enabled && snapshot.validation?.attempt === 0) {
56
- ctx.ui.notify(`State Flow restored disabled: ${snapshot.validation.error}`, "error");
320
+ pendingPublication = snapshot.meta.pendingPublication === undefined
321
+ ? undefined
322
+ : structuredClone(snapshot.meta.pendingPublication);
323
+ if (!snapshot.config.enabled && snapshot.meta.validation?.attempt === 0) {
324
+ ctx.ui.notify(`State Flow restored disabled: ${snapshot.meta.validation.error}`, "error");
57
325
  }
326
+ syncStateFlowTools();
58
327
  updateUi(ctx);
59
328
  }
60
329
 
@@ -66,9 +335,9 @@ export default function stateFlowExtension(pi: ExtensionAPI): void {
66
335
  }
67
336
 
68
337
  function queueTerminalRegeneration(error: string, ctx: ExtensionContext): void {
69
- const decision = nextValidation(snapshot.validation, error);
338
+ const decision = nextValidation(snapshot.meta.validation, error);
70
339
  if (decision.kind === "retry") {
71
- snapshot.validation = decision.feedback;
340
+ snapshot.meta.validation = decision.feedback;
72
341
  persist();
73
342
  retryQueued = true;
74
343
  pi.sendMessage({
@@ -79,8 +348,9 @@ export default function stateFlowExtension(pi: ExtensionAPI): void {
79
348
  return;
80
349
  }
81
350
  retryQueued = false;
82
- snapshot.validation = undefined;
351
+ snapshot.meta.validation = undefined;
83
352
  skillReads.clear();
353
+ artifactReads.clear();
84
354
  persist();
85
355
  ctx.ui.notify(`State Flow remains enabled after ${MAX_VALIDATION_RETRIES} automatic regeneration attempts; the last committed state was preserved: ${decision.error}`, "error");
86
356
  }
@@ -96,95 +366,229 @@ export default function stateFlowExtension(pi: ExtensionAPI): void {
96
366
  };
97
367
  }
98
368
 
369
+ pi.registerTool({
370
+ name: READ_STATE_TOOL_NAME,
371
+ label: "Read State",
372
+ description: "Read one effective or scoped State Flow materialization at offset 0–7 in the active causal lineage. Read-only and lazy; unavailable pre-origin history is an error. Use only for a concrete historical or scope-specific gap, not routine rereading of current context.",
373
+ promptSnippet: "Read one cached effective/global/CWD/session state at temporal offset 0–7",
374
+ parameters: Type.Object({
375
+ offset: Type.Optional(Type.Integer({ minimum: 0, maximum: 7, description: "Accepted transitions before current state; defaults to 0" })),
376
+ scope: Type.Optional(StringEnum(["effective", "global", "cwd", "session"] as const, { description: "Projection at that same boundary; defaults to effective" })),
377
+ }, { additionalProperties: false }),
378
+ async execute(_toolCallId, params, signal) {
379
+ if (!snapshot.config.enabled) throw new Error("State Flow is disabled on this session branch");
380
+ if (signal?.aborted) throw new Error("State Flow read was aborted");
381
+ if (!runtime?.view) throw new Error("State Flow temporal runtime is unavailable");
382
+ const { offset = 0, scope = "effective" } = params;
383
+ const state = runtime.read(offset, scope === "effective" ? undefined : scope);
384
+ const boundary = runtime.view.lineage.at(-1 - offset)!;
385
+ return {
386
+ content: [{ type: "text", text: JSON.stringify({ offset, scope, boundary, state }) }],
387
+ details: { offset, scope, transitionId: boundary.id },
388
+ };
389
+ },
390
+ });
391
+
392
+ pi.registerTool({
393
+ name: PATCH_STATE_TOOL_NAME,
394
+ 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.",
396
+ promptSnippet: "Materialize established future-relevant state as an immediate inference barrier",
397
+ promptGuidelines: [
398
+ "Use patch_state only when established future-relevant information would face meaningful loss or recovery risk if delayed until terminal reconciliation.",
399
+ "Call patch_state alone in an assistant response; choose subsequent actions only after its compact acknowledgement and rematerialized State Flow context.",
400
+ ],
401
+ executionMode: "sequential",
402
+ parameters: Type.Object({
403
+ scope: StringEnum(["session", "cwd", "global"] as const),
404
+ patch: Type.Record(Type.String(), Type.Unknown()),
405
+ }, { additionalProperties: false }),
406
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
407
+ if (!snapshot.config.enabled) throw new Error("State Flow is disabled on this session branch");
408
+ if (signal?.aborted) throw new Error("State Flow patch was aborted before materialization");
409
+ const stage = stageScopedPatch(
410
+ scopeStates,
411
+ { scope: params.scope as StateScope, patch: params.patch as ScopePatch },
412
+ skillReads.successful.values(),
413
+ runtime!.causalBasis(),
414
+ artifactReads.successful.values(),
415
+ );
416
+ commitStage(stage, ctx, false);
417
+ updateUi(ctx);
418
+ const publication = pendingPublication === undefined ? "" : "; durable publication pending";
419
+ return {
420
+ content: [{ type: "text", text: `State materialized at ${params.scope} scope${publication}.` }],
421
+ details: { scope: params.scope, step: snapshot.meta.step },
422
+ };
423
+ },
424
+ });
425
+
99
426
  pi.registerCommand("state-flow-start", {
100
427
  description: "Start State Flow mode",
101
428
  handler: async (_args, ctx) => {
102
- snapshot = startEpisode(hasPriorConversation(ctx.sessionManager.getBranch()));
103
- stagedFinal = undefined;
104
- retryQueued = false;
105
- runAnchorTimestamp = undefined;
106
- skillReads.clear();
107
- persist();
108
- updateUi(ctx);
109
- ctx.ui.notify(
110
- snapshot.bootstrap
111
- ? "State Flow enabled. The next complete agent run will migrate active context into state."
112
- : "State Flow enabled. The next prompt starts a fresh stateful agent run.",
113
- "info",
114
- );
429
+ if (!activeContext) restoreActiveBranch(ctx);
430
+ const previousSnapshot = structuredClone(snapshot);
431
+ try {
432
+ if (!runtime?.view && !snapshot.meta.durableBase && !branchStartsWithoutRuntime) {
433
+ throw new Error("Selected branch revision is unavailable; restore its original Git history before starting State Flow");
434
+ }
435
+ const branch = ctx.sessionManager.getBranch();
436
+ activeContext = ctx;
437
+ const session = sessionIdentity(ctx);
438
+ runtime ??= new TemporalRuntime(ctx.cwd, session.id, repositoryRoot, session.key);
439
+ if (branchStartsWithoutRuntime) runtime.prepare();
440
+ const bootstrap = (!branchHasSnapshot || !snapshot.config.enabled)
441
+ && hasPriorConversation(branch);
442
+ if (!runtime.view && snapshot.meta.durableBase) {
443
+ snapshot = runtime.restore(snapshot.meta.durableBase, snapshot);
444
+ setPendingPublication(snapshot.meta.pendingPublication);
445
+ branchHasSnapshot = true;
446
+ }
447
+ snapshot = branchHasSnapshot
448
+ ? resumeEpisode(snapshot, bootstrap)
449
+ : startEpisode(bootstrap);
450
+ branchHasSnapshot = true;
451
+ const publication = runtime.view
452
+ ? runtime.promote(snapshot) ?? runtime.publish(snapshot)
453
+ : runtime.initialize(snapshot, true, undefined, branchStartsWithoutRuntime);
454
+ if (publication) recordPublication(publication, ctx);
455
+ installScopeStates();
456
+ delete snapshot.legacySession;
457
+ clearRunTransient();
458
+ refreshArtifactInvalidations(ctx);
459
+ syncStateFlowTools();
460
+ persist();
461
+ updateUi(ctx);
462
+ ctx.ui.notify(
463
+ snapshot.meta.bootstrap
464
+ ? "State Flow enabled. The next complete agent run will migrate active context into state."
465
+ : "State Flow enabled. The next prompt starts a stateful agent run.",
466
+ "info",
467
+ );
468
+ } catch (error) {
469
+ snapshot = previousSnapshot;
470
+ syncStateFlowTools();
471
+ ctx.ui.notify(
472
+ `State Flow could not initialize CWD state: ${error instanceof Error ? error.message : String(error)}`,
473
+ "error",
474
+ );
475
+ }
115
476
  },
116
477
  });
117
478
 
118
479
  pi.registerCommand("state-flow-status", {
119
480
  description: "Show State Flow runtime status",
120
481
  handler: async (_args, ctx) => {
121
- ctx.ui.notify(detailedStatus(snapshot), "info");
482
+ ctx.ui.notify(detailedStatus(snapshot, statusDiagnostics(ctx)), "info");
122
483
  },
123
484
  });
124
485
 
125
486
  pi.registerCommand("state-flow-stop", {
126
- description: "Stop State Flow and clear its complete episode",
487
+ description: "Stop State Flow on the current session branch",
127
488
  handler: async (_args, ctx) => {
128
- snapshot = stopEpisode();
129
- stagedFinal = undefined;
130
- retryQueued = false;
131
- runAnchorTimestamp = undefined;
132
- skillReads.clear();
489
+ if (!activeContext) restoreActiveBranch(ctx);
490
+ let selected = runtime;
491
+ let current = snapshot;
492
+ if (!selected?.view && snapshot.meta.durableBase) {
493
+ const session = sessionIdentity(ctx);
494
+ selected = new TemporalRuntime(ctx.cwd, session.id, repositoryRoot, session.key);
495
+ current = selected.restore(snapshot.meta.durableBase, snapshot);
496
+ }
497
+ const stopped = stopEpisode(current);
498
+ const publication = selected?.view ? selected.publish(stopped) : undefined;
499
+ if (selected !== runtime) {
500
+ runtime = selected;
501
+ installScopeStates();
502
+ }
503
+ snapshot = stopped;
504
+ if (publication) recordPublication(publication, ctx);
505
+ branchHasSnapshot = true;
506
+ clearRunTransient();
507
+ syncStateFlowTools();
133
508
  persist();
134
509
  updateUi(ctx);
135
510
  },
136
511
  });
137
512
 
138
513
  pi.on("before_agent_start", (event) => {
139
- if (!snapshot.enabled) return;
514
+ if (!snapshot.config.enabled) return;
140
515
  if (!retryQueued) {
141
516
  skillReads.clear();
517
+ artifactReads.clear();
142
518
  }
143
- const rotatesRun = snapshot.specification !== undefined && !retryQueued;
519
+ const rotatesRun = snapshot.meta.specification !== undefined && !retryQueued;
144
520
  if (prepareRun(snapshot, event.prompt, retryQueued)) {
145
521
  if (rotatesRun) runAnchorTimestamp = undefined;
146
522
  persist();
147
523
  }
148
524
  return {
149
- systemPrompt: `${event.systemPrompt}\n\n${stateFlowProtocol(snapshot.bootstrap === true)}`,
525
+ systemPrompt: `${event.systemPrompt}\n\n${stateFlowProtocol(snapshot.meta.bootstrap === true)}`,
150
526
  };
151
527
  });
152
528
 
153
529
  pi.on("context", (event) => {
154
- if (!snapshot.enabled || snapshot.specification === undefined) return;
155
- if (snapshot.bootstrap) {
156
- if (retryQueued) return;
530
+ if (!snapshot.config.enabled || snapshot.meta.specification === undefined) return;
531
+ const effectiveState = overlayStates(scopeStates.global, scopeStates.cwd, scopeStates.session);
532
+ const recentTransitions = projectRecentTransitionsWithLimit(
533
+ snapshot.config.transitionWindow,
534
+ runtime?.recent() ?? [],
535
+ );
536
+ if (snapshot.meta.bootstrap) {
157
537
  const messages = withoutPrivateValidation(event.messages as AgentMessage[]);
158
- return messages.length === event.messages.length ? undefined : { messages };
538
+ return { messages: [runtimeContextMessage(snapshot, effectiveState, recentTransitions, artifactInvalidations), ...messages] };
159
539
  }
160
540
  const trajectory = currentRunTrajectory(
161
541
  event.messages as AgentMessage[],
162
- snapshot.specification,
542
+ snapshot.meta.specification,
163
543
  runAnchorTimestamp,
164
544
  );
165
545
  runAnchorTimestamp = trajectory.anchorTimestamp;
166
- return { messages: [runtimeContextMessage(snapshot), ...trajectory.messages] };
546
+ return {
547
+ messages: [
548
+ runtimeContextMessage(snapshot, effectiveState, recentTransitions, artifactInvalidations),
549
+ ...trajectory.messages,
550
+ ],
551
+ };
167
552
  });
168
553
 
169
554
  pi.on("tool_execution_start", (event) => {
170
- if (!snapshot.enabled) return;
555
+ if (!snapshot.config.enabled) return;
171
556
  // Pi emits this before tool_call. Keep the argument object as a fallback;
172
557
  // tool_call replaces it with the mutable, post-preflight input reference.
173
558
  skillReads.recordStart(event.toolCallId, event.toolName, event.args);
559
+ artifactReads.recordStart(event.toolCallId, event.toolName, event.args);
174
560
  });
175
561
 
176
- pi.on("tool_call", (event) => {
177
- if (!snapshot.enabled) return;
562
+ pi.on("tool_call", (event, ctx) => {
563
+ if (!snapshot.config.enabled) return;
564
+ const batch = assistantToolBatch(ctx, event.toolCallId);
565
+ const patchCalls = batch?.filter((name) => name === PATCH_STATE_TOOL_NAME).length ?? 0;
566
+ if (patchCalls > 0) {
567
+ if (patchCalls !== 1) {
568
+ return {
569
+ block: true,
570
+ reason: "A State Flow barrier response must contain exactly one patch_state call",
571
+ };
572
+ }
573
+ if (event.toolName !== PATCH_STATE_TOOL_NAME) {
574
+ return {
575
+ block: true,
576
+ reason: "Blocked by the patch_state barrier; reconsider this action after State Flow rematerializes context",
577
+ };
578
+ }
579
+ }
178
580
  skillReads.recordCall(event.toolCallId, event.toolName, event.input);
581
+ artifactReads.recordCall(event.toolCallId, event.toolName, event.input);
179
582
  });
180
583
 
181
584
  pi.on("tool_execution_end", (event) => {
182
- if (!snapshot.enabled) return;
585
+ if (!snapshot.config.enabled) return;
183
586
  skillReads.recordEnd(event.toolCallId, event.toolName, event.isError);
587
+ artifactReads.recordEnd(event.toolCallId, event.toolName, event.isError);
184
588
  });
185
589
 
186
590
  pi.on("message_end", (event, ctx): any => {
187
- if (!snapshot.enabled || event.message.role !== "assistant") return;
591
+ if (!snapshot.config.enabled || event.message.role !== "assistant") return;
188
592
  stagedFinal = undefined;
189
593
  const message = event.message as unknown as { role: "assistant"; stopReason?: string; content?: unknown };
190
594
  if (message.stopReason === "aborted") {
@@ -195,7 +599,7 @@ export default function stateFlowExtension(pi: ExtensionAPI): void {
195
599
  return rejectTerminal(message, `Assistant response ended with ${message.stopReason}`, ctx);
196
600
  }
197
601
  if (assistantToolCallCount(message.content) > 0 || message.stopReason === "toolUse") {
198
- retryQueued = snapshot.validation !== undefined;
602
+ retryQueued = snapshot.meta.validation !== undefined;
199
603
  const cleaned = stripStateComments(message.content);
200
604
  return cleaned.changed
201
605
  ? { message: { ...message, role: "assistant" as const, content: cleaned.content } }
@@ -203,7 +607,13 @@ export default function stateFlowExtension(pi: ExtensionAPI): void {
203
607
  }
204
608
  try {
205
609
  const parsed = parseTerminalPatch(message.content);
206
- stagedFinal = stageTransition(snapshot.state, parsed.patch, skillReads.successful);
610
+ stagedFinal = stageScopedTransition(
611
+ scopeStates,
612
+ parsed.transition,
613
+ skillReads.successful.values(),
614
+ runtime!.causalBasis(),
615
+ artifactReads.successful.values(),
616
+ );
207
617
  retryQueued = false;
208
618
  return { message: { ...message, role: "assistant" as const, content: parsed.responseContent } };
209
619
  } catch (error) {
@@ -212,16 +622,13 @@ export default function stateFlowExtension(pi: ExtensionAPI): void {
212
622
  });
213
623
 
214
624
  pi.on("turn_end", (event, ctx) => {
215
- if (!snapshot.enabled || !stagedFinal) {
625
+ if (!snapshot.config.enabled || !stagedFinal) {
216
626
  updateUi(ctx);
217
627
  return;
218
628
  }
219
629
  try {
220
- stagedFinal.nextState.response = finalizedAssistantResponse(event.message);
221
- if (commitTransition(snapshot, stagedFinal)) {
222
- skillReads.clear();
223
- persist();
224
- }
630
+ stagedFinal.nextStates.session.response = finalizedAssistantResponse(event.message);
631
+ commitStage(stagedFinal, ctx, true);
225
632
  } catch (error) {
226
633
  queueTerminalRegeneration(error instanceof Error ? error.message : String(error), ctx);
227
634
  }
@@ -230,9 +637,17 @@ export default function stateFlowExtension(pi: ExtensionAPI): void {
230
637
  });
231
638
 
232
639
  pi.on("agent_settled", (_event, ctx) => {
233
- if (snapshot.enabled && retryQueued) abandonRun(ctx);
640
+ if (snapshot.config.enabled && retryQueued) abandonRun(ctx);
234
641
  });
235
642
 
236
- pi.on("session_start", (_event, ctx) => restoreActiveBranch(ctx));
237
- pi.on("session_tree", (_event, ctx) => restoreActiveBranch(ctx));
643
+ pi.on("session_start", (event, ctx) => {
644
+ restoreActiveBranch(ctx, event.reason);
645
+ refreshArtifactInvalidations(ctx);
646
+ retryPendingPush(ctx);
647
+ updateUi(ctx);
648
+ });
649
+ pi.on("session_tree", (_event, ctx) => {
650
+ restoreActiveBranch(ctx);
651
+ refreshArtifactInvalidations(ctx);
652
+ });
238
653
  }