@llblab/pi-state-flow 0.25.4 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -18,12 +18,12 @@ The [relocation ledger](docs/agent-contract-relocation.md) maps every pre-compac
18
18
 
19
19
  - Treat canonical scope files as semantic authority and Git only as optional backup. Classify complete, wholly absent, partial and malformed cohorts before recovery; absent shared pairs may initialize only under accepted authority, while incomplete/private evidence fails closed. Never repair through ad-hoc writes. See [storage recovery](docs/usage.md#storage-and-recovery) and [transaction rule](docs/filesystem-recovery.md#transaction-rule).
20
20
  - Keep exact regular-file, byte-CAS and lock-serialized publication with cancelable waits, single-use callback-scoped capabilities and guarded rollback. Never hold exclusion across inference, source acquisition or Git; do not steal interrupted locks, claim kernel-atomic multi-file publication or promise power-loss durability. See [asynchronous transaction](docs/architecture.md#asynchronous-storage-transaction) and [durability boundary](docs/filesystem-recovery.md#power-loss-durability).
21
- - Attach Off branches through native policy bookkeeping only, deferring memory acquisition and recovery diagnostics until explicit Passive/Active. Preserve pending Off forks across cold reload with child-owned native markers, without reading the parent header/store until acquisition. When memory is selected, restore private retained boundaries over live shared scopes and copy exact proven source-session history into a fresh fork owner; never substitute current, empty, Git or another branch on expiry/failure. Explicit Start instead validates current same-session authority. Only accepted candidates install cache, checkpoint and mode. See [Pi lifecycle](docs/architecture.md#pi-lifecycle) and [fork contract](docs/fork-contract.md).
21
+ - Attach Off branches through native policy bookkeeping only, deferring memory acquisition and recovery diagnostics until explicit Passive/Active. Preserve pending Off forks across cold reload with child-owned native markers, without reading the parent header/store until acquisition. Memory never depends on the Pi step: it is the current same-session JSON state, advanced only by accepted `patch_state`/lifecycle publications. Startup, reload, resume and tree navigation validate and accept current same-session memory; native checkpoints supply only mode and run lifecycle, never a revision to rewind to. A fork copies its parent's current memory into a fresh child owner. Never substitute empty, Git, foreign or fabricated memory when current files are missing, corrupt or contradictory. Only accepted candidates install cache, checkpoint and mode. Unreadable current memory under Active retains Active policy, visibly reports `active (blocked)` and fences live inference through public Abort until accepted Active/Passive or explicit Off; never silently expose native history or an inactive indicator as fallback. See [Pi lifecycle](docs/architecture.md#pi-lifecycle) and [fork contract](docs/fork-contract.md).
22
22
  - Persist each material semantic change and its affected revisions exactly once, including accepted Session responses. Optional settled-turn Git backup may capture only already-accepted owned files, leave unrelated index/worktree data intact and push without force or semantic side effects. Defer busy backup when the host provides no settlement operation signal rather than blocking Abort; never move it to `turn_end` or add a durable push queue. Off cancels owned captures/pushes and suppresses late reporting; normal agent-operation completion must not cancel an independently admitted push, and foreign callers' pushes retain ownership. See [optional Git backup](docs/architecture.md#optional-git-backup).
23
23
  - Accept one atomic `patch_state` cohort across supplied scopes against current shared memory; reject empty scopes, unknown/retired grammar and model-authored `response`. Correct no-ops create no transition. Enforce the single-call inference barrier before sibling tools execute and retain conservative model-facing reconciliation when a result cannot be predicted. See [model tools](docs/architecture.md#model-tools) and [Pi lifecycle](docs/architecture.md#pi-lifecycle).
24
24
  - Reconcile the actual accepted ordinary answer at `turn_end` with response-owned cancellation and one accepted lifecycle publication; do not request private repair inference, ceremonial finalization patches or roll back accepted memory after cancellation. See [Pi lifecycle](docs/architecture.md#pi-lifecycle).
25
25
  - Capture specifications without writes at `before_agent_start`, then await one cancellable preparation acceptance before active inference; abort failed context preparation through Pi's public hook. Keep user text at user authority and state as fallible data. Preserve an existing conversation for exactly one bootstrap run, not forever. See [Pi lifecycle](docs/architecture.md#pi-lifecycle) and [pre-inference cancellation](docs/compatibility.md#pre-inference-cancellation).
26
- - Make Start await coherent current-head acceptance; unaccepted Off-to-Active retains deferred history and cannot confer current-memory authority on a superseding Passive choice. Passive selects local policy before asynchronous runtime-only persistence; preserve its independently owned fork/restoration work. Off instead cancels owned memory waits, clears semantic caches and records only native mode/continuation/fork bookkeeping without canonical I/O. Preserve already accepted publications and carried write fences; failed Passive persistence uses a native fence, never a substitute semantic checkpoint. Off exposes no frozen handoff. See [lifecycle planes](docs/architecture.md#lifecycle-planes) and [lifecycle operations](docs/usage.md#lifecycle-operations).
26
+ - Make Start await coherent current-head acceptance; unaccepted Off-to-Active retains deferred history and cannot confer current-memory authority on a superseding Passive choice. Passive selects local policy before asynchronous runtime-only persistence; preserve its independently owned fork/restoration work. Off instead cancels owned memory waits, clears semantic caches and records only native mode/continuation/fork bookkeeping without canonical I/O. Preserve already accepted publications and carried write fences; failed Passive persistence uses a native fence, never a substitute semantic checkpoint; a later explicit Passive retries current-memory acceptance and clears the fence only after acceptance. Off exposes no frozen handoff. See [lifecycle planes](docs/architecture.md#lifecycle-planes) and [lifecycle operations](docs/usage.md#lifecycle-operations).
27
27
  - Request completed-history native compaction only after an accepted non-bootstrap settled run, public usage ≥24,000 tokens and a uniquely captured first-user anchor; retain the complete latest run and foreign context. Use per-request owned markers, cancel stale/inactive owned hooks without default summary fallback, and prevent old completion from clearing a new plan. Await its native callback before returning, and leave Pi manual/threshold compaction and append-only history alone. See [lifecycle planes](docs/architecture.md#lifecycle-planes).
28
28
  - Contribute only State Flow's compact normative system-prompt section through Pi's section membrane; refresh it with current mode without overwriting foreign sections, forced-prompt precedence or native message identities. Never invent a continuation scheduler. See [lifecycle planes](docs/architecture.md#lifecycle-planes) and [host context compatibility](docs/compatibility.md#context-tools-and-provider-input).
29
29
 
package/BACKLOG.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Backlog
2
2
 
3
- The **0.25.4: Empty-Object Cleanup and Deletion Hints** hotfix outcomes belong in [CHANGELOG.md](CHANGELOG.md). This backlog retains publication, installed-client gates and deferred decisions.
3
+ The **0.25.5: Active Restoration Fence and Codemode Compaction** hotfix is published (exact-tag workflow, GitHub Release and npm commit verified) and bundled in published Pi Kit 0.27.6. **0.26.0: Stable Modes** is prepared and validated locally but not committed, tagged or published; Pi Kit sync follows its release. Outcomes belong in [CHANGELOG.md](CHANGELOG.md). This backlog retains installed-client gates and deferred decisions.
4
4
 
5
5
  ## Out of scope
6
6
 
@@ -8,9 +8,16 @@ The **0.25.4: Empty-Object Cleanup and Deletion Hints** hotfix outcomes belong i
8
8
  - Nested `lazy_navigation` and intent-ownership warnings, validation or rejection. Authored missing-deletion hints do not change cascade behavior.
9
9
  - Any reduction of lifecycle state; the tagged-union question stays deferred.
10
10
 
11
+ ## 0.26.0 acceptance
12
+
13
+ - **Installed stable-mode smoke (operator-owned).** After separately authorized reload, use disposable storage to confirm `/tree` to an old step and reload keep current memory writable in Active and Passive; a fork copies the parent's current memory; unreadable current files show `active (blocked)` in terminal/Telegram, Passive retries and Off releases inference only. Local/native validation does not certify the installed client.
14
+
15
+ ## 0.25.5 acceptance
16
+
17
+ - **Installed restoration/compaction smoke (operator-owned).** After separately authorized reload, use disposable storage to confirm failed Active restoration blocks provider inference across tree/reload, explicit mode recovery remains available, and native Codemode values/deletions survive completed-history compaction. Local/native tests do not certify the installed client.
18
+
11
19
  ## Carried gates
12
20
 
13
- - **0.25.4 publication and kit synchronization.** Verify the exact-tag workflow, GitHub Release and npm commit, then bundle and publish Pi Kit 0.27.5.
14
21
  - **Installed 0.25.4 cleanup smoke (operator-owned).** After separately authorized installation/reload, use disposable storage to confirm missing-deletion hints, recursive empty-object cleanup, inherited fallback and preserved array slots. Local validation and publication do not certify installed clients.
15
22
  - **Installed 0.25.3 inspection smoke (operator-owned).** After separately authorized installation/reload, inspect a large nested field: real layout newlines/quotes, separate omitted-character notice and intact genuine JSON string escapes. Use disposable storage; local adapter tests do not certify installed Telegram clients.
16
23
  - **Installed 0.25.2 smoke (operator-owned).** Disposable store: confirm one patch argument block followed by changed/no-op acknowledgements, compact rows with `showSuccessfulPatches: false`, and visible rejected arguments/errors.
package/CHANGELOG.md CHANGED
@@ -2,7 +2,17 @@
2
2
 
3
3
  > Each release keeps at most 8 outcome records of at most 512 characters.
4
4
 
5
- ## Unreleased
5
+ ## 0.26.0: Stable Modes
6
+
7
+ - `Step-independent memory`: Memory no longer depends on the Pi step. Startup, reload, resume and `/tree` attach the current same-session JSON state; native checkpoints supply only mode and run lifecycle. Old or expired branch points never block or rewind memory. Forks copy the parent's current memory. Past values remain readable through `read_state` offsets within retained history.
8
+ - `Removed boundary restoration (library API)`: With nothing left to rewind, `withRestoreTransaction`, `prepareBoundaryRestore`, `restoreBoundary`, `acceptRestoredOrigin`, `prepareBoundaryFork`, `HistoryBoundaryExpiredError` and the temporal boundary selectors are removed. `withForkTransaction(source, lifecycle, …)` now copies the parent's current memory inside its transaction; `lifecycle` carries only mode/bootstrap. Library consumers attach current memory through `withStartTransaction`.
9
+ - `Stable Passive`: Explicit Passive accepts validated current memory like Active and stays writable across reload, including after a failed mode write. Writes stay paused only while current memory is missing, corrupt, contradictory or unpublishable; failed retries add no duplicate fence.
10
+ - `Truthful blocked status`: Unreadable current memory under Active retains Active policy and shows `active (blocked)` in terminal/Telegram, instead of a hidden fence behind an Off indicator. Active or Passive accepts repaired memory; Off releases inference only. Status explains the block and recovery.
11
+
12
+ ## 0.25.5: Active Restoration Fence and Codemode Compaction
13
+
14
+ - `Active restoration fence`: Failed retained Active restoration aborts live inference instead of silently exposing native history under an inactive fallback. Expired tree/reload and contradictory-lineage native tests prove zero provider calls and unchanged memory. Valid selection, accepted Start or explicit Passive/Off releases the fence; historical authority is never substituted.
15
+ - `Codemode-safe compaction`: Exact native `codemode-store` metadata no longer blocks completed-history compaction. Full branch records remain intact; native Codemode reads prove values and deletions survive compaction, reload and resume. Unknown metadata and visible custom context remain protected.
6
16
 
7
17
  ## 0.25.4: Empty-Object Cleanup and Deletion Hints
8
18
 
package/README.md CHANGED
@@ -201,16 +201,15 @@ The default store is `~/.pi/agent/state-flow/`, independent of registered source
201
201
  - Shutdown cancels owned pushes and waits for that repository's active push to close or time out.
202
202
  - Commit failures warn locally. Repeated push failures produce one concise warning until a push succeeds, with redacted Git detail kept in the local diagnostic log. Neither failure rejects or rolls back accepted memory.
203
203
  - Backup needs a Git commit identity; accepting and persisting state does not.
204
- - Git history can be inspected separately, but it is not the authority for `read_state` or for automatic restoration of expired semantic boundaries.
204
+ - Git history can be inspected separately, but it is not the authority for `read_state` or for restoring memory.
205
205
 
206
206
  **Resume, tree navigation and forks:**
207
207
 
208
- - Memory-enabled resume and tree navigation restore the selected retained session boundary over the current shared global/CWD memory. Off defers this acquisition.
208
+ - **State Flow does not depend on the Pi step.** Memory is the current JSON state of each scope and changes only through accepted `patch_state` calls and run lifecycle. Resume and tree navigation restore the branch's mode, never an older memory revision; Off defers acquisition. Past values stay readable through `read_state` offsets within retained history.
209
209
  - A new session gets its own session layer.
210
- - Supported native forks copy the selected session state into a new owner without changing the parent's private data.
211
- - Expired, incomplete or contradictory boundaries never silently substitute newer private state during restoration.
212
- - Explicit Start is a mode change, not historical restoration. It activates the validated **current** memory of that same session, including private state, even after expired active/passive, interrupted or pre-runtime selections. Available aligned history and revisions survive; unavailable history is not recreated.
213
- - Malformed storage, unsafe fork copying and concurrent writes remain fenced.
210
+ - Supported native forks copy the parent's **current** session memory into a new owner without changing the parent's private data.
211
+ - Explicit Active or Passive accepts the validated current memory of that same session; modes stay stable.
212
+ - Missing, malformed or contradictory current files, unsafe fork copying and concurrent writes remain fenced and are never replaced by empty or foreign memory.
214
213
 
215
214
  See [fork support](docs/usage.md#fork-support-and-limits) and [storage recovery](docs/usage.md#storage-and-recovery).
216
215
 
@@ -221,9 +220,9 @@ See [fork support](docs/usage.md#fork-support-and-limits) and [storage recovery]
221
220
 
222
221
  How mode changes interact with storage:
223
222
 
224
- - Selecting Passive switches local policy/context immediately and awaits runtime-only persistence. Passive keeps independently owned restoration/fork work. If its persistence fails, local policy stays and publication is fenced until an accepted activation.
223
+ - Selecting Passive switches local policy/context immediately and awaits runtime-only persistence. Passive keeps independently owned attachment/fork work. If its persistence fails, local policy stays and publication is fenced until a later accepted Active or Passive selection.
225
224
  - Off cancels owned memory waits and saves only native mode/continuation/fork bookkeeping, without validating or rewriting canonical storage. It also cancels restoration/fork work and defers later acquisition.
226
- - Explicit Off inspection may read current stored values through a disposable validated reader. It does not activate memory, install cache or change the selected historical/fork boundary. Missing private authority stays unavailable.
225
+ - Explicit Off inspection may read current stored values through a disposable validated reader. It does not activate memory, install cache or change pending fork acquisition. Missing private authority stays unavailable.
227
226
  - Active waits for a coherent capture and acceptance; another mode or selection can withdraw its wait.
228
227
 
229
228
  State Flow accepts only the canonical store contract and provides no in-place format converter. Preserve existing data and check the [format boundary](docs/usage.md#moving-a-store-and-supported-formats) before changing versions or moving a store.
@@ -3,10 +3,11 @@ import { estimateTokens } from "@earendil-works/pi-coding-agent";
3
3
  export const STATE_FLOW_COMPACTION_SUMMARY = "State Flow accepted the completed work before this boundary. Current memory is restored from its retained semantic boundary and projected separately; use the retained native entries for subsequent work.";
4
4
  /** A modest margin above Pi's default 20k retained suffix absorbs estimation drift. */
5
5
  export const STATE_FLOW_COMPACTION_MIN_CONTEXT_TOKENS = 24_000;
6
- function stateFlowEntry(entry) {
6
+ function contextInvisibleEntry(entry) {
7
+ // Codemode reconstructs its store from the full native branch, not the compacted model context.
7
8
  return entry.type === "custom"
8
9
  && typeof entry.customType === "string"
9
- && entry.customType.startsWith("state-flow-");
10
+ && (entry.customType.startsWith("state-flow-") || entry.customType === "codemode-store");
10
11
  }
11
12
  export function shouldRequestStateFlowCompaction(usage) {
12
13
  return typeof usage?.tokens === "number"
@@ -45,7 +46,7 @@ export function planStateFlowCompaction(entries, boundary, step, runAnchorTimest
45
46
  const keep = entries.findIndex(isRunAnchor);
46
47
  if (keep < 0 || keep > terminal || entries.findLastIndex(isRunAnchor) !== keep)
47
48
  return undefined;
48
- if (entries.slice(0, keep).some((entry) => entry.type === "custom_message" || (entry.type === "custom" && !stateFlowEntry(entry))))
49
+ if (entries.slice(0, keep).some((entry) => entry.type === "custom_message" || (entry.type === "custom" && !contextInvisibleEntry(entry))))
49
50
  return undefined;
50
51
  const firstKeptEntryId = entries[keep]?.id;
51
52
  const leafId = entries.at(-1)?.id;
@@ -22,7 +22,7 @@ import { selectedBoundaryFailure, selectRetainedCheckpoint, waitForRecovery } fr
22
22
  import { TemporalRuntime } from "./runtime.js";
23
23
  import { discoverSnapshotData, findAssistantToolBatch, findBranchPolicy, findPassiveStopBoundary, hasPendingFork, hasPriorConversation, hasUncheckpointedConversation, isNewSession, retainsPhysicalSessionProjection, SNAPSHOT_ENTRY_TYPE } from "./session.js";
24
24
  import { hasCompiledSkillArtifact, hashSkillSource, registeredSkillResolver, SkillReadTracker } from "./skills.js";
25
- import { HistoryBoundaryExpiredError, emptySnapshot, migrationFailure, preRuntimeCheckpoint } from "./snapshot.js";
25
+ import { emptySnapshot, isActiveRestorationBlocked, migrationFailure, preRuntimeCheckpoint } from "./snapshot.js";
26
26
  import { emptyState, projectStateForModel } from "./state.js";
27
27
  import { compactStatus, detailedStatus, STATUS_KEY } from "./status.js";
28
28
  import { PublicationBusyError } from "./storage.js";
@@ -42,7 +42,6 @@ export default function stateFlowExtension(pi, options = {}) {
42
42
  let scopeStates = { global: emptyState(), cwd: emptyState(), session: emptyState() };
43
43
  let effectiveState = {};
44
44
  let branchStartsWithoutRuntime = false;
45
- let selectedHistoryExpired = false;
46
45
  let modePersistenceError;
47
46
  /** One pending inactive-mode persistence; later inactive choices coalesce until it publishes. */
48
47
  const inactivePersistence = new OwnedOperationSlot();
@@ -121,10 +120,11 @@ export default function stateFlowExtension(pi, options = {}) {
121
120
  if (modePersistenceError)
122
121
  throw new Error(`Memory writes paused after mode change: ${modePersistenceError}; use /state-flow-active`);
123
122
  }
123
+ /** Active lifecycle work requires validated memory, not merely a selected Active policy. */
124
124
  function isActive() {
125
- return snapshot.config.mode === "active";
125
+ return snapshot.config.mode === "active" && !isActiveRestorationBlocked(snapshot);
126
126
  }
127
- /** An unavailable or pending active selection keeps the configured inactive policy, never an invented one. */
127
+ /** Pending acquisition has no accepted Active memory yet. */
128
128
  function inactiveSelection(mode) {
129
129
  return mode === "active" ? config.inactiveMode : mode;
130
130
  }
@@ -390,7 +390,6 @@ export default function stateFlowExtension(pi, options = {}) {
390
390
  runtime = undefined;
391
391
  snapshot = emptySnapshot("off");
392
392
  branchStartsWithoutRuntime = withoutRuntime;
393
- selectedHistoryExpired = false;
394
393
  modePersistenceError = persistenceError;
395
394
  forkInitialization = reason === "fork";
396
395
  installScopeStates();
@@ -408,7 +407,6 @@ export default function stateFlowExtension(pi, options = {}) {
408
407
  runtime = createRuntime(ctx);
409
408
  installScopeStates();
410
409
  branchStartsWithoutRuntime = false;
411
- selectedHistoryExpired = false;
412
410
  forkInitialization = sessionStartReason === "fork";
413
411
  let selection = { kind: "settled" };
414
412
  let skipped = 0;
@@ -439,11 +437,11 @@ export default function stateFlowExtension(pi, options = {}) {
439
437
  ? { ...selected.checkpoint, mode: sourceFence.mode ?? config.inactiveMode } : selected.checkpoint };
440
438
  }
441
439
  catch (error) {
442
- snapshot = selectedBoundaryFailure(diagnosticText(error), inactiveSelection(selected.checkpoint.mode));
440
+ snapshot = selectedBoundaryFailure(diagnosticText(error), requestedMode ?? selected.checkpoint.mode);
443
441
  }
444
442
  }
445
443
  else if (selected.kind === "boundary") {
446
- selection = { kind: "restore", checkpoint: selected.checkpoint };
444
+ selection = { kind: "attach", checkpoint: selected.checkpoint };
447
445
  }
448
446
  else if (selected.kind === "pre-runtime") {
449
447
  snapshot = emptySnapshot(selected.mode);
@@ -500,6 +498,12 @@ export default function stateFlowExtension(pi, options = {}) {
500
498
  throw new Error("State Flow branch selection changed while awaiting publication");
501
499
  };
502
500
  let accepted = false;
501
+ const failSelection = (error) => {
502
+ const mode = pending.requestedMode ?? (selection.kind === "auto-start" ? "active"
503
+ : selection.kind === "attach" || selection.kind === "fork" ? selection.checkpoint.mode : snapshot.config.mode);
504
+ snapshot = selectedBoundaryFailure(diagnosticText(error), mode);
505
+ installScopeStates();
506
+ };
503
507
  // Install accepted memory before native writes; later ancillary failures cannot revert or replay it.
504
508
  const accept = (candidate, next, nativeWrites) => {
505
509
  accepted = true;
@@ -535,9 +539,18 @@ export default function stateFlowExtension(pi, options = {}) {
535
539
  : migrationFailure({}, "Current State Flow session memory is unavailable", pending.requestedMode ?? selection.mode);
536
540
  installScopeStates();
537
541
  }
538
- else if (selection.kind === "restore") {
539
- await candidate.withRestoreTransaction(selection.checkpoint, (restored, publish) => {
542
+ else if (selection.kind === "attach") {
543
+ // Memory is the current same-session files; the Pi checkpoint supplies only mode and run lifecycle.
544
+ await candidate.withStartTransaction((current, publish) => {
540
545
  assertCurrent();
546
+ if (!current)
547
+ throw new Error("Current State Flow session memory is unavailable");
548
+ const { checkpoint } = selection;
549
+ const restored = { config: { mode: checkpoint.mode }, meta: {
550
+ step: current.meta.step,
551
+ ...(checkpoint.bootstrap ? { bootstrap: true } : {}),
552
+ ...(checkpoint.specification === undefined ? {} : { specification: checkpoint.specification }),
553
+ } };
541
554
  // Canceled preparation or boundary continuation may have no specification. Retain uncompiled native context.
542
555
  if (restored.config.mode === "active" && restored.meta.specification === undefined
543
556
  && retainsPhysicalSessionProjection(reason) && hasUncheckpointedConversation(ctx.sessionManager.getBranch()))
@@ -548,6 +561,7 @@ export default function stateFlowExtension(pi, options = {}) {
548
561
  }, signal);
549
562
  }
550
563
  else if (selection.kind === "fork") {
564
+ // The runtime copies the parent's current memory; the checkpoint supplies only child mode/bootstrap.
551
565
  await candidate.withForkTransaction(selection.source, selection.checkpoint, (child, publish) => {
552
566
  assertCurrent();
553
567
  // Mode is selected independently of creating the child's private memory.
@@ -583,10 +597,7 @@ export default function stateFlowExtension(pi, options = {}) {
583
597
  }
584
598
  if (!isCurrent())
585
599
  return;
586
- if (error instanceof HistoryBoundaryExpiredError)
587
- selectedHistoryExpired = true;
588
- snapshot = selectedBoundaryFailure(diagnosticText(error), snapshot.config.mode === "active" ? config.inactiveMode : snapshot.config.mode);
589
- installScopeStates();
600
+ failSelection(error);
590
601
  }
591
602
  finally {
592
603
  pending.awaitingAcceptance = false;
@@ -595,8 +606,9 @@ export default function stateFlowExtension(pi, options = {}) {
595
606
  return;
596
607
  }
597
608
  settleSelection(ctx, reason, notifyRecovery, skipped, selected !== placeholder);
598
- if (snapshot.config.mode !== "passive" || runtime?.view)
609
+ if (snapshot.config.mode === "off" || isActive() || runtime?.view)
599
610
  return;
611
+ // Unavailable Active memory may expose shared reads, never substitute private memory or model context.
600
612
  const passive = await loadPassiveView(ctx, signal, isCurrent, notifyRecovery);
601
613
  if (passive === undefined)
602
614
  return;
@@ -612,8 +624,7 @@ export default function stateFlowExtension(pi, options = {}) {
612
624
  // Host failures before acceptance leave the selection unavailable, never invented empty memory.
613
625
  if (accepted || !isCurrent())
614
626
  return;
615
- snapshot = selectedBoundaryFailure(diagnosticText(error), snapshot.config.mode === "active" ? config.inactiveMode : snapshot.config.mode);
616
- installScopeStates();
627
+ failSelection(error);
617
628
  }
618
629
  finally {
619
630
  pending.awaitingAcceptance = false;
@@ -642,10 +653,7 @@ export default function stateFlowExtension(pi, options = {}) {
642
653
  function settleSelection(ctx, reason, notifyRecovery, skipped, selectedMemory) {
643
654
  const failure = !isActive() && snapshot.meta.validation?.attempt === 0 ? snapshot.meta.validation.error : undefined;
644
655
  if (failure !== undefined && notifyRecovery && !modePersistenceError) {
645
- if (selectedHistoryExpired)
646
- notifyProblem(ctx, "State Flow history is outside the retained temporal window; /state-flow-active can use current session memory.", "warning");
647
- else
648
- notifyProblem(ctx, `State Flow restore failed: ${failure}`, "error");
656
+ notifyProblem(ctx, `State Flow restore failed: ${failure}`, "error");
649
657
  }
650
658
  const continuation = selectedMemory ? selectedContinuation(ctx, reason) : undefined;
651
659
  if (continuation !== undefined) {
@@ -886,19 +894,23 @@ export default function stateFlowExtension(pi, options = {}) {
886
894
  return { ok: false, message, signal: AbortSignal.any([pending.signal, sharedInspectionLifetime.signal]) };
887
895
  }
888
896
  }
889
- async function activateCurrentState(ctx, pending) {
897
+ /** Explicit Active or Passive accepts validated current same-session memory without claiming unavailable history. */
898
+ async function activateCurrentState(ctx, pending, mode = "active", owns = () => startActivation.current?.controller === pending) {
890
899
  let selected = runtime;
891
900
  const owner = ctx.sessionManager.getSessionId();
892
901
  const sameSession = sessionIdentity(ctx);
893
- const initiallyActive = isActive();
902
+ const policy = () => `${snapshot.config.mode}:${isActive()}`;
903
+ const initialPolicy = policy();
904
+ const acceptedPolicy = `${mode}:${mode === "active"}`;
905
+ const active = mode === "active";
894
906
  let accepted = false;
895
907
  let receipt = AbortSignal.any([pending.signal, sharedInspectionLifetime.signal]);
896
908
  const signal = ctx.signal ? AbortSignal.any([pending.signal, ctx.signal]) : pending.signal;
897
- const isCurrent = () => startActivation.current?.controller === pending && !signal.aborted && runtime === selected && !shuttingDown
898
- && sameSession() && isActive() === (accepted || initiallyActive);
909
+ const isCurrent = () => owns() && !signal.aborted && runtime === selected && !shuttingDown
910
+ && sameSession() && policy() === (accepted ? acceptedPolicy : initialPolicy);
899
911
  const superseded = () => {
900
912
  pending.abort();
901
- return { ok: false, message: "State Flow activation was superseded", signal: pending.signal };
913
+ return { ok: false, message: active ? "State Flow activation was superseded" : "State Flow mode change was superseded", signal: pending.signal };
902
914
  };
903
915
  try {
904
916
  const activation = createRuntime(ctx);
@@ -913,29 +925,32 @@ export default function stateFlowExtension(pi, options = {}) {
913
925
  signal.throwIfAborted();
914
926
  if (!isCurrent())
915
927
  throw new Error("State Flow activation selection changed while awaiting publication");
916
- if (!current && !branchStartsWithoutRuntime)
928
+ if (!current && (!active || !branchStartsWithoutRuntime))
917
929
  throw new Error(snapshot.meta.validation?.error ?? "Current State Flow session memory is unavailable");
918
930
  const boundary = deferred && retainsPhysicalSessionProjection(deferred.reason)
919
931
  ? findPassiveStopBoundary(ctx.sessionManager.getBranch(), owner, PASSIVE_STOP_ENTRY_TYPE) : undefined;
920
932
  const bootstrap = hasPriorConversation(ctx.sessionManager.getBranch()) || passiveContinuation !== undefined || boundary !== undefined;
921
- const activated = current ? resumeEpisode(current, bootstrap) : startEpisode(bootstrap);
922
- const recoveredCurrent = selectedHistoryExpired;
933
+ const activated = !active ? deactivateEpisode(current, "passive")
934
+ : current ? resumeEpisode(current, bootstrap) : startEpisode(bootstrap);
935
+ const resumedWrites = modePersistenceError !== undefined;
923
936
  publish(activated);
924
937
  accepted = true;
925
- inactivePersistence.cancel();
938
+ // Passive acceptance runs inside its own inactive-persistence owner.
939
+ if (active)
940
+ inactivePersistence.cancel();
926
941
  runtime = selected = activation;
927
942
  snapshot = activated;
928
943
  activeContext = ctx;
929
- selectedHistoryExpired = false;
930
944
  modePersistenceError = undefined;
931
945
  installScopeStates();
932
946
  const continuation = passiveContinuation ?? bootstrapContinuation ?? (deferred ? selectedContinuation(ctx, deferred.reason) : undefined);
933
947
  deferredBranch = undefined;
934
948
  clearRunTransient();
935
949
  contextProjection.reset();
936
- passiveContinuation = undefined;
937
- bootstrapContinuation = snapshot.meta.bootstrap ? continuation : undefined;
938
- deferInferencePreparation();
950
+ passiveContinuation = active ? undefined : continuation;
951
+ bootstrapContinuation = active && snapshot.meta.bootstrap ? continuation : undefined;
952
+ if (active)
953
+ deferInferencePreparation();
939
954
  receipt = AbortSignal.any([pending.signal, sharedInspectionLifetime.signal]);
940
955
  recordPublication();
941
956
  syncStateFlowTools();
@@ -945,20 +960,25 @@ export default function stateFlowExtension(pi, options = {}) {
945
960
  pi.appendEntry(PASSIVE_STOP_ENTRY_TYPE, { reset: true, owner });
946
961
  }
947
962
  appendCheckpoint();
948
- ctx.ui.notify(recoveredCurrent
949
- ? "State Flow active from current session memory; unavailable historical state was not restored."
950
- : snapshot.meta.bootstrap
951
- ? "State Flow active. The next complete agent run will migrate active context into state."
952
- : "State Flow active. The next prompt starts a stateful agent run.", "info");
963
+ if (!active) {
964
+ if (resumedWrites)
965
+ ctx.ui.notify("State Flow passive; memory writes resumed from current session memory.", "info");
966
+ return { ok: true, message: "State Flow passive", signal: receipt };
967
+ }
968
+ ctx.ui.notify(snapshot.meta.bootstrap
969
+ ? "State Flow active. The next complete agent run will migrate active context into state."
970
+ : "State Flow active. The next prompt starts a stateful agent run.", "info");
953
971
  return { ok: true, message: "State Flow active", signal: receipt };
954
- }, signal, branchStartsWithoutRuntime);
972
+ }, signal, active && branchStartsWithoutRuntime);
955
973
  return isCurrent() ? result : superseded();
956
974
  }
957
975
  catch (error) {
958
976
  if (!isCurrent())
959
977
  return superseded();
960
- const message = conciseDiagnostic(`${accepted ? "State Flow active; lifecycle update failed" : "State Flow activation failed"}: ${diagnosticText(error)}`);
961
- notifyProblem(ctx, message, accepted ? "warning" : "error");
978
+ const message = conciseDiagnostic(`${accepted ? `State Flow ${mode}; lifecycle update failed` : active ? "State Flow activation failed" : "State Flow passive acceptance failed"}: ${diagnosticText(error)}`);
979
+ // Failed Passive acceptance falls back to its caller's write-fence report.
980
+ if (active || accepted)
981
+ notifyProblem(ctx, message, accepted ? "warning" : "error");
962
982
  return { ok: accepted, message, signal: receipt };
963
983
  }
964
984
  }
@@ -985,6 +1005,10 @@ export default function stateFlowExtension(pi, options = {}) {
985
1005
  ctx.ui.notify(detailedStatus(snapshot, statusDiagnostics(ctx)), "info");
986
1006
  },
987
1007
  });
1008
+ /** Unavailable selection or failed persistence needs current-memory acceptance, not a sticky Passive write fence. */
1009
+ function passiveRecoveryNeeded(mode) {
1010
+ return mode === "passive" && (modePersistenceError !== undefined || snapshot.meta.validation?.attempt === 0);
1011
+ }
988
1012
  /** Local policy, tools and UI change before any canonical wait. */
989
1013
  function applyInactiveMode(ctx, mode) {
990
1014
  snapshot = deactivateEpisode(snapshot, mode);
@@ -1020,7 +1044,7 @@ export default function stateFlowExtension(pi, options = {}) {
1020
1044
  if (snapshot.config.mode === mode) {
1021
1045
  const retained = selectRetainedCheckpoint(discoverSnapshotData(ctx.sessionManager.getBranch()).candidates, config.inactiveMode);
1022
1046
  const recordedMode = retained.kind === "pre-runtime" ? retained.mode : retained.kind === "boundary" ? retained.checkpoint.mode : undefined;
1023
- if (modePersistenceError || recordedMode === mode)
1047
+ if (!passiveRecoveryNeeded(mode) && (modePersistenceError || recordedMode === mode))
1024
1048
  return Promise.resolve({ ok: true, message: `State Flow is already ${mode}` });
1025
1049
  }
1026
1050
  inactivePersistence.cancel();
@@ -1074,7 +1098,6 @@ export default function stateFlowExtension(pi, options = {}) {
1074
1098
  acquisition.reset();
1075
1099
  runtime = undefined;
1076
1100
  snapshot = emptySnapshot("off");
1077
- selectedHistoryExpired = false;
1078
1101
  branchStartsWithoutRuntime = preRuntime;
1079
1102
  forkInitialization = pendingFork;
1080
1103
  deferredBranch = { owner: address.key, cwd: ctx.cwd, reason: pendingFork ? "fork" : undefined };
@@ -1117,8 +1140,38 @@ export default function stateFlowExtension(pi, options = {}) {
1117
1140
  const wasActive = current.config.mode === "active";
1118
1141
  let unfinished = current.meta.specification !== undefined
1119
1142
  || (inferencePreparation.current?.prompt !== undefined && !inferencePreparation.current.accepted);
1143
+ const recoverPassive = passiveRecoveryNeeded(mode);
1120
1144
  applyInactiveMode(ctx, mode);
1121
1145
  const stoppedAt = Date.now();
1146
+ if (recoverPassive) {
1147
+ const superseded = () => ({ ok: false, message: "State Flow mode change was superseded" });
1148
+ const owns = () => inactivePersistence.owns(pending) && !pending.controller.signal.aborted && !shuttingDown;
1149
+ try {
1150
+ // Join pending read-only recovery so its installation cannot supersede this acceptance.
1151
+ const restoring = branchRestoration.current?.operation;
1152
+ if (restoring)
1153
+ await waitForRecovery(restoring, pending.controller.signal);
1154
+ }
1155
+ catch {
1156
+ return superseded();
1157
+ }
1158
+ if (!owns())
1159
+ return superseded();
1160
+ // Passive is a stable mode: explicit selection accepts validated current memory instead of keeping a write fence.
1161
+ const recovered = await activateCurrentState(ctx, pending.controller, "passive", () => inactivePersistence.owns(pending));
1162
+ if (recovered.ok)
1163
+ pending.published = true;
1164
+ if (recovered.ok || !owns())
1165
+ return recovered;
1166
+ if (current.config.mode === mode && modePersistenceError) {
1167
+ // The existing native fence already records this policy; report why acceptance still failed.
1168
+ pending.published = true;
1169
+ const message = conciseDiagnostic(`State Flow passive; memory writes remain paused: ${recovered.message}`);
1170
+ notifyProblem(ctx, message, "warning");
1171
+ return { ok: true, message };
1172
+ }
1173
+ selected = runtime;
1174
+ }
1122
1175
  if (modePersistenceError) {
1123
1176
  // Writes stay paused; the native marker records only the newly selected inactive policy.
1124
1177
  pending.published = true;
@@ -1220,6 +1273,7 @@ export default function stateFlowExtension(pi, options = {}) {
1220
1273
  port: {
1221
1274
  snapshot: () => ({
1222
1275
  mode: snapshot.config.mode,
1276
+ inferenceBlocked: isActiveRestorationBlocked(snapshot),
1223
1277
  step: snapshot.meta.step,
1224
1278
  revisions: scopeRevisions(),
1225
1279
  bootstrap: snapshot.meta.bootstrap === true,
@@ -1307,6 +1361,12 @@ export default function stateFlowExtension(pi, options = {}) {
1307
1361
  return { messages: projection.project(source, view, () => runtimeContextHead(snapshot, view, projectRecentTransitionsWithLimit(config.historyLimit, runtime?.recent() ?? []))) };
1308
1362
  }
1309
1363
  function prepareContext(messages, ctx) {
1364
+ // Pi continues after hook errors; public Abort fences inference instead of exposing the native history fallback.
1365
+ if (isActiveRestorationBlocked(snapshot) && ctx.signal && !shuttingDown) {
1366
+ ctx.abort();
1367
+ notifyProblem(ctx, "State Flow inference blocked: Active memory restoration failed. Select a valid branch or use /state-flow-active for current memory; /state-flow-passive or /state-flow-off explicitly permits native context.", "error");
1368
+ return;
1369
+ }
1310
1370
  const pending = inferencePreparation.current;
1311
1371
  const selected = runtime;
1312
1372
  const operationSignal = ctx.signal;
@@ -1,4 +1,4 @@
1
- import { type InactiveMode, type RetainedBoundaryCheckpoint, type Snapshot } from "./snapshot.ts";
1
+ import { type InactiveMode, type RetainedBoundaryCheckpoint, type Snapshot, type StateFlowMode } from "./snapshot.ts";
2
2
  export type RetainedCheckpointSelection = {
3
3
  kind: "boundary";
4
4
  checkpoint: RetainedBoundaryCheckpoint;
@@ -17,4 +17,4 @@ export declare function selectRetainedCheckpoint(candidates: readonly unknown[],
17
17
  /** Withdraw a caller's join without cancelling independently owned recovery or mode persistence. */
18
18
  export declare function waitForRecovery<T>(operation: Promise<T>, signal: AbortSignal): Promise<T>;
19
19
  /** A selected boundary that cannot be resolved stays unavailable; callers never fall through to older evidence. */
20
- export declare function selectedBoundaryFailure(cause: string, mode?: InactiveMode): Snapshot;
20
+ export declare function selectedBoundaryFailure(cause: string, mode?: StateFlowMode): Snapshot;
@@ -2,7 +2,7 @@ import { type SessionAddress } from "./durable.ts";
2
2
  import { type ArtifactProvenance, type ArtifactProvenanceRegistry } from "./artifact.ts";
3
3
  import { publishTemporalStateToFiles } from "./storage.ts";
4
4
  import { type AcceptedTransition, type RecentTransitionWindow } from "./history.ts";
5
- import { type RetainedBoundaryCheckpoint, type RetainedPiCheckpoint, type Snapshot } from "./snapshot.ts";
5
+ import { type RetainedPiCheckpoint, type Snapshot, type StateFlowMode } from "./snapshot.ts";
6
6
  import { type MaterializedState, type SemanticState, type ScopedSemanticStates, type ScopedStates, type StateScope } from "./state.ts";
7
7
  import { type TemporalState } from "./temporal.ts";
8
8
  export type RuntimePublication = ReturnType<typeof publishTemporalStateToFiles>;
@@ -12,6 +12,11 @@ export interface RuntimePatchTransaction {
12
12
  readonly provenance: Record<StateScope, ArtifactProvenanceRegistry>;
13
13
  publish(snapshot: Snapshot, accepted?: AcceptedTransition, provenance?: Partial<Record<StateScope, Record<string, ArtifactProvenance>>>): RuntimePublication;
14
14
  }
15
+ /** Child policy recorded by the native fork; memory always comes from the parent's current files. */
16
+ export interface ForkLifecycle {
17
+ mode: StateFlowMode;
18
+ bootstrap?: true;
19
+ }
15
20
  /** A targeted removed scope was deliberately adopted as empty before refusing the stale semantic patch. */
16
21
  export declare class SharedScopeRemovalConflictError extends Error {
17
22
  readonly scopes: readonly StateScope[];
@@ -24,7 +29,6 @@ export declare class TemporalRuntime {
24
29
  private semanticRevision;
25
30
  private savedRuntime;
26
31
  private transaction;
27
- private restoredOriginPending;
28
32
  private provenanceByScope;
29
33
  /** Shared scopes whose wholly absent live basis was accepted after one stale-target refusal. */
30
34
  private readonly absentSharedScopes;
@@ -52,28 +56,9 @@ export declare class TemporalRuntime {
52
56
  retainedCheckpoint(snapshot: Snapshot): RetainedPiCheckpoint;
53
57
  usesCanonicalFiles(): boolean;
54
58
  recent(): RecentTransitionWindow;
55
- /** Prepare a retained session boundary from current canonical files; shared scopes remain live. */
56
- prepareBoundaryRestore(checkpoint: RetainedBoundaryCheckpoint): {
57
- snapshot: Snapshot;
58
- restore: () => Snapshot;
59
- };
60
- private prepareBoundaryRestoreBase;
61
- /** Restore and canonically accept one retained boundary as a single lifecycle operation. */
62
- restoreBoundary(checkpoint: RetainedBoundaryCheckpoint): {
63
- snapshot: Snapshot;
64
- publication: RuntimePublication;
65
- };
66
59
  /** Await a coherent read-only recovery view; this neither activates policy nor accepts publication authority. */
67
60
  refreshCurrentMemory(signal?: AbortSignal): Promise<Snapshot | undefined>;
68
61
  private loadCurrentMemoryBase;
69
- /** Copy one retained source-session boundary over the child's current shared scopes. */
70
- prepareBoundaryFork(source: SessionAddress, checkpoint: RetainedBoundaryCheckpoint): {
71
- snapshot: Snapshot;
72
- fork: () => {
73
- snapshot: Snapshot;
74
- publication: RuntimePublication;
75
- };
76
- };
77
62
  initialize(snapshot: Snapshot, allowCreateCwd: boolean, expectedShared?: Pick<ScopedStates, "global" | "cwd">, newSessionOrigin?: boolean): RuntimePublication | undefined;
78
63
  private initializeOrigin;
79
64
  /** Copy the private origin and apply configured retention folding, preserving live shared values/provenance. */
@@ -95,16 +80,12 @@ export declare class TemporalRuntime {
95
80
  withPatchTransaction<T>(action: (transaction: RuntimePatchTransaction) => T, signal?: AbortSignal): Promise<T>;
96
81
  /** Activate current owned memory; the caller must authorize a wholly absent private origin after waiting. */
97
82
  withStartTransaction<T>(action: (current: Snapshot | undefined, publish: (snapshot: Snapshot) => RuntimePublication) => T, signal?: AbortSignal, allowCreateOrigin?: boolean): Promise<T>;
98
- /** Select one retained private boundary beside current shared streams, then accept only after caller policy is rechecked. */
99
- withRestoreTransaction<T>(checkpoint: RetainedBoundaryCheckpoint, action: (selected: Snapshot, publish: (snapshot: Snapshot) => RuntimePublication) => T, signal?: AbortSignal): Promise<T>;
100
- /** Copy exact retained parent authority into an unoccupied child; the caller rechecks native selection after waiting. */
101
- withForkTransaction<T>(source: SessionAddress, checkpoint: RetainedBoundaryCheckpoint, action: (selected: Snapshot, publish: (snapshot: Snapshot) => RuntimePublication) => T, signal?: AbortSignal): Promise<T>;
83
+ /** Copy the parent's current session memory into an unoccupied child; the caller rechecks native selection after waiting. */
84
+ withForkTransaction<T>(source: SessionAddress, lifecycle: ForkLifecycle, action: (selected: Snapshot, publish: (snapshot: Snapshot) => RuntimePublication) => T, signal?: AbortSignal): Promise<T>;
102
85
  private prepareForkCandidate;
103
86
  /** Recheck caller policy after waiting, then accept only config/runtime over an already accepted private basis. */
104
87
  withLifecycleTransaction<T>(action: (publish: (snapshot: Snapshot) => RuntimePublication) => T, signal?: AbortSignal): Promise<T>;
105
88
  private withPublicationTransaction;
106
- /** Canonically accept a prepared retained-boundary origin before lifecycle-only persistence. */
107
- acceptRestoredOrigin(snapshot: Snapshot): RuntimePublication;
108
89
  publish(snapshot: Snapshot, semantic?: boolean, accepted?: AcceptedTransition, options?: {
109
90
  provenance?: Partial<Record<StateScope, Record<string, ArtifactProvenance>>>;
110
91
  }): RuntimePublication | undefined;