@llblab/pi-state-flow 0.27.5 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,47 @@
1
+ import { type ScopeSelection } from "./selection.ts";
2
+ import type { StateScope } from "./state.ts";
3
+ import { type StorageTransaction } from "./storage.ts";
4
+ /** One visible reset: the scope became wholly absent after its exact bytes were quarantined. */
5
+ export interface HealedScope {
6
+ scope: StateScope;
7
+ reason: string;
8
+ quarantine: string;
9
+ }
10
+ /** Healing outcome; `lifecycleAbsent` means this session owns no lifecycle after healing. */
11
+ export interface HealResult {
12
+ healed: HealedScope[];
13
+ lifecycleAbsent: boolean;
14
+ }
15
+ export interface HealRequest {
16
+ cwd: string;
17
+ sessionId: string;
18
+ sessionKey: string;
19
+ selection: ScopeSelection;
20
+ historyLimit: number;
21
+ root: string;
22
+ /** Wall-clock source for deterministic tests. */
23
+ now?: () => Date;
24
+ }
25
+ /**
26
+ * Only semantic decoding/validation failures are healable. Filesystem, lock, cancellation and
27
+ * foreign-owner identity failures keep failing closed because resetting cannot fix them safely.
28
+ */
29
+ export declare function isHealableCorruption(error: unknown): boolean;
30
+ /**
31
+ * Converge the selected owners to a loadable store: decode each owner independently, then the
32
+ * complete selected cohort. A broken owner is quarantined and becomes wholly absent, which the
33
+ * normal lifecycle treats as empty memory. Healthy stores are never written.
34
+ */
35
+ export declare function healSelectedStoreLocked(storage: StorageTransaction, request: HealRequest, signal?: AbortSignal): HealResult;
36
+ /** Never waits behind a live writer: a busy store is being used, so healing defers to a later attempt. */
37
+ export declare function healSelectedStore(request: HealRequest, signal?: AbortSignal): Promise<HealResult>;
38
+ /** One pending reset notice: projected to the model until an agent run settles after seeing it. */
39
+ export declare class HealNotice {
40
+ #private;
41
+ announce(message: string): void;
42
+ /** Model-facing text for the current request, marking it as seen. */
43
+ project(): string | undefined;
44
+ /** A settled run that saw the notice consumes it; an unseen notice survives. */
45
+ settle(): void;
46
+ }
47
+ export declare function describeHealedScopes(healed: readonly HealedScope[]): string;
@@ -0,0 +1,159 @@
1
+ // Domain: visible self-healing of unrecoverable canonical scope cohorts by quarantine and reset to absence.
2
+ // Excludes: semantic repair, Git restoration, foreign-owner data, transient I/O failures and Pi lifecycle policy.
3
+ import { createHash } from "node:crypto";
4
+ import { constants, lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
5
+ import { basename, dirname, relative, resolve } from "node:path";
6
+ import { canonicalJson } from "./json.js";
7
+ import { sessionRuntimePaths, temporalScopePaths } from "./durable.js";
8
+ import { captureScopeSelection } from "./selection.js";
9
+ import { RevisionUnavailableError } from "./snapshot.js";
10
+ import { assertStorageDirectory, PublicationBusyError, withStorageTransaction } from "./storage.js";
11
+ /**
12
+ * Only semantic decoding/validation failures are healable. Filesystem, lock, cancellation and
13
+ * foreign-owner identity failures keep failing closed because resetting cannot fix them safely.
14
+ */
15
+ export function isHealableCorruption(error) {
16
+ if (!(error instanceof Error))
17
+ return false;
18
+ if (error instanceof RevisionUnavailableError || error instanceof PublicationBusyError)
19
+ return false;
20
+ if (error.name === "AbortError")
21
+ return false;
22
+ if (typeof error.code === "string")
23
+ return false;
24
+ if (/identity mismatch/i.test(error.message))
25
+ return false;
26
+ if (error instanceof AggregateError)
27
+ return error.errors.every(isHealableCorruption);
28
+ return true;
29
+ }
30
+ function scopeFiles(request, scope) {
31
+ const paths = temporalScopePaths(request.cwd, request.sessionId, scope, request.root, request.sessionKey);
32
+ const semantic = [paths.checkpoint, paths.patches, paths.meta, resolve(paths.directory, "state.json")];
33
+ if (scope !== "session")
34
+ return semantic;
35
+ const runtime = sessionRuntimePaths(request.cwd, request.sessionId, request.root, request.sessionKey);
36
+ return [...semantic, runtime.config, runtime.runtime];
37
+ }
38
+ function readPresent(path) {
39
+ const stat = lstatSync(path, { throwIfNoEntry: false });
40
+ if (!stat)
41
+ return undefined;
42
+ if (!stat.isFile() || stat.isSymbolicLink())
43
+ throw new Error(`State Flow quarantine refuses a non-regular file: ${JSON.stringify(path)}`);
44
+ return readFileSync(path, { flag: constants.O_RDONLY | constants.O_NOFOLLOW });
45
+ }
46
+ /** Exact-byte private record first; canonical files are removed only after the record verifies. */
47
+ function quarantineScope(request, scope, reason) {
48
+ const root = resolve(request.root);
49
+ const files = scopeFiles(request, scope).map(path => ({ path, bytes: readPresent(path) })).filter(file => file.bytes !== undefined);
50
+ if (files.length === 0)
51
+ return undefined;
52
+ const at = (request.now?.() ?? new Date()).toISOString();
53
+ const content = `${canonicalJson({ version: 1, kind: "state-flow-quarantine", at, root, cwd: resolve(request.cwd),
54
+ sessionId: request.sessionId, sessionKey: request.sessionKey, scope, reason,
55
+ files: files.map(file => ({ path: relative(root, file.path), bytes: file.bytes.toString("base64") })) })}\n`;
56
+ const directory = resolve(dirname(root), `${basename(root)}-quarantine`);
57
+ assertStorageDirectory(directory);
58
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
59
+ const directoryStat = lstatSync(directory);
60
+ if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink() || (directoryStat.mode & 0o077) !== 0) {
61
+ throw new Error("State Flow quarantine directory must be private; canonical files preserved");
62
+ }
63
+ const digest = createHash("sha256").update(content).digest("hex").slice(0, 16);
64
+ const path = resolve(directory, `${at.replace(/[:.]/g, "-")}-${scope}-${digest}.json`);
65
+ try {
66
+ writeFileSync(path, content, { flag: "wx", mode: 0o600 });
67
+ }
68
+ catch (error) {
69
+ if (error.code !== "EEXIST")
70
+ throw error;
71
+ }
72
+ if (readFileSync(path, { encoding: "utf8", flag: constants.O_RDONLY | constants.O_NOFOLLOW }) !== content) {
73
+ throw new Error("State Flow quarantine record changed; canonical files preserved");
74
+ }
75
+ for (const file of files)
76
+ rmSync(file.path);
77
+ return { scope, reason, quarantine: path };
78
+ }
79
+ function probe(action, signal) {
80
+ try {
81
+ action();
82
+ return undefined;
83
+ }
84
+ catch (error) {
85
+ // Cancellation reasons are arbitrary values; they never prove corruption.
86
+ signal?.throwIfAborted();
87
+ if (!isHealableCorruption(error))
88
+ throw error;
89
+ return error;
90
+ }
91
+ }
92
+ /**
93
+ * Converge the selected owners to a loadable store: decode each owner independently, then the
94
+ * complete selected cohort. A broken owner is quarantined and becomes wholly absent, which the
95
+ * normal lifecycle treats as empty memory. Healthy stores are never written.
96
+ */
97
+ export function healSelectedStoreLocked(storage, request, signal) {
98
+ const wanted = captureScopeSelection(request.selection);
99
+ const { cwd, sessionId, sessionKey, root, historyLimit } = request;
100
+ const healed = [];
101
+ const reset = (scope, error) => {
102
+ const result = quarantineScope(request, scope, error.message);
103
+ if (result)
104
+ healed.push(result);
105
+ };
106
+ for (const scope of wanted.filter(owner => owner !== "session")) {
107
+ const failure = probe(() => storage.observeSelectedShared(cwd, captureScopeSelection([scope]), root), signal);
108
+ if (failure)
109
+ reset(scope, failure);
110
+ }
111
+ let lifecycle;
112
+ const lifecycleFailure = probe(() => { lifecycle = storage.inspectSelectedLifecycle(cwd, sessionId, wanted, root, sessionKey); }, signal);
113
+ if (lifecycleFailure) {
114
+ reset("session", lifecycleFailure);
115
+ return { healed, lifecycleAbsent: true };
116
+ }
117
+ if (!lifecycle)
118
+ return { healed, lifecycleAbsent: true };
119
+ if (wanted.includes("session") && lifecycle.runtime.meta.privateAcquisition !== "acquired")
120
+ return { healed, lifecycleAbsent: false };
121
+ // The session lifecycle anchors cross-owner lineage, so a contradictory cohort resets that private anchor.
122
+ const cohortFailure = probe(() => storage.prepareSelectedCurrent(cwd, sessionId, wanted, historyLimit, root, sessionKey), signal);
123
+ if (cohortFailure)
124
+ reset("session", cohortFailure);
125
+ return { healed, lifecycleAbsent: cohortFailure !== undefined };
126
+ }
127
+ /** Never waits behind a live writer: a busy store is being used, so healing defers to a later attempt. */
128
+ export async function healSelectedStore(request, signal) {
129
+ const root = resolve(request.root);
130
+ if (!lstatSync(root, { throwIfNoEntry: false }))
131
+ return { healed: [], lifecycleAbsent: true };
132
+ return withStorageTransaction(root, storage => healSelectedStoreLocked(storage, { ...request, root }, signal), signal, false);
133
+ }
134
+ /** One pending reset notice: projected to the model until an agent run settles after seeing it. */
135
+ export class HealNotice {
136
+ #message;
137
+ #projected = false;
138
+ announce(message) {
139
+ this.#message = message;
140
+ this.#projected = false;
141
+ }
142
+ /** Model-facing text for the current request, marking it as seen. */
143
+ project() {
144
+ if (this.#message === undefined)
145
+ return undefined;
146
+ this.#projected = true;
147
+ return `${this.#message}. Tell the user about this State Flow memory reset in your next answer.`;
148
+ }
149
+ /** A settled run that saw the notice consumes it; an unseen notice survives. */
150
+ settle() {
151
+ if (!this.#projected)
152
+ return;
153
+ this.#message = undefined;
154
+ this.#projected = false;
155
+ }
156
+ }
157
+ export function describeHealedScopes(healed) {
158
+ return healed.map(item => `${item.scope} memory was unreadable (${item.reason}) and was reset to empty; original bytes quarantined at ${item.quarantine}`).join("; ");
159
+ }
@@ -1,4 +1,4 @@
1
- export type StateFlowDiagnosticCategory = "invalid-patch" | "publication-conflict" | "finalization" | "barrier-block";
1
+ export type StateFlowDiagnosticCategory = "invalid-patch" | "publication-conflict" | "finalization" | "barrier-block" | "self-heal";
2
2
  /** Minimal structural block; only ordinary text keeps its exact content. */
3
3
  export interface StateFlowDiagnosticBlock {
4
4
  type: string;
@@ -41,5 +41,7 @@ export declare class StateFlowDiagnosticWriter {
41
41
  record(sessionId: string, cwd: string, error: string, category: StateFlowDiagnosticCategory, extras?: DiagnosticExtras): void;
42
42
  /** Push warnings stay short; retain the available Git failure detail locally even without opt-in logging. */
43
43
  recordBackupPushFailure(sessionId: string, cwd: string, error: string): boolean;
44
+ /** Memory resets are always recorded locally, independently of opt-in logging. */
45
+ recordSelfHeal(sessionId: string, cwd: string, error: string): boolean;
44
46
  private write;
45
47
  }
@@ -61,6 +61,10 @@ export class StateFlowDiagnosticWriter {
61
61
  recordBackupPushFailure(sessionId, cwd, error) {
62
62
  return this.write(sessionId, cwd, error, "publication-conflict", {}, false);
63
63
  }
64
+ /** Memory resets are always recorded locally, independently of opt-in logging. */
65
+ recordSelfHeal(sessionId, cwd, error) {
66
+ return this.write(sessionId, cwd, error, "self-heal", {});
67
+ }
64
68
  write(sessionId, cwd, error, category, extras, reportFailure = true) {
65
69
  try {
66
70
  const fromRepository = relative(this.repositoryRoot, this.path);
@@ -25,7 +25,7 @@ export declare function extractOwnedPaths(scope: StateScope, value: JsonValue):
25
25
  export declare function computeIntentCascade(scope: StateScope, before: SemanticState, after: SemanticState): OwnedPath[];
26
26
  /** Express cascade targets as explicit nested object-key deletions. */
27
27
  export declare function cascadeDeletionPatch(paths: readonly OwnedPath[]): JsonObject;
28
- /** Render an ownership target as its scoped `read_state` path. */
28
+ /** Render an ownership target as its scoped `state_flow_read` path. */
29
29
  export declare function formatOwnedPath(scope: StateScope, path: OwnedPath): string;
30
30
  /** Top-level ownership-eligible keys referenced by current intents of `scope`. */
31
31
  export declare function ownedTopLevelKeys(scope: StateScope, state: SemanticState): Record<OwnedPlane, Set<string>>;
@@ -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 read_state value paths; array selectors never parse.
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 `read_state` path. */
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
  }
@@ -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. read_state and patch_state 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.";
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;
@@ -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. read_state and patch_state 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: patch_state takes intents/strategy/tactics/artifacts/lazy object planes directly; never add an owner wrapper. read_state 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.';
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 patch_state before completion.\n\n`
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 read_state for concrete ${single ? "semantic" : "scope"}/retained-history gaps. lazy_navigation lists bounded effective lazy keys, not bodies. ${TASK_DRIVEN_HISTORY}
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: patch_state 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}
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 read_state and one atomic multi-scope patch, then verify both owners."} External transfers need verified acceptance before deletion. Never invent memory changes.
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("read_state requires at least one path");
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@llblab/pi-state-flow",
3
- "version": "0.27.5",
3
+ "version": "0.28.0",
4
4
  "license": "MIT",
5
5
  "private": false,
6
6
  "description": "Incremental scoped state/context/memory compiler for Pi, inspired by SKILL.state",
@@ -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
- `read_state` 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).
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 `read_state` 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.
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 `patch_state` 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 `patch_state` 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.
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 `patch_state` 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.
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 `read_state` paths or `$` references, and cannot be owned by intents. Values may use any language.
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 `patch_state`; ordinary completion requires no finalization patch.
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 `read_state` and `patch_state`; 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.
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, `read_state` uses flat ordinary paths (for example `{"path":"tactics"}`), and `patch_state` 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.
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 `read_state` 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.
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 `patch_state` 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.
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 `patch_state`, 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.
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 `patch_state` call. Stop after this review, including when nothing needs changing.
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.