@llblab/pi-state-flow 0.11.2 → 0.12.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
@@ -10,13 +10,13 @@
10
10
  - Correlate successful exact-path reads with the current ordinary global invalidation plan. Require each acquired stale source to have a compact compiler output at the same path in a global transition, reject model-authored provenance fields, and record the runtime-observed source hash plus current ordinary compiler revision in the global provenance registry. Compile routing descriptions by default, never raw Markdown or a full-file summary; preserve uncertainty and reserve richer compilations for reusable operational semantics.
11
11
  - Apply one materialized-first acquisition policy to every source: read only for a concrete relevant gap not covered by a sufficient compilation, an exact-source operation including edits, evidenced invalidation, contradiction/failure reconciliation, explicit request, or selection by bounded maintenance. New sessions, routine recall or activation, reassurance, and an index or description alone are not reasons to read. Changed hashes require rereading; prefer the smallest sufficient read.
12
12
  - Keep artifact maintenance opt-in, low-frequency, and side-effect free until a selected source is acquired. Select only otherwise-fresh artifacts old enough for maintenance, rank missing/unparseable `compiled_at` first then oldest timestamp and path, and enforce strict per-cycle read-count and source-byte ceilings. Treat source bytes as the conservative source-token upper bound. Never let maintenance displace correctness invalidation; use explicit invalidation refresh for full rebuilds and never mutate source files.
13
- - Load optional agent-level `state-flow.json` once per extension load/reload. Its `directory` selects the state store, `autoStart` defaults false for genuinely new sessions, and `remotePublication` selects `off`, `turn-end`, or compatibility `transition`. State Flow always owns durable memory while enabled and global semantic memory is always available; these are invariants, not configuration switches. Keep runtime configuration and provenance outside model-patchable semantic state.
13
+ - Load optional agent-level `state-flow.json` once per extension load/reload. Its `directory` selects the state store, `autoStart` defaults false for genuinely new sessions, `showSuccessfulPatches` defaults true for interactive successful-call JSON rendering, and `remotePublication` selects `off`, `turn-end`, or compatibility `transition`. State Flow always owns durable memory while enabled and global semantic memory is always available; these are invariants, not configuration switches. Keep runtime configuration and provenance outside model-patchable semantic state.
14
14
  - Keep runtime configuration and provenance separate from model-patchable semantic state. Persist session `config.json` for enablement/projection settings and `meta.json` for lineage, counters, branch identity, durable base, publication, migration metadata, and session-scope artifact provenance; global and CWD scopes own their artifact provenance in scope `meta.json`. Neither participates in scope overlay. New Pi checkpoints contain only a durable revision pointer, or `{disabled:true}` when no durable runtime exists on that branch. Preserve exact Git hashes for Git-backed revisions and give file-only current-cohort references an unambiguous distinct identity; file references use `file:<64 lowercase hex>`, bind the store root and complete scoped/runtime cohort, and must not pretend to provide arbitrary cold or branch history. Operationally unavailable references (including expired file cohorts, missing Git, and publication exclusion) retain selection rather than falling through to older disabled markers; malformed immutable targets remain a distinct recovery case; they are not a parallel authoritative semantic or config/meta store. Emit a disabled marker only from proven pre-runtime branch provenance; missing/invalid revisions and failed restoration do not establish that permission. Predecessor checkpoint formats are read-only migration input. Validate immutable pointer targets before acquiring the live publication basis; transient publication failures preserve the selected retry reference rather than choosing older semantic state. In Git mode, runtime `revision: "self"` resolves to the commit owning the config/meta pair, not an unrelated later repository commit. File publication uses explicit `publication: "files"` provenance and resolves the exact complete live cohort instead of claiming a Git owner. Use a distinct `meta.temporalRevision` when a runtime-only write selects older semantic scopes; restore their artifact provenance from that same revision and preserve live shared checkpoints, tails, and provenance during session config/meta writes. Persist publication intent as unconfirmed before pushing; reconcile that exact existing commit after restart rather than embedding an impossible self-hash or inventing semantic history.
15
15
  - Overlay materialized state recursively in `global → cwd → session` order. Scope-local deletion removes only that scope's key so a lower-scope value becomes visible again; scope never changes instruction authority. Route branch/run-local continuation to session, project-local reusable state and Skill artifacts to CWD, and cross-project reusable state to global.
16
16
  - Reserve `state` for the runtime materialized semantic view. For each scope, current state is exactly `materialize(checkpoint.json, patches.jsonl)`: an older anchored checkpoint plus its ordered tail of at most seven materially effective semantic patches. On overflow, apply the oldest patch into the checkpoint, advance its `through` boundary, remove it, and append the new patch. Never truncate unapplied replay records or replay patches over an already-current snapshot.
17
17
  - Give every accepted semantic transition one opaque identity shared by all affected scope records, with explicit active causal lineage. A branch-local position can order identities but never acts as a global counter, substitutes for identity, or merges forks. Unchanged scopes contribute no record and remain unchanged at that boundary. Adopt revision-proven inherited streams at a new session origin without rewriting their checkpoints/tails; pre-origin coordinates are not one shared clock. A restored branch adopts current proven live shared streams it does not modify at a fresh origin while preserving its selected session layer; a shared scope the accepted transition actually changes must still match its selected basis or fail closed naming that scope. Reconciliation adoption is not a fabricated semantic transition, parent link, or retry loop. True semantic no-ops and origin adoption do not advance semantic history.
18
18
  - Define `state[n]` and `state.global[n]`, `state.cwd[n]`, `state.session[n]` at the same nth previous accepted transition boundary in the active lineage, never the nth local patch of each scope. Guarantee offsets zero through seven once the lineage has seven proven transitions; report earlier-than-origin history as unavailable for new/migrated lineages and reject offsets beyond seven on the hot interface. Reconstruct scopes at one target before overlaying them.
19
- - Keep historical reads lazy through the smallest runtime/model read interface. Normal inference gets only current effective state and useful bounded compact transition context, never eight full snapshots. `patch_state` is the sole semantic mutation tool. `read_state` exposes one cached effective/global/CWD/session projection at offset 0–7, defaulting to effective/0; it returns the exact boundary with semantic state and never publishes, appends a checkpoint, or advances history. Both tools follow branch enablement and host tool restrictions; the patch barrier blocks reader siblings too. Live/cached checkpoint plus tails own the hot path; use Git for branch restoration and explicit cold inspection, not to rebuild current state on every inference.
19
+ - Keep historical reads lazy through the smallest runtime/model read interface. Normal inference gets only current effective state and useful bounded compact transition context, never eight full snapshots. `patch_state` is the sole semantic mutation tool. `read_state` resolves current-as-index-zero aliases for effective/scoped materializations and scope-local retained accepted patches; materialization indices share the composed causal lineage while `patches[n]` walks the selected scope's retained patch tail. The prior offset/scope form remains a compatibility input and cannot combine with `path`. Reads return the exact boundary and never publish, append a checkpoint, or advance history. Both tools follow branch enablement and host tool restrictions; the patch barrier blocks reader siblings too. Live/cached checkpoint plus tails own the hot path; use Git for branch restoration and explicit cold inspection, not to rebuild current state on every inference.
20
20
  - Store runtime state in its own directory with optional Git durability, defaulting to `state-flow/` beneath Pi's configured agent directory (`~/.pi/agent/state-flow/` normally), independently from the Knowledge Markdown source root. Use exactly these owned paths: `checkpoint.json`, `patches.jsonl`, and `meta.json` for global; `<cwd-key>/checkpoint.json`, `<cwd-key>/patches.jsonl`, and `<cwd-key>/meta.json` for CWD; `<cwd-key>/<session-key>/checkpoint.json`, `patches.jsonl`, `config.json`, and `meta.json` for session. Do not create `.state-flow`, `scopes`, or another storage/history namespace. Mirror Pi's native CWD session-directory encoding and JSONL-basename session key (deriving `<header timestamp>_<UUID>` for in-memory sessions), while retaining separately verifiable canonical identity provenance in owned state. Keep the UUID authoritative, reject unsafe segments and mismatches rather than selecting another scope, and use CWD checkpoint ownership to fail closed on Pi-name collisions.
21
21
  - Classify every filesystem cohort before recovery: complete valid evidence is usable; total absence is recoverable only from an explicit semantic default or exact surviving authority; partial, malformed, contradictory, or authority-losing evidence fails closed at the smallest dependent capability. A wholly absent untouched global/CWD checkpoint-tail pair is current empty shared reality and must not resurrect selected cold values; a patch targeting that disappeared scope is stale and must fail for reinference. Missing provenance means unavailable freshness, not semantic corruption. Perform every repair through normal locked/CAS publication, never ad-hoc writes.
22
22
  - Migrate legacy current `state.json` losslessly into an initial anchored checkpoint with an empty tail; current snapshots are the sole semantic recovery basis, independent of the presence or validity of explanatory journals, including historical revision reads. Preserve only proven history, remove obsolete files within the successful scoped migration, and never retain two authoritative formats. Exercise migrations in temporary repositories rather than modifying the user's active Knowledge data during development.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,11 @@
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## 0.12.0: Unified state reads and visible patches
8
+
9
+ - `Unified state reads`: `read_state` now resolves current-as-index-zero paths for effective/scoped materializations and retained scope patches while preserving the prior offset/scope input for compatibility. Materialization paths share the composed causal timeline; patch paths walk accepted records for their selected scope.
10
+ - `Successful patch visibility`: Interactive successful `patch_state` rows show the applied JSON arguments by default. Agent-level `showSuccessfulPatches: false` restores compact summaries; rejected calls and private validation payloads remain separate.
11
+
7
12
  ## 0.11.2: Single hierarchical Back control
8
13
 
9
14
  - `Telegram inspection navigation`: Removes the chooser-owned `⬅️ Back` button from Show state. The section framework now supplies the only navigation row, `⬆️ Back`, which returns directly to the State Flow section; the four scope choices and read-only Rich state inspection are unchanged.
package/README.md CHANGED
@@ -68,7 +68,7 @@ Memory overlays **global → project CWD → session**. Put reusable cross-proje
68
68
 
69
69
  **Resuming an existing Pi session restores its selected State Flow state and enablement.** A genuinely new session starts with an empty session layer and inherits only shared global/CWD memory; it does not resume another session's private work. Tree navigation follows the selected branch, not whichever state happens to be at Git `HEAD`.
70
70
 
71
- The agent can inspect `state[0]` through `state[7]`: now and up to seven prior accepted transitions. Every scope is read at the same causal boundary. Git-backed stores retain older committed history separately.
71
+ The agent can inspect `state`/`state[0]` through `state[7]`: now and up to seven prior accepted transitions. Scoped paths such as `state.cwd[1]` use the same causal boundary; `state.global.patches[0]` reads the latest retained accepted patch for that scope. Git-backed stores retain older committed history separately.
72
72
 
73
73
  ## Boundaries worth knowing
74
74
 
@@ -202,12 +202,18 @@ Both [tested Pi SDKs](compatibility.md) choose or create `SessionManager` before
202
202
  {"session":{"working":{"next":"Verify the corrected behavior"}},"final":true}
203
203
  ```
204
204
 
205
- `read_state` defaults to effective state at offset zero. It accepts one optional `scope` (`effective`, `global`, `cwd`, or `session`) and integer `offset` from zero to seven, returning `{offset, scope, boundary, state}`. It reads cached selected state without Git queries, publication, checkpoint append, or a semantic step. Pre-origin history is an error, not an empty state.
205
+ `read_state` accepts one unified path. `state == state[0]` is the current effective materialization; `state.global == state.global[0]` (and CWD/session equivalents) selects that scope at the same composed causal boundary. `state.global.patches == state.global.patches[0]` reads the latest accepted retained global patch, with higher patch indices walking only that scope's retained accepted patches. Indices are bounded to zero through seven; unavailable pre-origin or pre-tail history is an error. Resolver aliases are not literal JSON containers. Reads stay cached and create no Git query, publication, checkpoint append, or semantic step.
206
206
 
207
207
  ```json
208
- {"offset":1,"scope":"cwd"}
208
+ {"path":"state.cwd[1]"}
209
209
  ```
210
210
 
211
+ ```json
212
+ {"path":"state.global.patches[0]"}
213
+ ```
214
+
215
+ The prior `{offset, scope}` form remains accepted for session/tool-call compatibility, but cannot be combined with `path`.
216
+
211
217
  Both tools follow branch enablement and host restrictions. The patch barrier also blocks reader siblings. These tools do not impose project schemas or state-size caps; semantic usefulness, scope choice, and compression remain model responsibilities. Every ordinary handoff reconciles touched and obviously stale visible state. Feature/release/campaign completion, project switches, and active-version changes additionally require one bounded scoped ownership and obsolescence pass: global retains only established cross-project/user/environment knowledge, CWD owns reusable project truth, and session owns branch/run continuation. Scope movement uses targeted reads and destination verification before source deletion rather than an automatic maintenance loop.
212
218
 
213
219
  ### Embedding
@@ -2,9 +2,13 @@
2
2
 
3
3
  This matrix records exact tested dependency stacks, not the version of an operator's running Pi process. Package peer ranges admit `^0.84.4 || ^0.85.1`; keep Pi, AI and agent-core on a matching release line. Mixed-version stacks and later releases are not separate test evidence.
4
4
 
5
+ ## Current release candidate
6
+
7
+ The 0.12.0 candidate passes `npm run validate` on the repository-local 0.84.4 dependency graph: typecheck, import check, and 451/451 tests. Its focused path/config/interactive-rendering cohort passes 41/41, including current-as-index-zero `read_state` aliases, composed-lineage scoped reads, retained scope-patch reads, legacy `{offset, scope}` compatibility, and both visible/default and suppressed `patch_state` argument rendering. A live enabled host also resolves current and historical legacy reads; the host must reload the candidate before its model-facing tool schema can expose the new `path` input. The 0.85.1 full-suite result below belongs to the earlier source checkpoint and has not been repeated for this candidate.
8
+
5
9
  ## Tested matrix
6
10
 
7
- The compatibility checks use Linux/x64, Node 26.8.1, Git 2.55.0, TypeScript 7.0.2 and Node types 26.4.0.
11
+ The historical compatibility checks use Linux/x64, Node 26.8.1, Git 2.55.0, TypeScript 7.0.2 and Node types 26.4.0.
8
12
 
9
13
  | Pi / AI / agent-core | SDK's pi-tui / TypeBox | Typecheck / import | Full suite |
10
14
  | --- | --- | --- | --- |
package/docs/usage.md CHANGED
@@ -35,6 +35,7 @@ Optional `state-flow.json` beneath Pi's agent directory, normally `~/.pi/agent/s
35
35
  "directory": "~/.pi/agent/state-flow",
36
36
  "autoStart": false,
37
37
  "logging": false,
38
+ "showSuccessfulPatches": true,
38
39
  "remotePublication": "turn-end"
39
40
  }
40
41
  ```
@@ -42,6 +43,7 @@ Optional `state-flow.json` beneath Pi's agent directory, normally `~/.pi/agent/s
42
43
  - `directory`: State store. The default is `state-flow/` beneath the agent directory. Absolute paths, `~`/`~/`, and relative paths are accepted; relative paths resolve from the configuration directory, not project CWD.
43
44
  - `autoStart`: Defaults to `false`. When `true`, genuinely new sessions use the same initialization as explicit Start, including fresh CWDs.
44
45
  - `logging`: Defaults to `false`. When enabled, records rejected patches and unresolved terminal/fallback diagnostics locally at `tmp/state-flow/logs.jsonl` beneath the agent directory.
46
+ - `showSuccessfulPatches`: Defaults to `true`. In interactive Pi, successful `patch_state` rows show the applied JSON arguments beneath the compact result; set it to `false` to keep only the summary. Rejected calls still use ordinary error rendering and private validation details are never added.
45
47
  - `remotePublication`: New-runtime policy: `turn-end` queues the newest accepted commit for asynchronous push; `off` keeps commits local; `transition` retains synchronous compatibility behavior. Existing branches keep their persisted policy.
46
48
 
47
49
  Settings are read once at extension load. After editing, use `/reload` or restart Pi. A missing file uses defaults without creating a configuration file; malformed JSON, unknown keys, or invalid values fail loading rather than silently selecting another store.
package/index.ts CHANGED
@@ -204,3 +204,4 @@ export {
204
204
  type StateFlowTelegramView
205
205
  } from "./lib/telegram.ts";
206
206
  export { advanceTemporalState, readTemporalState, type TemporalState } from "./lib/temporal.ts";
207
+ export { parseStateReadPath, readStatePath, type StateReadQuery, type StateReadResult } from "./lib/query.ts";
package/lib/config.ts CHANGED
@@ -11,6 +11,8 @@ export interface StateFlowConfig {
11
11
  autoStart: boolean;
12
12
  /** Opt-in local capture of rejected patch attempts and unresolved terminal drafts. */
13
13
  logging: boolean;
14
+ /** Show successful patch_state arguments in the interactive tool row. */
15
+ showSuccessfulPatches: boolean;
14
16
  remotePublication?: "off" | "turn-end" | "transition";
15
17
  }
16
18
 
@@ -21,6 +23,7 @@ export function loadStateFlowConfig(agentDir = getAgentDir()): StateFlowConfig {
21
23
  directory: getDurableRepositoryRoot(agentDir),
22
24
  autoStart: false,
23
25
  logging: false,
26
+ showSuccessfulPatches: true,
24
27
  };
25
28
  let value: unknown;
26
29
  try {
@@ -29,12 +32,13 @@ export function loadStateFlowConfig(agentDir = getAgentDir()): StateFlowConfig {
29
32
  } catch (error) {
30
33
  throw new Error(`Cannot read State Flow configuration: ${path}`, { cause: error });
31
34
  }
32
- const allowed = new Set(["directory", "autoStart", "logging", "remotePublication"]);
35
+ const allowed = new Set(["directory", "autoStart", "logging", "showSuccessfulPatches", "remotePublication"]);
33
36
  if (!isObject(value) || Object.keys(value).some((key) => !allowed.has(key))) {
34
37
  throw new Error(`State Flow configuration contains unknown settings: ${path}`);
35
38
  }
36
39
  if (Object.hasOwn(value, "autoStart") && typeof value.autoStart !== "boolean") throw new Error(`State Flow autoStart must be a boolean: ${path}`);
37
40
  if (Object.hasOwn(value, "logging") && typeof value.logging !== "boolean") throw new Error(`State Flow logging must be a boolean: ${path}`);
41
+ if (Object.hasOwn(value, "showSuccessfulPatches") && typeof value.showSuccessfulPatches !== "boolean") throw new Error(`State Flow showSuccessfulPatches must be a boolean: ${path}`);
38
42
  if (Object.hasOwn(value, "remotePublication") && value.remotePublication !== "off" && value.remotePublication !== "turn-end" && value.remotePublication !== "transition") {
39
43
  throw new Error(`State Flow remotePublication must be off, turn-end, or transition: ${path}`);
40
44
  }
@@ -48,6 +52,7 @@ export function loadStateFlowConfig(agentDir = getAgentDir()): StateFlowConfig {
48
52
  directory: expanded === undefined ? defaults.directory : resolve(dirname(path), expanded),
49
53
  autoStart: value.autoStart === true,
50
54
  logging: value.logging === true,
55
+ showSuccessfulPatches: value.showSuccessfulPatches !== false,
51
56
  ...(value.remotePublication === undefined ? {} : { remotePublication: value.remotePublication as "off" | "turn-end" | "transition" }),
52
57
  };
53
58
  }
package/lib/extension.ts CHANGED
@@ -3,6 +3,7 @@ import { randomUUID } from "node:crypto";
3
3
  import { StringEnum, Type } from "@earendil-works/pi-ai";
4
4
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
5
5
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
+ import { Text } from "@earendil-works/pi-tui";
6
7
  import { assistantToolCallCount, finalizedAssistantResponse, stateFlowProtocol } from "./protocol.ts";
7
8
  import { createPassiveContinuation, currentRunTrajectory, passiveContinuationMessages, runtimeContextMessage, VALIDATION_MESSAGE_TYPE, withoutPrivateValidation, type PassiveContinuation } from "./context.ts";
8
9
  import { ArtifactReadTracker } from "./acquisition.ts";
@@ -26,6 +27,7 @@ import { acquirePublicationWorkerLease, loadPublicationQueue, publicationQueuePa
26
27
  import { runPublicationWorker } from "./publication.ts";
27
28
  import { getKnowledgeRoot, GlobalMarkdownDiscovery } from "./discovery.ts";
28
29
  import { isObject, sameJson } from "./json.ts";
30
+ import { readStatePath } from "./query.ts";
29
31
  import {
30
32
  cwdScopeKey,
31
33
  resolveSessionAddress,
@@ -762,23 +764,33 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
762
764
  pi.registerTool({
763
765
  name: READ_STATE_TOOL_NAME,
764
766
  label: "Read State",
765
- description: "Read one effective or scoped State Flow materialization at offset 0–7 in the active causal lineage. Read-only and lazy; unavailable pre-origin history is an error. Use only for a concrete historical or scope-specific gap, not routine rereading of current context.",
766
- promptSnippet: "Read one cached effective/global/CWD/session state at temporal offset 0–7",
767
+ description: "Read State Flow through a unified path such as state, state[1], state.cwd[2], or state.global.patches[0]. The legacy offset/scope form remains accepted. Read-only and lazy; unavailable hot history is an error.",
768
+ promptSnippet: "Read cached state or accepted scope patches with a unified path",
767
769
  parameters: Type.Object({
768
- offset: Type.Optional(Type.Integer({ minimum: 0, maximum: 7, description: "Accepted transitions before current state; defaults to 0" })),
769
- scope: Type.Optional(StringEnum(["effective", "global", "cwd", "session"] as const, { description: "Projection at that same boundary; defaults to effective" })),
770
+ path: Type.Optional(Type.String({ description: "Unified query path; current aliases use index 0" })),
771
+ offset: Type.Optional(Type.Integer({ minimum: 0, maximum: 7, description: "Legacy accepted-transition offset; defaults to 0" })),
772
+ scope: Type.Optional(StringEnum(["effective", "global", "cwd", "session"] as const, { description: "Legacy projection at the same boundary; defaults to effective" })),
770
773
  }, { additionalProperties: false }),
771
774
  async execute(_toolCallId, params, signal) {
772
775
  try {
776
+ type ReadDetails = { path?: string; offset?: number; scope?: string; transitionId: string };
773
777
  if (!snapshot.config.enabled) throw new Error("State Flow is disabled on this session branch");
774
778
  if (signal?.aborted) throw new Error("State Flow read was aborted");
775
779
  if (!runtime?.view) throw new Error("State Flow temporal runtime is unavailable");
780
+ if (params.path !== undefined) {
781
+ if (params.offset !== undefined || params.scope !== undefined) throw new Error("read_state path cannot be combined with legacy offset or scope");
782
+ const result = readStatePath(runtime.view, params.path);
783
+ return {
784
+ content: [{ type: "text", text: `\n${JSON.stringify(result)}` }],
785
+ details: { path: params.path, transitionId: result.boundary.id } as ReadDetails,
786
+ };
787
+ }
776
788
  const { offset = 0, scope = "effective" } = params;
777
789
  const state = runtime.read(offset, scope === "effective" ? undefined : scope);
778
790
  const boundary = runtime.view.lineage.at(-1 - offset)!;
779
791
  return {
780
792
  content: [{ type: "text", text: `\n${JSON.stringify({ offset, scope, boundary, state: projectStateForModel(state) })}` }],
781
- details: { offset, scope, transitionId: boundary.id },
793
+ details: { offset, scope, transitionId: boundary.id } as ReadDetails,
782
794
  };
783
795
  } catch (error) {
784
796
  throw separatedFailure(error);
@@ -804,6 +816,11 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
804
816
  final: Type.Optional(Type.Boolean({ description: "Set exactly true to permit this iteration to finish at a later turn_end" })),
805
817
  }, { additionalProperties: false }),
806
818
  prepareArguments: normalizePatchStateArguments,
819
+ renderResult(result, { isPartial }, theme, context) {
820
+ const text = result.content.find((block) => block.type === "text")?.text ?? "";
821
+ if (isPartial || context.isError || !config.showSuccessfulPatches) return new Text(text, 0, 0);
822
+ return new Text(`${text.trimStart()}\n${theme.fg("dim", JSON.stringify(context.args, null, 2))}`, 0, 0);
823
+ },
807
824
  async execute(toolCallId, params, signal, _onUpdate, ctx) {
808
825
  try {
809
826
  if (!snapshot.config.enabled) throw new Error("State Flow is disabled on this session branch");
package/lib/query.ts ADDED
@@ -0,0 +1,40 @@
1
+ import { projectStateForModel, type MaterializedState, type ScopePatch, type StateScope } from "./state.ts";
2
+ import { readTemporalState, type TemporalState, type TransitionBoundary } from "./temporal.ts";
3
+
4
+ export type StateReadQuery =
5
+ | { kind: "state"; path: string; offset: number; scope?: StateScope }
6
+ | { kind: "patch"; path: string; offset: number; scope: StateScope };
7
+
8
+ export type StateReadResult =
9
+ | { path: string; boundary: TransitionBoundary; state: MaterializedState }
10
+ | { path: string; boundary: TransitionBoundary; patch: ScopePatch & { response?: string } };
11
+
12
+ const PATH_PATTERN = /^state(?:\[(\d+)\])?(?:\.(global|cwd|session)(?:\[(\d+)\])?(?:\.patches(?:\[(\d+)\])?)?)?$/;
13
+
14
+ /** Resolve the compact model-facing path grammar without treating aliases as literal JSON containers. */
15
+ export function parseStateReadPath(path: string): StateReadQuery {
16
+ const match = PATH_PATTERN.exec(path);
17
+ if (!match) throw new Error("Invalid State Flow read path");
18
+ const [, effectiveOffset, scope, scopeOffset, patchOffset] = match;
19
+ if (effectiveOffset !== undefined && scope !== undefined) throw new Error("State Flow read path cannot index both state and a scope");
20
+ if (path.includes(".patches") && scopeOffset !== undefined) throw new Error("Index patches after .patches, not after the scope");
21
+ const rawOffset = patchOffset ?? scopeOffset ?? effectiveOffset ?? "0";
22
+ const offset = Number(rawOffset);
23
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset > 7) throw new Error("State Flow read path index must be an integer from 0 to 7");
24
+ if (patchOffset !== undefined || path.endsWith(".patches")) {
25
+ return { kind: "patch", path, offset, scope: scope as StateScope };
26
+ }
27
+ return { kind: "state", path, offset, ...(scope === undefined ? {} : { scope: scope as StateScope }) };
28
+ }
29
+
30
+ export function readStatePath(view: TemporalState, path: string): StateReadResult {
31
+ const query = parseStateReadPath(path);
32
+ if (query.kind === "state") {
33
+ const boundary = view.lineage[view.lineage.length - 1 - query.offset];
34
+ if (!boundary) throw new Error("Requested history predates the proven temporal origin");
35
+ return { path, boundary: structuredClone(boundary), state: projectStateForModel(readTemporalState(view, query.offset, query.scope)) };
36
+ }
37
+ const record = view.scopes[query.scope].patches.at(-1 - query.offset);
38
+ if (!record) throw new Error(`Requested ${query.scope} patch predates retained hot history`);
39
+ return { path, boundary: structuredClone(record.transition), patch: structuredClone(record.patch) };
40
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@llblab/pi-state-flow",
3
- "version": "0.11.2",
3
+ "version": "0.12.0",
4
4
  "private": false,
5
5
  "description": "Incremental scoped state/context compiler for Pi, inspired by SKILL.state",
6
6
  "keywords": [
@@ -53,9 +53,11 @@
53
53
  "peerDependencies": {
54
54
  "@earendil-works/pi-agent-core": "^0.84.4 || ^0.85.1",
55
55
  "@earendil-works/pi-ai": "^0.84.4 || ^0.85.1",
56
- "@earendil-works/pi-coding-agent": "^0.84.4 || ^0.85.1"
56
+ "@earendil-works/pi-coding-agent": "^0.84.4 || ^0.85.1",
57
+ "@earendil-works/pi-tui": "^0.84.4 || ^0.85.1"
57
58
  },
58
59
  "devDependencies": {
60
+ "@earendil-works/pi-tui": "0.84.4",
59
61
  "@types/node": "latest",
60
62
  "typescript": "latest"
61
63
  }
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: state-flow-memory
3
- description: Audit and reconcile State Flow durable memory across global, CWD, and session scopes. Preserve commitments, established learning, and the point of continuation without freezing provisional approaches. Use for explicit memory curation, ownership migration, contradiction cleanup, stale continuation review, externally evidenced promotion, or a feature/release/project phase-boundary reconciliation required by the State Flow runtime contract; not for unrelated routine turns or background maintenance.
3
+ description: Audit and reconcile State Flow durable memory across global, CWD, and session scopes. Preserve commitments, established learning, and the point of continuation without freezing provisional approaches. Use after completing a major feature, important release, large body of work, campaign, project phase, or meaningful checkpoint—even when the user did not explicitly ask for memory work—as well as for explicit memory curation, ownership migration, contradiction cleanup, stale continuation review, externally evidenced promotion, and active-version boundaries; not for unrelated routine turns or background maintenance.
4
4
  ---
5
5
 
6
6
  # State Flow Memory Curation
@@ -78,6 +78,8 @@ Do not erase a meaningful correction, uncertainty, commitment, negative result,
78
78
 
79
79
  ### Reconcile phase boundaries
80
80
 
81
+ After a major feature, important release, large body of work, or meaningful checkpoint reaches completion or its final stage, proactively optimize the affected State Flow scopes. Distill implementation-specific detail into durable consequences, remove trajectory-bound scaffolding, and rebalance knowledge across global, CWD, and session ownership so the resulting state stays alive, reusable, and open to better future methods rather than preserving the shape of the finished effort.
82
+
81
83
  A completed feature, release, campaign, project switch, or active-version change is evidence that its working set needs one bounded review. Remove completed task lists, obsolete release/version state, run identifiers, timings, incident chronology, dead experiments, and stale continuation. Retain shipped status only when it remains a prerequisite, durable rule, open risk, or useful retrieval pointer.
82
84
 
83
85
  State branches may move as applicability changes. Global is limited to established cross-project, user, or environment knowledge; CWD owns reusable project truth; session owns branch/run continuation. Narrow project-specific global material into CWD, promote genuinely cross-project learning only when evidence supports the broader boundary, and move reusable session learning into CWD without carrying its transient run shell.