@llblab/pi-state-flow 0.27.6 → 1.0.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.
@@ -3,62 +3,21 @@ import { resolve } from "node:path";
3
3
  import { parseArtifactProvenanceRegistry } from "./artifact.js";
4
4
  import { MAX_HISTORY_LIMIT } from "./history.js";
5
5
  import { canonicalJson, isJsonValue, isObject, validatePatch } from "./json.js";
6
- import { parseStateReadPath, parseValuePath } from "./query.js";
7
6
  import { assertRetainedModules, validateRetainedModules } from "./semantic-module.js";
8
7
  import { assertNoRetiredSemanticPlanes } from "./state.js";
9
8
  import { validateScopeStream } from "./temporal.js";
10
- const LEGACY_PLANES = new Map([["contract", "strategy"], ["working", "tactics"]]);
11
- const LEGACY_SEMANTIC_PLANES = new Set(["intents", "contract", "working", "artifacts", "response", "lazy"]);
12
- const LEGACY_LOCATOR = /^(?:((?:effective|global|cwd|session)(?:\[\d+\])?(?:\.patches(?:\[\d+\])?)?)\.)?(contract|working)(?=$|\.|\[)/;
13
- const MARKED_LOCATOR = /(?<![\p{L}\p{N}_$.[\]:/\\-])\$([\p{L}\p{N}_$.[\]:-]+)(?![\p{L}\p{N}_$.[\]:/\\-])/gu;
14
- function translateLocator(path) {
15
- const match = LEGACY_LOCATOR.exec(path);
16
- if (!match)
17
- return path;
18
- const [, prefix, plane] = match;
19
- const suffix = path.slice(match[0].length);
20
- try {
21
- if (prefix)
22
- parseStateReadPath(prefix, MAX_HISTORY_LIMIT);
23
- // The unchanged lazy root lets the shared parser validate selectors after legacy names retire.
24
- parseValuePath(`lazy${suffix}`);
25
- }
26
- catch {
27
- return path;
28
- }
29
- return `${prefix ? `${prefix}.` : ""}${LEGACY_PLANES.get(plane)}${suffix}`;
9
+ /** A known retired format, not corruption: self-healing must never reset it. */
10
+ export class RetiredSemanticFormatError extends Error {
30
11
  }
31
- function translateReferences(value) {
32
- if (typeof value === "string")
33
- return value.replace(MARKED_LOCATOR, (_token, path) => `$${translateLocator(path)}`);
34
- if (Array.isArray(value))
35
- return value.map(translateReferences);
36
- if (!isObject(value))
37
- return value;
38
- return Object.fromEntries(Object.entries(value).map(([key, child]) => [key,
39
- key === "$ref" && typeof child === "string" ? translateLocator(child) : translateReferences(child)]));
40
- }
41
- function translateArtifacts(value) {
42
- if (!isObject(value))
43
- return translateReferences(value);
44
- return Object.fromEntries(Object.entries(value).map(([path, card]) => [path, !isObject(card) ? translateReferences(card)
45
- : Object.fromEntries(Object.entries(card).map(([key, child]) => [key,
46
- // Retired embedded provenance is evidence, never a semantic reference namespace.
47
- ["hash", "compiler", "compiled_at"].includes(key) ? structuredClone(child) : translateReferences(child)]))]));
48
- }
49
- /** Translate a raw legacy checkpoint or replay patch before any known-field filtering. */
50
- export function translateLegacySemanticObject(value) {
51
- validatePatch(value);
52
- for (const plane of LEGACY_PLANES.values()) {
53
- if (Object.hasOwn(value, plane))
54
- throw new Error(`Target State Flow semantic plane in legacy format: ${plane}`);
55
- }
56
- return Object.fromEntries(Object.entries(value).map(([key, child]) => [LEGACY_PLANES.get(key) ?? key,
57
- key === "artifacts" ? translateArtifacts(child) : LEGACY_SEMANTIC_PLANES.has(key) ? translateReferences(child) : structuredClone(child)]));
12
+ /** State Flow 1.0.0 ended the temporary contract/working conversion window; refusal stays explicit. */
13
+ export function refuseRetiredSemanticVersion(version) {
14
+ throw new RetiredSemanticFormatError(`Unsupported State Flow semantic metadata version ${String(version)}: legacy contract/working memory is no longer converted since State Flow 1.0.0; open it once with State Flow 0.x to convert it`);
58
15
  }
59
16
  /** Build a detached target candidate; publication still belongs to the guarded storage transaction. */
60
17
  export function prepareSemanticMigration(value, scope, sourceVersion, historyLimit = MAX_HISTORY_LIMIT, targetModules) {
61
- if (sourceVersion !== 1 && sourceVersion !== 2 && sourceVersion !== 3 && sourceVersion !== 4)
18
+ if (sourceVersion === 1 || sourceVersion === 2)
19
+ refuseRetiredSemanticVersion(sourceVersion);
20
+ if (sourceVersion !== 3 && sourceVersion !== 4)
62
21
  throw new Error("Unsupported State Flow migration source version");
63
22
  validatePatch(value);
64
23
  if (!isObject(value.checkpoint) || !Array.isArray(value.patches))
@@ -76,8 +35,6 @@ export function prepareSemanticMigration(value, scope, sourceVersion, historyLim
76
35
  if (sourceVersion !== 4 && targetModules !== undefined && isObject(state)
77
36
  && Object.keys(state).some(key => key.startsWith("x_")))
78
37
  throw new Error("Legacy State Flow external namespace collision");
79
- if (sourceVersion < 3)
80
- return translateLegacySemanticObject(state);
81
38
  validatePatch(state);
82
39
  assertNoRetiredSemanticPlanes(state);
83
40
  return structuredClone(state);
@@ -136,7 +93,9 @@ export function prepareSerializedScopeMigration(sources, scope, expectedCwd, tar
136
93
  if (!isObject(metadata))
137
94
  throw new Error("Invalid State Flow migration metadata");
138
95
  const version = metadata.version;
139
- if (version !== 1 && version !== 2 && version !== 3 && version !== 4)
96
+ if (version === 1 || version === 2)
97
+ refuseRetiredSemanticVersion(version);
98
+ if (version !== 3 && version !== 4)
140
99
  throw new Error("Unsupported State Flow migration source version");
141
100
  if (version === 4)
142
101
  validateRetainedModules(metadata.modules);
@@ -159,7 +118,7 @@ export function prepareSerializedScopeMigration(sources, scope, expectedCwd, tar
159
118
  if (!isObject(temporal) || !Object.hasOwn(temporal, "checkpoint") || !Array.isArray(temporal.patches)) {
160
119
  throw new Error("Invalid State Flow migration temporal metadata");
161
120
  }
162
- if (version >= 3 && !Object.hasOwn(temporal, "revision"))
121
+ if (!Object.hasOwn(temporal, "revision"))
163
122
  throw new Error("State Flow target migration metadata requires a revision");
164
123
  const checkpointText = decodeMigrationText(basis.checkpoint.bytes, "checkpoint");
165
124
  const patchesText = decodeMigrationText(basis.patches.bytes, "tail");
@@ -171,7 +130,7 @@ export function prepareSerializedScopeMigration(sources, scope, expectedCwd, tar
171
130
  throw new Error("State Flow migration metadata does not match its semantic tail");
172
131
  const candidate = prepareSemanticMigration({
173
132
  ...(version === 4 ? { modules: metadata.modules } : {}),
174
- revision: temporal.revision === undefined ? patches.length : temporal.revision,
133
+ revision: temporal.revision,
175
134
  checkpoint: { through: temporal.checkpoint, state: checkpoint },
176
135
  patches: patches.map((patch, index) => ({ transition: boundaries[index], patch })),
177
136
  }, scope, version, MAX_HISTORY_LIMIT, targetModules);
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@llblab/pi-state-flow",
3
- "version": "0.27.6",
3
+ "version": "1.0.0",
4
4
  "license": "MIT",
5
5
  "private": false,
6
6
  "description": "Incremental scoped state/context/memory compiler for Pi, inspired by SKILL.state",
@@ -514,7 +514,7 @@ Without removals on a complete accepted cohort, publication preserves semantic/p
514
514
  3. **Acceptance.** Same-session attachment accepts current memory through `withStartTransaction` under the checkpoint's mode; a fork copies the parent's current memory; a truly new auto-start origin uses `withStartTransaction` with creation authority (rechecking branch evidence after waiting); failed-Stop reload uses read-only recovery. Bootstrap and policy are derived after waiting and published in that single acceptance.
515
515
  4. **Installation.** Only the current lifetime installs memory, checkpoint, continuation, tools and UI before yielding; a later native-write failure only warns.
516
516
 
517
- **Failed Active selection.** Unreadable current memory (missing, corrupt, partial or contradictory files), a failed fork copy or automatic Start failure retains the selected Active mode with unavailable-memory validation. The inference fence is derived from that mode and validation, not an independent flag under an inactive fallback. No Active lifecycle work or fabricated projection runs before validated acceptance; shared reads may remain available. Terminal and Telegram show `active (blocked)` with explicit recovery guidance. The live `context` hook calls public `ctx.abort()` before returning; merely throwing would let Pi continue with native history. Reloading while current memory stays unreadable reconstructs the fence. Accepted Start or accepted explicit Passive releases it; explicit Off permits native context but grants no memory authority. Signal-less inspection does not cancel or clear the fence.
517
+ **Failed Active selection.** Missing, corrupt, partial or contradictory current files first go through one visible [self-healing](filesystem-recovery.md#self-healing) attempt. Memory still unavailable after that (an unhealable cause), a failed fork copy or automatic Start failure retains the selected Active mode with unavailable-memory validation. The inference fence is derived from that mode and validation, not an independent flag under an inactive fallback. No Active lifecycle work or fabricated projection runs before validated acceptance; shared reads may remain available. Terminal and Telegram show `active (blocked)` with explicit recovery guidance. The live `context` hook calls public `ctx.abort()` before returning; merely throwing would let Pi continue with native history. Reloading while current memory stays unreadable reconstructs the fence. Accepted Start or accepted explicit Passive releases it; explicit Off permits native context but grants no memory authority. Signal-less inspection does not cancel or clear the fence.
518
518
 
519
519
  **Interaction with mode choices:**
520
520
 
@@ -26,9 +26,9 @@ Since 0.27.6 the advertised tools are `state_flow_read` and `state_flow_patch`.
26
26
 
27
27
  ## Canonical scope format admission
28
28
 
29
- Core-only canonical scope metadata remains **version 3**, with `strategy` and `tactics` fields. The implemented **version 4** codec additionally retains external object-plane descriptors and opaque values independently of loaded definitions; absent internal `modules` metadata keeps existing v3 output. Declared legacy versions **1/2** translate before known-field filtering. Target-format `contract`/`working` roots reject; nested domain keys remain ordinary JSON. Unsupported versions fail closed. These scope versions are distinct from selection-aware Session lifecycle v2 and public module API v1; supported legacy lifecycle-v1 admission retains its complete-cohort proof requirements. External-root tools, captured Active/Passive context and Active producers shipped in 0.27.0; see the [public module boundary](public-module-contract.md).
29
+ Core-only canonical scope metadata remains **version 3**, with `strategy` and `tactics` fields. The implemented **version 4** codec additionally retains external object-plane descriptors and opaque values independently of loaded definitions; absent internal `modules` metadata keeps existing v3 output. Since **1.0.0**, retired versions **1/2** are refused explicitly instead of translated, and target-format `contract`/`working` roots stay reserved; nested domain keys remain ordinary JSON. Unsupported versions fail closed. These scope versions are distinct from selection-aware Session lifecycle v2 and public module API v1; supported legacy lifecycle-v1 admission retains its complete-cohort proof requirements. External-root tools, captured Active/Passive context and Active producers shipped in 0.27.0; see the [public module boundary](public-module-contract.md).
30
30
 
31
- Legacy inspection is observational. Owned semantic acceptance may convert only admitted owner scopes, after complete target-cohort/identity validation, exact source CAS and a verified private backup outside canonical authority. Missing legacy revisions credit retained records only; conversion itself adds no learning transition. Opaque capture/rollback preserves arbitrary original bytes while semantic interpretation requires valid UTF-8. See [migration proof and support limits](semantic-compatibility-decision.md#guarded-publication-and-support-boundary) and [backup/recovery guidance](usage.md#moving-a-store-and-supported-formats).
31
+ A retired cohort needs one State Flow 0.x Active/Start acceptance before upgrading. Owned acceptance there converted only admitted owner scopes, after complete target-cohort/identity validation, exact source CAS and a verified private backup outside canonical authority; conversion added no learning transition. Descriptor upgrades and legacy lifecycle conversion still follow that same guarded path. Opaque capture/rollback preserves arbitrary original bytes while semantic interpretation requires valid UTF-8. See [migration proof and support limits](semantic-compatibility-decision.md#guarded-publication-and-support-boundary) and [backup/recovery guidance](usage.md#moving-a-store-and-supported-formats).
32
32
 
33
33
  This breaking semantic API/storage change shipped in **0.27.0** and is retained in **0.27.1**. Existing exported names remain where applicable but their fields, callbacks, schemas and paths use Strategy/Tactics; no permanent old-field aliases are provided. Upgrade/quiesce old consumers before deployment: already-deployed unsafe low-level callers cannot be universally fenced. No active store was operated on during development.
34
34
 
@@ -2,6 +2,8 @@
2
2
 
3
3
  State Flow classifies absence separately from partial or malformed evidence. Recovery may derive bytes only from an authoritative surviving cohort or from a semantic default that the owner explicitly permits. It never invents history, ownership, provenance, or external success.
4
4
 
5
+ The "fails closed" rules below describe what a single operation does with partial or malformed evidence. They are not permanent: the next acquisition heals an unrecoverable owner visibly; see [self-healing](#self-healing).
6
+
5
7
  ## Resource rules
6
8
 
7
9
  ### Global `checkpoint.json` + `patches.jsonl`
@@ -138,3 +140,15 @@ Every semantic repair follows the ordinary transaction path:
138
140
  - Authored `state_flow_patch` operations select this basis under the awaited store lock and publish only after complete validation. A rejected first patch never leaves separately published empty initialization.
139
141
  - Raw precomputed replay targeting a disappeared selected basis still fails closed.
140
142
  - Discarded history is unavailable and is never reconstructed or promoted back into current shared memory.
143
+
144
+ ## Self-healing
145
+
146
+ `lib/healing.ts` is the single owner allowed to remove canonical bytes outside publication. It runs only after an acquisition (startup, reload, resume, tree navigation, Start, Passive, pre-runtime shared observation) has failed, so healthy stores pay nothing and keep their existing lock timing.
147
+
148
+ 1. Take the store publication lock without waiting; a live writer means the store is in use, so healing defers to a later attempt.
149
+ 2. Decode each selected shared owner alone, then the session lifecycle, then the complete selected cohort.
150
+ 3. For an owner that fails with a semantic decode/validation error, write one private exact-byte record (`<parent-of-store>/<store-name>-quarantine/<time>-<scope>-<digest>.json`, directory 0700, file 0600, verified by reading back), then delete that owner's canonical files so it becomes wholly absent. A cohort-level lineage contradiction resets the session (the lineage anchor), never healthy shared owners.
151
+ 4. Retry the failed acquisition once. A session that is now absent, or a boundary whose session memory was missing, restarts from empty memory under the branch's captured mode and selection.
152
+ 5. Announce every reset to the operator (warning), the model (one projected notice until a run that saw it settles) and the local diagnostic log (always, independent of `logging`).
153
+
154
+ Never healed: filesystem errors, lock or busy states, cancellation, and identity mismatches that indicate another owner's data. Those keep failing closed. Quarantine records are recovery evidence for manual restoration, not an automatic fallback.
@@ -16,20 +16,18 @@ Evidence baseline: package 0.26.5, commit `4494fee9da8258cdf5f02c42672a0eb9866a5
16
16
  - **One-time and recoverable:** Produce a detached, collision-checked conversion candidate, translate recognized semantic references, validate all retained replay boundaries, and publish checkpoint/tail/metadata together using existing exclusion/CAS/rollback. The accepted target version makes repeat acquisition idempotent. Ordinary inspection and history reads do not become migration writes; source discovery alone grants no publication authority.
17
17
  - **Fail closed:** Reject coexisting old/new root names for explicit reconciliation, unsupported versions, malformed replay, partial evidence and occupied/conflicting destinations. Do not silently merge or destroy evidence. Already-recorded ownership cascades do not run a second time.
18
18
  - **Retirement insight:** Removing the temporary converter does not remove version admission. An unsupported old store must fail explicitly after retirement, not be reinterpreted as newly available user-defined planes.
19
- - **Settled support timing:** These are State Flow package versions. Throughout **0.x**, retain legacy `contract`/`working` conversion and reserve those retired owner-root names. Beginning **1.0.0**, that temporary legacy support and reservation window ends; explicit unsupported-version refusal remains. There is no separate **1.1** deadline. Released **0.27.0/0.27.1** retain the converter and reservations; 0.27.2 consolidation preserves that policy. This policy does not authorize immediate code removal, release, working-store conversion or automatic registration of new planes. Package release numbers are not persisted schema identifiers.
19
+ - **Settled support timing, now applied:** The temporary `contract`/`working` converter was retained throughout **0.x** and removed in **1.0.0**. Retired owner-root names stay reserved; explicit unsupported-version refusal remains and now covers versions 1/2 with an actionable message. Recovering a retired store requires one State Flow 0.x Active/Start acceptance first. Package release numbers are not persisted schema identifiers.
20
20
  - **Operational boundary:** Version checks in this checkout cannot retrofit already-deployed old low-level callers. Upgrade/quiesce unsupported writers before converting shared cohorts; development only exercises temporary stores. No implicit active-store conversion, downgrade or release publication.
21
21
 
22
22
  ## Pure conversion boundary
23
23
 
24
- `lib/migration.ts` owns the temporary, side-effect-free conversion candidate. `prepareSemanticMigration` requires an explicit supported source metadata version. Versions 1/2 translate to target **3**; already-target v3/v4 candidates are validated and detached without another semantic rename. Admitted retained-module descriptors select target **4**, including the guarded first external-root admission; v4 descriptors cannot be dropped or silently changed. These are scope-format identifiers, independent of package SemVer and Pi SDK versions; native readers expose one Strategy/Tactics dialect. This module is not exported from the package root and grants no file/publication authority.
24
+ `lib/migration.ts` owns the side-effect-free semantic codec. `prepareSemanticMigration` admits only metadata versions 3/4; retired versions 1/2 throw `RetiredSemanticFormatError`, which self-healing treats as a known old format rather than corruption. Admission and refusal stay separate: an unsupported old store fails explicitly and is never reinterpreted as user-defined planes. Admitted retained-module descriptors select target **4**, including the guarded first external-root admission; v4 descriptors cannot be dropped or silently changed. These are scope-format identifiers, independent of package SemVer and Pi SDK versions; native readers expose one Strategy/Tactics dialect. This module is not exported from the package root and grants no file/publication authority.
25
25
 
26
- - Root `contract`/`working` become `strategy`/`tactics`; sparse absence, empty legacy branches, patch deletion markers, arrays, ordinary nested keys and opaque unknown root data remain intact. Any target root name in declared legacy data rejects, even without an old sibling. Target candidates reject retired roots in checkpoints and patches, including deletion attempts.
27
- - Recognized exact structured `$ref` locators and deliberate textual `$path` tokens translate only the plane position. Scope, historical selectors, array/range spelling and ownership classification remain unchanged. The query domain supplies shared selector syntax validation without target lookup. Unsupported/unparseable locators, unmarked prose and resource paths stay unchanged; no reference is hydrated or granted authority.
28
- - Artifact registry keys and retained embedded `hash`/`compiler`/`compiled_at` evidence stay opaque. Eligible semantic description/compilation references may translate, but provenance is not a semantic-reference namespace. Hidden provenance metadata is outside this stream candidate and is preserved unchanged by the serialized preflight below.
26
+ - Retired root `contract`/`working` stay reserved: current checkpoints and patches reject them, including deletion attempts, and they are never reinterpreted as external planes.
29
27
  - Candidate construction validates replay, preserves every transition identity/parent/position and owner revision, and returns detached data. It does not normalize empties, invent a transition, rerun ownership cascades, fold history or write a store.
30
- - Legacy objects translate before target semantic validation, with extra envelope fields retained until strict validation. The temporary reverse-validation bridge is removed. Malformed legacy/target fixtures ensure that conversion cannot sanitize an invalid envelope into acceptance.
28
+ - Artifact registry keys and retained embedded `hash`/`compiler`/`compiled_at` evidence stay opaque; provenance is not a semantic-reference namespace and is preserved unchanged by the serialized preflight.
31
29
 
32
- `tests/migration.test.ts` proves root reservation/collision handling, locator boundaries and opaque provenance, candidate detachment/idempotence, every retained owner boundary and aligned effective overlay at limits 0/1/7/100, and malformed replay refusal. These are deterministic conversion proofs, not interruption/CAS/backup tests or a live-model evaluation.
30
+ `tests/migration.test.ts` proves explicit retired-version refusal, root reservation, detached exact-byte receipts, module-descriptor upgrade with collision refusal, and malformed replay rejection. These are deterministic codec proofs, not interruption/CAS/backup tests or a live-model evaluation.
33
31
 
34
32
  ## Serialized owner-cohort preflight
35
33
 
package/docs/usage.md CHANGED
@@ -290,32 +290,33 @@ See the [storage contract](architecture.md#storage-and-identity) for the exact l
290
290
 
291
291
  **Wholly absent shared files.** A checkpoint and its tail are one semantic pair. If both live files of a global or CWD scope disappear, State Flow treats that complete absence as current empty shared reality. An authored `state_flow_patch` applies to that empty basis under exclusion, and normal file-cohort CAS creates the accepted pair without resurrecting cold values or orphaned compilation evidence. Raw precomputed replay still refuses a removed selected target rather than replaying stale normalized changes.
292
292
 
293
- **Corruption fails closed.** These are never replaced:
293
+ **Unrecoverable owners self-heal, visibly.** When startup, reload, resume, tree navigation, Start or Passive cannot accept memory, State Flow examines each selected owner once:
294
294
 
295
- - exactly one surviving pair member;
296
- - present malformed JSON or unsupported checkpoint envelopes;
297
- - semantic/metadata boundary mismatches and identity contradictions;
298
- - partial session runtime evidence.
295
+ - An owner that cannot be decoded (exactly one surviving pair member, malformed JSON, unsupported envelopes, semantic/metadata boundary mismatches, partial or contradictory session runtime evidence) has its exact bytes copied to a private record in `<parent-of-store>/<store-name>-quarantine/` and is then reset to wholly absent, which is empty memory. Healthy owners are untouched; a cross-owner lineage contradiction resets the private session anchor, not shared memory.
296
+ - A boundary whose stored session memory is missing restarts that session from empty memory too.
297
+ - Every reset is announced: a terminal/Telegram warning names the owner, the cause and the quarantine record; the next model request carries a notice asking the agent to tell the user; the local diagnostic log records it even when `logging` is off.
298
+ - Healing never waits behind a live writer, and filesystem errors, lock problems, cancellation and foreign-owner identity mismatches are not healed: they keep the fail-closed behavior below.
299
299
 
300
- Memory never depends on the Pi step, so an old or expired branch checkpoint is not a failure: attachment always uses the current same-session files. State Flow does not substitute Git history, empty memory or another session's files.
300
+ Memory never depends on the Pi step, so an old or expired branch checkpoint is not a failure: attachment always uses the current same-session files. State Flow does not substitute Git history or another session's files.
301
301
 
302
- **When current session memory is unreadable** (missing, corrupt, partial or contradictory files):
302
+ **When current session memory stays unavailable** (an unhealable cause):
303
303
 
304
- - Under Active, the selected mode remains Active and the indicator shows `active (blocked)`. Live inference is aborted before the provider instead of silently sending native history under an inactive fallback. Reload/resume retains this fence. Repair the files and choose Active/Passive; explicit Off permits native context without reading memory. Signal-less inspection remains observational.
305
- - Global/CWD memory stays readable; the unavailable session layer is never replaced by an empty one.
304
+ - Under Active, the selected mode remains Active and the indicator shows `active (blocked)`. Live inference is aborted before the provider instead of silently sending native history under an inactive fallback. Reload/resume retains this fence. Fix the cause and choose Active/Passive; explicit Off permits native context without reading memory. Signal-less inspection remains observational.
305
+ - Global/CWD memory stays readable; the unavailable session layer is never silently replaced.
306
306
  - Session reads and every `state_flow_patch` refuse without changing canonical files or appending substitute checkpoints.
307
- - **Modes are stable.** Explicit Passive accepts validated current same-session memory exactly like Active, keeping Passive policy. Only while current memory is still unreadable or unpublishable does Passive keep native inference with paused writes and report the cause. Off records native policy only.
307
+ - **Modes are stable.** Explicit Passive accepts validated current same-session memory exactly like Active, keeping Passive policy. Only while current memory is still unavailable or unpublishable does Passive keep native inference with paused writes and report the cause. Off records native policy only.
308
308
  - Status distinguishes a write fence from unavailable materialization.
309
309
 
310
+ **Empty stores read as empty.** On a branch without accepted memory, `state_flow_read` returns `null` for absent shared values instead of reporting an unavailable runtime; a selected but not yet created Session reports that the first accepted `state_flow_patch` creates it.
311
+
310
312
  **Explicit Start uses current memory.**
311
313
 
312
314
  - It independently validates the current same-session canonical cohort, preserving private memory, artifact provenance, revisions, step and available aligned history.
313
315
  - Expired active/passive pointers and unfinished runtime work do not block activation. A pre-runtime selection also keeps current accepted same-session memory instead of resetting it.
314
316
  - Start bootstraps the conversation available on the selected Pi branch, without resurrecting an old unfinished specification or claiming that expired historical private state was restored.
315
317
  - Independently advanced shared scopes may require a new temporal origin; unavailable history is never invented.
316
- - Exact-cohort CAS rejects a concurrent writer, and incomplete or corrupt storage stays untouched.
318
+ - Exact-cohort CAS rejects a concurrent writer; incomplete or corrupt storage is changed only by visible self-healing.
317
319
  - An unaccepted native fork retries copying its parent's current memory rather than inventing child memory.
318
- - When evidence is missing, repair it or open a genuinely new Pi session.
319
320
 
320
321
  **Artifact evidence and replication:**
321
322
 
@@ -351,14 +352,15 @@ Commit or push failure is diagnostic-only; repeated push failures warn once per
351
352
 
352
353
  **Supported formats.** State Flow accepts only canonical checkpoint/tail files, temporal metadata and the separate session config/runtime contract.
353
354
 
354
- **Why files can still contain `contract`/`working` after an update.** Installing or reloading the package is not a whole-store migration. Legacy reads translate those roots to `strategy`/`tactics` in memory; disk conversion occurs only when an owned semantic transaction accepts the participating cohort. Off, inspection and runtime-only mode persistence do not perform it. Unselected owners and untouched historical sessions remain in their supported legacy format until their own acceptance; accepting one session never scans or upgrades every project/session. To convert an existing cohort, first quiesce old writers, then explicitly accept its current memory with Active/Start using the upgraded code. Keep the verified migration backup; do not rename JSON keys manually or reopen old writers against converted files.
355
+ **Retired `contract`/`working` cohorts are refused, not converted.** State Flow 1.0.0 ended the temporary conversion window. A scope whose metadata still declares version 1 or 2 now fails with an explicit message naming the scope: open the store once with a State Flow 0.x release so its owned Active/Start acceptance converts it, then upgrade. Renaming JSON keys by hand is never supported.
355
356
 
356
- - Scope metadata versions 1/2 remain readable through explicit `contract → strategy`, `working → tactics` translation before field filtering. Current/historical tools expose only the target dialect; retired root writes reject rather than becoming aliases. Legacy missing revisions credit only retained tail records.
357
- - Core-only writes use scope metadata v3; retained external-module descriptors select v4. Both use Strategy/Tactics. On owned semantic acceptance, supported legacy/descriptor upgrades use the same backup, lock/CAS and rollback checks without advancing revisions/causal identities for representation alone. Ordinary inspection and runtime-only mode persistence do not convert files. Upgrade/quiesce all writers before enabling the new code: already-deployed low-level readers cannot be universally fenced by a format number.
357
+ - Retired root names stay reserved: `contract` and `working` written into a current checkpoint or patch reject, including deletion attempts, and are never reinterpreted as user-defined planes.
358
+ - Self-healing never applies to this refusal. A retired cohort is a known old format, not corruption, so its bytes are left exactly as they are.
359
+ - Core-only writes use scope metadata v3; retained external-module descriptors select v4. Both use Strategy/Tactics. On owned semantic acceptance, descriptor upgrades and legacy lifecycle config/runtime conversion use the same backup, lock/CAS and rollback checks without advancing revisions/causal identities for representation alone. Ordinary inspection and runtime-only mode persistence do not convert files. Upgrade/quiesce all writers before enabling the new code: already-deployed low-level readers cannot be universally fenced by a format number.
358
360
  - Unsupported checkpoint envelopes, combined session metadata, `state.json`, hashed layouts and semantic Pi checkpoint envelopes fail as unsupported, without rewriting existing bytes.
359
361
  - Canonical semantic objects lacking optional fields, such as `intents` or `lazy`, are valid sparse state and do not cross this boundary.
360
- - Before a supported legacy or explicit metadata upgrade is canonically published, the storage owner writes and verifies an exact-byte JSON backup at `<parent-of-store>/<store-name>-migration-backups/<sha256>.json` (created with directory mode 0700, file mode 0600 on the verified platform; existing non-private paths reject). It lists converted scopes and updated paths alongside the transaction's owned file basis, relative paths, identities, Base64 originals and explicit missing entries, including required Session config/runtime. It never discovers unrelated projects/sessions or source bodies. The returned publication exposes `migrationBackup`; completed backups survive rollback and exact retries reuse them. Backup failure blocks canonical writes.
361
- - This backup is recovery evidence outside canonical authority, not a Git commit, journal, automatic fallback or power-loss guarantee. Quiesce writers and request a reviewed complete-cohort recovery before downgrade/restoration; do not overwrite intervening foreign data or restore just one file. Retain backups privately. State Flow 0.x retains legacy conversion and retired-root reservations; the temporary support window ends at State Flow 1.0.0, with unsupported versions still explicitly rejected. Released 0.27.0/0.27.1 retain their converter/reservations, and 0.27.2 preserves that policy; no automatic removal, release or working-store operation follows from consolidation. See the [settled support policy](semantic-compatibility-decision.md#implementation-direction-and-reserved-names).
362
+ - Before a descriptor upgrade or legacy lifecycle conversion is canonically published, the storage owner writes and verifies an exact-byte JSON backup at `<parent-of-store>/<store-name>-migration-backups/<sha256>.json` (created with directory mode 0700, file mode 0600 on the verified platform; existing non-private paths reject). It lists converted scopes and updated paths alongside the transaction's owned file basis, relative paths, identities, Base64 originals and explicit missing entries, including required Session config/runtime. It never discovers unrelated projects/sessions or source bodies. The returned publication exposes `migrationBackup`; completed backups survive rollback and exact retries reuse them. Backup failure blocks canonical writes.
363
+ - This backup is recovery evidence outside canonical authority, not a Git commit, journal, automatic fallback or power-loss guarantee. Quiesce writers and request a reviewed complete-cohort recovery before downgrade/restoration; do not overwrite intervening foreign data or restore just one file. Retain backups privately. State Flow 1.0.0 removed the temporary `contract`/`working` converter and kept both retired-root names reserved; unsupported versions are still refused explicitly. Need the converter one more time? Use a State Flow 0.x release. See the [settled support policy](semantic-compatibility-decision.md#implementation-direction-and-reserved-names).
362
364
 
363
365
  ### Conflicts and interrupted publication
364
366
 
package/lib/durable.ts CHANGED
@@ -19,7 +19,7 @@ import {
19
19
  type ArtifactProvenanceRegistry,
20
20
  } from "./artifact.ts";
21
21
  import { MAX_HISTORY_LIMIT } from "./history.ts";
22
- import { prepareSerializedScopeMigration } from "./migration.ts";
22
+ import { prepareSerializedScopeMigration, refuseRetiredSemanticVersion } from "./migration.ts";
23
23
  import { canonicalJson, isJsonValue, isObject, type JsonObject } from "./json.ts";
24
24
  import { validateScopeStream, validateTemporalState, type ScopeStream, type TemporalState } from "./temporal.ts";
25
25
  import { assertRetainedModules, validateRetainedModules } from "./semantic-module.ts";
@@ -83,7 +83,7 @@ export type ScopeStreamPresence =
83
83
  | { kind: "present"; stream: ScopeStream };
84
84
 
85
85
  function isSupportedScopeMetadataVersion(version: unknown): boolean {
86
- return version === 1 || version === 2 || version === 3 || version === 4;
86
+ return version === 3 || version === 4;
87
87
  }
88
88
 
89
89
  /** Distinguish a wholly absent semantic cohort from partial or malformed surviving authority. */
@@ -110,6 +110,7 @@ export function classifyScopeStream(
110
110
  throw new Error(`Unsupported State Flow ${scope} storage format`);
111
111
  }
112
112
  const metadata = parseMetadataDocument(metaSource, `State Flow ${scope} metadata`);
113
+ if (metadata.version === 1 || metadata.version === 2) refuseRetiredSemanticVersion(metadata.version);
113
114
  if (!isSupportedScopeMetadataVersion(metadata.version)) throw new Error(`Unsupported State Flow ${scope} metadata version`);
114
115
  // In Unicode mode this range matches lone UTF-16 surrogates, not valid pairs or JSON escapes.
115
116
  if ([checkpointSource, patchesSource, metaSource].some((source) => /[\uD800-\uDFFF]/u.test(source))) {
package/lib/extension.ts CHANGED
@@ -40,7 +40,8 @@ import { compactStatus, detailedStatus, STATUS_KEY, type StatusDiagnostics } fro
40
40
  import { PublicationBusyError, loadSelectedFileCohort, type SelectedFilePublication } from "./storage.ts";
41
41
  import { captureScopeSelection, DEFAULT_SCOPE_SELECTION, parseScopeSelectionArguments, scopeSelectionArgumentCompletions, type ScopeSelection } from "./selection.ts";
42
42
  import { createStateFlowTelegramAdapter, type StateFlowTelegramControlResult, type StateFlowTelegramInspection, type StateFlowTelegramLoader, type StateFlowTelegramScope } from "./telegram.ts";
43
- import { readTemporalScopes, temporalScopeRevisions, type ScopeRevisions } from "./temporal.ts";
43
+ import { createSelectedTemporalState, readTemporalScopes, temporalScopeRevisions, type ScopeRevisions, type SelectedTemporalState } from "./temporal.ts";
44
+ import { describeHealedScopes, healSelectedStore, HealNotice, type HealResult } from "./healing.ts";
44
45
  import { commitSelectedTransition, stageSelectedScopePatches, stageSelectedScopedTransition, type ModuleReplacement } from "./transition.ts";
45
46
 
46
47
  export interface StateFlowExtensionOptions {
@@ -129,6 +130,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
129
130
  let effectiveState: SemanticState = {};
130
131
  let branchStartsWithoutRuntime = false;
131
132
  let modePersistenceError: string | undefined;
133
+ const healNotice = new HealNotice();
132
134
  /** One pending inactive-mode persistence; later inactive choices coalesce until it publishes. */
133
135
  const inactivePersistence = new OwnedOperationSlot<InactivePersistence>();
134
136
  const startActivation = new OwnedOperationSlot<ModeOperation>();
@@ -181,6 +183,38 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
181
183
  ctx.ui.notify(conciseDiagnostic(message), level);
182
184
  }
183
185
 
186
+ /** Announce a reset to both operator and model; a reset is never silent. */
187
+ function announceHealing(ctx: ExtensionContext, message: string): void {
188
+ healNotice.announce(message);
189
+ diagnosticWriter.recordSelfHeal(sessionAddress(ctx).id, ctx.cwd, message);
190
+ ctx.ui.notify(message, "warning");
191
+ }
192
+
193
+ /** Quarantine unrecoverable selected owners before acceptance; unhealable failures keep failing closed downstream. */
194
+ async function healCurrentStore(ctx: ExtensionContext, wanted: ScopeSelection, signal: AbortSignal): Promise<HealResult | undefined> {
195
+ const address = sessionAddress(ctx);
196
+ let result: HealResult;
197
+ try {
198
+ result = await healSelectedStore({ cwd: ctx.cwd, sessionId: address.id, sessionKey: address.key, selection: wanted,
199
+ historyLimit: config.historyLimit, root: repositoryRoot }, signal);
200
+ } catch (error) {
201
+ if (signal.aborted) throw error;
202
+ return undefined;
203
+ }
204
+ if (result.healed.length) announceHealing(ctx, `State Flow self-healed: ${describeHealedScopes(result.healed)}`);
205
+ return result;
206
+ }
207
+
208
+ /** A pre-runtime branch with no stored cohort reads as empty memory instead of an unavailable runtime. */
209
+ function emptyPreRuntimeView(wanted: ScopeSelection): SelectedTemporalState | undefined {
210
+ if (!branchStartsWithoutRuntime || snapshot.config.mode === "off" || snapshot.meta.validation?.attempt === 0
211
+ || branchRestoration.current?.awaitingAcceptance) return undefined;
212
+ // Shared absence is empty reality; unacquired Session keeps its explicit selected-unavailable diagnostic.
213
+ const shared = wanted.filter(scope => scope !== "session");
214
+ if (!shared.length) return undefined;
215
+ return createSelectedTemporalState(Object.fromEntries(shared.map(scope => [scope, {}])), captureScopeSelection(shared), "empty:pre-runtime", config.historyLimit);
216
+ }
217
+
184
218
  function notifyActiveContext(message: string): void {
185
219
  try {
186
220
  if (activeContext) notifyProblem(activeContext, message, "warning");
@@ -695,9 +729,30 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
695
729
  return branchRestoration.track(pending, attachBranch(ctx, pending, selection, sessionStartReason, notifyRecovery, skipped), false);
696
730
  }
697
731
 
732
+ /**
733
+ * After a failed attachment, heal selected owners once. Returns the selection to retry, or undefined when healing
734
+ * changed nothing; expected-but-absent session memory restarts visibly from empty memory.
735
+ */
736
+ async function healBranchSelection(ctx: ExtensionContext, selection: BranchSelection, requestedMode: InactiveMode | undefined, signal: AbortSignal): Promise<BranchSelection | undefined> {
737
+ if (selection.kind === "settled") return undefined;
738
+ const healing = await healCurrentStore(ctx, nativeScopeSelection(ctx), signal).catch(() => undefined);
739
+ if (!healing || signal.aborted || shuttingDown) return undefined;
740
+ if (healing.lifecycleAbsent && (selection.kind === "attach" || selection.kind === "current")) {
741
+ const mode = requestedMode ?? (selection.kind === "current" ? selection.mode : selection.checkpoint.mode);
742
+ if (mode === "off") return undefined;
743
+ if (!healing.healed.some(item => item.scope === "session")) {
744
+ announceHealing(ctx, "State Flow self-healed: session memory files were missing and session memory restarts empty");
745
+ }
746
+ branchStartsWithoutRuntime = true;
747
+ modePersistenceError = undefined;
748
+ return mode === "active" ? { kind: "auto-start" } : { kind: "pre-runtime", mode };
749
+ }
750
+ return healing.healed.length > 0 ? selection : undefined;
751
+ }
752
+
698
753
  async function attachBranch(
699
754
  ctx: ExtensionContext, pending: BranchRestoration, selection: BranchSelection,
700
- reason: unknown, notifyRecovery: boolean, skipped: number,
755
+ reason: unknown, notifyRecovery: boolean, skipped: number, healed = false,
701
756
  ): Promise<void> {
702
757
  const placeholder = runtime;
703
758
  let selected = runtime;
@@ -857,6 +912,12 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
857
912
  return;
858
913
  }
859
914
  if (!isCurrent()) return;
915
+ const retry = healed ? undefined : await healBranchSelection(ctx, selection, pending.requestedMode, signal);
916
+ if (retry && isCurrent()) {
917
+ pending.awaitingAcceptance = retry.kind !== "settled" && retry.kind !== "current";
918
+ return await attachBranch(ctx, pending, retry, reason, notifyRecovery, skipped, true);
919
+ }
920
+ if (!isCurrent()) return;
860
921
  failSelection(error);
861
922
  } finally {
862
923
  pending.awaitingAcceptance = false;
@@ -866,7 +927,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
866
927
  settleSelection(ctx, reason, notifyRecovery, skipped, selected !== placeholder);
867
928
  if (snapshot.config.mode === "off" || isActive() || readableView() || snapshot.meta.validation?.attempt === 0 || !branchStartsWithoutRuntime) return;
868
929
  // Only a proven pre-runtime Passive branch may observe shared owners without private acquisition.
869
- const passive = await loadPassiveView(ctx, signal, isCurrent, notifyRecovery);
930
+ const passive = await loadPassiveView(ctx, signal, isCurrent, notifyRecovery, !healed);
870
931
  if (passive === undefined) return;
871
932
  assertCurrent();
872
933
  // An intervening passive patch or inspection owns its newer cache, even on the same physical branch.
@@ -885,14 +946,21 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
885
946
  }
886
947
 
887
948
  /** Load current shared memory for passive projection without initializing or publishing it. */
888
- async function loadPassiveView(ctx: ExtensionContext, signal: AbortSignal, isCurrent: () => boolean, notify: boolean): Promise<TemporalRuntime | undefined> {
949
+ async function loadPassiveView(ctx: ExtensionContext, signal: AbortSignal, isCurrent: () => boolean, notify: boolean, heal = true): Promise<TemporalRuntime | undefined> {
889
950
  const wanted = nativeScopeSelection(ctx), shared = wanted.filter(scope => scope !== "session");
890
951
  if (!shared.length) return undefined;
891
952
  const passive = createRuntime(ctx);
953
+ const observe = () => passive.refreshSelectedShared(captureScopeSelection(shared), () => {
954
+ if (!isCurrent() || !sameJson(nativeScopeSelection(ctx), wanted)) throw new Error("State Flow observation selection changed");
955
+ }, signal);
892
956
  try {
893
- await passive.refreshSelectedShared(captureScopeSelection(shared), () => {
894
- if (!isCurrent() || !sameJson(nativeScopeSelection(ctx), wanted)) throw new Error("State Flow observation selection changed");
895
- }, signal);
957
+ try { await observe(); }
958
+ catch (error) {
959
+ if (!heal || signal.aborted || !isCurrent()) throw error;
960
+ const healing = await healCurrentStore(ctx, captureScopeSelection(shared), signal).catch(() => undefined);
961
+ if (!healing?.healed.length) throw error;
962
+ await observe();
963
+ }
896
964
  } catch (error) {
897
965
  if (isCurrent() && !signal.aborted && notify && !modePersistenceError) notifyProblem(ctx, `State Flow passive memory is unavailable: ${diagnosticText(error)}`, "warning");
898
966
  return undefined;
@@ -989,11 +1057,12 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
989
1057
  const requestedPaths = [...(params.paths ?? [params.path!])];
990
1058
  const paths = requestedPaths.map(path => normalizeModelReadPath(path, wanted, config.historyLimit));
991
1059
  check();
992
- const view = readableView(selected);
1060
+ const view = readableView(selected) ?? emptyPreRuntimeView(wanted);
993
1061
  // Wanted policy was checked by normalization; an observational subset is not an exclusion.
994
1062
  for (const path of paths) {
995
1063
  const owner = /^(global|cwd|session)(?=\.|\[|$)/.exec(path)?.[1] as StateScope | undefined;
996
- if (owner && !view?.selection.includes(owner)) throw new Error(`State Flow ${owner}: selected, unavailable`);
1064
+ if (owner && !view?.selection.includes(owner)) throw new Error(`State Flow ${owner}: selected, unavailable${branchStartsWithoutRuntime
1065
+ ? "; no memory is stored for it yet, and an accepted state_flow_patch creates it" : ""}`);
997
1066
  }
998
1067
  if (!view) throw new Error("State Flow temporal runtime is unavailable");
999
1068
  check();
@@ -1239,6 +1308,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
1239
1308
  async function activateCurrentState(
1240
1309
  ctx: ExtensionContext, pending: AbortController, mode: "active" | "passive" = "active",
1241
1310
  owns = () => startActivation.current?.controller === pending,
1311
+ healing?: HealResult,
1242
1312
  ): Promise<StateFlowTelegramControlResult> {
1243
1313
  let selected = runtime;
1244
1314
  const wanted = nativeScopeSelection(ctx);
@@ -1265,15 +1335,24 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
1265
1335
  const retained = selectRetainedCheckpoint(discovery.candidates, config.inactiveMode);
1266
1336
  branchStartsWithoutRuntime = retained.kind === "pre-runtime" || (discovery.candidates.length === 0 && discovery.errors.length === 0);
1267
1337
  }
1338
+ // After a failed attempt, a missing or reset session lifecycle restarts visibly from empty memory instead of blocking forever.
1339
+ const sessionReset = healing?.lifecycleAbsent === true && !forkInitialization && !branchPolicy(ctx).forkPending
1340
+ && !(selected?.cwd === ctx.cwd && selected.sessionKey === activation.sessionKey && selected.selectedView()?.selection.includes("session"));
1341
+ if (sessionReset) {
1342
+ if (!branchStartsWithoutRuntime && !healing!.healed.some(item => item.scope === "session")) {
1343
+ announceHealing(ctx, "State Flow self-healed: session memory files were missing and session memory restarts empty");
1344
+ }
1345
+ branchStartsWithoutRuntime = true;
1346
+ }
1268
1347
  // Off activation owns one cancellable current-head publication, not an independent read-only restore.
1269
1348
  const acceptActivation = (current: Snapshot | undefined, publish: (next: Snapshot) => SelectedFilePublication) => {
1270
1349
  signal.throwIfAborted();
1271
1350
  if (!isCurrent()) throw new Error("State Flow activation selection changed while awaiting publication");
1272
- if (!current && (!active || !branchStartsWithoutRuntime)) throw new Error(snapshot.meta.validation?.error ?? "Current State Flow session memory is unavailable");
1351
+ if (!current && (!(active || sessionReset) || !branchStartsWithoutRuntime)) throw new Error(snapshot.meta.validation?.error ?? "Current State Flow session memory is unavailable");
1273
1352
  const boundary = deferred && retainsPhysicalSessionProjection(deferred.reason)
1274
1353
  ? branchPolicy(ctx).stop : undefined;
1275
1354
  const bootstrap = hasPriorConversation(ctx.sessionManager.getBranch()) || passiveContinuation !== undefined || boundary !== undefined;
1276
- const activated = !active ? deactivateEpisode(current!, "passive")
1355
+ const activated = !active ? deactivateEpisode(current ?? startEpisode(false), "passive")
1277
1356
  : current ? resumeEpisode(current, bootstrap) : startEpisode(bootstrap);
1278
1357
  if (active) {
1279
1358
  // Explicit Start accepts current memory, not the prior run's prompt or repair attempt.
@@ -1337,8 +1416,9 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
1337
1416
  if (forkInitialization || branchPolicy(ctx).forkPending) throw new Error("Pending fork cannot use independent private acquisition");
1338
1417
  acquiredResult = acceptActivation(basis.snapshot, activated => publish(activated));
1339
1418
  } }, publish => { check(); publish(); return acquiredResult; }, signal, true);
1340
- } else if (active && branchStartsWithoutRuntime && !acceptedSession && !disposition) {
1341
- const next = startEpisode(hasPriorConversation(ctx.sessionManager.getBranch()) || passiveContinuation !== undefined);
1419
+ } else if ((active || sessionReset) && branchStartsWithoutRuntime && !acceptedSession && !disposition) {
1420
+ const started = startEpisode(hasPriorConversation(ctx.sessionManager.getBranch()) || passiveContinuation !== undefined);
1421
+ const next = active ? started : deactivateEpisode(startEpisode(false), "passive");
1342
1422
  result = await activation.withSelectedFirstPatchTransaction(wanted, next, transaction => {
1343
1423
  check();
1344
1424
  if (!branchStartsWithoutRuntime || forkInitialization) throw new Error("State Flow origin authority changed");
@@ -1349,6 +1429,12 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
1349
1429
  return isCurrent() ? result : superseded();
1350
1430
  } catch (error) {
1351
1431
  if (!isCurrent()) return superseded();
1432
+ if (!accepted && healing === undefined) {
1433
+ // Self-healing is lazy: healthy stores never pay for it, and one retry bounds convergence.
1434
+ const healed = await healCurrentStore(ctx, wanted, signal).catch(() => undefined);
1435
+ if (!isCurrent()) return superseded();
1436
+ if (healed && (healed.healed.length > 0 || healed.lifecycleAbsent)) return activateCurrentState(ctx, pending, mode, owns, healed);
1437
+ }
1352
1438
  const message = conciseDiagnostic(`${accepted ? `State Flow ${mode}; lifecycle update failed` : active ? "State Flow activation failed" : "State Flow passive acceptance failed"}: ${diagnosticText(error)}`);
1353
1439
  // An unaccepted activation cannot replace retained lifecycle or poison an independent Stop.
1354
1440
  // Attachment owns required-proof unavailability; failed Passive acceptance reports through its caller's fence.
@@ -1782,7 +1868,9 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
1782
1868
  // Off removes the owned section, including one contributed before an in-flight mode change.
1783
1869
  const protocol = isActive() ? stateFlowProtocol(snapshot.meta.bootstrap === true, nativeScopeSelection(ctx))
1784
1870
  : passiveMemoryAvailable() ? passiveMemoryProtocol(nativeScopeSelection(ctx)) : undefined;
1785
- return { messages: projectSystemProtocol(event.messages, protocol) };
1871
+ // Only a request that can carry the section consumes the reset notice.
1872
+ const notice = snapshot.config.mode !== "off" && event.messages.some(message => message.role === "system") ? healNotice.project() : undefined;
1873
+ return { messages: projectSystemProtocol(event.messages, [protocol, notice].filter(Boolean).join("\n\n") || undefined) };
1786
1874
  });
1787
1875
 
1788
1876
  // Optional transport checkpoint: no payload/header inspection or transformation.
@@ -2096,6 +2184,8 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
2096
2184
  });
2097
2185
 
2098
2186
  pi.on("agent_before_settle", async (_event, ctx) => {
2187
+ // Passive has no response reconciliation: its settled run is the accepted turn for already published patches.
2188
+ if (!shuttingDown && snapshot.config.mode === "passive" && memoryToolsAvailable()) backup.markTurnAccepted();
2099
2189
  if (shuttingDown || !memoryToolsAvailable() || !backup.takeSettledTurn()) return;
2100
2190
  const operationSignal = ctx.signal;
2101
2191
  const lifetime = backup.lifetime;
@@ -2129,6 +2219,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
2129
2219
  });
2130
2220
 
2131
2221
  pi.on("agent_settled", async (_event, ctx) => {
2222
+ healNotice.settle();
2132
2223
  if (telegramStartPending && !isActive()) {
2133
2224
  telegramStartPending = false;
2134
2225
  await startStateFlow(ctx);