@llblab/pi-state-flow 0.27.5 → 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 +5 -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/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 +16 -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/package.json +1 -1
- package/skills/state-flow-guide/SKILL.md +8 -6
- package/skills/state-flow-memory/SKILL.md +8 -6
package/docs/usage.md
CHANGED
|
@@ -8,13 +8,13 @@ For the concept and installation, start with the [README](../README.md). This gu
|
|
|
8
8
|
|
|
9
9
|
State Flow has three distinct model-facing states. **Active versus passive changes the agent's workflow, not the existence of disk memory.**
|
|
10
10
|
|
|
11
|
-
- **Active:** Both `
|
|
11
|
+
- **Active:** Both `state_flow_read` and `state_flow_patch` are available, subject to host restrictions and valid memory authority.
|
|
12
12
|
- Prompts require the agent to consolidate future-relevant results into state before ending an iteration.
|
|
13
13
|
- The final meaningful semantic patch preserves the decisions, outcomes and continuation needed once the completed conversation leaves model projection.
|
|
14
14
|
- The next iteration starts from accepted state and its new input, not from the previous iteration's completed reasoning.
|
|
15
15
|
- The native trace stays inspectable: a clean model context does not mean deleting Pi history.
|
|
16
16
|
- **Passive:** Both memory tools are available, existing state except the `response` plane is projected into context, and the agent may read or patch memory as useful.
|
|
17
|
-
- The last Active answer is not repeated in automatic memory context, Stop handoffs or state updates. Its stored value and explicit `
|
|
17
|
+
- The last Active answer is not repeated in automatic memory context, Stop handoffs or state updates. Its stored value and explicit `state_flow_read` access remain intact; native/user/tool history is not redacted.
|
|
18
18
|
- Ordinary conversation continuity remains: there is no active iteration-ending context reset and no mandatory consolidation pressure.
|
|
19
19
|
- Accepted patches still reach the same canonical store, with the same validation and ownership guarantees.
|
|
20
20
|
- **Off:** Neither memory tool is exposed to the model, and State Flow injects no protocol, bootstrap/state context or frozen passive handoff. Stored memory and the native conversation trace are not deleted.
|
|
@@ -23,11 +23,11 @@ One session-owned `mode` selects these behaviors; there are no separate passive-
|
|
|
23
23
|
|
|
24
24
|
**Completion is semantic, not ceremonial.** In active mode, necessary final state changes must be accepted before relying on state-only continuation. That does not require:
|
|
25
25
|
|
|
26
|
-
- an empty `
|
|
26
|
+
- an empty `state_flow_patch` when memory is already current;
|
|
27
27
|
- an extra model turn;
|
|
28
28
|
- a special finalization tool.
|
|
29
29
|
|
|
30
|
-
In Active mode, `
|
|
30
|
+
In Active mode, `state_flow_patch` is an inference barrier, not automatically the end of an iteration; Passive has no such barrier. The runtime separately completes the run and captures the accepted ordinary answer only in Active participating Session. With Session excluded, completion is lifecycle-only unless another semantic change is accepted; no answer is backfilled or relocated.
|
|
31
31
|
|
|
32
32
|
**Two meanings of “bootstrap”:**
|
|
33
33
|
|
|
@@ -161,7 +161,7 @@ The canonical store is `state-flow/` beneath the agent directory. Keeping config
|
|
|
161
161
|
- Off exposes neither memory tools nor State Flow context.
|
|
162
162
|
- `scopes`: Missing means `global`, `cwd`, `session`. Any of the seven nonempty unique subsets is supported; order is canonicalized without rewriting the file. For example, `"scopes": ["cwd"]` selects project-only memory. The default is captured once for a new or not-yet-captured legacy branch; an existing choice survives reload, tree navigation and later default edits, and forks inherit their parent branch's choice. Mode-only commands/Telegram actions preserve it. Use explicit owner tokens on an existing mode command to change only the current branch's choice; a settings chooser is not required. Never edit accepted lifecycle files to select scopes. Disabled owners cannot be read/patched as model memory or relocated into another owner. Without Session, native answers are delivered but not stored/backfilled; a fork defers private acquisition rather than creating a hidden Session stream. See [native seven-selection integration](scope-selection-contract.md#retained-native-seven-selection-integration) and the [capture boundary](scope-selection-contract.md#configured-scope-defaults-and-native-capture).
|
|
163
163
|
- `logging`: Defaults to `false`. When enabled, rejected patch executions, active barrier blocks, preparation failures and accepted-answer reconciliation failures are recorded locally at `tmp/pi-state-flow/logs.jsonl` beneath the agent directory. Older `tmp/state-flow` logs are left untouched and are not migrated. Asynchronous Git push failures are recorded there even when this setting is off.
|
|
164
|
-
- `showSuccessfulPatches`: Defaults to `true`. In interactive Pi, `
|
|
164
|
+
- `showSuccessfulPatches`: Defaults to `true`. In interactive Pi, `state_flow_patch` rows show pretty-printed JSON arguments once in the call, with blank lines between adjacent memory sections; the result shows the acceptance or no-op acknowledgement, never a second patch. Set it to `false` to hide call arguments and keep the compact acknowledgement. Rejected calls retain their arguments and error acknowledgement; State Flow adds no private validation turn.
|
|
165
165
|
- `historyLimit`: Defaults to `7` and accepts integers from `0` through `100`. It counts accepted semantic transitions, **not elapsed time or conversation length**, and bounds materialized-history and scope patch-history offsets.
|
|
166
166
|
- Lowering it on reload/restore/fork folds excess tails forward without losing current state; selected boundaries outside the new window become unavailable.
|
|
167
167
|
- Zero keeps only current checkpoints.
|
|
@@ -171,7 +171,7 @@ The canonical store is `state-flow/` beneath the agent directory. Keeping config
|
|
|
171
171
|
|
|
172
172
|
- Before canonical runtime acceptance, an owner-bound native v2 policy record captures `{mode, scopes}` instead of a manufactured storage pair or accepted semantic boundary. A captured branch/fork choice survives later global-default edits.
|
|
173
173
|
- Off stays native-only even after an accepted runtime: its mode/bookmark overrides the earlier canonical mode without needing store access or granting semantic authority.
|
|
174
|
-
- Edit global defaults manually or through an authorized agent, not through `
|
|
174
|
+
- Edit global defaults manually or through an authorized agent, not through `state_flow_patch`.
|
|
175
175
|
- Legacy flag decoding is read-only; see [mode compatibility](compatibility.md#mode-configuration-compatibility).
|
|
176
176
|
|
|
177
177
|
**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 surfaces. With unavailable memory the tools may still reject reads or writes: declared tools do not prove usable storage.
|
|
@@ -184,7 +184,7 @@ The canonical store is `state-flow/` beneath the agent directory. Keeping config
|
|
|
184
184
|
|
|
185
185
|
**What gets recorded:**
|
|
186
186
|
|
|
187
|
-
- Rejected `
|
|
187
|
+
- Rejected `state_flow_patch` executions may include the exact attempted arguments and useful draft text, plus the error category and tool/call identity.
|
|
188
188
|
- The `barrier-block` category records only the blocked tool name, call id, reason and batch tool names, never sibling arguments or reasoning. Passive has no patch barrier, and with logging off no barrier blocks are recorded.
|
|
189
189
|
- Asynchronous push failures keep the available redacted Git error in the log regardless of `logging`. Interactive warnings stay short, appear once per failure streak and reset on success. If logging the push failure is unavailable, one warning shows the available detail instead.
|
|
190
190
|
- Successful patches are not logged, and reasoning bodies are excluded.
|
|
@@ -208,7 +208,7 @@ Treat logs and state files as private. Removing a secret from current state does
|
|
|
208
208
|
- Captured selected owners and, when different, available materialized owners; their known keys, local run step, exact available owner-revision vector and hot-history depth. Unavailable owners receive no fabricated value or zero revision.
|
|
209
209
|
- Known recovery or publication failures, actual artifact counts when nonzero, and pending invalidations. Status does not discover or validate sources.
|
|
210
210
|
- A `Scope memory:` block with one line per scope that has content: the UTF-8 byte size of each present nonempty plane and, when `tactics` or `lazy` has top-level entries, the share owned by an open intent of that scope (for example `- cwd: intents 137 B, tactics 32 B; intent-owned tactics 1/2`). It is operator-only: no notice, threshold or model-facing effect.
|
|
211
|
-
- One JSON representation of available selected memory in relative global → CWD → session order, with a blank line between top-level semantic planes. Nested JSON is unchanged; individual scope JSON remains available through `
|
|
211
|
+
- One JSON representation of available selected memory in relative global → CWD → session order, with a blank line between top-level semantic planes. Nested JSON is unchanged; individual scope JSON remains available through `state_flow_read`.
|
|
212
212
|
|
|
213
213
|
Status reports the selected mode and any Active restoration inference fence, while omitting 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.
|
|
214
214
|
|
|
@@ -243,7 +243,7 @@ When `pi-telegram` is available, its main-menu section shows `State Flow: active
|
|
|
243
243
|
**Memory inspection:**
|
|
244
244
|
|
|
245
245
|
- Owner-scope Rich snapshots show `#revision`; Effective shows the vector.
|
|
246
|
-
- Fields show pretty-printed JSON directly. Large fields show a bounded JSON prefix with a separate truncation notice and omitted-character count, not a JSON-encoded `preview` string. The preview may end mid-value; actual escapes inside JSON string values remain intact. These presentation limits never truncate stored memory or successful `
|
|
246
|
+
- Fields show pretty-printed JSON directly. Large fields show a bounded JSON prefix with a separate truncation notice and omitted-character count, not a JSON-encoded `preview` string. The preview may end mid-value; actual escapes inside JSON string values remain intact. These presentation limits never truncate stored memory or successful `state_flow_read` results.
|
|
247
247
|
- A failed-Passive write fence does not grant repair or cached fallback: explicit operator inspection still validates current canonical memory through a disposable reader. Peer-accepted current values remain observable without clearing the fence or installing a model cache.
|
|
248
248
|
- Inspection waits cancelably for its required current authority, even when model tools are disabled. It does not initialize, publish or advance storage.
|
|
249
249
|
- Data and displayed revisions come from the same observation; absent or invalid memory stays unavailable.
|
|
@@ -284,11 +284,11 @@ See the [storage contract](architecture.md#storage-and-identity) for the exact l
|
|
|
284
284
|
|
|
285
285
|
- Current and historical semantic views include only known fields present in the selected scope or overlay; absent fields and empty responses are omitted. Higher scopes contribute only present values.
|
|
286
286
|
- Built-in fields and metadata v4-declared external roots are known semantic content. Declared external values/history survive missing or incompatible definitions; unrelated unknown roots remain outside the supported semantic view. Retired target-format roots explicitly reject rather than being silently ignored. Nested data within admitted planes stays intact.
|
|
287
|
-
- An explicit `
|
|
287
|
+
- An explicit `state_flow_read` value query for an absent documented top-level field returns `null`, including an empty or absent `session.response`.
|
|
288
288
|
- Read-only inspection never normalizes or converts files. Start does not fill missing planes or create a semantic revision merely for normalization; independently authorized acceptance may perform the supported backed-up format conversion described below.
|
|
289
289
|
- An empty semantic object is different from a missing file or missing ownership metadata.
|
|
290
290
|
|
|
291
|
-
**Wholly absent shared files.** A checkpoint and its tail are one semantic pair. If both live files of a global or CWD scope disappear, State Flow treats that complete absence as current empty shared reality. An authored `
|
|
291
|
+
**Wholly absent shared files.** A checkpoint and its tail are one semantic pair. If both live files of a global or CWD scope disappear, State Flow treats that complete absence as current empty shared reality. An authored `state_flow_patch` applies to that empty basis under exclusion, and normal file-cohort CAS creates the accepted pair without resurrecting cold values or orphaned compilation evidence. Raw precomputed replay still refuses a removed selected target rather than replaying stale normalized changes.
|
|
292
292
|
|
|
293
293
|
**Corruption fails closed.** These are never replaced:
|
|
294
294
|
|
|
@@ -303,7 +303,7 @@ Memory never depends on the Pi step, so an old or expired branch checkpoint is n
|
|
|
303
303
|
|
|
304
304
|
- Under Active, the selected mode remains Active and the indicator shows `active (blocked)`. Live inference is aborted before the provider instead of silently sending native history under an inactive fallback. Reload/resume retains this fence. Repair the files and choose Active/Passive; explicit Off permits native context without reading memory. Signal-less inspection remains observational.
|
|
305
305
|
- Global/CWD memory stays readable; the unavailable session layer is never replaced by an empty one.
|
|
306
|
-
- Session reads and every `
|
|
306
|
+
- Session reads and every `state_flow_patch` refuse without changing canonical files or appending substitute checkpoints.
|
|
307
307
|
- **Modes are stable.** Explicit Passive accepts validated current same-session memory exactly like Active, keeping Passive policy. Only while current memory is still unreadable or unpublishable does Passive keep native inference with paused writes and report the cause. Off records native policy only.
|
|
308
308
|
- Status distinguishes a write fence from unavailable materialization.
|
|
309
309
|
|
|
@@ -327,7 +327,7 @@ See the complete [filesystem recovery contract](filesystem-recovery.md).
|
|
|
327
327
|
|
|
328
328
|
### Canonical files and optional Git backup
|
|
329
329
|
|
|
330
|
-
Canonical scope/runtime files own the current materialization and retained hot history, whether or not Git is available. Pi checkpoints record mode and run lifecycle for a branch, not a Git commit or a memory revision to rewind to. Restart and branch navigation always attach the current files; historical states remain available only through explicit `
|
|
330
|
+
Canonical scope/runtime files own the current materialization and retained hot history, whether or not Git is available. Pi checkpoints record mode and run lifecycle for a branch, not a Git commit or a memory revision to rewind to. Restart and branch navigation always attach the current files; historical states remain available only through explicit `state_flow_read` offsets within retained history.
|
|
331
331
|
|
|
332
332
|
**Local backup commit:**
|
|
333
333
|
|
|
@@ -362,7 +362,7 @@ Commit or push failure is diagnostic-only; repeated push failures warn once per
|
|
|
362
362
|
|
|
363
363
|
### Conflicts and interrupted publication
|
|
364
364
|
|
|
365
|
-
**Patches.** `
|
|
365
|
+
**Patches.** `state_flow_patch` waits asynchronously for a live cooperating writer, with native cancellation and no ordinary-contention deadline. It then applies authored Global/CWD operations to the current canonical values:
|
|
366
366
|
|
|
367
367
|
- Unmentioned fields survive.
|
|
368
368
|
- Overlapping assignments follow successful acceptance order.
|
|
@@ -397,9 +397,9 @@ No automatic crash repair or power-loss durability is promised, and Git backup h
|
|
|
397
397
|
|
|
398
398
|
## Lazy navigation and historical reading
|
|
399
399
|
|
|
400
|
-
With exactly one captured participating owner, `
|
|
400
|
+
With exactly one captured participating owner, `state_flow_read` needs no scope token: `lazy.releasePlan` reads current data, `effective[3].lazy.releasePlan` selects its retained older boundary, and a scalar `patches[0]` reads its latest retained owner patch. Ordinary `lazy.items[3]` still indexes an array. Optional explicit selected-owner paths remain legal. With multiple wanted owners, ordinary flat paths use the effective overlay and owner patch history requires `owner.patches[N]`; sparse available memory does not turn a multi-owner choice into one-owner mode. Unavailable history/owners still fail rather than returning invented empty data.
|
|
401
401
|
|
|
402
|
-
Returned current same-owner structured refs may be scope-free; persisted refs retain canonical ownership. For one wanted owner, `
|
|
402
|
+
Returned current same-owner structured refs may be scope-free; persisted refs retain canonical ownership. For one wanted owner, `state_flow_patch` now takes planes directly (for example `{ "tactics": { "ready": true } }`) and anchors eligible refs after native admission; do not add an owner wrapper. For multiple wanted owners, keep explicit participating owner patches in one atomic call. Canonical ownership/replay never become scope-free, and changing schema cannot admit an old call under a new owner. Single-owner Active/Passive/bootstrap instructions and packaged Skills use that same grammar. Active/Passive heads and projection-bound updates now render eligible same-owner current refs relatively; the lazy catalog points to `lazy` for one WANTED owner and `effective.lazy` for several. Active recent context uses `{id,at,patch}` for one owner and explicit `transitions` for several, retaining IDs/positions while omitting lazy bodies. These are read-only context DTOs, not patch arguments or storage/replay formats. Canonical provenance, source paths, history and cross-owner/resource refs remain intact. Registered Skill acquisition targets use direct `artifacts[exact source key]` in one-owner mode, explicit owners in multi mode; this target syntax is not a `state_flow_read` locator. Deletion text uses relative JSON pointers such as `/tactics/missing` for one owner, while result details retain canonical owners/paths. Newly generated Stop/reload/bootstrap handoffs render eligible current refs in the same captured interface. Canonical compiler diagnostics may name provenance owners; those are not extra patch wrappers, and retries use the declared flat planes. Exact source keys and canonical operator/error evidence are never broadly prefix-stripped. See the [context presentation boundary](single-scope-interface-contract.md#runtime-context-presentation).
|
|
403
403
|
|
|
404
404
|
Lazy bodies require explicit reads:
|
|
405
405
|
|
package/lib/config.ts
CHANGED
|
@@ -19,7 +19,7 @@ export interface StateFlowConfig {
|
|
|
19
19
|
inactiveMode: InactiveMode;
|
|
20
20
|
/** Opt-in local capture of rejected patch attempts and unresolved terminal drafts. */
|
|
21
21
|
logging: boolean;
|
|
22
|
-
/** Show successful
|
|
22
|
+
/** Show successful state_flow_patch arguments in the interactive tool row. */
|
|
23
23
|
showSuccessfulPatches: boolean;
|
|
24
24
|
historyLimit: number;
|
|
25
25
|
}
|
package/lib/extension.ts
CHANGED
|
@@ -54,8 +54,12 @@ export interface StateFlowExtensionOptions {
|
|
|
54
54
|
|
|
55
55
|
export { formatPatchStateArguments };
|
|
56
56
|
|
|
57
|
-
export const PATCH_STATE_TOOL_NAME = "
|
|
58
|
-
export const READ_STATE_TOOL_NAME = "
|
|
57
|
+
export const PATCH_STATE_TOOL_NAME = "state_flow_patch";
|
|
58
|
+
export const READ_STATE_TOOL_NAME = "state_flow_read";
|
|
59
|
+
const LEGACY_PATCH_STATE_TOOL_NAME = "patch_state";
|
|
60
|
+
const LEGACY_READ_STATE_TOOL_NAME = "read_state";
|
|
61
|
+
const STATE_FLOW_TOOL_NAMES = [PATCH_STATE_TOOL_NAME, READ_STATE_TOOL_NAME, LEGACY_PATCH_STATE_TOOL_NAME, LEGACY_READ_STATE_TOOL_NAME];
|
|
62
|
+
const isPatchStateTool = (name: string) => name === PATCH_STATE_TOOL_NAME || name === LEGACY_PATCH_STATE_TOOL_NAME;
|
|
59
63
|
const PASSIVE_STOP_ENTRY_TYPE = "state-flow-passive-stop";
|
|
60
64
|
|
|
61
65
|
const flatPatchParameters = Type.Object({
|
|
@@ -381,13 +385,13 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
381
385
|
// Every SDK registration is a fresh copy, preserving old response-wrapper declarations.
|
|
382
386
|
if (force || patchStateTool.parameters !== parameters) {
|
|
383
387
|
patchStateTool.parameters = parameters;
|
|
384
|
-
pi.registerTool({ ...
|
|
388
|
+
for (const tool of [patchStateTool, legacyPatchStateTool]) pi.registerTool({ ...tool, parameters, ...(external.length && tool === patchStateTool ? {
|
|
385
389
|
promptGuidelines: [...(patchStateTool.promptGuidelines ?? []), `Registered mutable object planes: ${external.join(", ")}. Availability and matching retained schema/policy are revalidated at acceptance.`],
|
|
386
390
|
} : {}) });
|
|
387
391
|
}
|
|
388
392
|
}
|
|
389
393
|
const active = pi.getActiveTools();
|
|
390
|
-
const owned =
|
|
394
|
+
const owned = STATE_FLOW_TOOL_NAMES;
|
|
391
395
|
if (owned.every((name) => active.includes(name) === available)) return;
|
|
392
396
|
pi.setActiveTools(available
|
|
393
397
|
? [...new Set([...active, ...owned])]
|
|
@@ -944,8 +948,10 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
944
948
|
} catch { return false; }
|
|
945
949
|
}
|
|
946
950
|
|
|
947
|
-
|
|
948
|
-
|
|
951
|
+
function readStateDefinition(name: string) {
|
|
952
|
+
return defineTool({
|
|
953
|
+
name,
|
|
954
|
+
...(name === LEGACY_READ_STATE_TOOL_NAME ? { prepareLoadout: () => ({ hiddenDeclarations: [name] }) } : {}),
|
|
949
955
|
label: "Read State",
|
|
950
956
|
description: "Read exact State Flow values or historical semantic patches with one path or an ordered path list. With one participating owner, semantic paths and structured references are scope-free, effective[N] selects that owner's historical boundary, and patches[N] selects its retained owner patch. With multiple owners, unscoped paths use the effective overlay and owner patch history requires an explicit owner. Optional global/cwd/session roots may address only participating available owners. Array selectors are zero-based indices or half-open [start..end] ranges, never temporal offsets inside a semantic value. Projection value returns data; keys returns minimal structure; patch intersects the selected path at its boundary. Path object keys must be ASCII identifiers ([A-Za-z_$][A-Za-z0-9_$-]*); non-ASCII keys cannot be addressed.",
|
|
951
957
|
promptSnippet: "Read exact state values, structures, or historical semantic patches",
|
|
@@ -957,7 +963,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
957
963
|
}, { additionalProperties: false }),
|
|
958
964
|
async execute(toolCallId, params, signal, _onUpdate, ctx) {
|
|
959
965
|
try {
|
|
960
|
-
const admission = nativeToolAdmission(toolCallId,
|
|
966
|
+
const admission = nativeToolAdmission(toolCallId, name, ctx);
|
|
961
967
|
admission?.revalidate();
|
|
962
968
|
if (admission) signal = signal ? AbortSignal.any([signal, admission.signal]) : admission.signal;
|
|
963
969
|
type ReadDetails = { path?: string; paths?: string[]; projection?: string; transitionId?: string };
|
|
@@ -977,8 +983,8 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
977
983
|
const wanted = captureScopeSelection(receipt.policy.scopes);
|
|
978
984
|
params = structuredClone(params);
|
|
979
985
|
check();
|
|
980
|
-
if (params.path === undefined && params.paths === undefined) throw new Error("
|
|
981
|
-
if (params.path !== undefined && params.paths !== undefined) throw new Error("
|
|
986
|
+
if (params.path === undefined && params.paths === undefined) throw new Error("state_flow_read requires path or paths");
|
|
987
|
+
if (params.path !== undefined && params.paths !== undefined) throw new Error("state_flow_read accepts path or paths, not both");
|
|
982
988
|
{
|
|
983
989
|
const requestedPaths = [...(params.paths ?? [params.path!])];
|
|
984
990
|
const paths = requestedPaths.map(path => normalizeModelReadPath(path, wanted, config.historyLimit));
|
|
@@ -1017,22 +1023,28 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
1017
1023
|
},
|
|
1018
1024
|
});
|
|
1019
1025
|
|
|
1020
|
-
|
|
1021
|
-
|
|
1026
|
+
}
|
|
1027
|
+
pi.registerTool(readStateDefinition(READ_STATE_TOOL_NAME));
|
|
1028
|
+
pi.registerTool({ ...readStateDefinition(LEGACY_READ_STATE_TOOL_NAME), promptSnippet: "", promptGuidelines: [] });
|
|
1029
|
+
|
|
1030
|
+
function patchStateDefinition(name: string) {
|
|
1031
|
+
return defineTool({
|
|
1032
|
+
name,
|
|
1033
|
+
...(name === LEGACY_PATCH_STATE_TOOL_NAME ? { prepareLoadout: () => ({ hiddenDeclarations: [name] }) } : {}),
|
|
1022
1034
|
label: "Patch State",
|
|
1023
1035
|
description: "The sole State Flow semantic mutation protocol. With one participating owner, supply intents/strategy/tactics/artifacts/lazy planes directly, without an owner wrapper. With multiple owners, supply one or more global, cwd, or session patches for participating owners; all supplied owners commit atomically. This call must be the only State Flow barrier in its assistant response. Intent updates run first, then clear owned same-scope strategy/tactics/lazy keys unless a remaining or new intent refs them, then other fields apply. Later writes can recreate cleared paths without old fields. Name keys in ASCII ([A-Za-z_$][A-Za-z0-9_$-]*) so read paths and refs resolve; values may use any language.",
|
|
1024
1036
|
promptSnippet: "Atomically patch participating semantic memory in its declared flat or multi-owner form",
|
|
1025
1037
|
promptGuidelines: [
|
|
1026
1038
|
RESPONSE_PATCH_GUIDELINE,
|
|
1027
1039
|
SCOPE_PARTICIPATION_GUIDELINE,
|
|
1028
|
-
"Use
|
|
1029
|
-
"Use
|
|
1030
|
-
"Call
|
|
1040
|
+
"Use state_flow_patch only for material durable semantic changes; ordinary answers need no finalization call.",
|
|
1041
|
+
"Use state_flow_patch as reconciliation, not append-only notes: place new knowledge at the narrowest valid scope and remove superseded or completed state from touched branches.",
|
|
1042
|
+
"Call state_flow_patch alone in an assistant response; after its acknowledgement, further reasoning, tools, and later state_flow_patch calls remain allowed.",
|
|
1031
1043
|
],
|
|
1032
1044
|
executionMode: "sequential",
|
|
1033
1045
|
parameters: config.scopes.length === 1 ? flatPatchParameters : scopedPatchParameters,
|
|
1034
1046
|
renderCall(args, theme, context) {
|
|
1035
|
-
const title = theme.fg("toolTitle", theme.bold(
|
|
1047
|
+
const title = theme.fg("toolTitle", theme.bold(name));
|
|
1036
1048
|
if (!config.showSuccessfulPatches && !context.isError) return new Text(title, 0, 0);
|
|
1037
1049
|
return new Text(`${title}\n${separatedOutput(theme.fg("dim", formatPatchStateArguments(args)))}`, 0, 0);
|
|
1038
1050
|
},
|
|
@@ -1044,7 +1056,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
1044
1056
|
signal = signal ? AbortSignal.any([signal, memoryToolLifetime.signal]) : memoryToolLifetime.signal;
|
|
1045
1057
|
let admitted = false;
|
|
1046
1058
|
try {
|
|
1047
|
-
const admission = nativeToolAdmission(toolCallId,
|
|
1059
|
+
const admission = nativeToolAdmission(toolCallId, name, ctx);
|
|
1048
1060
|
admission?.revalidate();
|
|
1049
1061
|
if (admission) signal = AbortSignal.any([signal, admission.signal]);
|
|
1050
1062
|
if (!memoryToolsAvailable()) throw new Error("State Flow tools are off for this session");
|
|
@@ -1164,7 +1176,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
1164
1176
|
try { attempted = structuredClone(params); } catch { attempted = undefined; }
|
|
1165
1177
|
const cause = diagnosticText(error);
|
|
1166
1178
|
recordDiagnostic(cause, /concurrently|advanced/.test(cause) ? "publication-conflict" : "invalid-patch", ctx, {
|
|
1167
|
-
input: attempted, tool:
|
|
1179
|
+
input: attempted, tool: name, toolCallId,
|
|
1168
1180
|
});
|
|
1169
1181
|
}
|
|
1170
1182
|
throw separatedFailure(error);
|
|
@@ -1172,7 +1184,11 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
1172
1184
|
},
|
|
1173
1185
|
});
|
|
1174
1186
|
|
|
1187
|
+
}
|
|
1188
|
+
const patchStateTool = patchStateDefinition(PATCH_STATE_TOOL_NAME);
|
|
1189
|
+
const legacyPatchStateTool = { ...patchStateDefinition(LEGACY_PATCH_STATE_TOOL_NAME), promptSnippet: "", promptGuidelines: [] };
|
|
1175
1190
|
pi.registerTool({ ...patchStateTool });
|
|
1191
|
+
pi.registerTool({ ...legacyPatchStateTool });
|
|
1176
1192
|
|
|
1177
1193
|
function startStateFlow(ctx: ExtensionContext, reselect = false): Promise<StateFlowTelegramControlResult> {
|
|
1178
1194
|
if (shuttingDown) return Promise.resolve({ ok: false, message: "State Flow is shutting down" });
|
|
@@ -1925,9 +1941,9 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
1925
1941
|
});
|
|
1926
1942
|
|
|
1927
1943
|
pi.on("tool_call", (event, ctx) => {
|
|
1928
|
-
const owned =
|
|
1944
|
+
const owned = STATE_FLOW_TOOL_NAMES.includes(event.toolName);
|
|
1929
1945
|
if (event.parentToolCallId) {
|
|
1930
|
-
if (event.toolName
|
|
1946
|
+
if (isPatchStateTool(event.toolName) && isActive()) return { block: true, reason: "state_flow_patch requires a direct native assistant barrier, not a nested call" };
|
|
1931
1947
|
try { nativeRequests.nested(event.toolCallId, event.toolName, event.parentToolCallId); }
|
|
1932
1948
|
catch { if (owned) return { block: true, reason: "State Flow tool batch has no current native request" }; }
|
|
1933
1949
|
}
|
|
@@ -1937,15 +1953,15 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
1937
1953
|
}
|
|
1938
1954
|
if (!isActive() || !currentNativeTool(event.toolCallId, event.toolName, ctx)) return;
|
|
1939
1955
|
const batch = findAssistantToolBatch(ctx.sessionManager, event.toolCallId);
|
|
1940
|
-
const patchCalls = batch?.filter(
|
|
1956
|
+
const patchCalls = batch?.filter(isPatchStateTool).length ?? 0;
|
|
1941
1957
|
if (patchCalls > 0) {
|
|
1942
1958
|
if (patchCalls !== 1) {
|
|
1943
|
-
const reason = "A State Flow barrier response must contain exactly one
|
|
1959
|
+
const reason = "A State Flow barrier response must contain exactly one state_flow_patch call";
|
|
1944
1960
|
recordDiagnostic(reason, "barrier-block", ctx, { tool: event.toolName, toolCallId: event.toolCallId, batchToolNames: batch });
|
|
1945
1961
|
return { block: true, reason };
|
|
1946
1962
|
}
|
|
1947
|
-
if (event.toolName
|
|
1948
|
-
const reason = "Blocked by the
|
|
1963
|
+
if (!isPatchStateTool(event.toolName)) {
|
|
1964
|
+
const reason = "Blocked by the state_flow_patch barrier; reconsider this action after State Flow rematerializes context";
|
|
1949
1965
|
recordDiagnostic(reason, "barrier-block", ctx, { tool: event.toolName, toolCallId: event.toolCallId, batchToolNames: batch });
|
|
1950
1966
|
return { block: true, reason };
|
|
1951
1967
|
}
|
package/lib/ownership.ts
CHANGED
|
@@ -11,7 +11,7 @@ export interface OwnedPath {
|
|
|
11
11
|
}
|
|
12
12
|
|
|
13
13
|
const OWNED_PLANES = new Set<string>(["strategy", "tactics", "lazy"]);
|
|
14
|
-
// Same key grammar as
|
|
14
|
+
// Same key grammar as state_flow_read value paths; array selectors never parse.
|
|
15
15
|
const OBJECT_KEY = /^[A-Za-z_$][A-Za-z0-9_$-]*$/;
|
|
16
16
|
|
|
17
17
|
/**
|
|
@@ -106,7 +106,7 @@ export function cascadeDeletionPatch(paths: readonly OwnedPath[]): JsonObject {
|
|
|
106
106
|
return patch;
|
|
107
107
|
}
|
|
108
108
|
|
|
109
|
-
/** Render an ownership target as its scoped `
|
|
109
|
+
/** Render an ownership target as its scoped `state_flow_read` path. */
|
|
110
110
|
export function formatOwnedPath(scope: StateScope, path: OwnedPath): string {
|
|
111
111
|
return [scope, path.plane, ...path.keys].join(".");
|
|
112
112
|
}
|
package/lib/protocol.ts
CHANGED
|
@@ -11,9 +11,9 @@ const PATCH_RESULT_PROTOCOL = "Head state/recent transitions are frozen at proje
|
|
|
11
11
|
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.";
|
|
12
12
|
export const SCOPE_PARTICIPATION_GUIDELINE = "Use only participating memory owners from the current protocol/view; scope names and examples describe grammar, not participation grants.";
|
|
13
13
|
|
|
14
|
-
export const PASSIVE_MEMORY_PROTOCOL = `State Flow passive memory is available.
|
|
14
|
+
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}`;
|
|
15
15
|
|
|
16
|
-
const FLAT_INTERFACE_PROTOCOL = 'One-owner interface:
|
|
16
|
+
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.';
|
|
17
17
|
|
|
18
18
|
function scopeGuidance(selection: ScopeSelection): string {
|
|
19
19
|
const meanings = { session: "session=branch/run continuation by default", cwd: "cwd=project knowledge", global: "global=cross-project/user/environment knowledge" };
|
|
@@ -106,7 +106,7 @@ export function stateFlowProtocol(bootstrap: boolean, scopes: ScopeSelection = D
|
|
|
106
106
|
const response = selected.includes("session") ? 'read-only prior answer; never patch it in any scope. Auto-stored at turn_end (empty="").'
|
|
107
107
|
: "read-only selected legacy data; never patch it in any scope. Session excluded: new answers are delivered, not stored or backfilled.";
|
|
108
108
|
const bootstrapProtocol = bootstrap
|
|
109
|
-
? `BOOTSTRAP RUN: Reconcile all relevant ${all ? "state" : "participating state"} and continuation through
|
|
109
|
+
? `BOOTSTRAP RUN: Reconcile all relevant ${all ? "state" : "participating state"} and continuation through state_flow_patch before completion.\n\n`
|
|
110
110
|
: "";
|
|
111
111
|
return `State Flow is enabled. It owns durable memory.
|
|
112
112
|
|
|
@@ -120,13 +120,13 @@ ${bootstrapProtocol}STATE:
|
|
|
120
120
|
|
|
121
121
|
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}` : ""}
|
|
122
122
|
|
|
123
|
-
READ: Use
|
|
123
|
+
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}
|
|
124
124
|
|
|
125
|
-
WRITE:
|
|
125
|
+
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}
|
|
126
126
|
|
|
127
127
|
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.
|
|
128
128
|
|
|
129
|
-
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
|
|
129
|
+
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.
|
|
130
130
|
|
|
131
131
|
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.
|
|
132
132
|
|
package/lib/query.ts
CHANGED
|
@@ -300,7 +300,7 @@ function diffObjects(previous: JsonValue, current: JsonValue): JsonValue {
|
|
|
300
300
|
|
|
301
301
|
/** Project exact current/historical state paths without exposing temporal metadata. */
|
|
302
302
|
export function readProjectedState(view: ReadableTemporalState, paths: readonly string[], projection: StateReadProjection = "value", historyLimit = DEFAULT_HISTORY_LIMIT): ProjectedStateRead {
|
|
303
|
-
if (paths.length === 0) throw new Error("
|
|
303
|
+
if (paths.length === 0) throw new Error("state_flow_read requires at least one path");
|
|
304
304
|
queryOwners(view);
|
|
305
305
|
if (projection === "patch") {
|
|
306
306
|
const patches = paths.map((path) => {
|
package/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.
|