@llblab/pi-state-flow 0.27.4 → 0.27.6
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 +3 -2
- package/BACKLOG.md +1 -1
- package/CHANGELOG.md +10 -0
- package/README.md +6 -4
- package/dist/lib/config.d.ts +1 -1
- package/dist/lib/extension.d.ts +2 -2
- package/dist/lib/extension.js +265 -249
- package/dist/lib/ownership.d.ts +1 -1
- package/dist/lib/ownership.js +2 -2
- package/dist/lib/protocol.d.ts +1 -1
- package/dist/lib/protocol.js +6 -6
- package/dist/lib/query.js +1 -1
- package/dist/lib/telegram.js +0 -2
- package/dist/package.json +1 -1
- package/dist/skills/state-flow-guide/SKILL.md +8 -6
- package/dist/skills/state-flow-memory/SKILL.md +8 -6
- package/docs/README.md +1 -1
- package/docs/architecture.md +16 -14
- package/docs/compatibility.md +10 -0
- package/docs/filesystem-recovery.md +1 -1
- package/docs/lazy-state.md +17 -17
- package/docs/public-module-contract.md +1 -1
- package/docs/scope-selection-contract.md +2 -0
- package/docs/semantic-module-contract.md +1 -1
- package/docs/single-scope-interface-contract.md +1 -1
- package/docs/usage.md +18 -16
- package/lib/config.ts +1 -1
- package/lib/extension.ts +39 -23
- package/lib/ownership.ts +2 -2
- package/lib/protocol.ts +6 -6
- package/lib/query.ts +1 -1
- package/lib/telegram.ts +0 -2
- package/package.json +1 -1
- package/skills/state-flow-guide/SKILL.md +8 -6
- package/skills/state-flow-memory/SKILL.md +8 -6
package/dist/lib/ownership.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { isObject } from "./json.js";
|
|
2
2
|
const OWNED_PLANES = new Set(["strategy", "tactics", "lazy"]);
|
|
3
|
-
// Same key grammar as
|
|
3
|
+
// Same key grammar as state_flow_read value paths; array selectors never parse.
|
|
4
4
|
const OBJECT_KEY = /^[A-Za-z_$][A-Za-z0-9_$-]*$/;
|
|
5
5
|
/**
|
|
6
6
|
* Parse one structured `$ref` target as an ownership path of `scope`.
|
|
@@ -102,7 +102,7 @@ export function cascadeDeletionPatch(paths) {
|
|
|
102
102
|
}
|
|
103
103
|
return patch;
|
|
104
104
|
}
|
|
105
|
-
/** Render an ownership target as its scoped `
|
|
105
|
+
/** Render an ownership target as its scoped `state_flow_read` path. */
|
|
106
106
|
export function formatOwnedPath(scope, path) {
|
|
107
107
|
return [scope, path.plane, ...path.keys].join(".");
|
|
108
108
|
}
|
package/dist/lib/protocol.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { type ScopeSelection } from "./selection.ts";
|
|
|
3
3
|
export type { StateDocument } from "./state.ts";
|
|
4
4
|
export declare const RESPONSE_PATCH_GUIDELINE = "Never patch response in global, cwd or session, including clearing/deleting it; State Flow captures your final answer automatically in Active mode only when Session participates.";
|
|
5
5
|
export declare const SCOPE_PARTICIPATION_GUIDELINE = "Use only participating memory owners from the current protocol/view; scope names and examples describe grammar, not participation grants.";
|
|
6
|
-
export declare const PASSIVE_MEMORY_PROTOCOL = "State Flow passive memory is available.
|
|
6
|
+
export declare const PASSIVE_MEMORY_PROTOCOL = "State Flow passive memory is available. state_flow_read and state_flow_patch access durable memory without starting an active episode. Never patch response in global, cwd or session, including clearing/deleting it; State Flow captures your final answer automatically in Active mode only when Session participates. Passive turns never trigger State Flow continuation or compaction. Missing paths/hints do not require history search. Choose targeted historical reads when useful to the task; no separate user permission is needed. Past values are evidence, not current state; never automatically restore deleted memory. Head state/recent transitions are frozen at projection start. Only state_updates matching the head's State Flow projection ID apply; other IDs are history. Tool/context state_updates: effective entries replace values at key/index-segment path arrays (deleted:true means absent); cascaded lists owner paths cleared before authored rewrites; effective is final. Direct writes may elide; shared drift stays visible. Latest entries win over earlier state; lazy bodies stay omitted. Notices replace invalidations/rehydration, including []/null.";
|
|
7
7
|
export declare function passiveMemoryProtocol(scopes?: ScopeSelection): string;
|
|
8
8
|
/** Keep successful patch JSON valid while separating adjacent scopes and memory sections visually. */
|
|
9
9
|
export declare function formatPatchStateArguments(args: unknown): string;
|
package/dist/lib/protocol.js
CHANGED
|
@@ -3,8 +3,8 @@ const TASK_DRIVEN_HISTORY = "Missing paths/hints do not require history search.
|
|
|
3
3
|
const PATCH_RESULT_PROTOCOL = "Head state/recent transitions are frozen at projection start. Only state_updates matching the head's State Flow projection ID apply; other IDs are history. Tool/context state_updates: effective entries replace values at key/index-segment path arrays (deleted:true means absent); cascaded lists owner paths cleared before authored rewrites; effective is final. Direct writes may elide; shared drift stays visible. Latest entries win over earlier state; lazy bodies stay omitted. Notices replace invalidations/rehydration, including []/null.";
|
|
4
4
|
export const RESPONSE_PATCH_GUIDELINE = "Never patch response in global, cwd or session, including clearing/deleting it; State Flow captures your final answer automatically in Active mode only when Session participates.";
|
|
5
5
|
export const SCOPE_PARTICIPATION_GUIDELINE = "Use only participating memory owners from the current protocol/view; scope names and examples describe grammar, not participation grants.";
|
|
6
|
-
export const PASSIVE_MEMORY_PROTOCOL = `State Flow passive memory is available.
|
|
7
|
-
const FLAT_INTERFACE_PROTOCOL = 'One-owner interface:
|
|
6
|
+
export const PASSIVE_MEMORY_PROTOCOL = `State Flow passive memory is available. state_flow_read and state_flow_patch access durable memory without starting an active episode. ${RESPONSE_PATCH_GUIDELINE} Passive turns never trigger State Flow continuation or compaction. ${TASK_DRIVEN_HISTORY} ${PATCH_RESULT_PROTOCOL}`;
|
|
7
|
+
const FLAT_INTERFACE_PROTOCOL = 'One-owner interface: state_flow_patch takes intents/strategy/tactics/artifacts/lazy object planes directly; never add an owner wrapper. state_flow_read accepts flat semantic paths, effective[N] history and a scalar patches[N] retained-patch alias; nested array[N] stays an array index. Current same-owner structured refs may use {"$ref":"lazy.plan"}; canonical ownership is retained internally. Explicit different-owner, historical/effective refs, source/resource paths and ordinary text keep their meaning, never become local permission.';
|
|
8
8
|
function scopeGuidance(selection) {
|
|
9
9
|
const meanings = { session: "session=branch/run continuation by default", cwd: "cwd=project knowledge", global: "global=cross-project/user/environment knowledge" };
|
|
10
10
|
return `Participating owners: ${selection.join(" ")}. Use the narrowest matching owner: ${[...selection].reverse().map(scope => meanings[scope]).join("; ")}. Excluded owners cannot be read, patched or acquired as memory. Do not broaden/relocate to fit selection.`;
|
|
@@ -97,7 +97,7 @@ export function stateFlowProtocol(bootstrap, scopes = DEFAULT_SCOPE_SELECTION) {
|
|
|
97
97
|
const response = selected.includes("session") ? 'read-only prior answer; never patch it in any scope. Auto-stored at turn_end (empty="").'
|
|
98
98
|
: "read-only selected legacy data; never patch it in any scope. Session excluded: new answers are delivered, not stored or backfilled.";
|
|
99
99
|
const bootstrapProtocol = bootstrap
|
|
100
|
-
? `BOOTSTRAP RUN: Reconcile all relevant ${all ? "state" : "participating state"} and continuation through
|
|
100
|
+
? `BOOTSTRAP RUN: Reconcile all relevant ${all ? "state" : "participating state"} and continuation through state_flow_patch before completion.\n\n`
|
|
101
101
|
: "";
|
|
102
102
|
return `State Flow is enabled. It owns durable memory.
|
|
103
103
|
|
|
@@ -111,13 +111,13 @@ ${bootstrapProtocol}STATE:
|
|
|
111
111
|
|
|
112
112
|
SCOPES: ${all ? "Use the narrowest scope: session=branch/run continuation by default; cwd=project knowledge; global=cross-project/user/environment knowledge." : scopeGuidance(selected)}${single ? `\nINTERFACE: ${FLAT_INTERFACE_PROTOCOL}` : ""}
|
|
113
113
|
|
|
114
|
-
READ: Use
|
|
114
|
+
READ: Use state_flow_read for concrete ${single ? "semantic" : "scope"}/retained-history gaps. lazy_navigation lists bounded effective lazy keys, not bodies. ${TASK_DRIVEN_HISTORY}
|
|
115
115
|
|
|
116
|
-
WRITE:
|
|
116
|
+
WRITE: state_flow_patch is the sole model-authored semantic mutation mechanism; ${single ? "the supplied planes are validated and durably accepted for the captured owner as one atomic transition. Updates use current canonical values after cancelable lock waiting." : "all supplied scopes are validated and durably accepted as one atomic transition. Global/CWD use current canonical values after cancelable lock waiting."} Correct repeats succeed without new revisions. ${PATCH_RESULT_PROTOCOL}
|
|
117
117
|
|
|
118
118
|
PATCH: Use ${single ? "flat semantic plane object patches for material updates, not acknowledgments. Omit unchanged planes; do not wrap them in an owner object." : `${names} object patches for material updates, not acknowledgments. Omit empty scopes.`} ${single ? "artifacts/strategy/tactics/intents/lazy are objects; nested values are ordinary JSON." : "artifacts/strategy/tactics/intents are objects; lazy is ordinary JSON."} Omitted fields persist. Never patch runtime config/meta/response. Objects merge recursively; arrays/primitives replace. An object containing only canonical "[N]" keys recursively patches array elements. Indexed deletion is forbidden; nested object null deletes; materialized null is forbidden.
|
|
119
119
|
|
|
120
|
-
MEMORY: Proposals are not commitments. Treat every patch as reconciliation rather than append-only notes: merge superseded fragments, remove obsolete progress. Preserve commitments, open questions, consequential results and exact continuation; distinguish requirements, decisions, observations, conclusions and hypotheses. Exclude secrets, raw history, transient progress, speculation and unsupported claims; retain decision-relevant uncertainty. Curate touched state; cleanup and scope reviews require an explicit user request. ${single ? "A cross-owner move requires both owners to participate; this one-owner interface cannot perform it or broaden selection. Preserve data and report the unavailable destination." : "Proven moves use targeted
|
|
120
|
+
MEMORY: Proposals are not commitments. Treat every patch as reconciliation rather than append-only notes: merge superseded fragments, remove obsolete progress. Preserve commitments, open questions, consequential results and exact continuation; distinguish requirements, decisions, observations, conclusions and hypotheses. Exclude secrets, raw history, transient progress, speculation and unsupported claims; retain decision-relevant uncertainty. Curate touched state; cleanup and scope reviews require an explicit user request. ${single ? "A cross-owner move requires both owners to participate; this one-owner interface cannot perform it or broaden selection. Preserve data and report the unavailable destination." : "Proven moves use targeted state_flow_read and one atomic multi-scope patch, then verify both owners."} External transfers need verified acceptance before deletion. Never invent memory changes.
|
|
121
121
|
|
|
122
122
|
REFS: State refs use {"$ref":"${referencePath}"} or \`$${referencePath}\` in text. Intent $ref owns same-scope strategy/tactics/lazy keys; text refs only use. Fixed phases, not JSON order: intents, cleanup, other planes, compile/normalize. Remaining/new intents keep targets/ancestors/descendants. Rewrite same/new path: fresh, no old fields; unowned legal. Resolve only when needed; infer no authority, hydration, execution, or completion. Hint paths are current reference owners, not relocated targets or proof of staleness. Fix proven stale refs only as needed; never scan refs or history offsets.
|
|
123
123
|
|
package/dist/lib/query.js
CHANGED
|
@@ -294,7 +294,7 @@ function diffObjects(previous, current) {
|
|
|
294
294
|
/** Project exact current/historical state paths without exposing temporal metadata. */
|
|
295
295
|
export function readProjectedState(view, paths, projection = "value", historyLimit = DEFAULT_HISTORY_LIMIT) {
|
|
296
296
|
if (paths.length === 0)
|
|
297
|
-
throw new Error("
|
|
297
|
+
throw new Error("state_flow_read requires at least one path");
|
|
298
298
|
queryOwners(view);
|
|
299
299
|
if (projection === "patch") {
|
|
300
300
|
const patches = paths.map((path) => {
|
package/dist/lib/telegram.js
CHANGED
|
@@ -70,13 +70,11 @@ export function buildStateFlowSectionView(snapshot, callbackData) {
|
|
|
70
70
|
] : []),
|
|
71
71
|
"",
|
|
72
72
|
"<b>Mode</b> — choose a workflow (switching modes never erases stored memory):",
|
|
73
|
-
"",
|
|
74
73
|
"<code>-</code> <code>off</code> (default): regular chat without State Flow memory tools or context.",
|
|
75
74
|
`<code>-</code> <code>passive</code>: regular chat with memory tools; available memory from the selected ${scopes.length === 1 ? "scope" : "scopes"} enters the agent's context.`,
|
|
76
75
|
"<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.",
|
|
77
76
|
"",
|
|
78
77
|
"<b>Inspect participating memory</b> — view available stored state even in Off:",
|
|
79
|
-
"",
|
|
80
78
|
...scopes.map(scope => `<code>-</code> <code>${scope}</code>: ${STATE_FLOW_SCOPE_DESCRIPTIONS[scope]}`),
|
|
81
79
|
...(scopes.length > 1
|
|
82
80
|
? ["<code>-</code> <code>effective</code>: merged state of the selected scopes in order from the general to the specific."]
|
package/dist/package.json
CHANGED
|
@@ -9,6 +9,8 @@ description: >
|
|
|
9
9
|
|
|
10
10
|
# State Flow Guide
|
|
11
11
|
|
|
12
|
+
Use the advertised `state_flow_read` and `state_flow_patch` names. Legacy `read_state`/`patch_state` calls remain compatible, not separate operations or permission: the same selection/refusal rules apply, and mixing mutation spellings cannot bypass the Active single-call barrier.
|
|
13
|
+
|
|
12
14
|
State Flow's on-demand operational reference. Resolve the usage question or identified operation, not a memory audit. The installed runtime protocol and schemas take precedence.
|
|
13
15
|
|
|
14
16
|
## Mode
|
|
@@ -36,7 +38,7 @@ A proposal is not a commitment. Preserve an accepted plan's phases, dependencies
|
|
|
36
38
|
|
|
37
39
|
Reuse sufficient visible state. The memory head and its recent transitions are frozen at projection start. Apply later `state_updates` only when their `projection` matches the head's `State Flow projection:` ID; older native results remain historical. Effective update paths are key/index arrays whose values replace that path, while `deleted: true` means absence. The optional `cascaded` array lists paths cleared in the intermediate ownership phase, relative for one WANTED owner and owner-scoped for multiple WANTED owners, even if later authored writes recreate them, including nested lazy keys; it contains no values, is never elided, and does not mean the effective path is absent if a broader-scope value remains. Current notices can replace invalidation lists or rehydration phase, including clearing them with `[]` or `null`; lazy bodies still require explicit reads.
|
|
38
40
|
|
|
39
|
-
`
|
|
41
|
+
`state_flow_read` accepts `path` or `paths`, never both. Multi-path reads succeed or fail together. Projections: `value` (default), `keys` (structure), `patch` (intersecting change at the selected boundary).
|
|
40
42
|
|
|
41
43
|
With exactly one WANTED owner, ordinary read paths are flat, with no scope token. Sole-owner example arguments:
|
|
42
44
|
|
|
@@ -50,17 +52,17 @@ With exactly one WANTED owner, ordinary read paths are flat, with no scope token
|
|
|
50
52
|
|
|
51
53
|
`effective[N].tactics` selects a temporal boundary; `tactics.items[N]` indexes a nested array. Sole-owner `patches[N]` is the scalar owner patch-history alias. With multiple WANTED owners, ordinary unscoped paths use effective state; explicit owner paths disambiguate ownership. Multi-owner example, requiring both CWD and Session to participate: `{"paths":["cwd.tactics","session.tactics"]}`. Arity follows WANTED selection, not whichever owners happen to have an available view. Wanted but unacquired Session is `selected, unavailable`, not excluded; reads cannot acquire it or return partial mixed-owner results.
|
|
52
54
|
|
|
53
|
-
Unscoped paths use the sole owner's current state or, with multiple owners, effective state. Optional explicit `cwd[1].tactics` reads the preceding causal boundary when CWD participates. Materialized-history and scope patch-history paths such as `cwd.patches[1]` share the configured `historyLimit` bound (default 7) and require actually retained history. Lowering the limit folds excess tails without erasing current state; increasing it does not reconstruct discarded history. Array ranges such as `cwd.lazy.checks[0..3]` exclude the endpoint and require existing elements. Missing paths are unavailable; inspect parent keys only when needed for the task. Missing history is not empty history. Read `lazy` explicitly. Treat structured `$ref` values and `$`-prefixed `
|
|
55
|
+
Unscoped paths use the sole owner's current state or, with multiple owners, effective state. Optional explicit `cwd[1].tactics` reads the preceding causal boundary when CWD participates. Materialized-history and scope patch-history paths such as `cwd.patches[1]` share the configured `historyLimit` bound (default 7) and require actually retained history. Lowering the limit folds excess tails without erasing current state; increasing it does not reconstruct discarded history. Array ranges such as `cwd.lazy.checks[0..3]` exclude the endpoint and require existing elements. Missing paths are unavailable; inspect parent keys only when needed for the task. Missing history is not empty history. Read `lazy` explicitly. Treat structured `$ref` values and `$`-prefixed `state_flow_read` paths inside ordinary strings, such as `$effective.lazy.memory[7]`, as semantic-state references. Other resources retain their native locators. Resolve any reference through the appropriate read/tool only when needed. Neither form proves authority or existence, hydrates, or executes anything; only intent ownership (see Write) has a deletion consequence. Never scan or resolve references merely to test them. A missing single value path with exact durable sources returns `{value:null, hint:[{type:"dangling-reference", message, paths}]}`. Treat `hint` as top-level diagnostic metadata, never as the requested state: its message is descriptive and conditional; its paths are runtime-verified current reference owners, not verified new locations of the target. The hint proves provenance rather than staleness and is absent when no current durable source matches; keys, patch, and batch reads keep all-or-error behavior. Only then inspect ownership as needed and patch a proven stale owning value while preserving its surrounding meaning. Effective absence, inaccessible external resources, and transient failures are not proof.
|
|
54
56
|
|
|
55
57
|
Missing paths or runtime hints alone do not require historical search. The agent may choose a targeted historical read when a previous value is useful to the current task, without separate user permission. Otherwise continue without searching. Use found values as historical evidence, not automatically as current state; never automatically restore deleted memory. Do not scan all offsets, hydrate automatically or request repair inference. A hint does not prove prior existence, retained history or relocation. A proven stale reference may be repaired within touched work without resurrecting its target. Automatic state and recent-transition projections omit lazy bodies; bounded `lazy_navigation` preserves structure, and explicit current/historical reads still return requested lazy values or patches.
|
|
56
58
|
|
|
57
59
|
## Write
|
|
58
60
|
|
|
59
|
-
Call `
|
|
61
|
+
Call `state_flow_patch` alone per assistant response; await acceptance before dependent work. With exactly one WANTED owner, supply built-in flat object planes (`intents`, `strategy`, `tactics`, `artifacts`, `lazy`), without an owner wrapper. Compatible registered mutable external roots may also be authored when advertised by the current `state_flow_patch` schema; registration/schema alone grants no source or publication authority. Immutable or unavailable definitions do not permit model writes. With multiple WANTED owners, supply one or more explicit participating owners from `global`, `cwd`, and `session`; supplied scopes commit atomically. Arity follows WANTED selection, not available view; selection is not a grant of authority. Default to Session for current work only when it participates, CWD for reusable project knowledge, and Global for established cross-project knowledge. Preserve these meanings; an unavailable owner is not a reason to write its data into a broader one. Omit unchanged planes in a sole-owner patch and unchanged scopes in a multi-owner patch.
|
|
60
62
|
|
|
61
63
|
The runtime waits cancelably for publication ownership, then applies authored Global/CWD operations to current canonical values. Untouched fields survive; overlapping targets follow successful acceptance order. Correct repeats succeed as `State already current.` without another semantic revision. Do not repeat external actions during a memory wait, or rebuild an entire scope from an older snapshot. Session ownership/history fences remain private, not a universal merge.
|
|
62
64
|
|
|
63
|
-
When present, semantic planes `intents`, `strategy`, `tactics`, `artifacts`, and `lazy` are objects; nested lazy values may contain ordinary JSON without stored nulls. Stored checkpoints and patches may omit any documented plane. Current and historical views assemble only known fields present in the selected scopes. Absent fields and empty responses are omitted from views. Known content includes metadata-declared external roots; missing or incompatible definitions never authorize discarding that retained data. Only the current admitted authoring grammar is writable. Nested data within known planes remains intact. Explicit value reads of an absent documented top-level field return `null`. Authored `
|
|
65
|
+
When present, semantic planes `intents`, `strategy`, `tactics`, `artifacts`, and `lazy` are objects; nested lazy values may contain ordinary JSON without stored nulls. Stored checkpoints and patches may omit any documented plane. Current and historical views assemble only known fields present in the selected scopes. Absent fields and empty responses are omitted from views. Known content includes metadata-declared external roots; missing or incompatible definitions never authorize discarding that retained data. Only the current admitted authoring grammar is writable. Nested data within known planes remains intact. Explicit value reads of an absent documented top-level field return `null`. Authored `state_flow_patch` keeps its documented field grammar. Objects merge, arrays/scalars replace, and omitted nonempty fields persist. Accepted supplied scopes recursively omit empty object fields and planes, including explicit `{}`; the scope root remains `{}`. This also cleans legacy empty branches in that scope, which can advance its revision once. Array slots and empty arrays remain; empty object fields inside elements disappear without shifting indices. Model projection hides legacy empty branches, but exact current/historical reads and untouched scopes are not normalized. Nested `null` removes an owned object key; empty ancestors disappear and inherited content may reappear. Canonical `"[N]"` keys patch existing array elements; indexed deletion and out-of-bounds indices are forbidden. Replace the whole array to add/remove elements. Missing authored object-key deletions succeed with a nonfatal hint showing relative JSON Pointers for one WANTED owner or owner-scoped pointers for multiple WANTED owners, for the target and first unavailable component; result details retain canonical ownership. Hints are not state, do not advance revisions and do not prove a typo; check the address only when deletion was expected to change something. Never guess or automatically correct the target.
|
|
64
66
|
|
|
65
67
|
Work from intents. A structured `{"$ref"}` anywhere inside an intent owns ("delete with me") an existing object key under `strategy`, `tactics` or `lazy` in the same scope; a textual `$path` mention only uses it. In a sole-owner patch, current flat structured refs anchor to that exact owner before canonical intent ownership/cascade processing. Existing canonical historical, effective, cross-owner and resource refs, and textual mentions are never stripped or rebound. Opening a task (sole-owner example, valid for any one WANTED owner):
|
|
66
68
|
|
|
@@ -80,7 +82,7 @@ Sole-owner preservation example: retain the known exact source path and existing
|
|
|
80
82
|
{"tactics":{"evidence":{"source":"/project/specs/api.md","historic":{"$ref":"session[1].tactics.api"},"cross":{"$ref":"global.strategy.api"},"effective":{"$ref":"effective.tactics.api"},"resource":{"$ref":"https://example.invalid/api"},"text":"$session.tactics.api"}}}
|
|
81
83
|
```
|
|
82
84
|
|
|
83
|
-
Name object keys in ASCII matching `[A-Za-z_$][A-Za-z0-9_$-]*` (for example `api_plan`, not a Cyrillic or spaced key): other keys cannot be addressed by `
|
|
85
|
+
Name object keys in ASCII matching `[A-Za-z_$][A-Za-z0-9_$-]*` (for example `api_plan`, not a Cyrillic or spaced key): other keys cannot be addressed by `state_flow_read` paths or `$` references, and cannot be owned by intents. Values may use any language.
|
|
84
86
|
|
|
85
87
|
Never edit backing files, `response`, configuration, provenance, or runtime metadata. Verify changed owner paths when needed; check effective state after override deletion.
|
|
86
88
|
|
|
@@ -92,7 +94,7 @@ In active mode, compile each required invalidated ordinary artifact at its exact
|
|
|
92
94
|
|
|
93
95
|
New answers are stored only in Active mode with Session participating. With Session excluded, answer normally without response persistence, backfill, shared relocation or a hidden private layer; selected legacy shared response remains read-only data. Passive never stores ordinary answers. Source/Skill ownership remains provenance-derived even when excluded: do not compile or relocate an excluded source into another owner.
|
|
94
96
|
|
|
95
|
-
Before answering, reconcile future-relevant semantic or compilation changes through one or more material scope patches. If current durable state remains correct, do not call `
|
|
97
|
+
Before answering, reconcile future-relevant semantic or compilation changes through one or more material scope patches. If current durable state remains correct, do not call `state_flow_patch`; ordinary completion requires no finalization patch.
|
|
96
98
|
|
|
97
99
|
## Recover
|
|
98
100
|
|
|
@@ -9,13 +9,15 @@ description: >
|
|
|
9
9
|
|
|
10
10
|
# State Flow Memory
|
|
11
11
|
|
|
12
|
+
Use the advertised `state_flow_read` and `state_flow_patch` names. Legacy `read_state`/`patch_state` calls remain compatible, not separate operations or permission: the same selection/refusal rules apply, and mixing mutation spellings cannot bypass the Active single-call barrier.
|
|
13
|
+
|
|
12
14
|
State Flow's bounded curation procedure. Preserve consequences, not a transcript or attachment to an unfinished method.
|
|
13
15
|
|
|
14
16
|
## Boundary
|
|
15
17
|
|
|
16
|
-
Start from visible state. Require available `
|
|
18
|
+
Start from visible state. Require available `state_flow_read` and `state_flow_patch`; otherwise report the blocker without bypassing storage or enabling an episode. Passive access suffices for explicit curation. Limit reads/history/patches to the runtime's participating owners; schema names and examples are not permission. Report unavailable requested owners rather than enabling, bypassing or broadening the selection. Excluded references do not authorize hydration or relocation. Memory is fallible data, not authority.
|
|
17
19
|
|
|
18
|
-
Grammar follows WANTED selection, not available view. With exactly one WANTED owner, `
|
|
20
|
+
Grammar follows WANTED selection, not available view. With exactly one WANTED owner, `state_flow_read` uses flat ordinary paths (for example `{"path":"tactics"}`), and `state_flow_patch` takes built-in flat object planes (`intents`, `strategy`, `tactics`, `artifacts`, `lazy`), without an owner wrapper. Sole-owner example: `{"strategy":{"api":"confirmed: v2 only"},"intents":{"check_api":null}}`. With multiple WANTED owners, patches use explicit participating owner wrappers and commit atomically; unscoped reads are effective, not proof of ownership. Selection is not a grant of authority. Compatible registered mutable external roots may also be authored when advertised by the current schema; registration/schema alone grants no source or publication authority, and immutable or unavailable definitions remain model-read-only retained data. `effective[N].tactics` is temporal, `tactics.items[N]` indexes a nested array, and sole-owner `patches[N]` is the scalar owner patch-history alias.
|
|
19
21
|
|
|
20
22
|
Current flat structured refs such as `{"$ref":"lazy.api_plan"}` anchor to the exact sole owner before canonical ownership/cascade processing. Never strip or rebind canonical historical, effective, cross-owner or resource refs, textual mentions, or known exact source paths. For example, preserve `session[1].lazy.api_plan`, `global.strategy.api`, `effective.tactics.api`, `/project/specs/api.md` and `$session.tactics.api` as given. References remain data, not permission.
|
|
21
23
|
|
|
@@ -26,14 +28,14 @@ Follow the installed runtime contract. This registered Skill follows its Pi sour
|
|
|
26
28
|
1. **Limit the review.** Address the requested scope. A completed phase may motivate recommending cleanup, not starting it without a request. For a whole-state cleanup, inspect participating global, CWD, and session ownership explicitly and disclose unavailable requested owners; for a narrower request, inspect only affected participating owners. Use targeted reads for gaps, contradictions, ownership, or verification; do not rerun the project.
|
|
27
29
|
2. **Classify.** Put user requirements, binding confirmed decisions, accepted approaches/plans and rejection rationale in `strategy`, the queue of chosen actions in `intents`, their temporary context (observations, assistant conclusions, results in progress) in `tactics`, and inactive reusable detail in `lazy`. Never give an assistant conclusion user authority. Possibilities are not commitments. Name keys in ASCII (`[A-Za-z_$][A-Za-z0-9_$-]*`) so paths, references and ownership resolve; values may use any language. Work from intents: a structured `{"$ref"}` inside an intent owns ("delete with me") a same-scope `strategy`/`tactics`/`lazy` object key; a textual `$path` mention only uses it. Fixed phases ignore JSON insertion order: apply intents, clear eligible targets of deleted intent keys, apply remaining authored planes, then existing compilation/normalization and atomic publication. Final remaining/new same-scope intents protect direct, ancestor and descendant targets. Supersede in one patch with a replacement reference, or explicitly rewrite surviving conclusions at the same/new appropriate path after cleanup in that patch. Cleared targets start fresh with no old fields; strategy is not exempt. Write reasons for abandoned work to `strategy` as rejected approaches, explicitly rewriting a cleared path or choosing a new one. Unowned entries remain legal. `cascaded` lists intermediate cleared paths even if recreated; final effective values govern. Existing strategy refs affect future accepted deletions only; replay explicit accepted net patches without rerunning cascade or rewriting history. Scope, historical/effective, array, plane-root, structured-key and source boundaries remain unchanged.
|
|
28
30
|
3. **Keep evidence boundaries.** Preserve corrections, prerequisites, bounded negative results, and useful uncertainty. Separate requirements, decisions, observations, conclusions, and hypotheses. Silence is not acceptance; repetition is not verification. One implementation's failure does not reject an approach. Neither freeze provisional methods nor reopen confirmed decisions without grounds.
|
|
29
|
-
4. **Compact for continuation.** Remove duplicates, obsolete progress, unsupported claims, and secrets. Keep sufficient results, real retrieval pointers, pending interaction, and known next checks. Observations are not live external facts. Keep `lazy` shallow and priority-ordered. Recognize optional structured `$ref` values and `$`-prefixed `
|
|
31
|
+
4. **Compact for continuation.** Remove duplicates, obsolete progress, unsupported claims, and secrets. Keep sufficient results, real retrieval pointers, pending interaction, and known next checks. Observations are not live external facts. Keep `lazy` shallow and priority-ordered. Recognize optional structured `$ref` values and `$`-prefixed `state_flow_read` paths inside ordinary strings as semantic-state references; other resources retain native locators. No reference form proves authority or existence, authorizes execution, or implies completion; only intent ownership has a deletion consequence. Never scan or resolve references merely to find broken ones. When the bounded review independently needs a reference, a missing single value path with exact durable sources returns `{value:null, hint:[{type:"dangling-reference", message, paths}]}`. Treat the top-level hint as conditional navigation and provenance, never as requested state or proof of staleness; its paths are runtime-verified current reference owners, not verified new locations of the target, while no hint does not prove invention. Inspect ownership only as needed, then patch a proven stale owning value while preserving surrounding meaning. Effective absence or external inaccessibility is insufficient.
|
|
30
32
|
5. **Check ownership.** Prefer `session` for branch/run continuation, `cwd` for project knowledge, and `global` for established cross-project knowledge. Effective values do not prove ownership; inspect participating owners before moves. Do not broaden or relocate memory merely because its proper owner is excluded. Broader applicability requires evidence.
|
|
31
33
|
|
|
32
34
|
Missing paths or runtime hints alone do not require historical search. The agent may choose a targeted historical read when a previous value is useful to the current task, without separate user permission. Otherwise continue without searching. Use found values as historical evidence, not automatically as current state; never automatically restore deleted memory. Do not scan all offsets, hydrate automatically or request repair inference. A hint does not prove prior existence, retained history or relocation. A proven stale reference may be repaired within touched work without resurrecting its target. Lazy bodies require explicit reads; automatic state/history projections retain navigation without hydrating those bodies.
|
|
33
35
|
|
|
34
36
|
## Transfer only when needed
|
|
35
37
|
|
|
36
|
-
Resolve destination conflicts without overwriting stronger or unrelated knowledge. For a proven move between scopes of one State Flow store, inspect both owners, then use one atomic multi-scope `
|
|
38
|
+
Resolve destination conflicts without overwriting stronger or unrelated knowledge. For a proven move between scopes of one State Flow store, inspect both owners, then use one atomic multi-scope `state_flow_patch` for destination and source changes. Both owners must participate: a sole-owner selection cannot perform this two-owner transfer. Report the blocker without fabricating an unavailable destination, widening selection or relocating data to an available owner. Verify both owners and effective inheritance afterward; reconcile affected references. A rejected cohort leaves neither side partially accepted.
|
|
37
39
|
|
|
38
40
|
External transfers require confirmed destination and write authority. Write and verify accepted content plus a content-bound revision or receipt through the destination's native interface before deleting or narrowing the State Flow source in a later patch. Recheck the source for intervening changes. Preserve it when acceptance is ambiguous. Never export secrets or broaden sensitive material without authorization.
|
|
39
41
|
|
|
@@ -41,6 +43,6 @@ External transfers require confirmed destination and write authority. Write and
|
|
|
41
43
|
|
|
42
44
|
A fresh executor must recover constraints, results, open questions, commitments, and the next action without inheriting an unapproved method. New answers persist only in Active mode with Session participating; otherwise deliver them without response backfill or shared relocation. Never rewrite selected legacy shared response as a new answer.
|
|
43
45
|
|
|
44
|
-
Patch only material changes with `
|
|
46
|
+
Patch only material changes with `state_flow_patch`, alone per assistant response; await acceptance. Plane values must be objects; nested `null` deletes an owned object key, not a stored value. Canonical `"[N]"` keys patch existing array elements; indexed deletion and out-of-bounds indices are forbidden. Replace the whole array to add/remove elements. Ordinary completion requires no finalization patch. Never edit backing files, `response`, configuration, or runtime metadata. Read changed owner paths; inspect parent keys for deletions and effective state for inheritance changes.
|
|
45
47
|
|
|
46
|
-
After rejection or interruption, inspect accepted state before bounded recovery. Report unresolved checks and partial transfers without dumping memory or implying historical erasure. Before answering, apply only material durable changes; when nothing needs changing, make no `
|
|
48
|
+
After rejection or interruption, inspect accepted state before bounded recovery. Report unresolved checks and partial transfers without dumping memory or implying historical erasure. Before answering, apply only material durable changes; when nothing needs changing, make no `state_flow_patch` call. Stop after this review, including when nothing needs changing.
|
package/docs/README.md
CHANGED
|
@@ -12,7 +12,7 @@ Start with the [project README](../README.md) for installation and the memory mo
|
|
|
12
12
|
## Integration and verification
|
|
13
13
|
|
|
14
14
|
- [Architecture](architecture.md): Semantic state, temporal history, Pi lifecycle, storage transactions, artifact acquisition and embedding APIs.
|
|
15
|
-
- [SDK compatibility](compatibility.md): Required packages, verified environments, host lifecycle requirements and isolated validation procedures.
|
|
15
|
+
- [SDK compatibility](compatibility.md): Required packages, canonical/legacy tool-name dispatch and host allowlists, verified environments, host lifecycle requirements and isolated validation procedures.
|
|
16
16
|
- [Session performance](performance.md): Run synthetic benchmarks, interpret their metrics and understand the current cost model. No provider-cache or latency guarantees.
|
|
17
17
|
- [Temporal acceptance](temporal-acceptance.md): Find the tests that witness each required property, including cancellation, ownership and replay.
|
|
18
18
|
- [Semantic handoff contract](semantic-handoff-contract.md): Current Intents / Strategy / Tactics meanings and ownership, the offline-bundle patch corpus and explicitly historical M0 preservation evidence. Deterministic acceptance is not live-model quality evidence.
|
package/docs/architecture.md
CHANGED
|
@@ -116,13 +116,15 @@ checkpoint.json + patches.jsonl
|
|
|
116
116
|
- The top-level `state` segment is rejected. Pre-origin history is unavailable rather than empty.
|
|
117
117
|
- Once enough accepted transitions are proven, offsets zero through the configured `historyLimit` stay addressable at their shared causal boundaries.
|
|
118
118
|
|
|
119
|
-
**Responses in history.** 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 creates no transition merely to replace an absent response with `""`. Ordinary completion needs no `
|
|
119
|
+
**Responses in history.** 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 creates no transition merely to replace an absent response with `""`. Ordinary completion needs no `state_flow_patch` call when durable semantic state is already correct.
|
|
120
120
|
|
|
121
121
|
## Pi lifecycle
|
|
122
122
|
|
|
123
|
-
### `
|
|
123
|
+
### `state_flow_patch` acceptance
|
|
124
124
|
|
|
125
|
-
`patch_state`
|
|
125
|
+
`state_flow_read` and `state_flow_patch` are the canonical advertised names. Explicit legacy `read_state`/`patch_state` dispatch uses the same operations with exact original native-name admission; selection/schema refresh, Off activation and the Active mutation barrier cover both spellings. Hidden legacy declarations use the SDK loadout membrane, not history rewriting or a second publication path. See [tool-name compatibility](compatibility.md#tool-name-compatibility) for host allowlists and the bounded evidence.
|
|
126
|
+
|
|
127
|
+
`state_flow_patch` is the sole mutation tool:
|
|
126
128
|
|
|
127
129
|
1. It acquires store exclusion before selecting current Global/CWD.
|
|
128
130
|
2. Preserving private Session ownership, it applies intents only, clears deleted intents' eligible same-scope strategy/tactics/lazy object-key targets protected by no final remaining/new intent (including ancestor/descendant references), then applies remaining authored planes before existing compilation/normalization. These phases ignore JSON insertion order; rewriting a cleared target creates fresh knowledge without old fields. Unowned entries remain legal.
|
|
@@ -181,7 +183,7 @@ The cache owns no persistence, publication authority or continuation scheduler,
|
|
|
181
183
|
|
|
182
184
|
**Diagnostics.** Opt-in local JSONL diagnostic categories are `invalid-patch`, `publication-conflict`, `finalization` and `barrier-block`.
|
|
183
185
|
|
|
184
|
-
- Active preflight records each blocked call when a batch has multiple `
|
|
186
|
+
- Active preflight records each blocked call when a batch has multiple `state_flow_patch` calls or a sibling of its single `state_flow_patch` call.
|
|
185
187
|
- A `barrier-block` record holds only the blocked tool name, call id, existing block reason and ordered batch tool names. It captures no sibling arguments, reasoning or draft content.
|
|
186
188
|
- Logging off creates no barrier record, and Passive has no barrier.
|
|
187
189
|
- Diagnostic persistence is outside canonical state and cannot change the blocking decision.
|
|
@@ -189,9 +191,9 @@ The cache owns no persistence, publication authority or continuation scheduler,
|
|
|
189
191
|
|
|
190
192
|
### Reads, answers and the protocol
|
|
191
193
|
|
|
192
|
-
`
|
|
194
|
+
`state_flow_read` reads one cached effective or scoped projection, at current index zero or at a retained causal index up to the configured `historyLimit`. It never publishes or advances history.
|
|
193
195
|
|
|
194
|
-
**Answers.** Before answering, the model uses `
|
|
196
|
+
**Answers.** Before answering, the model uses `state_flow_patch` 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.
|
|
195
197
|
|
|
196
198
|
- There is no terminal eligibility latch, finalization patch, repair inference or fallback budget.
|
|
197
199
|
- If required ordinary-artifact compilation prevents reconciliation, State Flow reports the failure without generating another inference. Optional Skill acquisition never blocks unrelated reconciliation.
|
|
@@ -203,7 +205,7 @@ The cache owns no persistence, publication authority or continuation scheduler,
|
|
|
203
205
|
|
|
204
206
|
```text
|
|
205
207
|
SEMANTIC STATE intents + strategy + tactics + artifacts + response + lazy
|
|
206
|
-
MUTATION BARRIER
|
|
208
|
+
MUTATION BARRIER state_flow_patch(scope patches) → rematerialized next inference
|
|
207
209
|
CONTEXT PROJECTION Active state | Passive memory/handoff | Off: no injection
|
|
208
210
|
```
|
|
209
211
|
|
|
@@ -417,7 +419,7 @@ meta.json
|
|
|
417
419
|
|
|
418
420
|
### Runtime transaction APIs
|
|
419
421
|
|
|
420
|
-
**`TemporalRuntime.withPatchTransaction`** routes `
|
|
422
|
+
**`TemporalRuntime.withPatchTransaction`** routes `state_flow_patch` through this capability.
|
|
421
423
|
|
|
422
424
|
- Its synchronous callback receives detached exact sparse scope semantics (without read defaults), their causal basis and provenance, plus one single-use `publish` operation. It cannot access selection or raw storage methods.
|
|
423
425
|
- Shared drift is adopted before staging, not used to reject a stale agent. The exact accepted private cohort stays fenced against another physical writer or unselected history.
|
|
@@ -698,7 +700,7 @@ The package exposes read-only host contracts that:
|
|
|
698
700
|
|
|
699
701
|
### Model tools
|
|
700
702
|
|
|
701
|
-
**`
|
|
703
|
+
**`state_flow_patch` grammar.** Captured WANTED participation, not the number of supplied targets or currently available owners, selects the model interface. One owner takes direct semantic planes without an owner wrapper; two/three owners take explicit participating `global`, `cwd` or `session` patches. See the [accepted interface boundary](single-scope-interface-contract.md#deterministic-m3-checkpoint); schema/selection DATA never grants source/private/publication authority.
|
|
702
704
|
|
|
703
705
|
- Each supplied canonical owner patch contains object-valued `artifacts`, `strategy`, `tactics`, `intents` and `lazy`; in one-owner model arguments these planes are top-level. Nested values are ordinary JSON.
|
|
704
706
|
- Recursive object merge updates fields, arrays/primitives replace, and nested object-key `null` deletes, including inside newly created objects. Deletion-only patches through absent ancestors create no empty parents. Accepted supplied scopes recursively omit empty object fields and empty planes: deleting the last child removes its empty ancestors, and explicit `{}` is not a retained value. Nonempty omitted fields persist; an object patch that turns a scalar/array into an empty object removes that field. Cleanup is scope-local and can reveal inherited values; it stops at the scope root and never removes array slots.
|
|
@@ -731,12 +733,12 @@ For multiple wanted owners including Session (for example Global+Session), an ex
|
|
|
731
733
|
|
|
732
734
|
Full details: [intent ownership](lazy-state.md#intent-ownership).
|
|
733
735
|
|
|
734
|
-
**Reference forms.** Semantic-state references use either the optional structured `{"$ref":"cwd.lazy.plan"}` convention, or `$` immediately followed by one valid `
|
|
736
|
+
**Reference forms.** Semantic-state references use either the optional structured `{"$ref":"cwd.lazy.plan"}` convention, or `$` immediately followed by one valid `state_flow_read` path inside ordinary text, for example `$effective.lazy.memory[7]`. The text prefix distinguishes references from incidental path-like prose and leaves a deterministic seam for possible future parsing. Resource paths, document locators, URIs, Skill identities and agent identities keep their native syntax.
|
|
735
737
|
|
|
736
738
|
- State Flow stores all forms as ordinary JSON and, apart from intent ownership, does not parse or validate targets.
|
|
737
|
-
- The agent resolves a relevant locator explicitly, through `
|
|
739
|
+
- The agent resolves a relevant locator explicitly, through `state_flow_read` or the appropriate external tool. Presence alone creates no authority, existence proof, dependency, hydration, execution or completion semantics.
|
|
738
740
|
|
|
739
|
-
**Reactive repair.** The agent never scans or resolves references merely to test them. Only after one requested value path is missing does the query domain perform one bounded reverse lookup over current model-patchable semantic planes for exact structured `$ref` or `$path` matches. When matches exist, `
|
|
741
|
+
**Reactive repair.** The agent never scans or resolves references merely to test them. Only after one requested value path is missing does the query domain perform one bounded reverse lookup over current model-patchable semantic planes for exact structured `$ref` or `$path` matches. When matches exist, `state_flow_read` returns the explicit diagnostic sentinel `{value:null, hint:[{type:"dangling-reference", message, paths}]}`:
|
|
740
742
|
|
|
741
743
|
- `hint` is a top-level sibling, not state data. Its message describes unavailability conditionally.
|
|
742
744
|
- `paths` contains at most three runtime-verified current reference-owner addresses, not verified new locations of the requested data.
|
|
@@ -746,7 +748,7 @@ Full details: [intent ownership](lazy-state.md#intent-ownership).
|
|
|
746
748
|
|
|
747
749
|
**History is task-driven.** Missing paths or hints alone do not require historical search. The agent may independently choose targeted historical reading when a previous value is useful to the current task; no separate user permission is required. Historical values are evidence, not automatically current state or a reason to restore deleted memory. Runtime never scans history for reference owners, triggers repair inference or hydrates lazy bodies. Effective absence does not establish ownership, and unavailable history, external inaccessibility or a transient read failure does not prove a broken reference.
|
|
748
750
|
|
|
749
|
-
**`
|
|
751
|
+
**`state_flow_read` addressing.** It accepts exactly one of scalar `path` or ordered semantic `paths`, with `value`, `keys` or `patch` projection; batches stay all-or-error. One wanted owner's ordinary flat paths bind that owner; multi-owner flat paths use the effective overlay, even when the available view has only one owner.
|
|
750
752
|
|
|
751
753
|
- Explicit owner roots/examples below require that owner to participate and its requested current/historical authority to be available. Selection or an address alone does not acquire missing private memory.
|
|
752
754
|
- `effective == effective[0]` is the current effective materialization; `global == global[0]` (and the CWD/session equivalents) selects that scope at the same composed causal boundary.
|
|
@@ -802,7 +804,7 @@ Current same-owner structured refs can render flat for one owner while storage r
|
|
|
802
804
|
- Optional `mode` overrides the new-session default without changing retained session policy.
|
|
803
805
|
- `onRuntime` receives a cached `read(offset?, scope?)` accessor; an omitted scope means effective state. Use it only after runtime initialization/restoration.
|
|
804
806
|
|
|
805
|
-
The pure `readTemporalState(view, offset, scope?)` accessor is exported separately. SDK hosts with an explicit tool allowlist must include both `
|
|
807
|
+
The pure `readTemporalState(view, offset, scope?)` accessor is exported separately. SDK hosts with an explicit tool allowlist must include both `state_flow_patch` and `state_flow_read` when they want model access.
|
|
806
808
|
|
|
807
809
|
**Shutdown.** Honor Pi's `session_shutdown` lifecycle before disposing an embedded session.
|
|
808
810
|
|
package/docs/compatibility.md
CHANGED
|
@@ -14,6 +14,16 @@ State Flow requires matching `pi-coding-agent`, `pi-agent-core`, `pi-ai` and `pi
|
|
|
14
14
|
|
|
15
15
|
Detailed behavioral witnesses live in [temporal acceptance](temporal-acceptance.md); benchmark methodology and source-bound results live in [performance](performance.md).
|
|
16
16
|
|
|
17
|
+
## Tool-name compatibility
|
|
18
|
+
|
|
19
|
+
Since 0.27.6 the advertised tools are `state_flow_read` and `state_flow_patch`. Explicit legacy `read_state`/`patch_state` calls dispatch through the same read/patch implementation with their exact native call name and ID; historical calls are not rewritten. Legacy declarations are hidden through the public SDK `prepareLoadout` membrane while remaining active for dispatch. This is tool-name compatibility only: no old semantic fields, wrapper grammar, storage formats or conversion rules are reinstated.
|
|
20
|
+
|
|
21
|
+
- Active and Passive activate both spellings; Off removes both and retained wrappers still reject. Only canonical names contribute prompt guidance and provider declarations.
|
|
22
|
+
- Selected-owner/schema refresh applies to both mutation spellings. A schema is not an owner receipt; stale, foreign, consumed or unbound native calls still reject before publication.
|
|
23
|
+
- Active counts both mutation spellings as one barrier family: multiple calls, including mixed names, all reject; siblings of a single mutation are blocked. Nested Active mutation rejects under either name. Passive keeps its existing explicit-parent nested-call behavior and no new inference barrier.
|
|
24
|
+
- An SDK host's explicit allowlist remains authoritative. Include `state_flow_read` and `state_flow_patch` for new requests, plus `read_state` and `patch_state` when legacy calls must dispatch. State Flow does not widen a host allowlist or rewrite native history to compensate.
|
|
25
|
+
- Extension/native-request tests and real source/packed SDK witnesses cover name equivalence, retained reads, no-op history, scope-schema refresh, refusal, nested calls, mixed-name barriers and Off. These are deterministic isolated checks, not installed-client rollout or live-model certification.
|
|
26
|
+
|
|
17
27
|
## Canonical scope format admission
|
|
18
28
|
|
|
19
29
|
Core-only canonical scope metadata remains **version 3**, with `strategy` and `tactics` fields. The implemented **version 4** codec additionally retains external object-plane descriptors and opaque values independently of loaded definitions; absent internal `modules` metadata keeps existing v3 output. Declared legacy versions **1/2** translate before known-field filtering. Target-format `contract`/`working` roots reject; nested domain keys remain ordinary JSON. Unsupported versions fail closed. These scope versions are distinct from selection-aware Session lifecycle v2 and public module API v1; supported legacy lifecycle-v1 admission retains its complete-cohort proof requirements. External-root tools, captured Active/Passive context and Active producers shipped in 0.27.0; see the [public module boundary](public-module-contract.md).
|
|
@@ -135,6 +135,6 @@ Every semantic repair follows the ordinary transaction path:
|
|
|
135
135
|
|
|
136
136
|
**A wholly absent shared scope is current empty reality**, not permission to restore cached cold values or leftover compilation evidence.
|
|
137
137
|
|
|
138
|
-
- Authored `
|
|
138
|
+
- Authored `state_flow_patch` operations select this basis under the awaited store lock and publish only after complete validation. A rejected first patch never leaves separately published empty initialization.
|
|
139
139
|
- Raw precomputed replay targeting a disappeared selected basis still fails closed.
|
|
140
140
|
- Discarded history is unavailable and is never reconstructed or promoted back into current shared memory.
|
package/docs/lazy-state.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Lazy state through progressive `
|
|
1
|
+
# Lazy state through progressive `state_flow_read`
|
|
2
2
|
|
|
3
3
|
This document describes the implemented lazy-state contract. [BACKLOG.md](../BACKLOG.md) owns release readiness; [temporal acceptance](temporal-acceptance.md) maps behavior to executable evidence.
|
|
4
4
|
|
|
@@ -11,9 +11,9 @@ State Flow supports the optional object-root `lazy` plane in every participating
|
|
|
11
11
|
|
|
12
12
|
The model-facing surface remains small:
|
|
13
13
|
|
|
14
|
-
- `
|
|
14
|
+
- `state_flow_read` reads one path or an ordered list of paths using one explicit projection.
|
|
15
15
|
- `value` and `patch` return only the requested semantic snapshot or patch; `keys` returns narrowly bounded structural `meta` followed by `keys`.
|
|
16
|
-
- `
|
|
16
|
+
- `state_flow_patch` remains a recursive semantic patch, not an edit-command language.
|
|
17
17
|
- Array index selectors extend ordinary patch addressing; there are no `insert`, `remove`, `move`, or generalized query operations.
|
|
18
18
|
|
|
19
19
|
> Retention is not activation. Hot state carries what must matter now; lazy state preserves what may matter later; an explicit read activates only the current trajectory.
|
|
@@ -59,7 +59,7 @@ Hot planes:
|
|
|
59
59
|
|
|
60
60
|
- It is canonical semantic JSON, validated and versioned with its owning scope.
|
|
61
61
|
- Its bodies are excluded from automatic state and recent-transition projections, including lazy writes, replacements and deletions. Empty visible patches/transitions disappear without renumbering history; hot changes remain visible.
|
|
62
|
-
- Bounded baseline navigation exposes presence, path and structure without bodies. Explicit current/historical `
|
|
62
|
+
- Bounded baseline navigation exposes presence, path and structure without bodies. Explicit current/historical `state_flow_read` values and patches may contain lazy bodies; already communicated native/user/tool/response text is not redacted.
|
|
63
63
|
- Reading it does not mutate state, freshness, usage metadata, history, or future context.
|
|
64
64
|
|
|
65
65
|
### Semantic references
|
|
@@ -67,7 +67,7 @@ Hot planes:
|
|
|
67
67
|
A reference is semantic content, not a runtime type. There are two forms:
|
|
68
68
|
|
|
69
69
|
- **Structured:** the optional `{"$ref":"cwd.lazy.plan"}` object.
|
|
70
|
-
- **Textual:** inside any ordinary string or paragraph, `$` immediately followed by one valid `
|
|
70
|
+
- **Textual:** inside any ordinary string or paragraph, `$` immediately followed by one valid `state_flow_read` path, for example `$effective.lazy.memory[7]`. The prefix separates a deliberate reference from incidental path-like text, and leaves a deterministic seam if code-based parsing is ever justified.
|
|
71
71
|
|
|
72
72
|
File paths, document sections, URIs, artifact locators, Skill identities and agent identities keep their native syntax.
|
|
73
73
|
|
|
@@ -75,9 +75,9 @@ File paths, document sections, URIs, artifact locators, Skill identities and age
|
|
|
75
75
|
|
|
76
76
|
This translation does not scan prose, index targets, validate existence, or infer authority, hydration, execution or completion. The separate [intent ownership](#intent-ownership) rule gives eligible canonical refs their bounded cleanup meaning.
|
|
77
77
|
|
|
78
|
-
When a reference matters, the agent resolves it explicitly: with `
|
|
78
|
+
When a reference matters, the agent resolves it explicitly: with `state_flow_read` for semantic paths, or with the appropriate external read/tool for other resources. A locator helps retrieval but does not replace content required for the current decision.
|
|
79
79
|
|
|
80
|
-
**Reference repair is reactive, not a maintenance scan.** The agent does not enumerate, audit or resolve references merely to test them. Only after one requested `
|
|
80
|
+
**Reference repair is reactive, not a maintenance scan.** The agent does not enumerate, audit or resolve references merely to test them. Only after one requested `state_flow_read` value path is missing does State Flow perform one bounded reverse lookup over current model-patchable semantic planes for exact structured `$ref` and `$path` matches. The reverse lookup searches current reference owners only, never history. If it finds matches, the tool returns `{value:null, hint:[{type:"dangling-reference", message, paths}]}`:
|
|
81
81
|
|
|
82
82
|
- `hint` is explicit top-level metadata, not state data. Its conditional message describes unavailability.
|
|
83
83
|
- Its path array contains at most three runtime-verified current reference owners, not verified new locations of the target.
|
|
@@ -136,7 +136,7 @@ Ownership evaluates canonical references after model anchoring. A sole-CWD model
|
|
|
136
136
|
- `artifacts`/`response`/`intents` targets;
|
|
137
137
|
- paths still unscoped in canonical data, or `effective` paths;
|
|
138
138
|
- missing targets;
|
|
139
|
-
- keys outside the `
|
|
139
|
+
- keys outside the `state_flow_read` key grammar `[A-Za-z_$][A-Za-z0-9_$-]*`, for example keys with spaces, dots or non-Latin letters.
|
|
140
140
|
|
|
141
141
|
**Receipt.** `state_updates.cascaded` lists targets cleared in the intermediate ownership phase, even if later authored writes recreate them. With multiple wanted owners paths stay scoped, for example `["session.lazy.plans.x", "session.tactics.draft"]`; with exactly one wanted owner they are relative, for example `["lazy.plans.x", "tactics.draft"]`. Canonical ownership and result details remain scoped. Paths only, never lazy bodies or deleted values. The list is deterministic (Global, CWD, Session, then each scope's cascade order), absent when no target cascaded, and never omitted as a predictable write. Nested lazy deletions are reported even when the top-level `lazy_navigation` catalog is unchanged.
|
|
142
142
|
|
|
@@ -155,11 +155,11 @@ Explicit paths such as `global.lazy`, `cwd.lazy`, and `session.lazy` preserve di
|
|
|
155
155
|
|
|
156
156
|
Active obligations, current constraints, unresolved next actions, and facts required for the next correct action remain hot.
|
|
157
157
|
|
|
158
|
-
## Progressive `
|
|
158
|
+
## Progressive `state_flow_read`
|
|
159
159
|
|
|
160
160
|
### Request shape
|
|
161
161
|
|
|
162
|
-
`
|
|
162
|
+
`state_flow_read` accepts either one path or an ordered path list:
|
|
163
163
|
|
|
164
164
|
```json
|
|
165
165
|
{
|
|
@@ -434,9 +434,9 @@ It may identify:
|
|
|
434
434
|
|
|
435
435
|
- Whether effective lazy state exists.
|
|
436
436
|
- Its immediate top-level keys and kinds.
|
|
437
|
-
- The exact `
|
|
437
|
+
- The exact `state_flow_read` path for deeper inspection.
|
|
438
438
|
|
|
439
|
-
The hint is emitted as `lazy_navigation` with `available` and the exact root `path`. For an object root it includes the complete immediate `keys` → child-kind map only when there are at most 32 keys and its canonical JSON is at most 1,024 characters. Otherwise it omits `keys` entirely rather than presenting a partial catalog. This keeps the hint bounded while `
|
|
439
|
+
The hint is emitted as `lazy_navigation` with `available` and the exact root `path`. For an object root it includes the complete immediate `keys` → child-kind map only when there are at most 32 keys and its canonical JSON is at most 1,024 characters. Otherwise it omits `keys` entirely rather than presenting a partial catalog. This keeps the hint bounded while `state_flow_read` itself returns every explicitly requested value or key set; omission from the hint never makes lazy state unreachable.
|
|
440
440
|
|
|
441
441
|
## Activation and promotion
|
|
442
442
|
|
|
@@ -447,16 +447,16 @@ A lazy read enriches only the current tool-result trajectory. It does not:
|
|
|
447
447
|
- Become authoritative merely because it was retrieved.
|
|
448
448
|
- Update semantic freshness, usage counters, or history.
|
|
449
449
|
|
|
450
|
-
When a retrieved fact becomes necessary for future correctness, the agent promotes a distilled consequence through an ordinary hot `
|
|
450
|
+
When a retrieved fact becomes necessary for future correctness, the agent promotes a distilled consequence through an ordinary hot `state_flow_patch` mutation:
|
|
451
451
|
|
|
452
452
|
- Durable requirement or decision → `strategy`.
|
|
453
453
|
- Current fact, uncertainty, or continuation → `tactics`.
|
|
454
454
|
- Source-addressed reusable compilation → `artifacts`.
|
|
455
455
|
- Historical support with no current consequence → remain under `lazy`.
|
|
456
456
|
|
|
457
|
-
## `
|
|
457
|
+
## `state_flow_patch` and arrays
|
|
458
458
|
|
|
459
|
-
`
|
|
459
|
+
`state_flow_patch` remains the sole semantic mutation and publication barrier. There is no `edits` array and no operation vocabulary such as `replace`, `insert`, `remove`, or `move`.
|
|
460
460
|
|
|
461
461
|
Existing recursive semantics continue:
|
|
462
462
|
|
|
@@ -484,7 +484,7 @@ Normative index behavior:
|
|
|
484
484
|
|
|
485
485
|
- `"[N]"` addresses an existing zero-based element of the retained array.
|
|
486
486
|
- Every addressed index must exist against the one captured publication basis.
|
|
487
|
-
- If any index is invalid, the entire `
|
|
487
|
+
- If any index is invalid, the entire `state_flow_patch` call fails and publishes nothing.
|
|
488
488
|
- An indexed scalar or array value is replaced.
|
|
489
489
|
- An indexed object receives the ordinary recursive object patch; the materialized element is the resulting replacement value at that index.
|
|
490
490
|
- Multiple indexed and object changes in one call share one validation and one lock/CAS publication cohort.
|
|
@@ -566,7 +566,7 @@ Before release, implementation evidence must prove:
|
|
|
566
566
|
- Whole-array replacement and indexed scalar, array, object, nested, multi-index, and stale-basis patches remain atomic.
|
|
567
567
|
- Reload/resume/tree attach current lazy state with the rest of the owning scope; a supported fork copies parent-current lazy content only when private acquisition is admitted. Historical reads select the same retained causal boundary as other planes.
|
|
568
568
|
- Malformed canonical lazy data fails closed without rewriting the store; rejected queries and patches preserve accepted hot state.
|
|
569
|
-
- Unsupported store formats and `
|
|
569
|
+
- Unsupported store formats and `state_flow_read` inputs fail actionably without rewriting retained bytes.
|
|
570
570
|
|
|
571
571
|
## Limits and change authority
|
|
572
572
|
|
|
@@ -42,7 +42,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
42
42
|
}
|
|
43
43
|
```
|
|
44
44
|
|
|
45
|
-
With this companion registered, a sole participating owner can persist `{"x_acme_notes":{"entries":["accepted"]}}` through `
|
|
45
|
+
With this companion registered, a sole participating owner can persist `{"x_acme_notes":{"entries":["accepted"]}}` through `state_flow_patch` and read `x_acme_notes` through `state_flow_read`. Multiple participating owners retain explicit scope wrappers. The context callback executes on admitted Active/Passive provider contexts; its data is transported as fallible user-level data, not system instructions. Pi 1.0.0 uses `session_shutdown`, not `shutdown`.
|
|
46
46
|
|
|
47
47
|
Registration returns an idempotent disposer for that exact instance. It cannot revoke a later equal-ID registration or another host generation. Catalog changes abort old catalog signals; host retirement removes only its own binding before signaling cancellation. Snapshots capture immutable policy, callback identities and definition order. Constructor-injected services remain bound to their original instance. Trusted callbacks are not an effects sandbox, and a catalog snapshot alone is not publication authority.
|
|
48
48
|
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
## Status and baseline
|
|
4
4
|
|
|
5
|
+
**Tool names since 0.27.6:** Advertise `state_flow_read`/`state_flow_patch`, retaining explicit legacy `read_state`/`patch_state` dispatch as the same owned operations. The original request, selection, nested refusal and mixed-name barrier requirements apply to either spelling; see [tool-name compatibility](compatibility.md#tool-name-compatibility). Historical checkpoints below retain their original tool names and evidence.
|
|
6
|
+
|
|
5
7
|
**All seven nonempty selections and public command/completion controls shipped in 0.27.0.** The [M2 functional boundary](#m2-functional-acceptance-boundary) records bounded deterministic acceptance, including captured policy, private acquisition, Session-excluded response suppression, deferred forks and mode-only Telegram controls. The [flat model interface](single-scope-interface-contract.md) also shipped in 0.27.0; it does not change these scope/private authorities. No settings chooser is required. [BACKLOG.md](../BACKLOG.md) owns outstanding work.
|
|
6
8
|
|
|
7
9
|
This document owns selected-scope policy and its authority boundaries; [usage](usage.md) owns operator syntax/configuration. The proposals, candidate gates and validation totals in implementation-checkpoint sections below are historical at their named M0/M2 source boundaries. Later retained integration superseded their all-three-only, pending-selector and deferred-copy implementation limits, not their preservation duties or original review verdicts. They are not current prerequisites.
|
|
@@ -20,7 +20,7 @@ interface SemanticModule<Content extends JsonValue, Input = undefined> {
|
|
|
20
20
|
}
|
|
21
21
|
```
|
|
22
22
|
|
|
23
|
-
- **`immutable`:** The main agent cannot author that bound plane through `
|
|
23
|
+
- **`immutable`:** The main agent cannot author that bound plane through `state_flow_patch`. An independently authorized runtime/producer may still propose replacements. This is not frozen historical content or a flag that a model can toggle in its payload. Current bindings freeze the declaration; ordinary domain keys named `immutable` or `content` do not become policy.
|
|
24
24
|
- **`id`:** Stable identity for static host binding and diagnostics. It neither reserves a root nor grants native/source/private authority.
|
|
25
25
|
- **`validate`:** Admit present module content and producer candidates. Absence stays absent; no defaults are invented. Observation and canonical acceptance are distinct: artifact projection admits retained legacy bookkeeping as an ordinary object, while canonical artifact validation remains in the existing artifact/state/transition owners.
|
|
26
26
|
- **`context`:** Synchronous, mode-aware computation from captured data. An empty array contributes nothing. It may return multiple data/conversation contributions; it does not run a publisher or edit native history.
|
|
@@ -8,7 +8,7 @@ The task is to remove mandatory scope knowledge from ordinary single-owner model
|
|
|
8
8
|
|
|
9
9
|
## Schema decision
|
|
10
10
|
|
|
11
|
-
Choose **same-name declaration replacement at captured policy arity changes**, using the installed SDK's `registerTool` refresh path.
|
|
11
|
+
Choose **same-name declaration replacement at captured policy arity changes**, using the installed SDK's `registerTool` refresh path. Advertise only the two canonical names, `state_flow_read` and `state_flow_patch`. Since 0.27.6, the explicitly authorized [tool-name compatibility path](compatibility.md#tool-name-compatibility) also retains hidden legacy dispatch; it supersedes the earlier two-registered-names-only policy without changing this schema/owner boundary. Cache the applicable flat-versus-multi interface shape; do not register per inference, ordinary patch, mode-only toggle or same-arity owner change. No new registry, holder, epoch, provider framework or parallel API is earned.
|
|
12
12
|
|
|
13
13
|
This is a refinement of the preferred stable disjoint grammar based on an actual serializer constraint, not an assumption that a union is unsupported everywhere. OpenAI Responses and Google preserve the tested alternatives. Ordinary non-strict Anthropic serialization in the pinned stack does not preserve root exclusivity; a top-level object-union loses its field vocabulary altogether. Shape-specific flat/scoped objects preserve the applicable advertised family across all three adapters. They **do not** magically restore root closure/nonempty constraints where the adapter discards those, so native validation and runtime admission remain authoritative.
|
|
14
14
|
|