@llblab/pi-state-flow 0.22.0 → 0.23.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 +42 -56
- package/BACKLOG.md +13 -5
- package/CHANGELOG.md +10 -0
- package/README.md +4 -6
- package/dist/lib/config.js +5 -4
- package/dist/lib/extension.js +6 -8
- package/dist/lib/logging.d.ts +4 -1
- package/dist/lib/logging.js +1 -0
- package/dist/lib/telegram.d.ts +1 -1
- package/dist/lib/telegram.js +15 -10
- package/dist/package.json +3 -3
- package/dist/skills/state-flow-guide/SKILL.md +1 -1
- package/docs/README.md +1 -0
- package/docs/agent-contract-relocation.md +72 -0
- package/docs/architecture.md +20 -18
- package/docs/compatibility.md +2 -2
- package/docs/temporal-acceptance.md +2 -2
- package/docs/usage.md +11 -7
- package/lib/config.ts +5 -4
- package/lib/extension.ts +6 -8
- package/lib/logging.ts +5 -1
- package/lib/telegram.ts +15 -11
- package/package.json +3 -3
- package/skills/state-flow-guide/SKILL.md +1 -1
package/docs/README.md
CHANGED
|
@@ -7,4 +7,5 @@
|
|
|
7
7
|
- [Temporal acceptance](temporal-acceptance.md): Required temporal properties and their executable witnesses.
|
|
8
8
|
- [SDK compatibility](compatibility.md): Tested dependency stacks, public lifecycle seams, isolated validation, and host limits.
|
|
9
9
|
- [Physical fork contract](fork-contract.md): Session-stream copying, live shared memory, child ownership/origin, and tested support boundaries.
|
|
10
|
+
- [Agent contract relocation ledger](agent-contract-relocation.md): Source-bound paragraph-to-owner parity map for the compact `AGENTS.md`, with transferred clauses and validation evidence.
|
|
10
11
|
- [Session performance](performance.md): Reproducible native-Pi/stateful workloads, long-session resume measurements, two-process publication probes, and evidence limits.
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# Agent contract relocation ledger
|
|
2
|
+
|
|
3
|
+
This is the source-bound **paragraph-to-owner parity map** for the 8,141-word pre-compaction `AGENTS.md` (SHA-256 `0d328eacc96d6b67c5eb036a51adc27e1dcd24d20bb6695f2fff6d5a3c87737b`; source lines 3–58, based on commit `70baecde` plus the Passive-footprint and `barrier-block` edits). Each `L##` identifies exactly one original bullet/paragraph. Its destination is the current owner of that paragraph's reusable contract; where necessary, a compact root rule or executable witness is also named. The root remains approximately 1,300 words; its 0.23.0 default-mode rule supersedes the original Passive-default clause. This is a reviewed documentation trace, not a claim that prose links alone prove runtime correctness.
|
|
4
|
+
|
|
5
|
+
## Composition, semantics, and model access
|
|
6
|
+
|
|
7
|
+
- L03 domain ownership, entrypoint and mirrored tests → [composition](architecture.md#composition), [invariant tests](../tests/invariants.test.ts).
|
|
8
|
+
- L04 Active opt-in, former Passive default/conditional projection, Off → [configuration](usage.md#configuration), [mode behavior](usage.md#active-passive-and-configured-off).
|
|
9
|
+
- L05 three session-owned mode workflows and global default → [mode behavior](usage.md#active-passive-and-configured-off), [configuration](usage.md#configuration).
|
|
10
|
+
- L06 native trace, frozen head, run anchors and foreign context → [Pi lifecycle](architecture.md#pi-lifecycle), [context limits](performance.md#context-projection-and-trajectory-selection), [lifecycle witnesses](temporal-acceptance.md#required-properties-and-witnesses).
|
|
11
|
+
- L07 sparse planes, projection, lazy filtering and intents → [semantic state](architecture.md#semantic-state), [model tools](architecture.md#model-tools), [lazy state](lazy-state.md).
|
|
12
|
+
- L08 artifact entries and hidden provenance → [artifact routing](architecture.md#artifact-routing).
|
|
13
|
+
- L09 exact registered-path observation → [artifact routing](architecture.md#artifact-routing), [source acquisition](usage.md#memory-and-source-acquisition).
|
|
14
|
+
- L10 compilation classifier, fingerprints and Skill masking → [artifact routing](architecture.md#artifact-routing).
|
|
15
|
+
- L11 stable exact-path acquisition and fork provenance → [artifact routing](architecture.md#artifact-routing), [Git/restore provenance](architecture.md#optional-git-backup), [fork contract](fork-contract.md).
|
|
16
|
+
- L12 global config, legacy modes and limits → [configuration](usage.md#configuration), [mode compatibility](compatibility.md#mode-configuration-compatibility).
|
|
17
|
+
- L13 session runtime/config/checkpoints and continuation authority → [storage and identity](architecture.md#storage-and-identity), [session continuation](architecture.md#session-continuation), [mode restoration](compatibility.md#mode-selection-and-memory-restoration).
|
|
18
|
+
- L14 overlay, scope ownership and Skill routing → [semantic state](architecture.md#semantic-state), [artifact routing](architecture.md#artifact-routing).
|
|
19
|
+
- L17 composed historical offsets → [temporal model](architecture.md#temporal-model).
|
|
20
|
+
- L18 lazy historical reads and tool availability → [model tools](architecture.md#model-tools), [lazy navigation](usage.md#lazy-navigation-and-historical-reading).
|
|
21
|
+
- L27 patch grammar, shared-head staging and private ownership → [model tools](architecture.md#model-tools), [asynchronous transaction](architecture.md#asynchronous-storage-transaction).
|
|
22
|
+
- L28 barrier and minimal acceptance receipts → [Pi lifecycle](architecture.md#pi-lifecycle), [tool preflight evidence](performance.md#tool-preflight-parent-traversal).
|
|
23
|
+
- L29 accepted-response reconciliation and cancellation → [Pi lifecycle](architecture.md#pi-lifecycle), [session behavior](usage.md#session-behavior).
|
|
24
|
+
- L35 omission, empty-scope rejection and response equivalence → [model tools](architecture.md#model-tools), [temporal model](architecture.md#temporal-model).
|
|
25
|
+
- L37 public-boundary draft detachment → [storage and identity](architecture.md#storage-and-identity), [COW evidence](performance.md#memory-only-owned-draft-cow).
|
|
26
|
+
- L38 recursive patch/null and replay → [model tools](architecture.md#model-tools), [semantic state](architecture.md#semantic-state).
|
|
27
|
+
- L39 no project schemas or size/action ledgers → [model tools](architecture.md#model-tools), [operational boundaries](../README.md#operational-boundaries).
|
|
28
|
+
- L49 no strict boundedness claim → [operational boundaries](../README.md#operational-boundaries), [performance limits](performance.md#scope).
|
|
29
|
+
- L51 tool toggle and Passive read/write boundary → [mode behavior](usage.md#active-passive-and-configured-off), [model tools](architecture.md#model-tools).
|
|
30
|
+
|
|
31
|
+
## Canonical storage, lifecycle, and backup
|
|
32
|
+
|
|
33
|
+
- L15 anchored checkpoints/tails and retention folding → [temporal model](architecture.md#temporal-model), [storage and identity](architecture.md#storage-and-identity).
|
|
34
|
+
- L16 opaque causal identity, origins and shared drift → [temporal model](architecture.md#temporal-model), [Pi lifecycle](architecture.md#pi-lifecycle).
|
|
35
|
+
- L19 canonical layout and identity → [storage and identity](architecture.md#storage-and-identity).
|
|
36
|
+
- L20 optimistic durability, optional backup and contention → [power-loss boundary](filesystem-recovery.md#power-loss-durability), [asynchronous transaction](architecture.md#asynchronous-storage-transaction), [optional Git backup](architecture.md#optional-git-backup).
|
|
37
|
+
- L21 cohort classification and missing shared pairs → [recovery](usage.md#missing-partial-and-malformed-storage), [transaction rule](filesystem-recovery.md#transaction-rule).
|
|
38
|
+
- L22 predecessor formats and no in-place migration → [format boundary](usage.md#moving-a-store-and-the-017-format-boundary), [optional Git backup](architecture.md#optional-git-backup).
|
|
39
|
+
- L23 exact-file CAS, awaited transaction and rollback → [asynchronous transaction](architecture.md#asynchronous-storage-transaction), [storage and identity](architecture.md#storage-and-identity), [transaction rule](filesystem-recovery.md#transaction-rule).
|
|
40
|
+
- L24 initialization and exact-source fork → [Pi lifecycle](architecture.md#pi-lifecycle), [fork contract](fork-contract.md).
|
|
41
|
+
- L25 retained-boundary restore, failed-Stop read-only recovery and selection races → [Pi lifecycle](architecture.md#pi-lifecycle), [mode restoration](compatibility.md#mode-selection-and-memory-restoration).
|
|
42
|
+
- L26 independent revisions, backup capture/index/push/shutdown → [temporal model](architecture.md#temporal-model), [optional Git backup](architecture.md#optional-git-backup).
|
|
43
|
+
- L40 first active context preparation, abort and specification authority → [Pi lifecycle](architecture.md#pi-lifecycle), [pre-inference cancellation](compatibility.md#pre-inference-cancellation).
|
|
44
|
+
- L41 one existing-session bootstrap run → [session behavior](usage.md#session-behavior).
|
|
45
|
+
- L42 selected-branch retained-boundary restoration → [Pi lifecycle](architecture.md#pi-lifecycle), [fork contract](fork-contract.md).
|
|
46
|
+
- L44 Start/current-head acceptance and Active default → [asynchronous transaction](architecture.md#asynchronous-storage-transaction), [mode behavior](usage.md#active-passive-and-configured-off).
|
|
47
|
+
- L45 Passive/Off persistence and frozen Stop handoff → [Pi lifecycle](architecture.md#pi-lifecycle), [mode operations](usage.md#lifecycle-operations), [mode restoration](compatibility.md#mode-selection-and-memory-restoration).
|
|
48
|
+
- L46 failed-Stop marker and fence → [storage recovery](usage.md#storage-and-recovery), [Pi lifecycle](architecture.md#pi-lifecycle).
|
|
49
|
+
- L47 settled native compaction boundary → [session behavior](usage.md#session-behavior), [SDK settlement](compatibility.md#settlement-cancellation), [lifecycle witnesses](temporal-acceptance.md#required-properties-and-witnesses).
|
|
50
|
+
|
|
51
|
+
## Operator, agent, and development policy
|
|
52
|
+
|
|
53
|
+
- L30 terminal handoff plane routing → [operational guidance](architecture.md#operational-guidance-and-memory-curation), [semantic state](architecture.md#semantic-state).
|
|
54
|
+
- L31 consequential evidence, semantic references and dangling hints → [model tools](architecture.md#model-tools), [lazy navigation](usage.md#lazy-navigation-and-historical-reading), [memory curation](architecture.md#operational-guidance-and-memory-curation).
|
|
55
|
+
- L32 volatile observation and external-effects revalidation → [operational boundaries](../README.md#operational-boundaries), [memory guidance](usage.md#memory-and-source-acquisition).
|
|
56
|
+
- L33 registered Skill acquisition → [artifact routing](architecture.md#artifact-routing).
|
|
57
|
+
- L34 bounded curation and verified transfers → [operational guidance](architecture.md#operational-guidance-and-memory-curation), [memory Skill](../skills/state-flow-memory/SKILL.md).
|
|
58
|
+
- L36 logging categories, privacy and error elision → [diagnostic privacy](usage.md#diagnostic-logging-and-privacy), [barrier contract](architecture.md#pi-lifecycle).
|
|
59
|
+
- L43 terminal status and read-only scope inspection → [status and controls](usage.md#status-and-controls), [observability](architecture.md#observability).
|
|
60
|
+
- L48 system section, context refresh and foreign prompt precedence → [Pi lifecycle](architecture.md#pi-lifecycle), [host context compatibility](compatibility.md#context-tools-and-provider-input).
|
|
61
|
+
- L50 extension-agnostic core and Telegram controls/receipts → [composition](architecture.md#composition), [observability](architecture.md#observability), [Telegram compatibility](compatibility.md#telegram-adapter).
|
|
62
|
+
- L52 tag release authority and version alignment → [release workflow](../.github/workflows/release.yml), [release boundary](../BACKLOG.md#release-boundary). Retain the durable no-token constraint in compact `AGENTS.md` until a permanent developer contract owns it.
|
|
63
|
+
- L53 opt-in benchmark location and source identity → [benchmark guide](../benchmarks/README.md), [performance validation](performance.md#validation-and-reporting).
|
|
64
|
+
- L54 provider callback completion witness → [temporal acceptance](temporal-acceptance.md#required-properties-and-witnesses), [integration tests](../tests/integration.test.ts).
|
|
65
|
+
- L55 awaited fixture handlers and withdrawal witness → [temporal acceptance](temporal-acceptance.md#required-properties-and-witnesses), [extension tests](../tests/extension.test.ts).
|
|
66
|
+
- L56 tracked `dist/` and build/package parity → [release workflow](../.github/workflows/release.yml), [release invariant tests](../tests/invariants.test.ts). Retain the developer rule in compact `AGENTS.md` unless a durable release guide takes ownership.
|
|
67
|
+
- L57 current docs vs delivery history → [documentation index](README.md), compact `AGENTS.md` (durable documentation policy).
|
|
68
|
+
- L58 validation order → compact `AGENTS.md` (durable development rule), [validation procedure](compatibility.md#validation-procedure).
|
|
69
|
+
|
|
70
|
+
## Verification evidence
|
|
71
|
+
|
|
72
|
+
The map names all 56 source paragraphs exactly once. Each was compared with its destinations; the highest-risk clause groups were checked explicitly: L06/L45 native run anchors and Stop context, L23–L26 CAS/backup/rollback, L28 receipt-elision bounds, L31 reference/epistemic limits, L36 diagnostic privacy, L47 native compaction and L50 callback revocation. An additional exact-code-token audit exposed otherwise easy-to-lose clauses: legacy `{disabled:true}`, in-memory header key derivation, materialization equality, `contract.compiled_skills` rejection, Skill compiler revision, runtime-origin null exception and normalized artifact replay. Those are now stated in architecture; terse `patches[n]` and `{value:null, hint:[...]}` from the source are represented there by the more precise scoped patch path and expanded dangling-reference sentinel. The remaining uniquely durable developer rules, including no live-store fixture edits, stay in the compact root. `tests/invariants.test.ts` is unchanged; native and domain-specific witnesses remain in their named test files. Package, context and domain-DAG validation establish the final checked boundary; they cannot substitute for semantic judgment about future models.
|
package/docs/architecture.md
CHANGED
|
@@ -36,7 +36,7 @@ Runtime views select these documented semantic planes when present; stored scope
|
|
|
36
36
|
}
|
|
37
37
|
```
|
|
38
38
|
|
|
39
|
-
- `intents` retains only chosen active commitments.
|
|
39
|
+
- `intents` retains only chosen active commitments, not a planner, scheduler, task manager or execution loop.
|
|
40
40
|
- `contract` retains durable requirements, decisions, interfaces and rejected approaches.
|
|
41
41
|
- `working` retains verified current facts, unresolved work and exact continuation.
|
|
42
42
|
- `artifacts` maps exact source paths to compiled routing metadata.
|
|
@@ -51,13 +51,13 @@ global → CWD → session
|
|
|
51
51
|
|
|
52
52
|
Later scopes win. A scope-local `null` deletion removes only that scope's key and may reveal an inherited value. Scope represents applicability and ownership, never instruction authority.
|
|
53
53
|
|
|
54
|
-
Missing planes are valid sparse semantics, not incomplete storage. Checkpoint/tail codecs select only known top-level fields on read and write; unknown fields are not retained in runtime streams or carried into later writes. Nested data within known planes remains intact. Retained record identities and positions survive even when filtering leaves an empty patch. `readTemporalView` selects present known fields at the requested boundary, then overlays scopes without inventing fields. Empty and absent responses have the same projection meaning. `readTemporalState` and the embedding callback retain default-bearing compatibility views for internal registry consumers; those defaults never become stored overrides or model context. Passive reads and Start do not fill checkpoint fields or create revisions for normalization; missing shared pairs initialize as empty objects. Authored staging uses raw scope presence and derives replay from actual writes. Existing empty/no-op tail records retain their proven boundaries; new no-op writes still create none. Present documented fields retain usable object/string types, valid artifact entries and the no-stored-null rule; ignored fields may contain arbitrary JSON. Malformed JSON and invalid storage/history authority remain errors.
|
|
54
|
+
Missing planes are valid sparse semantics, not incomplete storage. Checkpoint/tail codecs select only known top-level fields on read and write; unknown fields are not retained in runtime streams or carried into later writes. Nested data within known planes remains intact. Retained record identities and positions survive even when filtering leaves an empty patch. `readTemporalView` selects present known fields at the requested boundary, then overlays scopes without inventing fields. Empty and absent responses have the same projection meaning; clearing a nonempty response projects as deletion. Explicit reads of absent documented top-level fields return `null`. `readTemporalState` and the embedding callback retain default-bearing compatibility views for internal registry consumers; those defaults never become stored overrides or model context. Passive reads and Start do not fill checkpoint fields or create revisions for normalization; missing shared pairs initialize as empty objects. Authored staging uses raw scope presence and derives runtime-normalized replay from actual accepted writes, including complete artifact replacement; replay must reproduce accepted state exactly. Existing empty/no-op tail records retain their proven boundaries; new no-op writes still create none. Present documented fields retain usable object/string types, valid artifact entries and the no-stored-null rule; ignored fields may contain arbitrary JSON. Malformed JSON and invalid storage/history authority remain errors.
|
|
55
55
|
|
|
56
56
|
State Flow is the memory owner while enabled. Cross-project/user/environment knowledge belongs in global state, project-only knowledge in CWD, and branch/run continuation in session. Global availability is not a feature switch and does not authorize secrets, raw history, transient progress, speculative clutter, or unsupported assertions. Explicitly uncertain hypotheses remain eligible only when they can affect an open decision.
|
|
57
57
|
|
|
58
58
|
## Temporal model
|
|
59
59
|
|
|
60
|
-
All scopes participate in one active causal lineage. One accepted semantic transition receives one opaque identity shared by every changed scope. Sparse transitions do not create records for unchanged scopes.
|
|
60
|
+
All scopes participate in one active causal lineage. One accepted semantic transition receives one opaque identity shared by every changed scope. A branch-local position may order identities but never substitutes for a global counter or merges forks; origin adoption is not an invented semantic transition or retry loop. Sparse transitions do not create records for unchanged scopes.
|
|
61
61
|
|
|
62
62
|
Each scope stores:
|
|
63
63
|
|
|
@@ -65,11 +65,11 @@ Each scope stores:
|
|
|
65
65
|
checkpoint.json + patches.jsonl
|
|
66
66
|
```
|
|
67
67
|
|
|
68
|
-
The checkpoint is an older anchored materialization.
|
|
68
|
+
The checkpoint is an older anchored materialization. Current scope state is exactly `materialize(checkpoint.json, patches.jsonl, meta.json)` at the selected anchored boundary; the tail contains at most the configured `historyLimit` effective patches. On overflow, the oldest tail patch folds into the checkpoint before the new patch is appended; unapplied replay records are never truncated or replayed over an already-current snapshot.
|
|
69
69
|
|
|
70
70
|
Persisted streams and lineage are validated against the format maximum before applying a newly configured lower limit. Restore/reload/fork accepts only boundaries inside the configured window, then folds excess scope tails during canonical origin acceptance. That representation-only folding preserves selected private state and current shared values/provenance; a fork never rewrites parent-private files. Zero keeps only current checkpoints, and a later increase does not reconstruct discarded records or lineage.
|
|
71
71
|
|
|
72
|
-
`effective[n]`, `global[n]`, `cwd[n]`, and `session[n]` resolve the same nth previous causal boundary; the history index remains a composed-lineage offset, not a scope revision. Separately, each materially changed owner advances its persisted semantic revision once. Global and CWD counters remain shared across their canonical writers, Session remains private, and Effective is identified by the current `g#c#s#` revision vector. The retired top-level `state` segment is rejected; pre-origin history is unavailable rather than empty.
|
|
72
|
+
`effective[n]`, `global[n]`, `cwd[n]`, and `session[n]` resolve the same nth previous causal boundary; the history index remains a composed-lineage offset, not a scope revision. Separately, each materially changed owner advances its persisted semantic revision once. Global and CWD counters remain shared across their canonical writers, Session remains private, and Effective is identified by the current `g#c#s#` revision vector. The retired top-level `state` segment is rejected; pre-origin history is unavailable rather than empty. Once enough accepted transitions are proven, offsets zero through the configured `historyLimit` remain addressable at their shared causal boundaries.
|
|
73
73
|
|
|
74
74
|
A changed accepted response is runtime-owned, session-only semantic state and advances history. An accepted empty answer finalizes normally; it clears a previous nonempty response, but does not create a transition merely to replace an absent response with `""`. Ordinary completion requires no `patch_state` call when durable semantic state is already correct.
|
|
75
75
|
|
|
@@ -83,6 +83,8 @@ Unreported state changes, changing artifact hints, invalidation lists and rehydr
|
|
|
83
83
|
|
|
84
84
|
Tool preflight follows Pi's public `getLeafEntry()` / `getEntry(parentId)` links to the nearest assistant containing the current call ID. It inspects that response's complete tool batch without constructing the whole branch or caching a batch across calls/selections. Foreign custom entries and earlier sibling results remain in the native trace. A missing call ID still searches the selected ancestry and preserves the existing unmatched-call behavior; this is not an unconditional constant-time guarantee. See [measured traversal evidence](performance.md#tool-preflight-parent-traversal).
|
|
85
85
|
|
|
86
|
+
Opt-in local JSONL diagnostic categories are `invalid-patch`, `publication-conflict`, `finalization` and `barrier-block`. Active preflight records each blocked call when a batch has multiple `patch_state` calls or a sibling of its single `patch_state` call. A `barrier-block` record has the blocked tool name, call id, existing block reason and ordered batch tool names only: it does not capture sibling arguments, reasoning or draft content. Logging off creates no barrier record; Passive has no barrier. Diagnostic persistence is outside canonical state and cannot change the blocking decision. Asynchronous Git push failure detail is the separate logging-off exception; see [diagnostic privacy](usage.md#diagnostic-logging-and-privacy).
|
|
87
|
+
|
|
86
88
|
`read_state` reads one cached effective or scoped projection at current index zero or a retained causal index through the configured `historyLimit`. It never publishes or advances history.
|
|
87
89
|
|
|
88
90
|
Before answering, the model uses `patch_state` only when future-relevant durable state must change. The exact accepted ordinary answer is reconciled directly into runtime-owned `response` at `turn_end`, including `""` when the accepted answer is empty; no terminal eligibility latch, finalization patch, repair inference, or fallback budget exists. If required ordinary-artifact compilation prevents reconciliation, State Flow reports the failure without generating another inference. Optional Skill acquisition never blocks unrelated reconciliation. State Flow does not parse `state_flow` or generic HTML comments; historical comments are ordinary text and other extensions retain their own comment handling.
|
|
@@ -138,13 +140,13 @@ meta.json
|
|
|
138
140
|
<cwd-key>/<session-key>/runtime.json
|
|
139
141
|
```
|
|
140
142
|
|
|
141
|
-
CWD and session keys mirror Pi's native encoding. The Pi UUID remains authoritative; readable directory keys never replace identity validation.
|
|
143
|
+
CWD and session keys mirror Pi's native encoding, deriving the in-memory session key from `<header timestamp>_<UUID>` when no JSONL basename exists. The Pi UUID remains authoritative; readable directory keys never replace identity validation. Reject unsafe segments, mismatches and CWD-key ownership collisions rather than selecting a different scope.
|
|
142
144
|
|
|
143
|
-
Root `config.json` is read-only operator configuration whose `mode` supplies the new-session default (
|
|
145
|
+
Root `config.json` is read-only operator configuration whose `mode` supplies the new-session default (Off when absent and no legacy mode flags are present); it never participates in semantic overlay or State Flow-owned staging. Include operator configuration in operator-managed copies/versioning. `checkpoint.json` is only the canonical materialized semantic state, and each nonblank `patches.jsonl` line is only one semantic patch. Every scope's `meta.json` symmetrically owns its independent semantic revision, checkpoint/tail boundaries and artifact provenance, with CWD ownership added where applicable. Session `config.json` serializes only its concrete `mode` (`active`, `passive`, `off`), independently of later global defaults; session `runtime.json` asymmetrically owns lineage, the internal branch step, session identity, and the full specification only while a run is unfinished. Runtime metadata stores no storage receipt, Git identity, temporal revision pointer, publication mode or push intent. Predecessor combined session metadata is unsupported; session `meta.json`, `config.json`, and `runtime.json` must already satisfy their canonical ownership contracts. Metadata writers replace only their owned leaves and preserve JSON-safe unknown siblings. A pre-revision 0.17 scope initializes its counter from the still-retained semantic tail and persists that baseline on its next owned write; folded ancestry is not guessed. Revision-aware writes emit scope metadata version 2 while continuing to read version 1. The version fence makes an older writer refuse a scope after its first revision-aware write instead of silently dropping the counter; all cooperating instances should still upgrade together. Pi checkpoints retain only a semantic boundary plus lifecycle fields, or a proven inactive pre-runtime `{mode}` marker. Supported legacy flags and native `{disabled:true}` markers decode read-only; mixed session `mode`/`enabled` representations are rejected, and no eager migration runs. Revision-pointer checkpoints are unsupported and fail closed without Git restoration.
|
|
144
146
|
|
|
145
147
|
In-memory patching detaches one basis at its public boundary, then privately path-copies changed object/array containers while sharing untouched nodes only inside that owned draft. Incoming replacement values remain detached; staging no longer makes redundant cohort/per-scope pre-clones. Mutable staged responses and artifact registries stay isolated from accepted scopes, and commit/public temporal reads retain their detachment boundaries. This is not cross-version mutable sharing or a new disk generation format; see [copy-work evidence](performance.md#memory-only-owned-draft-cow).
|
|
146
148
|
|
|
147
|
-
All owned writes use same-directory atomic replacement, regular-file and symlink checks, prepared byte receipts and CAS validation. Unrelated files and detected concurrent bytes are preserved. Rollback restores only bytes still matching the failed publisher's output.
|
|
149
|
+
All owned writes use same-directory atomic replacement, regular-file and symlink checks, prepared opaque source-byte receipts and CAS validation. Unrelated files and detected concurrent bytes are preserved. Rollback restores only bytes still matching the failed publisher's output. Use validated structural JSON equality for in-process semantic comparisons; cryptographic hashes are for compact identities crossing process or persistence boundaries.
|
|
148
150
|
|
|
149
151
|
### Asynchronous storage transaction
|
|
150
152
|
|
|
@@ -200,7 +202,7 @@ Predecessor checkpoint envelopes, combined session metadata, `state.json`, hashe
|
|
|
200
202
|
|
|
201
203
|
State Flow never discovers source directories. Before enabled inference it inspects only exact source paths already registered as artifacts in global, CWD, or session state. Observation uses regular non-symlink file metadata `{size, mtimeNs}` without reading bodies. Proven absence removes the artifact from each owning scope; unavailable, relative, directory, or symlink evidence is non-destructive. Unregistered files are never observed.
|
|
202
204
|
|
|
203
|
-
A model-visible artifact entry requires only a description:
|
|
205
|
+
A model-visible artifact entry requires only a non-empty description:
|
|
204
206
|
|
|
205
207
|
```json
|
|
206
208
|
{
|
|
@@ -209,21 +211,21 @@ A model-visible artifact entry requires only a description:
|
|
|
209
211
|
}
|
|
210
212
|
```
|
|
211
213
|
|
|
212
|
-
Runtime-owned compilation evidence is retained per scope in `meta.json`; current ordinary artifacts use `sourceFingerprint: {size, mtimeNs}` plus `compilerRevision`, while retained `sourceHash`/`compiledAt` are transitional compatibility evidence. At artifact-entry level, every model scope patch rejects authored `hash`, `compiler`, `compiled_at`, `sourceHash`, `sourceFingerprint`, `compilerRevision`, `compiledAt`, `source_hash_verified`, and `hint` fields, including field-deletion markers, even without a preceding read. Retained legacy evidence stays readable; ordinary semantic edits and whole-artifact deletion remain valid. Compiler output may add other finite non-null JSON metadata; known optional semantic fields include `kind`, `tags` and `compilation`. Tags are unique trimmed non-empty strings and support deterministic candidate filtering, but never authorize reading.
|
|
214
|
+
Runtime-owned compilation evidence is retained per scope in `meta.json`; current ordinary artifacts use `sourceFingerprint: {size, mtimeNs}` plus `compilerRevision`, while retained `sourceHash`/`compiledAt` are transitional compatibility evidence. At artifact-entry level, every model scope patch rejects authored `hash`, `compiler`, `compiled_at`, `sourceHash`, `sourceFingerprint`, `compilerRevision`, `compiledAt`, `source_hash_verified`, and `hint` fields, including field-deletion markers, even without a preceding read. Retained legacy evidence stays readable but its embedded `hash`/`compiler`/`compiled_at` fields are omitted from model projection; ordinary semantic edits and whole-artifact deletion remain valid. Compiler output may add other finite non-null JSON metadata; known optional semantic fields include `kind`, `tags` and `compilation`. Tags are unique trimmed non-empty strings and support deterministic candidate filtering, but never authorize reading.
|
|
213
215
|
|
|
214
|
-
The public `classifyArtifactCompilationNeed` owns acquisition/rehydration and ordinary-artifact Pi decisions. An observed fingerprint needs matching valid retained fingerprint evidence; missing/malformed fingerprints, malformed compiler evidence, or a changed compiler request compilation without removing semantics. Changed size or signed nanosecond mtime (including pre-epoch dates) preserves the value and adds a runtime-only model `hint`. Fingerprint-only decisions ignore unused legacy hashes; explicit current-hash observations and the separate Skill hash protocol remain checked. Rehydration read plans carry detached fingerprints and optional hashes, never invented identities.
|
|
216
|
+
The retired `contract.compiled_skills` location is rejected; Skill compilations belong only in source-addressed artifacts, with no fabricated source hashes. The public `classifyArtifactCompilationNeed` owns acquisition/rehydration and ordinary-artifact Pi decisions. An observed fingerprint needs matching valid retained fingerprint evidence; missing/malformed fingerprints, malformed compiler evidence, or a changed compiler request compilation without removing semantics. Changed size or signed nanosecond mtime (including pre-epoch dates) preserves the value and adds a runtime-only model `hint`. Fingerprint-only decisions ignore unused legacy hashes; explicit current-hash observations and the separate Skill hash protocol remain checked. Rehydration read plans carry detached fingerprints and optional hashes, never invented identities.
|
|
215
217
|
|
|
216
218
|
Invalidation notices identify the selected `global`, `cwd`, or `session` owner. Guidance and missing-output errors direct compilation to that exact scope/path, without relocating the entry or creating a global copy. Successful exact reads require stable fingerprints before/after acquisition and at publication, then publish compiler output and provenance to that owner under scope causal-basis CAS. Generic maintenance computes no content hash. Effective Skill entries mask lower ordinary entries and retain their separate hash protocol.
|
|
217
219
|
|
|
218
220
|
Compilation is routing, not a substitute for source text. Full source is read only for a concrete unresolved gap, exact source/edit operation, fingerprint invalidation, contradiction/failure, or explicit request. The rehydration planner supports new-bootstrap, resume-bootstrap and later-step phases without hidden directory traversal.
|
|
219
221
|
|
|
220
|
-
Skill acquisition applies only to exact registered Pi Skills. State Flow resolves identity and ownership through the public
|
|
222
|
+
Skill acquisition applies only to exact registered Pi Skills. State Flow resolves identity and ownership through the public `getCommands()` inventory's `sourceInfo.scope`, rather than file-path conventions: Pi `user`, `project` and `temporary` source scopes map to State Flow `global`, `cwd` and `session`. A successful read with matching current source hash needs no new compilation. Otherwise the tool result names the exact optional target. Attempted durable output at the reported scope and path requires a non-empty description, `kind: "skill"` and a non-empty compilation describing applicability, constraints and failure conditions; an omitted output leaves the read volatile and does not block unrelated patches or ordinary completion. The accepted compilation replaces the complete prior Skill card and provenance, storing runtime-owned `sourceHash` and `skill-artifact-v1` `compilerRevision`; obsolete evidence cannot survive refresh. Source bodies do not persist in state. Matching provenance proves source-version consistency, not semantic fidelity, truth, or higher instruction authority.
|
|
221
223
|
|
|
222
224
|
## Operational guidance and memory curation
|
|
223
225
|
|
|
224
226
|
The packaged Skills deliberately separate two responsibilities. `state-flow-guide` is the on-demand operational reference for concrete read, patch, inheritance, acquisition, completion, and recovery questions; it does not initiate memory audits or unsolicited cleanup. `state-flow-memory` performs one explicitly requested bounded curation over stale knowledge, commitments, continuation, ownership, and external handoffs; phase completion does not activate an audit.
|
|
225
227
|
|
|
226
|
-
Curation may persist reusable guidance from a registered Skill at its provenance-derived scope. Within one store, a proven scope move inspects both owners, resolves conflicts, and commits destination/source changes through one atomic multi-scope patch, followed by ownership/overlay verification. Existing Skill artifacts written under the former CWD-only policy are not silently promoted: a later registered read identifies the current owner, while explicit curation may move proven reusable content and remove the old owner atomically.
|
|
228
|
+
Curation may persist reusable guidance from a registered Skill at its provenance-derived scope. Treat terminal state as a decision-relevant handoff rather than a progress transcript: retain operational knowledge in source-addressed artifacts, confirmed constraints/decisions and rejected approaches in contract, observations/failures/uncertainties and exact continuation in working, and only chosen active commitments in intents. Distinguish user requirements from assistant conclusions and hypotheses; preserve consequential negative evidence and reconsideration conditions. Do not silently overwrite established constraints when evidence conflicts, treat working observations as live external facts, or infer success/absence of external effects from restored memory. After interruption, inspect the relevant effects before repetition. These are model stewardship duties, not deterministic semantic gates. Within one store, a proven scope move inspects both owners, resolves conflicts, and commits destination/source changes through one atomic multi-scope patch, followed by ownership/overlay verification. Existing Skill artifacts written under the former CWD-only policy are not silently promoted: a later registered read identifies the current owner, while explicit curation may move proven reusable content and remove the old owner atomically.
|
|
227
229
|
|
|
228
230
|
External transfers use the destination's native interface and receipts; accepted-copy verification precedes source deletion in a later State Flow patch. State Flow defines no promotion registry, status schema, record type, or dedicated promotion tool; destination uncertainty simply leaves the source intact.
|
|
229
231
|
|
|
@@ -250,7 +252,7 @@ The [tested Pi SDK baseline](compatibility.md) chooses or creates `SessionManage
|
|
|
250
252
|
|
|
251
253
|
### Model tools
|
|
252
254
|
|
|
253
|
-
`patch_state` accepts one or more fixed `global`, `cwd`, and `session` semantic patches. Supplied scopes contain object-valued `artifacts`, `contract`, `working`, and `intents`, plus object-valued `lazy` whose nested values are ordinary JSON; omitted fields preserve their values, recursive object merge updates them, arrays/primitives replace, and nested object-key `null` deletes. Materialized null, empty supplied scopes, unknown top-level fields, model-authored `response`, and retired finalization or patch grammars are rejected. Correct repeated results succeed as `State already current.` without another semantic revision or history record; avoid gratuitous acknowledgment patches. Global/CWD overlap follows successful acceptance order, while unmentioned current fields survive. Session ownership is not a shared-memory merge.
|
|
255
|
+
`patch_state` accepts one or more fixed `global`, `cwd`, and `session` semantic patches. Supplied scopes contain object-valued `artifacts`, `contract`, `working`, and `intents`, plus object-valued `lazy` whose nested values are ordinary JSON; omitted fields preserve their values, recursive object merge updates them, arrays/primitives replace, and nested object-key `null` deletes. Materialized null within documented semantic planes, empty supplied scopes, unknown top-level fields, model-authored `response`, and retired finalization or `{scope, patch}` / `unchanged` grammars are rejected. The semantic null rule does not apply to runtime envelopes such as an origin's null parent. Correct repeated results succeed as `State already current.` without another semantic revision or history record; avoid gratuitous acknowledgment patches. Global/CWD overlap follows successful acceptance order, while unmentioned current fields survive. Session ownership is not a shared-memory merge.
|
|
254
256
|
|
|
255
257
|
```json
|
|
256
258
|
{"session":{"intents":{"next":"Verify the corrected behavior"}}}
|
|
@@ -270,7 +272,7 @@ The [tested Pi SDK baseline](compatibility.md) chooses or creates `SessionManage
|
|
|
270
272
|
|
|
271
273
|
Unscoped semantic paths such as `intents.next` alias the current effective overlay. `value`, `keys`, and `patch` projections plus ordered `paths` batches remain all-or-error.
|
|
272
274
|
|
|
273
|
-
Both tools are exposed in Active/Passive and withdrawn in Off, subject to 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. Ordinary handoffs reconcile touched state. Dedicated cleanup and scope review require an explicit user request, including at feature/release/project boundaries. Global retains established cross-project/user/environment knowledge, CWD owns reusable project truth, and session owns branch/run continuation. Intra-store moves use targeted owner reads and one atomic multi-scope patch followed by verification; external moves require verified destination acceptance before source deletion.
|
|
275
|
+
Both tools are exposed in Active/Passive and withdrawn in Off, subject to host restrictions; mode toggles preserve unrelated active tools. Passive reads never initialize storage, but an explicit passive patch may initialize absent canonical storage without starting an episode. 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. Ordinary handoffs reconcile touched state. Dedicated cleanup and scope review require an explicit user request, including at feature/release/project boundaries. Global retains established cross-project/user/environment knowledge, CWD owns reusable project truth, and session owns branch/run continuation. Intra-store moves use targeted owner reads and one atomic multi-scope patch followed by verification; external moves require verified destination acceptance before source deletion.
|
|
274
276
|
|
|
275
277
|
### Embedding
|
|
276
278
|
|
|
@@ -284,12 +286,12 @@ Agent configuration is read once per extension load; session runtime configurati
|
|
|
284
286
|
|
|
285
287
|
## Observability
|
|
286
288
|
|
|
287
|
-
The inspection-capable Telegram port accepts synchronous or Promise-returning `select(mode)` results with optional revocation signals, while the legacy `StateFlowTelegramPort` stays synchronous. Controls initiate callback acknowledgement alongside execution rather than waiting for a network round trip before local Stop. Final feedback follows completion, uses the current menu and escapes late failures without answering the callback twice. Revoked receipts, newer callback navigation and disposal suppress stale view writes; they never roll back canonical acceptance.
|
|
289
|
+
The inspection-capable Telegram port accepts synchronous or Promise-returning `select(mode)` results with optional revocation signals, while the legacy `StateFlowTelegramPort` stays synchronous. Controls initiate callback acknowledgement alongside execution rather than waiting for a network round trip before local Stop. Final feedback follows completion, uses the current menu and escapes late failures without answering the callback twice. Revoked receipts, newer callback navigation and disposal suppress stale view writes; they never roll back canonical acceptance. Obsolete start/stop callback keyboards may refresh the current view but never silently select a mode.
|
|
288
290
|
|
|
289
|
-
Status is a projection of the selected runtime and semantic view, not a second store. Compact terminal status uses accent `state-flow` with dim `active` or `passive`, and is hidden in Off. Telegram main-menu status uses `State Flow: active`, `State Flow: passive` or `State Flow: off`. `/state-flow-status` retains the `g#c#s#` vector beside concise diagnostics and blank-line-separated top-level semantic JSON. Mode is read directly from the session's selected enum, never derived from a pending patch or separate passive flags. Requested Global, CWD and Session Rich snapshots show their independent `#revision`, while Effective shows the vector. Global/CWD Rich views omit the empty structural response placeholder; Session and Effective expose the Session-owned response. Missing evidence stays unavailable instead of appearing empty. The optional Telegram leaf adapter presents the current mode as a monospace value in the submenu heading and
|
|
291
|
+
Status is a projection of the selected runtime and semantic view, not a second store. Compact terminal status uses accent `state-flow` with dim `active` or `passive`, and is hidden in Off. Telegram main-menu status uses `State Flow: active`, `State Flow: passive` or `State Flow: off`. `/state-flow-status` retains the `g#c#s#` vector beside concise diagnostics and blank-line-separated top-level semantic JSON. Mode is read directly from the session's selected enum, never derived from a pending patch or separate passive flags. Requested Global, CWD and Session Rich snapshots show their independent `#revision`, while Effective shows the vector. Global/CWD Rich views omit the empty structural response placeholder; Session and Effective expose the Session-owned response. Missing evidence stays unavailable instead of appearing empty. The optional Telegram leaf adapter presents the current mode as a monospace value in the submenu heading, followed by matching Mode and Inspect memory headings (long-dash-separated description ending in a colon), each separated by a blank line from its settings-style monospaced-key list, above one radio row `Off | Passive | Active`: selected Off uses 🟡, Passive 🟣 or Active 🟢, and inactive choices use ⚫️; four direct scope-inspection buttons follow, while inspection remains available in all three modes. Inspection may refresh live Global/CWD streams in memory so foreign accepted revisions become visible, but never publishes or increments a revision. If model-facing passive access is disabled and no runtime is selected, inspection may lazily load existing canonical shared state under the same read-only rule. The awaited `StateFlowTelegramInspectionPort` returns a `StateFlowTelegramInspection` containing state and matching revisions, plus an optional revocation signal checked immediately before presentation. Stop, selection changes and shutdown cancel obsolete reads without altering newer memory or clearing write fences. The existing synchronous `StateFlowTelegramPort` contract remains supported. A callback is acknowledged before waiting; late failures appear escaped in the existing menu, without a second answer to an expired query. Registration is fail-open and disposal belongs to session shutdown. Local diagnostics stay outside semantic state and cannot change accepted state. Operator-facing fields and privacy boundaries are in [usage](usage.md#status-and-controls).
|
|
290
292
|
|
|
291
293
|
## Validation boundaries
|
|
292
294
|
|
|
293
295
|
Structural validation proves JSON shape, exact identity, causal lineage, compilation evidence, CAS and publication invariants. A valid state, receipt, source hash, or compiler revision cannot prove semantic importance, truth, sufficient compilation, correct scope, useful curation, or historical deletion. Those remain model-judgment concerns evaluated separately from deterministic transport checks.
|
|
294
296
|
|
|
295
|
-
The deterministic continuity and temporal evidence map is in [temporal-acceptance.md](temporal-acceptance.md). Release-scoped open work is in [BACKLOG.md](../BACKLOG.md), and shipped outcomes belong in [CHANGELOG.md](../CHANGELOG.md).
|
|
297
|
+
The deterministic continuity and temporal evidence map is in [temporal-acceptance.md](temporal-acceptance.md). Release-scoped open work is in [BACKLOG.md](../BACKLOG.md), and shipped outcomes belong in [CHANGELOG.md](../CHANGELOG.md). The exact-tag [release workflow](../.github/workflows/release.yml) owns npm Trusted Publisher publication with provenance and creates a GitHub Release only after public-package verification. Keep `dist/` tracked and rebuild it from final sources and package metadata; Git tracking, source/build parity and npm `files` inventory are separate proofs. Never substitute a long-lived npm token. Native scripted-provider tests need a completion assertion outside the callback because Pi can turn an in-provider assertion failure into an assistant error. Await startup/tree fixture handlers, and in contention tests prove withdrawal while exclusion remains held before releasing storage and joining replacement selection.
|
package/docs/compatibility.md
CHANGED
|
@@ -42,9 +42,9 @@ Operation signals are not universal. Idle commands and session events can lack t
|
|
|
42
42
|
|
|
43
43
|
## Mode configuration compatibility
|
|
44
44
|
|
|
45
|
-
Global `config.json` accepts `mode: "active" | "passive" | "off"`, defaulting to
|
|
45
|
+
Global `config.json` accepts `mode: "active" | "passive" | "off"`, defaulting to Off when no mode policy is configured, solely as the initial policy for new sessions. Session `config.json` uses the same key for the concrete retained choice; commands and Telegram never edit the global default. Before semantic initialization, an inactive choice is retained in a native `{mode}` checkpoint instead.
|
|
46
46
|
|
|
47
|
-
Legacy decoding is read-only. Without explicit global mode, `autoStart: true` means Active
|
|
47
|
+
Legacy decoding is read-only. Without explicit global mode, the absence of all legacy mode flags means Off; `autoStart: true` means Active, while any present legacy mode flag retains its former mapping: `passiveBootstrap: false` together with `passiveTools: false` means Off, and otherwise the fallback is Passive. An operator who previously relied on an absent configuration for implicit Passive must now select Passive in that session or set global `mode: "passive"` for new sessions. Explicit global mode overrides valid legacy flags; invalid values still fail validation. Session `enabled:true` remains Active, and `enabled:false` is non-active. Native legacy inactive checkpoints use the configured inactive fallback, never an Active default. Session config and native checkpoints reject mixed `mode`/`enabled` representations, even when apparently consistent, rather than choosing between two stored policies. Ordinary writers emit only mode; no eager migration or semantic normalization runs.
|
|
48
48
|
|
|
49
49
|
The extension SDK uses an optional `mode` default override, and both Telegram port variants use `snapshot.mode` plus `select(mode)`. Old callback keyboards may refresh the view without selecting a mode. Synchronous enum-based ports remain supported; this does not promise the removed Start/Stop port signatures.
|
|
50
50
|
|
|
@@ -23,7 +23,7 @@ This is a maintained property-to-test map for the current canonical-file contrac
|
|
|
23
23
|
17. **Historical restoration is distinct from activation:** `tests/recovery.test.ts` rejects unavailable selections without older-pointer or disabled-marker fallback. Extension/native tests fence passive publication until explicit current-memory activation, with unchanged canonical bytes in both inactive modes. Native “real Pi activates current … memory after expired tree selection and reload” cases cover passive, active and interrupted work plus the next provider's private-memory input. Runtime current-head tests preserve semantics, provenance, revisions, step and available history across old modes, distinguish absent from incomplete private authority, adopt validated foreign shared streams without private leakage or invented history, and reject a concurrent private writer. Native pre-runtime and inherited-fork-selection witnesses preserve current owned session memory instead of resetting it or recopying a parent. Repeated active Start leaves response reconciliation intact. Ordinary conversation with only a pre-runtime mode checkpoint still bootstraps; unaccepted fork identity/CWD repair retries the exact source.
|
|
24
24
|
18. **Tree/resume select the correct lineage:** `tests/integration.test.ts` — “real Pi preserves branch-local state through compaction and rejects an expired sibling after fresh-origin navigation” and “real Pi old tree branch stop and resume preserve selected semantics without rewinding shared files”.
|
|
25
25
|
19. **Stop changes policy, not semantic history:** `tests/runtime.test.ts` lifecycle-only witnesses use a separate process to advance global/CWD semantics or provenance, including wider foreign retention, then prove exact semantic/sidecar preservation, unchanged steps, idempotent Stop, and same-session/stale-evidence refusal. Native Stop/new-request witnesses verify the accepted shared view reaches handoff/inference without a lifecycle semantic write, while the current-head native witness accepts a shared write racing after inference and retains its actual accepted predecessor. Mid-tool Stop tests preserve ordinary/bootstrap trajectories through tree, reload, resume, and restart. The native “real Pi retains a native split-turn continuation through late tools” Stop/no-Stop controls actually remove the original user with native threshold compaction, then require summary, paired reads and foreign context in model input. The Stop case also checks frozen semantics/step, unchanged trace prefix, tree/reload/cold resume/bootstrap restart, no resurrection of discarded input, and persistent foreign context after the next active run. Pure passive-selector tests cover missing, colliding and nonfinite recorded active anchors and explicit preservation of unfinished compilation. The native “real Pi repeated Start/Stop preserves uncompiled conversation and its prior boundary” cases cover initial/restarted bootstrap, repeated idle toggles, reload, unchanged native trace, and release after accepted compilation; extension tests cover interrupted idle Stop with and without a captured anchor. Completed idle/legacy cutoffs remain bounded. The extension's failed-Stop matrix covers concurrent private writers, invalid lock ownership and malformed runtime files in both inactive modes: the selected mode remains applied, canonical bytes stay unchanged, accepted memory and native conversation survive, and only Passive projects the handoff; reload is read-only, and writes remain fenced until accepted Start. Native “real Pi failed Stop stays passive through late tools, tree, reload and resume” cases verify provider inputs, rejected tool calls, untouched trace prefixes, private memory, current foreign writes, and recovery through explicit Start. A native fork witness retains disabled policy without inheriting the parent's fence. Session tests bind fence lifetime to owner/reset/accepted-checkpoint evidence; runtime current-head tests prove read-only loading changes no canonical bytes. `tests/storage.test.ts` fences lifecycle-only writes to config/runtime files; `tests/extension.test.ts` covers idle/legacy cutoffs and new/fork boundaries.
|
|
26
|
-
20. **Compact mode, inspectable revisions:** `tests/status.test.ts` proves Active/Passive terminal indicators omit revisions, Off alone hides the indicator, and `/state-flow-status` retains the effective `g#c#s#` vector with blank lines between top-level JSON planes. `tests/telegram.test.ts` verifies mode-only section labels,
|
|
26
|
+
20. **Compact mode, inspectable revisions:** `tests/status.test.ts` proves Active/Passive terminal indicators omit revisions, Off alone hides the indicator, and `/state-flow-status` retains the effective `g#c#s#` vector with blank lines between top-level JSON planes. `tests/telegram.test.ts` verifies mode-only section labels, capitalized radio options with one mode-specific selected marker and ⚫️ inactive markers, direct scope buttons, owner Rich headings with `#revision` and Effective with `g#c#s#`. Telegram can inspect existing shared memory even in Off without initializing or mutating storage. Failure-fenced inspection retains accepted cached memory without overwriting another writer.
|
|
27
27
|
21. **Independent revisions survive folding and foreign writers:** `tests/temporal.test.ts` proves each materially changed scope advances once for sparse and multi-scope cohorts, response-only transitions advance only Session, no-ops advance none, selected retained history restores the matching revision, and folding never resets it. `tests/durable.test.ts` covers revision serialization plus the pre-revision 0.17 retained-tail baseline. `tests/runtime.test.ts` uses an independent file-backed writer to advance Global, then refreshes the first runtime without file mutation and proves `G1/C0/S1` becomes `G1/C0/S2` after one private Session patch.
|
|
28
28
|
22. **Current-head atomic model publication:** `tests/runtime.test.ts` applies authored independent/overlapping assignments, deletion and arrays to current shared values, preserves another owner's private files, and derives the predecessor/revisions from that basis. Compilation witnesses replace complete cards with matching provenance, preserve untouched evidence, accept repeats and refuse orphaned evidence after semantic-pair disappearance. Partial/malformed shared evidence and concurrent/unselected private authority stay fenced. Fault injection rolls back a mixed publication without installing the candidate's shared adoption or private draft. Extension tests reject a first passive patch without publishing empty setup, and recheck acquired-source freshness after lock waiting. Native “real Pi awaits foreign publication” cases hold an independent process beyond the former wait budget, verify responsive waiting/cancellation with unchanged canonical bytes, and require the next provider to see accepted current Global/CWD plus its own Session, never the foreign private layer.
|
|
29
29
|
23. **Awaited response acceptance owns its lifecycle:** `tests/extension.test.ts` verifies waiting against current shared memory, one accepted checkpoint without a second publication, rollback without candidate/cache or lifecycle installation, cancellation at Stop/session/tree/shutdown boundaries, shutdown fencing and superseding-answer isolation. Native “real Pi awaits response publication” witnesses wait behind an independent writer for over two seconds, then prove later boundary handlers and continuation inference see the accepted response, current Global/CWD and only their own Session. Native Abort withdraws the wait without changing canonical bytes, the prior response or unfinished specification, and without requesting a repair inference.
|
|
@@ -76,7 +76,7 @@ This is a maintained property-to-test map for the current canonical-file contrac
|
|
|
76
76
|
- Runtime/Skill guidance names the reported artifact owner. Registered-Skill unit and native witnesses use Pi's public command source metadata to map user/project/temporary Skills to global/CWD/session, ignore unregistered `SKILL.md` reads, skip matching hashes, permit unrelated patches while compilation remains optional, retain strict attempted-output validation, and publish source-hash provenance to the exact reported owner.
|
|
77
77
|
- `tests/transition.test.ts` rejects authored provenance fields and field deletions in every scope through both staging entrypoints, without requiring a preceding read; legacy semantic edits and whole-artifact deletion remain valid. The native “real Pi rejects no-read provenance forgery atomically and accepts a corrected model patch” witness proves whole-cohort rejection and recovery, while existing artifact/Skill tests preserve runtime-owned compilation evidence and legacy decoding.
|
|
78
78
|
- `tests/storage.test.ts` covers exact file-cohort references, file CAS/rollback, and shared writer exclusion. The asynchronous transaction witnesses pause an independent writer between tail and metadata renames for longer than the old wait budget: the waiting process remains responsive and captures the complete accepted receipt only after release. Local waiters, cancellation before acquisition/publication, interrupted/malformed/empty locks, root/lifetime binding, active recursive refusal, deferred work after context expiry, rollback and replaced-owner preservation are separately checked. The current-head and response witnesses above additionally prove awaited model patch/finalization integration; runtime startup/recovery and exact restoration/fork cutover, including Start's initial attachment and unaccepted-fork paths, are covered by items 35–40. Current-head Start and accepted-runtime Stop are covered above; optional settlement backup uses the selected no-signal deferral rather than an upstream release gate. `tests/runtime.test.ts` and native Pi lifecycle tests cover retained-boundary restart, immediate barriers, finalized response, config-only stop, and unavailable-reference provenance. Canonical files supply current state and bounded hot history; arbitrary cold revision recovery is unsupported.
|
|
79
|
-
- `tests/runtime.test.ts` and native integration cover retained-boundary restoration and fork after lowering `historyLimit` to 0/1: current shared values/provenance and selected private state survive folding, parent-private fork files remain unchanged, out-of-window selections fail closed, and later increases do not reconstruct discarded history. `tests/config.test.ts` covers optional agent configuration, path precedence/expansion, invalid input, load-time caching and read-only behavior. Session tests and native Pi distinguish configured new-session auto-start from branch-local resume/tree/stop. `tests/extension.test.ts` proves registered artifacts are reconciled only at enabled inference boundaries. The global default is
|
|
79
|
+
- `tests/runtime.test.ts` and native integration cover retained-boundary restoration and fork after lowering `historyLimit` to 0/1: current shared values/provenance and selected private state survive folding, parent-private fork files remain unchanged, out-of-window selections fail closed, and later increases do not reconstruct discarded history. `tests/config.test.ts` covers optional agent configuration, path precedence/expansion, invalid input, load-time caching and read-only behavior. Session tests and native Pi distinguish configured new-session auto-start from branch-local resume/tree/stop. `tests/extension.test.ts` proves registered artifacts are reconciled only at enabled inference boundaries. The global default is Off without a configured mode; CWD materialization alone never grants Active mode.
|
|
80
80
|
|
|
81
81
|
## Validation and limits
|
|
82
82
|
|
package/docs/usage.md
CHANGED
|
@@ -24,7 +24,7 @@ Active, Passive and Off select the current session's workflow and model-facing a
|
|
|
24
24
|
|
|
25
25
|
`/state-flow-active` activates the current Pi branch over validated current same-session memory, initializing absent storage when safe. No remote is required. Starting mid-conversation retains Pi's active context for one complete bootstrap run, during which the agent must compile future-relevant information into state. Repeating Active while already active leaves the in-progress run unchanged. On an attached branch, current-memory activation waits asynchronously for a coherent canonical cohort; pending repeats share the wait. Until acceptance, the existing inactive mode and any write fence remain in effect. Passive, Off or branch selection can withdraw obsolete activation; an error after acceptance does not undo accepted memory.
|
|
26
26
|
|
|
27
|
-
- **New session:** Adopts global `mode`, defaulting to
|
|
27
|
+
- **New session:** Adopts global `mode`, defaulting to Off. An inactive default is recorded once in Pi as `{mode:"off"}` or `{mode:"passive"}` without creating semantic storage. An Active default initializes a distinct empty Session layer over global/CWD memory, never another session's private continuation.
|
|
28
28
|
- **Resume:** Restores the selected session's retained mode, state and lineage. Later global default changes do not override it.
|
|
29
29
|
- **Tree navigation:** Restores the selected retained private boundary over live shared scopes without checking out or resetting the shared store.
|
|
30
30
|
- **Abort inference:** Stops generation or an outstanding response-publication wait while already accepted patches remain durable for continued work and corrected direction in the same session. Cancellation before response acceptance keeps the previous response and unfinished run; cancellation after acceptance never rolls it back. It does not require immediate remote replication.
|
|
@@ -52,7 +52,7 @@ Optional global `config.json` at the root of the State Flow repository, normally
|
|
|
52
52
|
|
|
53
53
|
```json
|
|
54
54
|
{
|
|
55
|
-
"mode": "
|
|
55
|
+
"mode": "off",
|
|
56
56
|
"logging": false,
|
|
57
57
|
"showSuccessfulPatches": true,
|
|
58
58
|
"historyLimit": 7
|
|
@@ -60,22 +60,26 @@ Optional global `config.json` at the root of the State Flow repository, normally
|
|
|
60
60
|
```
|
|
61
61
|
|
|
62
62
|
The canonical store is `state-flow/` beneath the agent directory. Keeping configuration inside that repository removes the separate agent-level `state-flow.json`; SDK embeddings may still provide an explicit repository override.
|
|
63
|
-
- `mode`: `"active"`, `"passive"` or `"off"`; defaults to `"
|
|
64
|
-
- `logging`: Defaults to `false`. When enabled, records rejected
|
|
63
|
+
- `mode`: `"active"`, `"passive"` or `"off"`; defaults to `"off"`. Supplies the default only for genuinely new sessions. Active initializes missing storage when safe; Passive reads existing memory without publishing, and its first explicit patch may initialize absent storage without starting an episode or compaction. Off exposes neither memory tools nor State Flow context.
|
|
64
|
+
- `logging`: Defaults to `false`. When enabled, records rejected patch executions, active barrier blocks, preparation failures and accepted-answer reconciliation failures locally at `tmp/state-flow/logs.jsonl` beneath the agent directory. Asynchronous Git push failures are recorded there even when this setting is off.
|
|
65
65
|
- `showSuccessfulPatches`: Defaults to `true`. In interactive Pi, successful `patch_state` rows show only the applied pretty-printed JSON arguments, with blank lines between adjacent memory sections; set it to `false` to keep only the compact summary. Rejected calls still use ordinary error rendering; State Flow adds no private validation turn.
|
|
66
66
|
- `historyLimit`: Defaults to `7` and accepts integers from `0` through `100`. It counts accepted semantic transitions, **not elapsed time or conversation length**. It bounds materialized-history and scope patch-history offsets. Lowering it on reload/restore/fork folds excess tails forward without losing current state; selected boundaries outside the new window are unavailable. Zero retains only current checkpoints. Raising the limit affects only future retention and cannot reconstruct discarded history.
|
|
67
67
|
|
|
68
68
|
Session `config.json` uses the same `mode` key for its concrete choice; commands and Telegram change that session only. Before canonical runtime acceptance, Pi's native `{mode}` checkpoint owns the choice instead of a manufactured storage pair. Edit global defaults manually or through an authorized agent, not `patch_state`. Legacy flag decoding is read-only; see [mode compatibility](compatibility.md#mode-configuration-compatibility).
|
|
69
69
|
|
|
70
|
+
**Passive model-facing footprint:** When selected, Passive declares both memory tools even with no canonical store; its system-prompt section and projected memory message appear only after a validated memory view is loaded. New sessions default to Off, which exposes none of these State Flow model-facing surfaces. With unavailable memory the tools may still reject reads or writes; declared tools do not prove usable storage.
|
|
71
|
+
|
|
72
|
+
A source-bound UTF-8 byte probe of the 0.22.0 tree (`3242d762`, isolated `tests/harness.ts` and `tests/storage-fixture.ts`, default config, empty native transcript, `before_agent_start("Probe")` then `context`) measured the two `{name,description,parameters}` tool definitions as **1,728 JSON bytes**. A wholly absent store added **0 protocol and 0 projected-message bytes**. A validated empty Global state (`{}`) added **959 protocol bytes** and **321 serialized message bytes**; `global.working={sample:"x"}` added the same **959** plus **351 message bytes**. These component sizes include the projection marker in the message but exclude native prompt/tool wrappers, conversation, provider tokenization and variable user memory; they are not token-cost or cache-hit claims.
|
|
73
|
+
|
|
70
74
|
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.
|
|
71
75
|
|
|
72
76
|
`PI_CODING_AGENT_DIR` changes both the default State Flow repository and its global configuration location. State Flow has no source-directory or Knowledge-root configuration. SDK repository overrides are documented under [embedding](architecture.md#embedding); an overridden repository owns its own root `config.json`.
|
|
73
77
|
|
|
74
78
|
### Diagnostic logging and privacy
|
|
75
79
|
|
|
76
|
-
Rejected
|
|
80
|
+
Rejected `patch_state` execution records may contain exact attempted arguments and useful draft text, plus the error category and tool/call identity. The `barrier-block` category instead records only the blocked tool name, call id, reason and batch tool names (never sibling arguments or reasoning); Passive has no patch barrier, and logging off records no barrier blocks. Asynchronous push failures retain the available redacted Git error there regardless of `logging`; interactive warnings stay short and appear once per failure streak, then reset on success. If logging the push failure is unavailable, one warning exposes the available detail instead. Successful patches are not logged; reasoning bodies are excluded. Logs are not semantic state, scope metadata, Pi checkpoints, or publication input. If the log path overlaps a custom state repository, capture fails closed instead of committing it. A logging failure changes no accepted state and produces at most one local warning.
|
|
77
81
|
|
|
78
|
-
Logs remain local unless you move them; rotation/deletion is operator-owned. State Flow-authored errors and warnings display as one compact line: long operands
|
|
82
|
+
Logs remain local unless you move them; rotation/deletion is operator-owned. State Flow-authored errors and warnings display as one compact line: flatten nested/aggregate causes into transportable text rather than relying on `Error.cause`. Elide long operands with `…` before shortening prose so the operation, exact offending scope, target basename/suffix and actionable reason remain visible; do not split Unicode pairs or mistake prose apostrophes for quoted paths. Enabled diagnostic records keep the full target and rejected input for investigation. An explicit Start retry reports its final failure once rather than repeating its startup warning. Tool failures still keep the required blank line beneath their heading. Treat logs and state files as private. Removing a secret from current state does not erase older offsets, Git history, native sessions, or remote copies.
|
|
79
83
|
|
|
80
84
|
## Status and controls
|
|
81
85
|
|
|
@@ -87,7 +91,7 @@ Logs remain local unless you move them; rotation/deletion is operator-owned. Sta
|
|
|
87
91
|
|
|
88
92
|
Status omits the already-visible mode and generic ownership/configuration prose. Failed inspection reports unavailable evidence, not invented empty state. Status is observational: it does not read source files, calculate fingerprints, create invalidations, or mutate semantic state.
|
|
89
93
|
|
|
90
|
-
The terminal indicator is accent `state-flow` plus dim `active` or `passive`; Off hides it. Global, CWD and Session own independent semantic revisions; one atomic transition advances each materially changed scope once, including session-only response reconciliation. Effective has no scalar counter and uses the compact lowercase `g#c#s#` revision vector, without slashes or spaces between counters. That vector appears in `/state-flow-status` and Telegram's Effective inspection, not the compact indicators. When `pi-telegram` is available, its main-menu section shows `State Flow: active`, `State Flow: passive` or `State Flow: off`. Off exposes neither tool nor State Flow model context. Requested owner-scope Rich snapshots show `#revision`; Effective shows the vector. During a failed-Stop write fence, inspection uses the accepted cache without a potentially conflicting refresh. Otherwise, Telegram inspection waits cancelably to load or refresh one coherent shared view, even when passive model tools are disabled. It does not initialize, publish, or advance storage. Data and displayed revisions belong to the same observation; absent/invalid memory stays unavailable. Stop, session/tree changes and shutdown cancel obsolete observations. The button acknowledges immediately, and a late failure appears in the menu instead of an expired callback popup. The submenu heading displays the current value in monospace.
|
|
94
|
+
The terminal indicator is accent `state-flow` plus dim `active` or `passive`; Off hides it. Global, CWD and Session own independent semantic revisions; one atomic transition advances each materially changed scope once, including session-only response reconciliation. Effective has no scalar counter and uses the compact lowercase `g#c#s#` revision vector (for example, `g15c8s31`), without slashes or spaces between counters. That vector appears in `/state-flow-status` and Telegram's Effective inspection, not the compact indicators. When `pi-telegram` is available, its main-menu section shows `State Flow: active`, `State Flow: passive` or `State Flow: off`. Off exposes neither tool nor State Flow model context. Requested owner-scope Rich snapshots show `#revision`; Effective shows the vector. During a failed-Stop write fence, inspection uses the accepted cache without a potentially conflicting refresh. Otherwise, Telegram inspection waits cancelably to load or refresh one coherent shared view, even when passive model tools are disabled. It does not initialize, publish, or advance storage. Data and displayed revisions belong to the same observation; absent/invalid memory stays unavailable. Stop, session/tree changes and shutdown cancel obsolete observations. The button acknowledges immediately, and a late failure appears in the menu instead of an expired callback popup. The submenu heading displays the current value in monospace. The bold Mode heading uses a long dash, description ending in a colon, and a blank line before its settings-style list. Each line uses a monospaced minus and lowercase monospaced mode value, then a plain colon and description. The descriptions progress from regular chat with no memory (Off, the new-session default), to ordinary chat with memory tools and an available combined memory view (Passive), to the same memory access with completed answers followed by memory-first continuation (Active); they do not claim a new physical Pi session or disable native compaction. The bold Inspect memory heading follows the same long-dash-description-colon and blank-line pattern. Its four lines use the same monospaced minus/value and plain colon format for `global`, `cwd`, `session` and `effective`, describing individual scopes and their combined view. Inspection works in Off even though its memory does not reach the agent. A horizontal radio row presents `Off | Passive | Active`: the selected option uses 🟡, 🟣 or 🟢 respectively, and each inactive option uses ⚫️. Four direct Global/CWD/Session/Effective buttons follow without another chooser. Ordinary successful controls add no redundant mode receipt; diagnostic outcomes remain visible. Telegram Active requested during a run waits for settlement; Passive and Off apply immediately. All controls use the same lifecycle owners as the terminal commands. The adapter is optional and the Pi commands remain available without it. Open implementation work is tracked in [BACKLOG.md](../BACKLOG.md).
|
|
91
95
|
|
|
92
96
|
## Storage and recovery
|
|
93
97
|
|
package/lib/config.ts
CHANGED
|
@@ -27,8 +27,8 @@ export function loadStateFlowConfig(agentDir = getAgentDir(), repositoryRoot = g
|
|
|
27
27
|
const path = join(directory, "config.json");
|
|
28
28
|
const defaults: StateFlowConfig = {
|
|
29
29
|
directory,
|
|
30
|
-
mode: "
|
|
31
|
-
inactiveMode: "
|
|
30
|
+
mode: "off",
|
|
31
|
+
inactiveMode: "off",
|
|
32
32
|
logging: false,
|
|
33
33
|
showSuccessfulPatches: true,
|
|
34
34
|
historyLimit: DEFAULT_HISTORY_LIMIT,
|
|
@@ -53,11 +53,12 @@ export function loadStateFlowConfig(agentDir = getAgentDir(), repositoryRoot = g
|
|
|
53
53
|
if (Object.hasOwn(value, "showSuccessfulPatches") && typeof value.showSuccessfulPatches !== "boolean") throw new Error(`State Flow showSuccessfulPatches must be a boolean: ${path}`);
|
|
54
54
|
if (Object.hasOwn(value, "historyLimit") && (!Number.isSafeInteger(value.historyLimit) || (value.historyLimit as number) < 0 || (value.historyLimit as number) > MAX_HISTORY_LIMIT)) throw new Error(`State Flow historyLimit must be an integer from 0 to ${MAX_HISTORY_LIMIT}: ${path}`);
|
|
55
55
|
const legacyInactive: InactiveMode = value.passiveBootstrap !== false || value.passiveTools !== false ? "passive" : "off";
|
|
56
|
-
const
|
|
56
|
+
const hasLegacyMode = Object.hasOwn(value, "autoStart") || Object.hasOwn(value, "passiveBootstrap") || Object.hasOwn(value, "passiveTools");
|
|
57
|
+
const mode = isStateFlowMode(value.mode) ? value.mode : value.autoStart === true ? "active" : hasLegacyMode ? legacyInactive : "off";
|
|
57
58
|
return {
|
|
58
59
|
directory,
|
|
59
60
|
mode,
|
|
60
|
-
inactiveMode: isStateFlowMode(value.mode) ? inactiveModeFor(value.mode) : legacyInactive,
|
|
61
|
+
inactiveMode: isStateFlowMode(value.mode) ? inactiveModeFor(value.mode) : hasLegacyMode ? legacyInactive : "off",
|
|
61
62
|
logging: value.logging === true,
|
|
62
63
|
showSuccessfulPatches: value.showSuccessfulPatches !== false,
|
|
63
64
|
historyLimit: typeof value.historyLimit === "number" ? value.historyLimit : DEFAULT_HISTORY_LIMIT,
|
package/lib/extension.ts
CHANGED
|
@@ -1283,16 +1283,14 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
1283
1283
|
const patchCalls = batch?.filter((name) => name === PATCH_STATE_TOOL_NAME).length ?? 0;
|
|
1284
1284
|
if (patchCalls > 0) {
|
|
1285
1285
|
if (patchCalls !== 1) {
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
};
|
|
1286
|
+
const reason = "A State Flow barrier response must contain exactly one patch_state call";
|
|
1287
|
+
recordDiagnostic(reason, "barrier-block", ctx, { tool: event.toolName, toolCallId: event.toolCallId, batchToolNames: batch });
|
|
1288
|
+
return { block: true, reason };
|
|
1290
1289
|
}
|
|
1291
1290
|
if (event.toolName !== PATCH_STATE_TOOL_NAME) {
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
};
|
|
1291
|
+
const reason = "Blocked by the patch_state barrier; reconsider this action after State Flow rematerializes context";
|
|
1292
|
+
recordDiagnostic(reason, "barrier-block", ctx, { tool: event.toolName, toolCallId: event.toolCallId, batchToolNames: batch });
|
|
1293
|
+
return { block: true, reason };
|
|
1296
1294
|
}
|
|
1297
1295
|
}
|
|
1298
1296
|
skillReads.recordCall(event.toolCallId, event.toolName, event.input);
|
package/lib/logging.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { appendFileSync, closeSync, constants, fstatSync, lstatSync, mkdirSync,
|
|
|
3
3
|
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
4
4
|
import { isObject } from "./json.ts";
|
|
5
5
|
|
|
6
|
-
export type StateFlowDiagnosticCategory = "invalid-patch" | "publication-conflict" | "finalization";
|
|
6
|
+
export type StateFlowDiagnosticCategory = "invalid-patch" | "publication-conflict" | "finalization" | "barrier-block";
|
|
7
7
|
|
|
8
8
|
/** Minimal structural block; only ordinary text keeps its exact content. */
|
|
9
9
|
export interface StateFlowDiagnosticBlock {
|
|
@@ -22,6 +22,8 @@ export interface StateFlowDiagnosticRecord {
|
|
|
22
22
|
input?: unknown;
|
|
23
23
|
tool?: string;
|
|
24
24
|
toolCallId?: string;
|
|
25
|
+
/** Names only, in native assistant-batch order; never sibling arguments. */
|
|
26
|
+
batchToolNames?: string[];
|
|
25
27
|
}
|
|
26
28
|
|
|
27
29
|
/** Preserve exact text blocks and block boundaries; reasoning bodies are never duplicated. */
|
|
@@ -62,6 +64,7 @@ export interface DiagnosticExtras {
|
|
|
62
64
|
input?: unknown;
|
|
63
65
|
tool?: string;
|
|
64
66
|
toolCallId?: string;
|
|
67
|
+
batchToolNames?: readonly string[];
|
|
65
68
|
}
|
|
66
69
|
|
|
67
70
|
/** Own diagnostic path safety, projection, persistence, and one-shot failure reporting. */
|
|
@@ -105,6 +108,7 @@ export class StateFlowDiagnosticWriter {
|
|
|
105
108
|
...(extras.input === undefined ? {} : { input: extras.input }),
|
|
106
109
|
...(extras.tool === undefined ? {} : { tool: extras.tool }),
|
|
107
110
|
...(extras.toolCallId === undefined ? {} : { toolCallId: extras.toolCallId }),
|
|
111
|
+
...(extras.batchToolNames === undefined ? {} : { batchToolNames: [...extras.batchToolNames] }),
|
|
108
112
|
});
|
|
109
113
|
return true;
|
|
110
114
|
} catch (failure) {
|
package/lib/telegram.ts
CHANGED
|
@@ -135,14 +135,9 @@ export function formatStateFlowSectionLabel(snapshot: StateFlowTelegramSnapshot)
|
|
|
135
135
|
return `🌀 State Flow: ${snapshot.mode}`;
|
|
136
136
|
}
|
|
137
137
|
|
|
138
|
-
/** Match pi-telegram's settings-card value descriptions. */
|
|
139
|
-
const STATE_FLOW_SECTION_HELP = [
|
|
140
|
-
"<code>-</code> <code>off</code>: no memory tools or state bootstrap.",
|
|
141
|
-
"<code>-</code> <code>passive</code> (default): memory tools and context with ordinary conversation.",
|
|
142
|
-
"<code>-</code> <code>active</code>: state-driven episodes.",
|
|
143
|
-
].join("\n");
|
|
144
|
-
|
|
145
138
|
export const STATE_FLOW_MODES = ["off", "passive", "active"] as const satisfies readonly StateFlowMode[];
|
|
139
|
+
const STATE_FLOW_MODE_LABELS: Record<StateFlowMode, string> = { off: "Off", passive: "Passive", active: "Active" };
|
|
140
|
+
const STATE_FLOW_SELECTED_MARKERS: Record<StateFlowMode, string> = { off: "🟡", passive: "🟣", active: "🟢" };
|
|
146
141
|
|
|
147
142
|
function isStateFlowModeAction(value: string): value is StateFlowMode {
|
|
148
143
|
return (STATE_FLOW_MODES as readonly string[]).includes(value);
|
|
@@ -153,22 +148,31 @@ function modeReceiptNotice(mode: StateFlowMode, result: StateFlowTelegramControl
|
|
|
153
148
|
return result.message;
|
|
154
149
|
}
|
|
155
150
|
|
|
156
|
-
/**
|
|
151
|
+
/** One radio-style mode row followed directly by read-only scope actions. */
|
|
157
152
|
export function buildStateFlowSectionView(
|
|
158
153
|
snapshot: StateFlowTelegramSnapshot,
|
|
159
154
|
callbackData: (action: string, payload?: string) => string,
|
|
160
155
|
): StateFlowTelegramView {
|
|
161
156
|
const modes: StateFlowTelegramButton[] = STATE_FLOW_MODES.map((mode) => ({
|
|
162
|
-
text: `${mode === snapshot.mode ?
|
|
157
|
+
text: `${mode === snapshot.mode ? STATE_FLOW_SELECTED_MARKERS[mode] : "⚫️"} ${STATE_FLOW_MODE_LABELS[mode]}`,
|
|
163
158
|
callback_data: callbackData(mode),
|
|
164
159
|
}));
|
|
165
160
|
return {
|
|
166
161
|
text: [
|
|
167
162
|
`<b>🌀 State Flow:</b> <code>${snapshot.mode}</code>`,
|
|
168
163
|
"",
|
|
169
|
-
"
|
|
164
|
+
"<b>Mode</b> — choose a workflow (switching modes never erases stored memory):",
|
|
165
|
+
"",
|
|
166
|
+
"<code>-</code> <code>off</code> (default): regular chat without State Flow memory tools or context.",
|
|
167
|
+
"<code>-</code> <code>passive</code>: regular chat with memory tools; available combined memory enters the agent's context.",
|
|
168
|
+
"<code>-</code> <code>active</code>: same memory access; each completed answer closes a cycle, and the next request starts from saved state, not the full chat.",
|
|
169
|
+
"",
|
|
170
|
+
"<b>Inspect memory</b> — view stored state even in Off:",
|
|
170
171
|
"",
|
|
171
|
-
|
|
172
|
+
"<code>-</code> <code>global</code>: memory shared across projects and sessions.",
|
|
173
|
+
"<code>-</code> <code>cwd</code>: memory shared by sessions in this directory.",
|
|
174
|
+
"<code>-</code> <code>session</code>: private memory for this session, kept on resume.",
|
|
175
|
+
"<code>-</code> <code>effective</code>: merged Global, CWD and Session state; the agent can use it when memory is enabled and available.",
|
|
172
176
|
].join("\n"),
|
|
173
177
|
parseMode: "html",
|
|
174
178
|
replyMarkup: { inline_keyboard: [
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@llblab/pi-state-flow",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.23.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "Incremental scoped state/context/memory compiler for Pi, inspired by SKILL.state",
|
|
6
6
|
"keywords": [
|
|
@@ -76,7 +76,7 @@
|
|
|
76
76
|
"@earendil-works/pi-ai": "0.87.0",
|
|
77
77
|
"@earendil-works/pi-coding-agent": "0.87.0",
|
|
78
78
|
"@earendil-works/pi-tui": "0.87.0",
|
|
79
|
-
"@types/node": "
|
|
80
|
-
"typescript": "
|
|
79
|
+
"@types/node": "^26.4.0",
|
|
80
|
+
"typescript": "^7.0.2"
|
|
81
81
|
}
|
|
82
82
|
}
|
|
@@ -15,7 +15,7 @@ State Flow's on-demand operational reference. Resolve the usage question or iden
|
|
|
15
15
|
|
|
16
16
|
Passive tools access memory without starting an episode. Missing tools or storage are blockers, not permission to enable an episode or bypass storage; explanation alone remains possible.
|
|
17
17
|
|
|
18
|
-
Operator commands: `/state-flow-status` inspects; `/state-flow-active` selects state-driven episodes; `/state-flow-passive` selects ordinary conversation with both memory tools and existing-state projection; `/state-flow-off` removes both tools and all State Flow context, including frozen handoffs, without deleting memory. Commands and Telegram change only the current session's `mode`. Global `mode` defaults to
|
|
18
|
+
Operator commands: `/state-flow-status` inspects; `/state-flow-active` selects state-driven episodes; `/state-flow-passive` selects ordinary conversation with both memory tools and existing-state projection; `/state-flow-off` removes both tools and all State Flow context, including frozen handoffs, without deleting memory. Commands and Telegram change only the current session's `mode`. Global `mode` defaults to Off for new sessions and never overrides retained choices. Do not change mode without operator authorization.
|
|
19
19
|
|
|
20
20
|
## Map
|
|
21
21
|
|