# Changelog

> Each release keeps at most 8 outcome records of at most 512 characters.

## 0.8.0: Atomic cohorts and final eligibility

- `Protocol`: Replaced the single-scope PATCH and UNCHANGED forms with one canonical `patch_state({global?, cwd?, session?, final?})` call. Supplied scopes validate against one causal basis and publish as one atomic transition with a single identity, temporal boundary, durable cohort, and inference barrier; unknown fields, `final:false`, empty scopes, and material no-ops fail closed.
- `Eligibility`: `final:true` is now an ephemeral per-iteration latch rather than a resolution form. It permits a later `turn_end` without stopping reasoning, tools, or further patches; eligibility survives later activity and repeated final calls, resets only with the next enabled iteration, and `{final:true}` alone creates no semantic transition, identity, step, or Git commit.
- `Resolution`: An ineligible terminal draft is discarded and steered for at most three attempted completions. The first two attempts emit hidden same-run instructions; the third reports one bounded error while preserving committed state, enablement, and runtime-owned response. Failed and host-rejected patch calls consume no attempts, and only the accepted post-eligibility answer becomes `response`.
- `Diagnostics`: Rejected `patch_state` calls now retain their exact attempted arguments alongside the precise error, tool identity, call id, resolution-attempt count, and terminal-eligibility state; publication conflicts use the same record and successful patches are never logged.
- `Compatibility`: Persisted checkpoints, tails, provenance registries, scope layout, and Git/file durability are unchanged and need no migration; the removed model-facing grammar is not accepted as a compatibility alias.

## 0.7.0: Explicit resolution and leaner runtime

- `Protocol`: Made `patch_state` the sole model-authored semantic mutation path. Every enabled turn now requires a successful resolution call, each exactly PATCH `{scope, patch}` or UNCHANGED `{"unchanged":true}`; unresolved prose is discarded and steered within the same run, failed calls remain unresolved, and only the later accepted ordinary answer becomes runtime-owned `response`.
- `Stop`: `/state-flow-stop` still creates no semantic transition, but now prevents raw-history resurrection with a frozen effective-state handoff plus post-stop messages. The bounded projection survives reload, resume, and tree restoration for that physical session; active restart uses the same boundary for one migration run, while new/forked sessions inherit nothing.
- `Metadata`: Moved artifact source hashes, compiler revisions, and compilation timestamps from model-visible artifacts into each scope's existing `meta.json`. Missing evidence degrades only dependent freshness capabilities, malformed present evidence fails locally, and legacy embedded provenance remains readable compatibility input but is stripped from projection.
- `Temporal`: Removed configurable `transitionWindow` output in favor of one fixed seven-boundary hot history, while tolerating retired input. Restored branches now adopt proven advances in untouched global/CWD streams at a fresh origin and fail precisely when the current patch targets a shared scope that diverged; publication CAS still protects the captured basis.
- `Durability`: Git publication now commits the complete non-ignored state-repository delta, including tracked edits, new files, and manual deletions, before overlaying exact prepared State Flow bytes. Active files retain CAS protection, ignored files remain untouched, rollback preserves concurrent bytes, and the caller-visible index is synchronized to the accepted tree.
- `Activation`: Normal `turn-end`/`off` activation accepts locally without waiting for remote push, Markdown freshness discovery is deferred until the next enabled inference, and canonical stores skip full predecessor-format planning when legacy snapshot names are absent. Warm reactivation has one config commit; timing and Git Trace2 evidence are recorded in the architecture guide.
- `Diagnostics`: Added opt-in local JSONL diagnostics for rejected `patch_state` calls and intercepted unresolved drafts, excluding reasoning bodies and all semantic/publication planes. Logging failure is inert apart from one warning. Failed `patch_state` results remain real errors with a local blank-line rendering boundary.
- `Compatibility`: Preserved the four-field semantic shape, three scopes, storage paths, existing 0.6.x stores, optional Git/file durability, and remote policy without a bulk migration or new metadata file. Removed the terminal HTML-comment parser/retry protocol and its validation module; historical and foreign comments remain ordinary owner-controlled text.

## 0.6.0: Continuity without fixation

- `Memory`: Revised ordinary handoffs to preserve confirmed decisions, useful uncertainty, interaction consequences, completed prerequisites, bounded positive and negative results, and exact continuation without promoting provisional methods or unsupported assertions.
- `Skill`: Expanded the explicit `state-flow-memory` Skill with reframing, one bounded fresh-run review, compilation-first scheduling, write/readback/delete scope migration, recoverable partial results, and evidence-gated external promotion.
- `Curation`: Added regression coverage for the executable curation barrier sequence while preserving single-scope `patch_state`, terminal multi-scope reconciliation, trusted compiler metadata, native tool context, and local acceptance independently from remote replication.
- `Compatibility`: Preserved the 0.5.0 semantic shape and Git/file storage without migration, bulk rewrite, new dependency, or new runtime/config/tool contract.

## 0.5.0: Durable memory, compiled routing, and local-first publication

- `Publication`: Decoupled immediate local Git acceptance from optional remote replication with persisted `off`/`turn-end`/legacy `transition` policy, a symlink-safe CAS queue, descendant-only coalescing, asynchronous non-interactive workers, restart recovery, concurrency-safe confirmation, and truthful status diagnostics.
- `Memory`: Made State Flow the unconditional durable-memory owner while enabled, with global semantic memory always available at the narrowest correct scope; external promotion pointers remain optional semantic handoff records rather than runtime ownership configuration.
- `Artifacts`: Added extensible compiled artifact metadata, validated tags, deterministic candidate routing, and bounded visible source rehydration without persisting source bodies or treating routing as read authorization.
- `Continuation`: Added read-only native-session discovery, exact State Flow provenance checks, deterministic continuation ranking, and bootstrap planning while keeping automatic default resume deferred until Pi exposes a pre-session resolver hook.
- `Identity`: Unified Pi's session UUID and native storage key as one runtime address, centralized extension runtime construction, and skipped obsolete hashed-path probing once canonical CWD materialization is proven.
- `Validation`: Replaced transient semantic-equality SHA-256 calculations with validated structural JSON comparison while retaining cryptographic hashes for durable identity, freshness, integrity, CAS, and fingerprints.
- `Transcript`: Restored the empty-line boundary between the `patch_state` tool call and its materialization result in Pi and Telegram transcript rendering.
- `Skill`: Bundled the optional `state-flow-memory` Skill for explicit bounded audits, scope narrowing, contradiction cleanup, and evidence-gated external handoff without background maintenance.

## 0.4.0: Temporal state and independent durable storage

### Temporal state

- `Temporal`: Rebuilt materialized state on one parent-linked causal lineage. `state[0..7]` and each global/CWD/session projection now resolve the same accepted boundary, sparse multi-scope changes share one identity, response-only changes advance history, and semantic no-ops do not.
- `Temporal`: Added enabled-only `read_state` for lazy effective or scoped reads at offsets zero through seven. Reads use the cached checkpoint/tail runtime without publishing, while `patch_state` remains the sole mutator and an immediate inference barrier.
- `Lifecycle`: Preserved Pi's native tool loop and full inspectable session trace while reconciling each finalized answer into session response exactly once. New sessions inherit shared scopes without rewriting them; resume, tree navigation, stop, and pre-runtime branch starts preserve branch-local provenance.

### Storage and recovery

- `Storage`: Moved runtime state out of Knowledge into the independently configurable `agentDir/state-flow` store. Canonical scope files are anchored `checkpoint.json` plus bounded replayable `patches.jsonl`, with separate session `config.json` and `meta.json`; strict revision-only Pi checkpoints replace copied semantic snapshots.
- `Storage`: Made Git optional. File-only mode preserves the exact current cohort and hot history when the executable is absent; Git mode commits every accepted cohort immediately, keeps local-only repositories valid, retries the exact commit after remote failure, and adopts populated file stores without inventing earlier history.
- `Identity`: Aligned CWD and session directories with Pi's native readable layout, including JSONL filename stems and header-derived in-memory session names. Canonical owner metadata retains collision/foreign-identity checks; current Git-backed SHA-suffixed development stores migrate transactionally, while old Git revisions remain readable.
- `Recovery`: Added conservative current-state migration and branch restoration without checkout/reset. Historical reads select Git objects directly; unavailable pointers never authorize substituting live files, and changing the configured store does not silently relocate Knowledge-backed history.
- `Publication`: Hardened publication with shared exclusion, isolated indexes, exact prepared-byte receipts, compare-and-swap checks, symlink/path rejection, unrelated staging preservation, and conflict-aware byte-exact rollback.

### Configuration, context, and diagnostics

- `Configuration`: Added strict agent-level `state-flow.json`: `directory` selects storage and `autoStart` defaults to `false` for genuinely new sessions only. Absolute, config-relative, and home-relative paths are supported; SDK storage and Knowledge roots remain independent overrides.
- `Context`: Retained the canonical `artifacts`, `contract`, `working`, and `response` semantic shape, with recursive global → CWD → session overlay. Knowledge Markdown and Skill acquisition now use source-addressed, runtime-hashed artifact compilations and materialized-first read policy rather than raw-body injection.
- `Diagnostics`: Expanded status and acceptance documentation for selected revisions, active temporal boundaries, hot-history depth, retained scope tails, artifact freshness, pending publication, unavailable materialization, and all twenty temporal properties.

## 0.3.0: Optional memory patches and evidence-aware handoffs

- `Reality`: Require targeted revalidation of volatile observations and inspection of external effects after interruption or branch navigation; missing memory proves neither success nor absence of effects. Document the absence of rollback/freshness guarantees and preserve the restriction on routine Skill rereads. Add instruction-presence tests, not semantic or integration guarantees.
- `Memory`: Strengthen the handoff protocol with evidence-aware continuation, requirement/observation/hypothesis distinctions, conditional rejections, and contradiction reconciliation; preserve decision-relevant uncertainty during optimization. Add instruction-presence regressions, not semantic guarantees. Increase the protocol-only character budget to 3,700 (3,900 with bootstrap) for these obligations; state remains uncapped.
- `Terminal`: Accept ordinary non-empty terminal answers as empty memory patches: preserve memory and update the response without unnecessary regeneration, including answers split across text blocks.
- `Validation`: Keep malformed explicit envelopes and missing Skill compilations on the existing bounded validation path.
- `Planning`: Clear the backlog; documented integration and continuation-quality limitations remain, not release commitments.

## 0.2.3: Document protocol and validation limitations

- `Terminal`: Document that duplicate-comment detection also rejects literal State Flow envelope examples inside fenced or inline code in terminal answers, and provide a plain-JSON workaround.
- `Validation`: Clarify that mock lifecycle tests are not real Pi scheduler integration checks and that structural validation cannot guarantee semantic memory retention.
- `Runtime`: No runtime behavior changes.

## 0.2.2: README structure hotfix

- `Documentation`: Separate installation from usage, remove the redundant quick-start section, and move architecture details after the user-facing documentation.

## 0.2.1: README banner hotfix

- `Documentation`: Add the project banner to the README.

## 0.2.0: Modular runtime hardening

- `Documentation`: Add a task-first README quick start with explicit compatibility, opt-in behavior, one-off trial instructions, and Pi package security guidance.
- `Protocol`: Tighten the normative runtime protocol and enforce a regression-tested character budget; omit absent validation feedback from synthetic runtime context instead of serializing a redundant `null`.
- `Testing`: Redistribute lifecycle coverage from the former monolithic extension suite into the corresponding mirrored domain suites, leaving `extension.test.ts` focused on composition and using one shared test harness.
- `Architecture`: Split the runtime into independent `json`, `state`, `episode`, `snapshot`, `session`, `recovery`, `status`, `context`, `skills`, `terminal`, `validation`, `transition`, and `extension` modules under `lib/`; isolate explicit episode transitions, active-branch selection and recovery, status rendering, bounded retry decisions, atomic state staging, and compare-and-swap commits; mirror each domain under `tests/`, enforce an acyclic dependency graph with cross-domain invariant tests, and reduce `index.ts` to composition and public exports.
- `Lifecycle`: Register lifecycle commands in the canonical start, status, stop order.
- `Context`: Centralize synthetic runtime-context construction and private validation-message filtering in the independently tested context domain, keeping user-controlled specifications out of system-prompt composition.
- `Recovery`: Keep State Flow enabled and preserve the last committed state when terminal-validation retries are exhausted; only the transient retry chain is abandoned so the next user request can continue reliably.
- `Skill`: Track Skill reads through an independently tested lifecycle correlator in Pi's actual `tool_execution_start` → `tool_call` event order while retaining the mutable intercepted input reference, so later argument rewrites are attributed to the executed path.
- `Lifecycle`: Discard mismatched lifecycle records defensively so a stale or reused tool-call id cannot produce false Skill acquisition.
- `Validation`: Bound restored iteration and validation-attempt counters before incrementing them, reject exhausted live iteration counters explicitly, and cover both safe-integer boundaries so malformed branch metadata cannot corrupt retry accounting or status output.
- `Validation`: Reject restored non-JSON state values such as non-finite numbers before they can break hashing or silently materialize as `null`.
- `Recovery`: Fall back past malformed newer checkpoints to the newest valid active-branch snapshot, while still failing closed on cyclic or hostile snapshot objects when no valid checkpoint remains.
- `Recovery`: Reject malformed three-field state shapes rather than reinterpreting them as legacy working memory, and contain failures while enumerating hostile branch entries.
- `Validation`: Make canonical serialization and exported patch validation reject lossy or cyclic non-JSON inputs explicitly instead of returning invalid results or silently rewriting values.

## 0.1.5: Skill attribution and state model clarification

- `Skill`: Attribute successful Skill acquisition to finalized `tool_execution_start` arguments, with a tested compatibility fallback to the intercepted `tool_call` input.
- `State`: Clarify that the three-field materialized handoff coexists with mutable exogenous project and runtime state that can also shape model behavior.
- `Documentation`: Remove the obsolete `/reload` step from the usage instructions.

## 0.1.4: Release verification hotfix

- `Release`: Kept npm pack lifecycle output out of release inventory JSON so Trusted Publisher releases can complete public verification and GitHub Release creation.

## 0.1.3: Trusted Publisher release automation

- `Release`: Added immutable-tag GitHub Actions automation that validates the package, publishes and verifies npm through Trusted Publisher with provenance, and creates the matching GitHub Release.

## 0.1.2: Repository identity hotfix

- `Identity`: Aligned GitHub repository, package metadata, installation documentation, and release links under the canonical `llblab/pi-state-flow` identity.

## 0.1.1: Public npm distribution

- `Release`: Enabled public npm distribution for `@llblab/pi-state-flow`, including registry access and verified GitHub package metadata.
- `Skill`: Clarified that compiled Skill knowledge is stored persistently under `contract.compiled_skills`, never as another top-level state field.

## 0.1.0

- `Runtime`: Added an opt-in State Flow runtime inspired by SKILL.state, with argument-free lifecycle commands, per-user-run specifications, active-branch persistence, and one materialized explicit state.
- `Lifecycle`: Added native Pi tool-loop preservation: tool-bearing responses require no patch, current-run tool trajectory remains model-visible, and one terminal handoff commits state after the complete agent run.
- `State`: Added required flexible `contract` and `working` objects plus the required latest user-facing `response` string, recursive materialization, nested object-key `null` deletion, materialized-null rejection, and deterministic state compare-and-swap.
- `Terminal`: Kept arbitrary response content outside the transcript-private `<!-- state_flow … -->` memory-patch frame; the runtime strictly anchors the frame at the start of one terminal text block, requires exactly one blank separator, reconciles materialized `response` with Pi's finalized post-handler text at `turn_end`, and routes post-handler finalization failures through the same bounded hidden regeneration chain. Documented that the frame remains observable to streaming consumers before finalization.
- `Authority`: Kept user-controlled turn specifications at user authority by moving their repeated representation out of the system prompt and into synthetic user runtime context, including support for empty text in image-only prompts.
- `Recovery`: Added active-branch restoration after `/tree` navigation, clean abandonment of interrupted terminal-validation retries before the next user run, and cumulative retry accounting across intervening tool-bearing turns.
- `Context`: Preserved persistent and current-run custom context from other Pi extensions, attributed Skill acquisition from finalized executed arguments after mutable tool interception, and limited accidental intermediate-envelope stripping to a structurally valid leading frame.
- `State`: Hardened recursive patch materialization so JSON keys such as `__proto__` remain ordinary own data without changing object prototypes.
- `Packaging`: Added an explicit release file allowlist, Pi package discovery keywords, package-safe README targets, Pi/Node compatibility bounds, and a prepack validation gate so generated packages contain only runtime and human-facing release files.
- `Bootstrap`: Added bootstrap migration for enabling State Flow inside an existing session, per-run specification rotation, schema-free episode-level Skill compilation in `contract.compiled_skills` keyed by exact source path, and model-owned memory optimization that reorganizes inefficient structure and deletes stale, redundant, speculative, or low-value state.
- `Architecture`: Removed per-tool state commits, action authorization, Delta Window, observation envelopes, action ledgers, project schemas, state and patch byte caps, dynamic growth pressure, and all coupling to other extensions.
- `Protocol`: Compressed the static runtime protocol while retaining terminal, handoff, Skill-compilation, authority, and memory-optimization invariants.
- `Lifecycle`: Added stop-as-complete-episode-reset semantics, a compact accent `state-flow` plus dim `#<iteration>` status, and complete pretty-formatted state JSON output from `/state-flow-status`.
