@llblab/pi-state-flow 0.26.1 → 0.26.3

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/CHANGELOG.md CHANGED
@@ -2,6 +2,14 @@
2
2
 
3
3
  > Each release keeps at most 8 outcome records of at most 512 characters.
4
4
 
5
+ ## 0.26.3: Passive Response Isolation
6
+
7
+ - `Passive context`: Automatic Passive memory heads, Stop handoffs and state-update receipts omit the `response` plane, including after reload and mode changes. Active still sees the previous accepted answer. Canonical response storage, explicit reads and native/user/tool history are unchanged; no migration or configuration change is required.
8
+
9
+ ## 0.26.2: Automatic Response Guidance
10
+
11
+ - `Response ownership`: Active/bootstrap and Passive prompts explicitly forbid patching `response`; the `patch_state` guidelines forbid it in Global, CWD and Session, including clearing/deleting it, and explain that Active mode captures the final answer automatically. Runtime validation and answer capture are unchanged. No migration or configuration change is required.
12
+
5
13
  ## 0.26.1: Consistent Temporary Paths and Mode Colors
6
14
 
7
15
  - `Telegram mode colors`: The selected mode uses 🟣 Off, 🟡 Passive or 🟢 Active; unselected options remain ⚫️. Mode behavior and callbacks are unchanged.
package/README.md CHANGED
@@ -81,7 +81,7 @@ New sessions default to **Off**. Choose Passive for ordinary conversation with m
81
81
  ### Active, passive, off
82
82
 
83
83
  - `Active`: Memory tools are available, and the agent consolidates necessary final state changes before completing an iteration. Later iterations use accepted state and new input rather than completed prior reasoning.
84
- - `Passive`: Both memory tools are available, and existing state is projected once a validated memory view is available. The agent patches on demand, and ordinary conversation context continues without State Flow's active iteration reset.
84
+ - `Passive`: Both memory tools are available, and existing state except `response` is projected once a validated memory view is available. The agent patches on demand, and ordinary conversation context continues without State Flow's active iteration reset.
85
85
  - `Off`: The model sees neither memory tool nor any State Flow context, including a frozen passive handoff.
86
86
  - Startup, reload and tree attachment do not read or restore memory.
87
87
  - Selecting Off cancels pending memory waits and records only native policy/bookmarks.
@@ -115,7 +115,7 @@ Runtime views provide these documented planes:
115
115
  - `contract`: Requirements, decisions, rejected approaches, constraints and interface commitments.
116
116
  - `working`: Temporary context of those actions: observations, results and uncertainties.
117
117
  - `artifacts`: Source-addressed descriptions and compiled knowledge.
118
- - `response`: The exact latest accepted answer, including an empty string. The runtime captures it only in Session; Global/CWD receive no newly accepted answers, and stored scopes may omit it entirely. Effective uses the highest-priority nonempty value.
118
+ - `response`: The exact latest accepted answer, including an empty string. The runtime captures it only in Session; Global/CWD receive no newly accepted answers, and stored scopes may omit it entirely. Effective uses the highest-priority nonempty value. Active automatically projects it; Passive omits it from automatic context while keeping storage and explicit reads intact.
119
119
  - `lazy`: Supporting memory available through explicit reads; its body is omitted from baseline model context.
120
120
 
121
121
  Every plane is optional on disk:
@@ -39,7 +39,7 @@ export interface ContextView {
39
39
  phase: RehydrationPhase;
40
40
  } | null;
41
41
  }
42
- export declare function contextView(state: SemanticState, hints: ArtifactModelHints, invalidations: readonly ArtifactInvalidationNotice[], phase?: RehydrationPhase): ContextView;
42
+ export declare function contextView(state: SemanticState, hints: ArtifactModelHints, invalidations: readonly ArtifactInvalidationNotice[], phase?: RehydrationPhase, includeResponse?: boolean): ContextView;
43
43
  /** Volatile model projection only. Native messages own trajectory; this cache owns no persistence or lifecycle. */
44
44
  export declare class ContextProjection {
45
45
  private identity;
@@ -49,7 +49,7 @@ export declare class ContextProjection {
49
49
  private notices;
50
50
  reset(): void;
51
51
  /** Called only after successful publication and ancillary acceptance, immediately before returning the native result. */
52
- acceptPatch(before: SemanticState, after: SemanticState, patches: AtomicScopePatches, hints: ArtifactModelHints, cascades?: Partial<Record<StateScope, readonly OwnedPath[]>>): {
52
+ acceptPatch(before: SemanticState, after: SemanticState, patches: AtomicScopePatches, hints: ArtifactModelHints, cascades?: Partial<Record<StateScope, readonly OwnedPath[]>>, includeResponse?: boolean): {
53
53
  effective: ModelStateUpdate[];
54
54
  lazy_navigation?: {
55
55
  available: boolean;
@@ -129,8 +129,14 @@ function projectedStateUpdates(previous, current, patches, beforeNavigation, nav
129
129
  }
130
130
  return { effective, ...(navigation !== undefined && (beforeNavigation === undefined || !sameJson(beforeNavigation, navigation)) ? { lazy_navigation: navigation } : {}) };
131
131
  }
132
- export function contextView(state, hints, invalidations, phase) {
133
- return { state: projectStateForModel(state, hints), lazy_navigation: lazyNavigationHint(state),
132
+ function projectContextState(state, hints, includeResponse) {
133
+ const projected = projectStateForModel(state, hints);
134
+ if (!includeResponse)
135
+ delete projected.response;
136
+ return projected;
137
+ }
138
+ export function contextView(state, hints, invalidations, phase, includeResponse = true) {
139
+ return { state: projectContextState(state, hints, includeResponse), lazy_navigation: lazyNavigationHint(state),
134
140
  artifact_invalidations: structuredClone(invalidations), knowledge_rehydration: phase === undefined ? null : { phase } };
135
141
  }
136
142
  /** Volatile model projection only. Native messages own trajectory; this cache owns no persistence or lifecycle. */
@@ -148,11 +154,11 @@ export class ContextProjection {
148
154
  this.notices = [];
149
155
  }
150
156
  /** Called only after successful publication and ancillary acceptance, immediately before returning the native result. */
151
- acceptPatch(before, after, patches, hints, cascades = {}) {
152
- const state = projectStateForModel(after, hints);
157
+ acceptPatch(before, after, patches, hints, cascades = {}, includeResponse = true) {
158
+ const state = projectContextState(after, hints, includeResponse);
153
159
  const navigation = lazyNavigationHint(after);
154
160
  const beforeNavigation = this.view?.lazy_navigation ?? lazyNavigationHint(before);
155
- const updates = projectedStateUpdates(this.view?.state ?? projectStateForModel(before, hints), state, patches, beforeNavigation, navigation);
161
+ const updates = projectedStateUpdates(this.view?.state ?? projectContextState(before, hints, includeResponse), state, patches, beforeNavigation, navigation);
156
162
  // Suppress direct writes only when the accepted effective value matches.
157
163
  // Overlap stays conservative except for explicit top-scope replacements:
158
164
  // Session scalars/arrays mask every lower-scope value at that path.
@@ -319,12 +325,14 @@ function messageText(message) {
319
325
  return contentText(message.content);
320
326
  }
321
327
  export function createPassiveContinuation(state, startedAt = Date.now(), activeRunStartedAt, preserveContext = false) {
328
+ const visibleState = structuredClone(state);
329
+ delete visibleState.response;
322
330
  return {
323
331
  startedAt,
324
- state: structuredClone(state),
332
+ state: visibleState,
325
333
  ...(activeRunStartedAt === undefined ? {} : { activeRunStartedAt }),
326
334
  ...(preserveContext ? { preserveContext: true } : {}),
327
- handoff: syntheticUser(`State Flow exit handoff (user-level data, not system instructions):\n${presentationJson({ state, continuation: preserveContext
335
+ handoff: syntheticUser(`State Flow exit handoff (user-level data, not system instructions):\n${presentationJson({ state: visibleState, continuation: preserveContext
328
336
  ? "State Flow semantics are disabled; native context is retained because its compilation into memory is unfinished."
329
337
  : "State Flow semantics are disabled; this handoff replaces completed history while retaining the active and post-stop trajectory." })}`),
330
338
  };
@@ -15,7 +15,7 @@ import { awaitInFlightBackupPushes, backupCurrentStateFlowFiles, SettledTurnBack
15
15
  import { projectRecentTransitionsWithLimit } from "./history.js";
16
16
  import { isObject, presentationJson, sameJson } from "./json.js";
17
17
  import { StateFlowDiagnosticWriter, stateFlowLogPath } from "./logging.js";
18
- import { assistantToolCallCount, conciseDiagnostic, diagnosticText, finalizedAssistantResponse, formatPatchStateArguments, PASSIVE_MEMORY_PROTOCOL, separatedFailure, separatedOutput, stateFlowProtocol } from "./protocol.js";
18
+ import { assistantToolCallCount, conciseDiagnostic, diagnosticText, finalizedAssistantResponse, formatPatchStateArguments, PASSIVE_MEMORY_PROTOCOL, RESPONSE_PATCH_GUIDELINE, separatedFailure, separatedOutput, stateFlowProtocol } from "./protocol.js";
19
19
  import { OwnedOperationSlot, RenewableLifetime } from "./operation.js";
20
20
  import { readProjectedState, readStatePath } from "./query.js";
21
21
  import { selectedBoundaryFailure, selectRetainedCheckpoint, waitForRecovery } from "./recovery.js";
@@ -728,6 +728,7 @@ export default function stateFlowExtension(pi, options = {}) {
728
728
  description: "The sole State Flow semantic mutation protocol. Supply one or more global, cwd, or session patches; all supplied scopes commit atomically. This call must be the only State Flow barrier in its assistant response. Deleting an intent also deletes same-scope working/lazy keys its {\"$ref\"} values own unless another intent refs them. Name keys in ASCII ([A-Za-z_$][A-Za-z0-9_$-]*) so read paths and refs resolve; values may use any language.",
729
729
  promptSnippet: "Atomically patch one or more global/cwd/session scopes",
730
730
  promptGuidelines: [
731
+ RESPONSE_PATCH_GUIDELINE,
731
732
  "Use patch_state only for material durable semantic changes; ordinary answers need no finalization call.",
732
733
  "Use patch_state as reconciliation, not append-only notes: place new knowledge at the narrowest valid scope and remove superseded or completed state from touched branches.",
733
734
  "Call patch_state alone in an assistant response; after its acknowledgement, further reasoning, tools, and later patch_state calls remain allowed.",
@@ -811,7 +812,7 @@ export default function stateFlowExtension(pi, options = {}) {
811
812
  }
812
813
  clearAcceptedAcquisitions(new Set(acquiredArtifacts.map(({ path }) => path)));
813
814
  updateUi(ctx);
814
- const updates = contextProjection.acceptPatch(previousEffective, effectiveState, patches, acquisition.hints, stage.cascades);
815
+ const updates = contextProjection.acceptPatch(previousEffective, effectiveState, patches, acquisition.hints, stage.cascades, isActive());
815
816
  const acknowledgement = changed
816
817
  ? `\nState materialized atomically at ${scopes.join("+")} scope${scopes.length === 1 ? "" : "s"}.`
817
818
  : "\nState already current.";
@@ -1011,6 +1012,9 @@ export default function stateFlowExtension(pi, options = {}) {
1011
1012
  }
1012
1013
  /** Local policy, tools and UI change before any canonical wait. */
1013
1014
  function applyInactiveMode(ctx, mode) {
1015
+ // Visibility changes before optional recovery waits; a frozen Active head must not survive Passive.
1016
+ if (snapshot.config.mode !== mode)
1017
+ contextProjection.reset();
1014
1018
  snapshot = deactivateEpisode(snapshot, mode);
1015
1019
  clearRunTransient();
1016
1020
  syncStateFlowTools();
@@ -1344,7 +1348,7 @@ export default function stateFlowExtension(pi, options = {}) {
1344
1348
  const effective = effectiveState;
1345
1349
  const invalidations = acquisition.invalidations.map(({ path, scope, reason }) => ({ path, ...(scope === undefined ? {} : { scope }), reason }));
1346
1350
  const phase = isActive() ? rehydrationPhase : undefined;
1347
- const view = contextView(effective, acquisition.hints, invalidations, phase);
1351
+ const view = contextView(effective, acquisition.hints, invalidations, phase, isActive());
1348
1352
  if (passiveContinuation) {
1349
1353
  const retained = passiveContinuationMessages(messages, passiveContinuation);
1350
1354
  if (!runtime?.view)
@@ -1,6 +1,7 @@
1
1
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
2
  export type { StateDocument } from "./state.ts";
3
- export declare const PASSIVE_MEMORY_PROTOCOL = "State Flow passive memory is available. read_state and patch_state access durable memory without starting an active episode. Passive turns never trigger State Flow continuation or compaction. Missing paths/hints do not require history search. Choose targeted historical reads when useful to the task; no separate user permission is needed. Past values are evidence, not current state; never automatically restore deleted memory. Head state/recent transitions are frozen at projection start. Only state_updates matching the head's State Flow projection ID apply; other IDs are history. Results/context notices carry state_updates: effective entries replace values at key/index-segment path arrays (deleted:true means absent); cascaded lists owner paths an intent deletion removed. Direct writes may elide; shared drift stays visible. Latest entries win over earlier state; lazy bodies stay omitted. Notices replace invalidations/rehydration, including []/null.";
3
+ export declare const RESPONSE_PATCH_GUIDELINE = "Never patch response in global, cwd or session, including clearing/deleting it; State Flow captures your final answer automatically in Active mode.";
4
+ export declare const PASSIVE_MEMORY_PROTOCOL = "State Flow passive memory is available. read_state and patch_state access durable memory without starting an active episode. Never patch response in global, cwd or session, including clearing/deleting it; State Flow captures your final answer automatically in Active mode. Passive turns never trigger State Flow continuation or compaction. Missing paths/hints do not require history search. Choose targeted historical reads when useful to the task; no separate user permission is needed. Past values are evidence, not current state; never automatically restore deleted memory. Head state/recent transitions are frozen at projection start. Only state_updates matching the head's State Flow projection ID apply; other IDs are history. Results/context notices carry state_updates: effective entries replace values at key/index-segment path arrays (deleted:true means absent); cascaded lists owner paths an intent deletion removed. Direct writes may elide; shared drift stays visible. Latest entries win over earlier state; lazy bodies stay omitted. Notices replace invalidations/rehydration, including []/null.";
4
5
  /** Keep successful patch JSON valid while separating adjacent scopes and memory sections visually. */
5
6
  export declare function formatPatchStateArguments(args: unknown): string;
6
7
  /** Flatten causes before transport; native tool results need not retain Error.cause or AggregateError.errors. */
@@ -1,6 +1,7 @@
1
1
  const TASK_DRIVEN_HISTORY = "Missing paths/hints do not require history search. Choose targeted historical reads when useful to the task; no separate user permission is needed. Past values are evidence, not current state; never automatically restore deleted memory.";
2
2
  const PATCH_RESULT_PROTOCOL = "Head state/recent transitions are frozen at projection start. Only state_updates matching the head's State Flow projection ID apply; other IDs are history. Results/context notices carry state_updates: effective entries replace values at key/index-segment path arrays (deleted:true means absent); cascaded lists owner paths an intent deletion removed. Direct writes may elide; shared drift stays visible. Latest entries win over earlier state; lazy bodies stay omitted. Notices replace invalidations/rehydration, including []/null.";
3
- export const PASSIVE_MEMORY_PROTOCOL = `State Flow passive memory is available. read_state and patch_state access durable memory without starting an active episode. Passive turns never trigger State Flow continuation or compaction. ${TASK_DRIVEN_HISTORY} ${PATCH_RESULT_PROTOCOL}`;
3
+ export const RESPONSE_PATCH_GUIDELINE = "Never patch response in global, cwd or session, including clearing/deleting it; State Flow captures your final answer automatically in Active mode.";
4
+ export const PASSIVE_MEMORY_PROTOCOL = `State Flow passive memory is available. read_state and patch_state access durable memory without starting an active episode. ${RESPONSE_PATCH_GUIDELINE} Passive turns never trigger State Flow continuation or compaction. ${TASK_DRIVEN_HISTORY} ${PATCH_RESULT_PROTOCOL}`;
4
5
  const PATCH_DISPLAY_SECTION_KEYS = new Set(["global", "cwd", "session", "intents", "contract", "working", "artifacts", "response", "lazy"]);
5
6
  /** Keep successful patch JSON valid while separating adjacent scopes and memory sections visually. */
6
7
  export function formatPatchStateArguments(args) {
@@ -88,7 +89,7 @@ ${bootstrapProtocol}STATE:
88
89
  - contract: durable requirements, decisions, rejections, interfaces.
89
90
  - working: temporary context of intents: facts, validation, failures, domain state.
90
91
  - artifacts: source-path routing metadata; descriptions do not imply body acquisition.
91
- - response: previous answer; runtime stores the exact accepted answer at turn_end (empty="").
92
+ - response: read-only prior answer; never patch it in any scope. Auto-stored at turn_end (empty="").
92
93
  - lazy: retrieve explicitly.
93
94
 
94
95
  SCOPES: Use the narrowest scope: session=branch/run continuation by default; cwd=reusable project truth; global=established cross-project/user/environment knowledge.
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@llblab/pi-state-flow",
3
- "version": "0.26.1",
3
+ "version": "0.26.3",
4
4
  "license": "MIT",
5
5
  "private": false,
6
6
  "description": "Incremental scoped state/context/memory compiler for Pi, inspired by SKILL.state",
@@ -42,7 +42,7 @@ Runtime views select these documented semantic planes when present. Stored scope
42
42
  - `contract` retains durable requirements, decisions, interfaces and rejected approaches.
43
43
  - `working` is the temporary working context of those actions: verified current facts, results and uncertainties.
44
44
  - `artifacts` maps exact source paths to compiled routing metadata.
45
- - `response` is owned only by the session scope and stores the exact latest accepted assistant answer, including the empty string. Global/CWD do not receive newly accepted answers, and stored scopes may omit response entirely. An explicit nonempty Session answer overrides inherited values; an empty or absent response contributes nothing to projection.
45
+ - `response` is owned only by the session scope and stores the exact latest accepted assistant answer, including the empty string. Global/CWD do not receive newly accepted answers, and stored scopes may omit response entirely. An explicit nonempty Session answer overrides inherited values; an empty or absent response contributes nothing to Active projection. Automatic Passive context omits the response plane, including frozen Stop handoffs and state-update receipts. Canonical storage, explicit reads and native answer text are unchanged.
46
46
  - `lazy` is an optional stored object root for ordinary JSON detail. It defaults to `{}` only in internal compatibility views, is omitted from baseline model state and is read explicitly.
47
47
  - Automatic recent-transition projection also removes each whole `patch.lazy`, including deletions. Empty scoped patches and transitions disappear, and an empty projected window is omitted.
48
48
  - Visible hot patches keep their original identities, order and positions. Canonical history and explicit current/historical reads are unchanged.
@@ -61,7 +61,7 @@ Later scopes win. A scope-local `null` deletion removes only that scope's key an
61
61
  - Checkpoint/tail codecs select only known top-level fields on read and write; unknown fields are neither kept in runtime streams nor carried into later writes. Nested data within known planes stays intact.
62
62
  - Retained record identities and positions survive even when filtering leaves an empty patch.
63
63
  - `readTemporalView` selects present known fields at the requested boundary, then overlays scopes without inventing fields.
64
- - Empty and absent responses mean the same for projection; clearing a nonempty response projects as a deletion.
64
+ - Empty and absent responses mean the same for Active projection; clearing a nonempty response projects as a deletion. Passive omits the plane regardless of its value.
65
65
  - Explicit reads of absent documented top-level fields return `null`.
66
66
  - `readTemporalState` and the embedding callback keep default-bearing compatibility views for internal registry consumers. Those defaults never become stored overrides or model context.
67
67
  - Passive reads and Start do not fill checkpoint fields or create revisions for normalization; missing shared pairs initialize as empty objects.
package/docs/usage.md CHANGED
@@ -13,7 +13,8 @@ State Flow has three distinct model-facing states. **Active versus passive chang
13
13
  - The final meaningful semantic patch preserves the decisions, outcomes and continuation needed once the completed conversation leaves model projection.
14
14
  - The next iteration starts from accepted state and its new input, not from the previous iteration's completed reasoning.
15
15
  - The native trace stays inspectable: a clean model context does not mean deleting Pi history.
16
- - **Passive:** Both memory tools are available, existing state is projected into context, and the agent may read or patch it as useful.
16
+ - **Passive:** Both memory tools are available, existing state except the `response` plane is projected into context, and the agent may read or patch memory as useful.
17
+ - The last Active answer is not repeated in automatic memory context, Stop handoffs or state updates. Its stored value and explicit `read_state` access remain intact; native/user/tool history is not redacted.
17
18
  - Ordinary conversation continuity remains: there is no active iteration-ending context reset and no mandatory consolidation pressure.
18
19
  - Accepted patches still reach the same canonical store, with the same validation and ownership guarantees.
19
20
  - **Off:** Neither memory tool is exposed to the model, and State Flow injects no protocol, bootstrap/state context or frozen passive handoff. Stored memory and the native conversation trace are not deleted.
package/lib/context.ts CHANGED
@@ -121,8 +121,14 @@ export interface ContextView {
121
121
  knowledge_rehydration: { phase: RehydrationPhase } | null;
122
122
  }
123
123
 
124
- export function contextView(state: SemanticState, hints: ArtifactModelHints, invalidations: readonly ArtifactInvalidationNotice[], phase?: RehydrationPhase): ContextView {
125
- return { state: projectStateForModel(state, hints), lazy_navigation: lazyNavigationHint(state),
124
+ function projectContextState(state: SemanticState, hints: ArtifactModelHints, includeResponse: boolean): SemanticState {
125
+ const projected = projectStateForModel(state, hints);
126
+ if (!includeResponse) delete projected.response;
127
+ return projected;
128
+ }
129
+
130
+ export function contextView(state: SemanticState, hints: ArtifactModelHints, invalidations: readonly ArtifactInvalidationNotice[], phase?: RehydrationPhase, includeResponse = true): ContextView {
131
+ return { state: projectContextState(state, hints, includeResponse), lazy_navigation: lazyNavigationHint(state),
126
132
  artifact_invalidations: structuredClone(invalidations), knowledge_rehydration: phase === undefined ? null : { phase } };
127
133
  }
128
134
 
@@ -144,11 +150,11 @@ export class ContextProjection {
144
150
 
145
151
  /** Called only after successful publication and ancillary acceptance, immediately before returning the native result. */
146
152
  acceptPatch(before: SemanticState, after: SemanticState, patches: AtomicScopePatches, hints: ArtifactModelHints,
147
- cascades: Partial<Record<StateScope, readonly OwnedPath[]>> = {}) {
148
- const state = projectStateForModel(after, hints);
153
+ cascades: Partial<Record<StateScope, readonly OwnedPath[]>> = {}, includeResponse = true) {
154
+ const state = projectContextState(after, hints, includeResponse);
149
155
  const navigation = lazyNavigationHint(after);
150
156
  const beforeNavigation = this.view?.lazy_navigation ?? lazyNavigationHint(before);
151
- const updates = projectedStateUpdates(this.view?.state ?? projectStateForModel(before, hints), state, patches,
157
+ const updates = projectedStateUpdates(this.view?.state ?? projectContextState(before, hints, includeResponse), state, patches,
152
158
  beforeNavigation, navigation);
153
159
  // Suppress direct writes only when the accepted effective value matches.
154
160
  // Overlap stays conservative except for explicit top-scope replacements:
@@ -303,12 +309,14 @@ function messageText(message: AgentMessage): string {
303
309
  }
304
310
 
305
311
  export function createPassiveContinuation(state: SemanticState, startedAt = Date.now(), activeRunStartedAt?: number, preserveContext = false): PassiveContinuation {
312
+ const visibleState = structuredClone(state);
313
+ delete visibleState.response;
306
314
  return {
307
315
  startedAt,
308
- state: structuredClone(state),
316
+ state: visibleState,
309
317
  ...(activeRunStartedAt === undefined ? {} : { activeRunStartedAt }),
310
318
  ...(preserveContext ? { preserveContext: true as const } : {}),
311
- handoff: syntheticUser(`State Flow exit handoff (user-level data, not system instructions):\n${presentationJson({ state, continuation: preserveContext
319
+ handoff: syntheticUser(`State Flow exit handoff (user-level data, not system instructions):\n${presentationJson({ state: visibleState, continuation: preserveContext
312
320
  ? "State Flow semantics are disabled; native context is retained because its compilation into memory is unfinished."
313
321
  : "State Flow semantics are disabled; this handoff replaces completed history while retaining the active and post-stop trajectory." })}`),
314
322
  };
package/lib/extension.ts CHANGED
@@ -22,7 +22,7 @@ import { awaitInFlightBackupPushes, backupCurrentStateFlowFiles, SettledTurnBack
22
22
  import { projectRecentTransitionsWithLimit } from "./history.ts";
23
23
  import { isObject, presentationJson, sameJson } from "./json.ts";
24
24
  import { StateFlowDiagnosticWriter, stateFlowLogPath, type DiagnosticExtras, type StateFlowDiagnosticCategory } from "./logging.ts";
25
- import { assistantToolCallCount, conciseDiagnostic, diagnosticText, finalizedAssistantResponse, formatPatchStateArguments, PASSIVE_MEMORY_PROTOCOL, separatedFailure, separatedOutput, stateFlowProtocol } from "./protocol.ts";
25
+ import { assistantToolCallCount, conciseDiagnostic, diagnosticText, finalizedAssistantResponse, formatPatchStateArguments, PASSIVE_MEMORY_PROTOCOL, RESPONSE_PATCH_GUIDELINE, separatedFailure, separatedOutput, stateFlowProtocol } from "./protocol.ts";
26
26
  import { OwnedOperationSlot, RenewableLifetime, type OwnedOperation } from "./operation.ts";
27
27
  import { readProjectedState, readStatePath } from "./query.ts";
28
28
  import { selectedBoundaryFailure, selectRetainedCheckpoint, waitForRecovery } from "./recovery.ts";
@@ -746,6 +746,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
746
746
  description: "The sole State Flow semantic mutation protocol. Supply one or more global, cwd, or session patches; all supplied scopes commit atomically. This call must be the only State Flow barrier in its assistant response. Deleting an intent also deletes same-scope working/lazy keys its {\"$ref\"} values own unless another intent refs them. Name keys in ASCII ([A-Za-z_$][A-Za-z0-9_$-]*) so read paths and refs resolve; values may use any language.",
747
747
  promptSnippet: "Atomically patch one or more global/cwd/session scopes",
748
748
  promptGuidelines: [
749
+ RESPONSE_PATCH_GUIDELINE,
749
750
  "Use patch_state only for material durable semantic changes; ordinary answers need no finalization call.",
750
751
  "Use patch_state as reconciliation, not append-only notes: place new knowledge at the narrowest valid scope and remove superseded or completed state from touched branches.",
751
752
  "Call patch_state alone in an assistant response; after its acknowledgement, further reasoning, tools, and later patch_state calls remain allowed.",
@@ -820,7 +821,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
820
821
  }
821
822
  clearAcceptedAcquisitions(new Set(acquiredArtifacts.map(({ path }) => path)));
822
823
  updateUi(ctx);
823
- const updates = contextProjection.acceptPatch(previousEffective, effectiveState, patches, acquisition.hints, stage.cascades);
824
+ const updates = contextProjection.acceptPatch(previousEffective, effectiveState, patches, acquisition.hints, stage.cascades, isActive());
824
825
  const acknowledgement = changed
825
826
  ? `\nState materialized atomically at ${scopes.join("+")} scope${scopes.length === 1 ? "" : "s"}.`
826
827
  : "\nState already current.";
@@ -1006,6 +1007,8 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
1006
1007
 
1007
1008
  /** Local policy, tools and UI change before any canonical wait. */
1008
1009
  function applyInactiveMode(ctx: ExtensionContext, mode: InactiveMode): void {
1010
+ // Visibility changes before optional recovery waits; a frozen Active head must not survive Passive.
1011
+ if (snapshot.config.mode !== mode) contextProjection.reset();
1009
1012
  snapshot = deactivateEpisode(snapshot, mode);
1010
1013
  clearRunTransient();
1011
1014
  syncStateFlowTools();
@@ -1324,7 +1327,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
1324
1327
  const effective = effectiveState;
1325
1328
  const invalidations = acquisition.invalidations.map(({ path, scope, reason }) => ({ path, ...(scope === undefined ? {} : { scope }), reason }));
1326
1329
  const phase = isActive() ? rehydrationPhase : undefined;
1327
- const view = contextView(effective, acquisition.hints, invalidations, phase);
1330
+ const view = contextView(effective, acquisition.hints, invalidations, phase, isActive());
1328
1331
  if (passiveContinuation) {
1329
1332
  const retained = passiveContinuationMessages(messages, passiveContinuation);
1330
1333
  if (!runtime?.view) return { messages: retained };
package/lib/protocol.ts CHANGED
@@ -6,7 +6,9 @@ const TASK_DRIVEN_HISTORY = "Missing paths/hints do not require history search.
6
6
 
7
7
  const PATCH_RESULT_PROTOCOL = "Head state/recent transitions are frozen at projection start. Only state_updates matching the head's State Flow projection ID apply; other IDs are history. Results/context notices carry state_updates: effective entries replace values at key/index-segment path arrays (deleted:true means absent); cascaded lists owner paths an intent deletion removed. Direct writes may elide; shared drift stays visible. Latest entries win over earlier state; lazy bodies stay omitted. Notices replace invalidations/rehydration, including []/null.";
8
8
 
9
- export const PASSIVE_MEMORY_PROTOCOL = `State Flow passive memory is available. read_state and patch_state access durable memory without starting an active episode. Passive turns never trigger State Flow continuation or compaction. ${TASK_DRIVEN_HISTORY} ${PATCH_RESULT_PROTOCOL}`;
9
+ export const RESPONSE_PATCH_GUIDELINE = "Never patch response in global, cwd or session, including clearing/deleting it; State Flow captures your final answer automatically in Active mode.";
10
+
11
+ export const PASSIVE_MEMORY_PROTOCOL = `State Flow passive memory is available. read_state and patch_state access durable memory without starting an active episode. ${RESPONSE_PATCH_GUIDELINE} Passive turns never trigger State Flow continuation or compaction. ${TASK_DRIVEN_HISTORY} ${PATCH_RESULT_PROTOCOL}`;
10
12
 
11
13
  const PATCH_DISPLAY_SECTION_KEYS = new Set(["global", "cwd", "session", "intents", "contract", "working", "artifacts", "response", "lazy"]);
12
14
 
@@ -92,7 +94,7 @@ ${bootstrapProtocol}STATE:
92
94
  - contract: durable requirements, decisions, rejections, interfaces.
93
95
  - working: temporary context of intents: facts, validation, failures, domain state.
94
96
  - artifacts: source-path routing metadata; descriptions do not imply body acquisition.
95
- - response: previous answer; runtime stores the exact accepted answer at turn_end (empty="").
97
+ - response: read-only prior answer; never patch it in any scope. Auto-stored at turn_end (empty="").
96
98
  - lazy: retrieve explicitly.
97
99
 
98
100
  SCOPES: Use the narrowest scope: session=branch/run continuation by default; cwd=reusable project truth; global=established cross-project/user/environment knowledge.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@llblab/pi-state-flow",
3
- "version": "0.26.1",
3
+ "version": "0.26.3",
4
4
  "license": "MIT",
5
5
  "private": false,
6
6
  "description": "Incremental scoped state/context/memory compiler for Pi, inspired by SKILL.state",