@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.
- package/AGENTS.md +4 -3
- package/BACKLOG.md +1 -1
- package/CHANGELOG.md +10 -0
- package/README.md +7 -5
- package/dist/lib/config.d.ts +1 -1
- package/dist/lib/extension.d.ts +2 -2
- package/dist/lib/extension.js +378 -263
- package/dist/lib/healing.d.ts +47 -0
- package/dist/lib/healing.js +159 -0
- package/dist/lib/logging.d.ts +3 -1
- package/dist/lib/logging.js +4 -0
- 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 +17 -15
- package/docs/compatibility.md +10 -0
- package/docs/filesystem-recovery.md +15 -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 +29 -28
- package/lib/config.ts +1 -1
- package/lib/extension.ts +142 -37
- package/lib/healing.ts +168 -0
- package/lib/logging.ts +6 -1
- 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/dist/lib/extension.js
CHANGED
|
@@ -31,11 +31,16 @@ import { compactStatus, detailedStatus, STATUS_KEY } from "./status.js";
|
|
|
31
31
|
import { PublicationBusyError, loadSelectedFileCohort } from "./storage.js";
|
|
32
32
|
import { captureScopeSelection, DEFAULT_SCOPE_SELECTION, parseScopeSelectionArguments, scopeSelectionArgumentCompletions } from "./selection.js";
|
|
33
33
|
import { createStateFlowTelegramAdapter } from "./telegram.js";
|
|
34
|
-
import { readTemporalScopes, temporalScopeRevisions } from "./temporal.js";
|
|
34
|
+
import { createSelectedTemporalState, readTemporalScopes, temporalScopeRevisions } from "./temporal.js";
|
|
35
|
+
import { describeHealedScopes, healSelectedStore, HealNotice } from "./healing.js";
|
|
35
36
|
import { commitSelectedTransition, stageSelectedScopePatches, stageSelectedScopedTransition } from "./transition.js";
|
|
36
37
|
export { formatPatchStateArguments };
|
|
37
|
-
export const PATCH_STATE_TOOL_NAME = "
|
|
38
|
-
export const READ_STATE_TOOL_NAME = "
|
|
38
|
+
export const PATCH_STATE_TOOL_NAME = "state_flow_patch";
|
|
39
|
+
export const READ_STATE_TOOL_NAME = "state_flow_read";
|
|
40
|
+
const LEGACY_PATCH_STATE_TOOL_NAME = "patch_state";
|
|
41
|
+
const LEGACY_READ_STATE_TOOL_NAME = "read_state";
|
|
42
|
+
const STATE_FLOW_TOOL_NAMES = [PATCH_STATE_TOOL_NAME, READ_STATE_TOOL_NAME, LEGACY_PATCH_STATE_TOOL_NAME, LEGACY_READ_STATE_TOOL_NAME];
|
|
43
|
+
const isPatchStateTool = (name) => name === PATCH_STATE_TOOL_NAME || name === LEGACY_PATCH_STATE_TOOL_NAME;
|
|
39
44
|
const PASSIVE_STOP_ENTRY_TYPE = "state-flow-passive-stop";
|
|
40
45
|
const flatPatchParameters = Type.Object({
|
|
41
46
|
intents: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
|
|
@@ -59,6 +64,7 @@ export default function stateFlowExtension(pi, options = {}) {
|
|
|
59
64
|
let effectiveState = {};
|
|
60
65
|
let branchStartsWithoutRuntime = false;
|
|
61
66
|
let modePersistenceError;
|
|
67
|
+
const healNotice = new HealNotice();
|
|
62
68
|
/** One pending inactive-mode persistence; later inactive choices coalesce until it publishes. */
|
|
63
69
|
const inactivePersistence = new OwnedOperationSlot();
|
|
64
70
|
const startActivation = new OwnedOperationSlot();
|
|
@@ -107,6 +113,40 @@ export default function stateFlowExtension(pi, options = {}) {
|
|
|
107
113
|
function notifyProblem(ctx, message, level) {
|
|
108
114
|
ctx.ui.notify(conciseDiagnostic(message), level);
|
|
109
115
|
}
|
|
116
|
+
/** Announce a reset to both operator and model; a reset is never silent. */
|
|
117
|
+
function announceHealing(ctx, message) {
|
|
118
|
+
healNotice.announce(message);
|
|
119
|
+
diagnosticWriter.recordSelfHeal(sessionAddress(ctx).id, ctx.cwd, message);
|
|
120
|
+
ctx.ui.notify(message, "warning");
|
|
121
|
+
}
|
|
122
|
+
/** Quarantine unrecoverable selected owners before acceptance; unhealable failures keep failing closed downstream. */
|
|
123
|
+
async function healCurrentStore(ctx, wanted, signal) {
|
|
124
|
+
const address = sessionAddress(ctx);
|
|
125
|
+
let result;
|
|
126
|
+
try {
|
|
127
|
+
result = await healSelectedStore({ cwd: ctx.cwd, sessionId: address.id, sessionKey: address.key, selection: wanted,
|
|
128
|
+
historyLimit: config.historyLimit, root: repositoryRoot }, signal);
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
if (signal.aborted)
|
|
132
|
+
throw error;
|
|
133
|
+
return undefined;
|
|
134
|
+
}
|
|
135
|
+
if (result.healed.length)
|
|
136
|
+
announceHealing(ctx, `State Flow self-healed: ${describeHealedScopes(result.healed)}`);
|
|
137
|
+
return result;
|
|
138
|
+
}
|
|
139
|
+
/** A pre-runtime branch with no stored cohort reads as empty memory instead of an unavailable runtime. */
|
|
140
|
+
function emptyPreRuntimeView(wanted) {
|
|
141
|
+
if (!branchStartsWithoutRuntime || snapshot.config.mode === "off" || snapshot.meta.validation?.attempt === 0
|
|
142
|
+
|| branchRestoration.current?.awaitingAcceptance)
|
|
143
|
+
return undefined;
|
|
144
|
+
// Shared absence is empty reality; unacquired Session keeps its explicit selected-unavailable diagnostic.
|
|
145
|
+
const shared = wanted.filter(scope => scope !== "session");
|
|
146
|
+
if (!shared.length)
|
|
147
|
+
return undefined;
|
|
148
|
+
return createSelectedTemporalState(Object.fromEntries(shared.map(scope => [scope, {}])), captureScopeSelection(shared), "empty:pre-runtime", config.historyLimit);
|
|
149
|
+
}
|
|
110
150
|
function notifyActiveContext(message) {
|
|
111
151
|
try {
|
|
112
152
|
if (activeContext)
|
|
@@ -317,13 +357,14 @@ export default function stateFlowExtension(pi, options = {}) {
|
|
|
317
357
|
// Every SDK registration is a fresh copy, preserving old response-wrapper declarations.
|
|
318
358
|
if (force || patchStateTool.parameters !== parameters) {
|
|
319
359
|
patchStateTool.parameters = parameters;
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
360
|
+
for (const tool of [patchStateTool, legacyPatchStateTool])
|
|
361
|
+
pi.registerTool({ ...tool, parameters, ...(external.length && tool === patchStateTool ? {
|
|
362
|
+
promptGuidelines: [...(patchStateTool.promptGuidelines ?? []), `Registered mutable object planes: ${external.join(", ")}. Availability and matching retained schema/policy are revalidated at acceptance.`],
|
|
363
|
+
} : {}) });
|
|
323
364
|
}
|
|
324
365
|
}
|
|
325
366
|
const active = pi.getActiveTools();
|
|
326
|
-
const owned =
|
|
367
|
+
const owned = STATE_FLOW_TOOL_NAMES;
|
|
327
368
|
if (owned.every((name) => active.includes(name) === available))
|
|
328
369
|
return;
|
|
329
370
|
pi.setActiveTools(available
|
|
@@ -654,7 +695,30 @@ export default function stateFlowExtension(pi, options = {}) {
|
|
|
654
695
|
// attachBranch releases its own ownership; settlement only drains it for shutdown.
|
|
655
696
|
return branchRestoration.track(pending, attachBranch(ctx, pending, selection, sessionStartReason, notifyRecovery, skipped), false);
|
|
656
697
|
}
|
|
657
|
-
|
|
698
|
+
/**
|
|
699
|
+
* After a failed attachment, heal selected owners once. Returns the selection to retry, or undefined when healing
|
|
700
|
+
* changed nothing; expected-but-absent session memory restarts visibly from empty memory.
|
|
701
|
+
*/
|
|
702
|
+
async function healBranchSelection(ctx, selection, requestedMode, signal) {
|
|
703
|
+
if (selection.kind === "settled")
|
|
704
|
+
return undefined;
|
|
705
|
+
const healing = await healCurrentStore(ctx, nativeScopeSelection(ctx), signal).catch(() => undefined);
|
|
706
|
+
if (!healing || signal.aborted || shuttingDown)
|
|
707
|
+
return undefined;
|
|
708
|
+
if (healing.lifecycleAbsent && (selection.kind === "attach" || selection.kind === "current")) {
|
|
709
|
+
const mode = requestedMode ?? (selection.kind === "current" ? selection.mode : selection.checkpoint.mode);
|
|
710
|
+
if (mode === "off")
|
|
711
|
+
return undefined;
|
|
712
|
+
if (!healing.healed.some(item => item.scope === "session")) {
|
|
713
|
+
announceHealing(ctx, "State Flow self-healed: session memory files were missing and session memory restarts empty");
|
|
714
|
+
}
|
|
715
|
+
branchStartsWithoutRuntime = true;
|
|
716
|
+
modePersistenceError = undefined;
|
|
717
|
+
return mode === "active" ? { kind: "auto-start" } : { kind: "pre-runtime", mode };
|
|
718
|
+
}
|
|
719
|
+
return healing.healed.length > 0 ? selection : undefined;
|
|
720
|
+
}
|
|
721
|
+
async function attachBranch(ctx, pending, selection, reason, notifyRecovery, skipped, healed = false) {
|
|
658
722
|
const placeholder = runtime;
|
|
659
723
|
let selected = runtime;
|
|
660
724
|
const wanted = nativeScopeSelection(ctx);
|
|
@@ -845,6 +909,13 @@ export default function stateFlowExtension(pi, options = {}) {
|
|
|
845
909
|
notifyProblem(ctx, `State Flow memory restored; lifecycle update failed: ${diagnosticText(error)}`, "warning");
|
|
846
910
|
return;
|
|
847
911
|
}
|
|
912
|
+
if (!isCurrent())
|
|
913
|
+
return;
|
|
914
|
+
const retry = healed ? undefined : await healBranchSelection(ctx, selection, pending.requestedMode, signal);
|
|
915
|
+
if (retry && isCurrent()) {
|
|
916
|
+
pending.awaitingAcceptance = retry.kind !== "settled" && retry.kind !== "current";
|
|
917
|
+
return await attachBranch(ctx, pending, retry, reason, notifyRecovery, skipped, true);
|
|
918
|
+
}
|
|
848
919
|
if (!isCurrent())
|
|
849
920
|
return;
|
|
850
921
|
failSelection(error);
|
|
@@ -859,7 +930,7 @@ export default function stateFlowExtension(pi, options = {}) {
|
|
|
859
930
|
if (snapshot.config.mode === "off" || isActive() || readableView() || snapshot.meta.validation?.attempt === 0 || !branchStartsWithoutRuntime)
|
|
860
931
|
return;
|
|
861
932
|
// Only a proven pre-runtime Passive branch may observe shared owners without private acquisition.
|
|
862
|
-
const passive = await loadPassiveView(ctx, signal, isCurrent, notifyRecovery);
|
|
933
|
+
const passive = await loadPassiveView(ctx, signal, isCurrent, notifyRecovery, !healed);
|
|
863
934
|
if (passive === undefined)
|
|
864
935
|
return;
|
|
865
936
|
assertCurrent();
|
|
@@ -882,16 +953,27 @@ export default function stateFlowExtension(pi, options = {}) {
|
|
|
882
953
|
}
|
|
883
954
|
}
|
|
884
955
|
/** Load current shared memory for passive projection without initializing or publishing it. */
|
|
885
|
-
async function loadPassiveView(ctx, signal, isCurrent, notify) {
|
|
956
|
+
async function loadPassiveView(ctx, signal, isCurrent, notify, heal = true) {
|
|
886
957
|
const wanted = nativeScopeSelection(ctx), shared = wanted.filter(scope => scope !== "session");
|
|
887
958
|
if (!shared.length)
|
|
888
959
|
return undefined;
|
|
889
960
|
const passive = createRuntime(ctx);
|
|
961
|
+
const observe = () => passive.refreshSelectedShared(captureScopeSelection(shared), () => {
|
|
962
|
+
if (!isCurrent() || !sameJson(nativeScopeSelection(ctx), wanted))
|
|
963
|
+
throw new Error("State Flow observation selection changed");
|
|
964
|
+
}, signal);
|
|
890
965
|
try {
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
966
|
+
try {
|
|
967
|
+
await observe();
|
|
968
|
+
}
|
|
969
|
+
catch (error) {
|
|
970
|
+
if (!heal || signal.aborted || !isCurrent())
|
|
971
|
+
throw error;
|
|
972
|
+
const healing = await healCurrentStore(ctx, captureScopeSelection(shared), signal).catch(() => undefined);
|
|
973
|
+
if (!healing?.healed.length)
|
|
974
|
+
throw error;
|
|
975
|
+
await observe();
|
|
976
|
+
}
|
|
895
977
|
}
|
|
896
978
|
catch (error) {
|
|
897
979
|
if (isCurrent() && !signal.aborted && notify && !modePersistenceError)
|
|
@@ -952,261 +1034,273 @@ export default function stateFlowExtension(pi, options = {}) {
|
|
|
952
1034
|
return false;
|
|
953
1035
|
}
|
|
954
1036
|
}
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
const check = () => {
|
|
982
|
-
receipt.revalidate();
|
|
983
|
-
signal?.throwIfAborted();
|
|
984
|
-
if (!ctx || runtime !== selected || selected.sessionId !== receipt.policy.owner || receipt.policy.owner !== ctx.sessionManager.getSessionId() || receipt.policy.cwd !== ctx.cwd
|
|
985
|
-
|| selected.cwd !== ctx.cwd || selected.sessionKey !== sessionAddress(ctx).key)
|
|
986
|
-
throw new Error("State Flow read selection owner changed");
|
|
987
|
-
};
|
|
988
|
-
check();
|
|
989
|
-
const wanted = captureScopeSelection(receipt.policy.scopes);
|
|
990
|
-
params = structuredClone(params);
|
|
991
|
-
check();
|
|
992
|
-
if (params.path === undefined && params.paths === undefined)
|
|
993
|
-
throw new Error("read_state requires path or paths");
|
|
994
|
-
if (params.path !== undefined && params.paths !== undefined)
|
|
995
|
-
throw new Error("read_state accepts path or paths, not both");
|
|
996
|
-
{
|
|
997
|
-
const requestedPaths = [...(params.paths ?? [params.path])];
|
|
998
|
-
const paths = requestedPaths.map(path => normalizeModelReadPath(path, wanted, config.historyLimit));
|
|
999
|
-
check();
|
|
1000
|
-
const view = readableView(selected);
|
|
1001
|
-
// Wanted policy was checked by normalization; an observational subset is not an exclusion.
|
|
1002
|
-
for (const path of paths) {
|
|
1003
|
-
const owner = /^(global|cwd|session)(?=\.|\[|$)/.exec(path)?.[1];
|
|
1004
|
-
if (owner && !view?.selection.includes(owner))
|
|
1005
|
-
throw new Error(`State Flow ${owner}: selected, unavailable`);
|
|
1006
|
-
}
|
|
1007
|
-
if (!view)
|
|
1037
|
+
function readStateDefinition(name) {
|
|
1038
|
+
return defineTool({
|
|
1039
|
+
name,
|
|
1040
|
+
...(name === LEGACY_READ_STATE_TOOL_NAME ? { prepareLoadout: () => ({ hiddenDeclarations: [name] }) } : {}),
|
|
1041
|
+
label: "Read State",
|
|
1042
|
+
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.",
|
|
1043
|
+
promptSnippet: "Read exact state values, structures, or historical semantic patches",
|
|
1044
|
+
promptGuidelines: [SCOPE_PARTICIPATION_GUIDELINE],
|
|
1045
|
+
parameters: Type.Object({
|
|
1046
|
+
path: Type.Optional(Type.String({ description: "One semantic path. One owner: flat planes, effective[N] history or retained patches[N]. Multiple owners: effective overlay or explicit participating owner; patch history needs owner.patches[N]. Nested array selectors stay ordinary indices/ranges." })),
|
|
1047
|
+
paths: Type.Optional(Type.Array(Type.String(), { minItems: 1, description: "Ordered query paths evaluated as one all-or-error read" })),
|
|
1048
|
+
projection: Type.Optional(StringEnum(["value", "keys", "patch"], { description: "Value snapshot by default, structural keys with minimal meta, or the selected historical semantic patch" })),
|
|
1049
|
+
}, { additionalProperties: false }),
|
|
1050
|
+
async execute(toolCallId, params, signal, _onUpdate, ctx) {
|
|
1051
|
+
try {
|
|
1052
|
+
const admission = nativeToolAdmission(toolCallId, name, ctx);
|
|
1053
|
+
admission?.revalidate();
|
|
1054
|
+
if (admission)
|
|
1055
|
+
signal = signal ? AbortSignal.any([signal, admission.signal]) : admission.signal;
|
|
1056
|
+
if (!memoryToolsAvailable())
|
|
1057
|
+
throw new Error("State Flow tools are off for this session");
|
|
1058
|
+
if (signal?.aborted)
|
|
1059
|
+
throw new Error("State Flow read was aborted");
|
|
1060
|
+
assertSelectedBranchAvailable();
|
|
1061
|
+
const selected = runtime;
|
|
1062
|
+
if (!selected)
|
|
1008
1063
|
throw new Error("State Flow temporal runtime is unavailable");
|
|
1064
|
+
const receipt = admission ?? requestPolicy.capture();
|
|
1065
|
+
const check = () => {
|
|
1066
|
+
receipt.revalidate();
|
|
1067
|
+
signal?.throwIfAborted();
|
|
1068
|
+
if (!ctx || runtime !== selected || selected.sessionId !== receipt.policy.owner || receipt.policy.owner !== ctx.sessionManager.getSessionId() || receipt.policy.cwd !== ctx.cwd
|
|
1069
|
+
|| selected.cwd !== ctx.cwd || selected.sessionKey !== sessionAddress(ctx).key)
|
|
1070
|
+
throw new Error("State Flow read selection owner changed");
|
|
1071
|
+
};
|
|
1072
|
+
check();
|
|
1073
|
+
const wanted = captureScopeSelection(receipt.policy.scopes);
|
|
1074
|
+
params = structuredClone(params);
|
|
1009
1075
|
check();
|
|
1010
|
-
if (
|
|
1011
|
-
|
|
1012
|
-
if (
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
const
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
const
|
|
1076
|
+
if (params.path === undefined && params.paths === undefined)
|
|
1077
|
+
throw new Error("state_flow_read requires path or paths");
|
|
1078
|
+
if (params.path !== undefined && params.paths !== undefined)
|
|
1079
|
+
throw new Error("state_flow_read accepts path or paths, not both");
|
|
1080
|
+
{
|
|
1081
|
+
const requestedPaths = [...(params.paths ?? [params.path])];
|
|
1082
|
+
const paths = requestedPaths.map(path => normalizeModelReadPath(path, wanted, config.historyLimit));
|
|
1083
|
+
check();
|
|
1084
|
+
const view = readableView(selected) ?? emptyPreRuntimeView(wanted);
|
|
1085
|
+
// Wanted policy was checked by normalization; an observational subset is not an exclusion.
|
|
1086
|
+
for (const path of paths) {
|
|
1087
|
+
const owner = /^(global|cwd|session)(?=\.|\[|$)/.exec(path)?.[1];
|
|
1088
|
+
if (owner && !view?.selection.includes(owner))
|
|
1089
|
+
throw new Error(`State Flow ${owner}: selected, unavailable${branchStartsWithoutRuntime
|
|
1090
|
+
? "; no memory is stored for it yet, and an accepted state_flow_patch creates it" : ""}`);
|
|
1091
|
+
}
|
|
1092
|
+
if (!view)
|
|
1093
|
+
throw new Error("State Flow temporal runtime is unavailable");
|
|
1094
|
+
check();
|
|
1095
|
+
if (paths.some((path) => /^session(?:\.|\[|$)/.test(path)))
|
|
1096
|
+
assertSelectedBranchAvailable();
|
|
1097
|
+
if (paths.length === 1 && /^(?:global|cwd|session)\.patches(?:\[\d+\])?$/.test(paths[0])) {
|
|
1098
|
+
if (params.projection !== undefined && params.projection !== "value")
|
|
1099
|
+
throw new Error("Scope patch paths support only the value projection");
|
|
1100
|
+
const result = readStatePath(view, paths[0], config.historyLimit);
|
|
1101
|
+
if (!("patch" in result))
|
|
1102
|
+
throw new Error("Expected a scope patch path");
|
|
1103
|
+
const output = wanted.length === 1 ? projectModelReferences({ patch: result.patch }, wanted, wanted.flatMap(scope => Object.keys(view.scopes[scope]?.modules ?? {}))) : { patch: result.patch };
|
|
1104
|
+
check();
|
|
1105
|
+
return {
|
|
1106
|
+
content: [{ type: "text", text: `\n${JSON.stringify(output)}` }],
|
|
1107
|
+
details: { path: requestedPaths[0], transitionId: result.boundary.id },
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
const result = readProjectedState(view, paths, params.projection, config.historyLimit);
|
|
1111
|
+
const output = wanted.length === 1 ? projectModelReferences(result, wanted, wanted.flatMap(scope => Object.keys(view.scopes[scope]?.modules ?? {}))) : result;
|
|
1019
1112
|
check();
|
|
1020
1113
|
return {
|
|
1021
1114
|
content: [{ type: "text", text: `\n${JSON.stringify(output)}` }],
|
|
1022
|
-
details: { path: requestedPaths[0],
|
|
1115
|
+
details: { ...(params.path === undefined ? { paths: requestedPaths } : { path: requestedPaths[0] }), projection: params.projection ?? "value" },
|
|
1023
1116
|
};
|
|
1024
1117
|
}
|
|
1025
|
-
const result = readProjectedState(view, paths, params.projection, config.historyLimit);
|
|
1026
|
-
const output = wanted.length === 1 ? projectModelReferences(result, wanted, wanted.flatMap(scope => Object.keys(view.scopes[scope]?.modules ?? {}))) : result;
|
|
1027
|
-
check();
|
|
1028
|
-
return {
|
|
1029
|
-
content: [{ type: "text", text: `\n${JSON.stringify(output)}` }],
|
|
1030
|
-
details: { ...(params.path === undefined ? { paths: requestedPaths } : { path: requestedPaths[0] }), projection: params.projection ?? "value" },
|
|
1031
|
-
};
|
|
1032
1118
|
}
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
}
|
|
1037
|
-
}
|
|
1038
|
-
}
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
"
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
throw new Error("State Flow patch was aborted before materialization");
|
|
1076
|
-
if (!ctx)
|
|
1077
|
-
throw new Error("State Flow patch selection owner changed");
|
|
1078
|
-
const selected = runtime ??= createRuntime(ctx);
|
|
1079
|
-
const sameSession = sessionIdentity(ctx);
|
|
1080
|
-
const receipt = admission ?? requestPolicy.capture();
|
|
1081
|
-
const wanted = captureScopeSelection(receipt.policy.scopes);
|
|
1082
|
-
const catalog = moduleHost.captureIfBound();
|
|
1083
|
-
signal = AbortSignal.any([signal, receipt.signal, ...(catalog ? [catalog.signal] : [])]);
|
|
1084
|
-
const check = () => {
|
|
1085
|
-
receipt.revalidate();
|
|
1086
|
-
if (runtime !== selected || !sameSession() || selected.sessionId !== receipt.policy.owner || receipt.policy.owner !== ctx.sessionManager.getSessionId()
|
|
1087
|
-
|| receipt.policy.cwd !== ctx.cwd || selected.cwd !== ctx.cwd || selected.sessionKey !== sessionAddress(ctx).key)
|
|
1088
|
-
throw new Error("State Flow patch selection owner changed");
|
|
1089
|
-
assertPublicationAvailable();
|
|
1090
|
-
catalog?.assertCurrent();
|
|
1091
|
-
};
|
|
1092
|
-
// Rehash and normalize only after caller admission, still before canonical exclusion.
|
|
1093
|
-
check();
|
|
1094
|
-
const excluded = isObject(params) && Object.keys(params).find(key => DEFAULT_SCOPE_SELECTION.includes(key) && !wanted.includes(key));
|
|
1095
|
-
if (excluded)
|
|
1096
|
-
throw new Error(`State Flow ${excluded} patch scope is excluded`);
|
|
1097
|
-
params = structuredClone(params);
|
|
1098
|
-
check();
|
|
1099
|
-
admitted = true;
|
|
1100
|
-
const knownModules = [...new Set([...(catalog?.modules.map(module => module.id) ?? []),
|
|
1101
|
-
...wanted.flatMap(scope => Object.keys(readableView(selected)?.scopes[scope]?.modules ?? {}))])];
|
|
1102
|
-
const patches = normalizeModelPatches(params, wanted, knownModules);
|
|
1103
|
-
check();
|
|
1104
|
-
const scopes = Object.keys(patches);
|
|
1105
|
-
const firstAuthoring = selected.selectedView() === undefined;
|
|
1106
|
-
const acquiredArtifacts = structuredClone([...artifactReads.successful.values()]);
|
|
1107
|
-
const acquiredSkills = structuredClone([...skillReads.successful.values()]);
|
|
1108
|
-
const previousEffective = effectiveState;
|
|
1109
|
-
skillReads.validateCompilations(patches);
|
|
1110
|
-
const author = (transaction) => {
|
|
1111
|
-
check();
|
|
1112
|
-
if (runtime !== selected)
|
|
1113
|
-
throw new Error("State Flow session selection changed while awaiting publication");
|
|
1119
|
+
catch (error) {
|
|
1120
|
+
throw separatedFailure(error);
|
|
1121
|
+
}
|
|
1122
|
+
},
|
|
1123
|
+
});
|
|
1124
|
+
}
|
|
1125
|
+
pi.registerTool(readStateDefinition(READ_STATE_TOOL_NAME));
|
|
1126
|
+
pi.registerTool({ ...readStateDefinition(LEGACY_READ_STATE_TOOL_NAME), promptSnippet: "", promptGuidelines: [] });
|
|
1127
|
+
function patchStateDefinition(name) {
|
|
1128
|
+
return defineTool({
|
|
1129
|
+
name,
|
|
1130
|
+
...(name === LEGACY_PATCH_STATE_TOOL_NAME ? { prepareLoadout: () => ({ hiddenDeclarations: [name] }) } : {}),
|
|
1131
|
+
label: "Patch State",
|
|
1132
|
+
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.",
|
|
1133
|
+
promptSnippet: "Atomically patch participating semantic memory in its declared flat or multi-owner form",
|
|
1134
|
+
promptGuidelines: [
|
|
1135
|
+
RESPONSE_PATCH_GUIDELINE,
|
|
1136
|
+
SCOPE_PARTICIPATION_GUIDELINE,
|
|
1137
|
+
"Use state_flow_patch only for material durable semantic changes; ordinary answers need no finalization call.",
|
|
1138
|
+
"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.",
|
|
1139
|
+
"Call state_flow_patch alone in an assistant response; after its acknowledgement, further reasoning, tools, and later state_flow_patch calls remain allowed.",
|
|
1140
|
+
],
|
|
1141
|
+
executionMode: "sequential",
|
|
1142
|
+
parameters: config.scopes.length === 1 ? flatPatchParameters : scopedPatchParameters,
|
|
1143
|
+
renderCall(args, theme, context) {
|
|
1144
|
+
const title = theme.fg("toolTitle", theme.bold(name));
|
|
1145
|
+
if (!config.showSuccessfulPatches && !context.isError)
|
|
1146
|
+
return new Text(title, 0, 0);
|
|
1147
|
+
return new Text(`${title}\n${separatedOutput(theme.fg("dim", formatPatchStateArguments(args)))}`, 0, 0);
|
|
1148
|
+
},
|
|
1149
|
+
renderResult(result) {
|
|
1150
|
+
const text = result.content.find((block) => block.type === "text")?.text ?? "";
|
|
1151
|
+
return new Text(separatedOutput(text), 0, 0);
|
|
1152
|
+
},
|
|
1153
|
+
async execute(toolCallId, params, signal, _onUpdate, ctx) {
|
|
1154
|
+
signal = signal ? AbortSignal.any([signal, memoryToolLifetime.signal]) : memoryToolLifetime.signal;
|
|
1155
|
+
let admitted = false;
|
|
1156
|
+
try {
|
|
1157
|
+
const admission = nativeToolAdmission(toolCallId, name, ctx);
|
|
1158
|
+
admission?.revalidate();
|
|
1159
|
+
if (admission)
|
|
1160
|
+
signal = AbortSignal.any([signal, admission.signal]);
|
|
1114
1161
|
if (!memoryToolsAvailable())
|
|
1115
1162
|
throw new Error("State Flow tools are off for this session");
|
|
1116
1163
|
assertPublicationAvailable();
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
const
|
|
1125
|
-
const
|
|
1126
|
-
|
|
1127
|
-
const
|
|
1128
|
-
|
|
1129
|
-
|
|
1164
|
+
if (signal?.aborted)
|
|
1165
|
+
throw new Error("State Flow patch was aborted before materialization");
|
|
1166
|
+
if (!ctx)
|
|
1167
|
+
throw new Error("State Flow patch selection owner changed");
|
|
1168
|
+
const selected = runtime ??= createRuntime(ctx);
|
|
1169
|
+
const sameSession = sessionIdentity(ctx);
|
|
1170
|
+
const receipt = admission ?? requestPolicy.capture();
|
|
1171
|
+
const wanted = captureScopeSelection(receipt.policy.scopes);
|
|
1172
|
+
const catalog = moduleHost.captureIfBound();
|
|
1173
|
+
signal = AbortSignal.any([signal, receipt.signal, ...(catalog ? [catalog.signal] : [])]);
|
|
1174
|
+
const check = () => {
|
|
1175
|
+
receipt.revalidate();
|
|
1176
|
+
if (runtime !== selected || !sameSession() || selected.sessionId !== receipt.policy.owner || receipt.policy.owner !== ctx.sessionManager.getSessionId()
|
|
1177
|
+
|| receipt.policy.cwd !== ctx.cwd || selected.cwd !== ctx.cwd || selected.sessionKey !== sessionAddress(ctx).key)
|
|
1178
|
+
throw new Error("State Flow patch selection owner changed");
|
|
1179
|
+
assertPublicationAvailable();
|
|
1130
1180
|
catalog?.assertCurrent();
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
if (
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
const
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
return await selected.withSelectedPatchTransaction(author, check, signal);
|
|
1152
|
-
check();
|
|
1153
|
-
const disposition = await selected.inspectSelectedLifecycle(wanted, check, signal);
|
|
1154
|
-
if (disposition && !wanted.includes("session")) {
|
|
1155
|
-
return await selected.withSelectedCurrentTransaction(wanted, (_current, _publish, transaction) => author(Object.freeze({
|
|
1156
|
-
...transaction, snapshot: { ...transaction.snapshot, config: { mode: receipt.policy.mode } },
|
|
1157
|
-
})), check, signal);
|
|
1158
|
-
}
|
|
1159
|
-
if (disposition) {
|
|
1160
|
-
const acquire = () => {
|
|
1181
|
+
};
|
|
1182
|
+
// Rehash and normalize only after caller admission, still before canonical exclusion.
|
|
1183
|
+
check();
|
|
1184
|
+
const excluded = isObject(params) && Object.keys(params).find(key => DEFAULT_SCOPE_SELECTION.includes(key) && !wanted.includes(key));
|
|
1185
|
+
if (excluded)
|
|
1186
|
+
throw new Error(`State Flow ${excluded} patch scope is excluded`);
|
|
1187
|
+
params = structuredClone(params);
|
|
1188
|
+
check();
|
|
1189
|
+
admitted = true;
|
|
1190
|
+
const knownModules = [...new Set([...(catalog?.modules.map(module => module.id) ?? []),
|
|
1191
|
+
...wanted.flatMap(scope => Object.keys(readableView(selected)?.scopes[scope]?.modules ?? {}))])];
|
|
1192
|
+
const patches = normalizeModelPatches(params, wanted, knownModules);
|
|
1193
|
+
check();
|
|
1194
|
+
const scopes = Object.keys(patches);
|
|
1195
|
+
const firstAuthoring = selected.selectedView() === undefined;
|
|
1196
|
+
const acquiredArtifacts = structuredClone([...artifactReads.successful.values()]);
|
|
1197
|
+
const acquiredSkills = structuredClone([...skillReads.successful.values()]);
|
|
1198
|
+
const previousEffective = effectiveState;
|
|
1199
|
+
skillReads.validateCompilations(patches);
|
|
1200
|
+
const author = (transaction) => {
|
|
1161
1201
|
check();
|
|
1162
|
-
if (
|
|
1163
|
-
|
|
1164
|
-
|
|
1202
|
+
if (runtime !== selected)
|
|
1203
|
+
throw new Error("State Flow session selection changed while awaiting publication");
|
|
1204
|
+
if (!memoryToolsAvailable())
|
|
1205
|
+
throw new Error("State Flow tools are off for this session");
|
|
1206
|
+
assertPublicationAvailable();
|
|
1207
|
+
for (const acquired of acquiredArtifacts) {
|
|
1208
|
+
const observation = inspectRegisteredArtifactPaths([acquired.path])[0];
|
|
1209
|
+
if (acquired.sourceFingerprint === undefined || observation?.kind !== "present"
|
|
1210
|
+
|| !sameArtifactSourceFingerprint(acquired.sourceFingerprint, observation.fingerprint)) {
|
|
1211
|
+
throw new Error(`Artifact source changed after acquisition: ${acquired.path}`);
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
const stage = stageSelectedScopePatches(transaction, patches, acquiredSkills, transaction.causalBasis, acquiredArtifacts, catalog?.modules);
|
|
1215
|
+
const changed = transaction.selection.some((scope) => !sameJson(transaction.states[scope], stage.nextStates[scope])
|
|
1216
|
+
|| Object.entries(stage.provenanceUpdates[scope] ?? {}).some(([path, evidence]) => !Object.hasOwn(transaction.provenance[scope] ?? {}, path) || !sameJson(transaction.provenance[scope]?.[path], evidence)));
|
|
1217
|
+
const nextSnapshot = structuredClone(firstAuthoring ? transaction.snapshot : snapshot);
|
|
1218
|
+
let publication;
|
|
1219
|
+
commitSelectedTransition(nextSnapshot, transaction, stage, (accepted, next) => {
|
|
1220
|
+
catalog?.assertCurrent();
|
|
1221
|
+
publication = transaction.publish(next, accepted, stage.provenanceUpdates, stage.moduleAdditions);
|
|
1222
|
+
}, transaction.causalBasis, { finalizeRun: false });
|
|
1223
|
+
snapshot = nextSnapshot;
|
|
1224
|
+
installScopeStates();
|
|
1225
|
+
if (publication?.changed) {
|
|
1226
|
+
recordPublication();
|
|
1227
|
+
appendCheckpoint();
|
|
1228
|
+
}
|
|
1229
|
+
clearAcceptedAcquisitions(new Set(acquiredArtifacts.map(({ path }) => path)));
|
|
1230
|
+
updateUi(ctx);
|
|
1231
|
+
const updates = contextProjection.acceptPatch(previousEffective, effectiveState, patches, acquisition.hints, stage.cascades, isActive(), wanted);
|
|
1232
|
+
const acknowledgement = changed
|
|
1233
|
+
? `\nState materialized atomically at ${scopes.join("+")} scope${scopes.length === 1 ? "" : "s"}.`
|
|
1234
|
+
: "\nState already current.";
|
|
1235
|
+
return { content: [
|
|
1236
|
+
{ type: "text", text: acknowledgement + stage.missingDeletions.map(deletion => projectModelMissingDeletion(deletion, wanted)).map(({ path, unavailablePath }) => `\n\nHint: deletion skipped at ${path}; target absent. First unavailable component: ${unavailablePath}. Check the path if you expected an existing value.`).join("") },
|
|
1237
|
+
...(updates ? [{ type: "text", text: `\n${presentationJson({ state_updates: updates })}` }] : []),
|
|
1238
|
+
], details: { scopes, step: snapshot.meta.step, changed, missingDeletions: stage.missingDeletions } };
|
|
1165
1239
|
};
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
acquire();
|
|
1169
|
-
if (!base)
|
|
1170
|
-
throw new Error("Unacquired State Flow first mutation source disappeared");
|
|
1171
|
-
let result;
|
|
1172
|
-
return await selected.withSelectedSessionAcquisitionTransaction({ kind: "unacquired", base, selection: wanted,
|
|
1173
|
-
snapshot: { ...disposition.snapshot, config: { mode: receipt.policy.mode } }, historyLimit: config.historyLimit,
|
|
1174
|
-
author: (basis, publish) => {
|
|
1175
|
-
acquire();
|
|
1176
|
-
result = author(Object.freeze({ selection: wanted,
|
|
1177
|
-
states: readTemporalScopes(basis.view, 0, config.historyLimit), snapshot: basis.snapshot,
|
|
1178
|
-
modules: Object.fromEntries(wanted.filter(scope => basis.view.scopes[scope]?.modules !== undefined).map(scope => [scope, structuredClone(basis.view.scopes[scope].modules)])),
|
|
1179
|
-
causalBasis: basis.view.lineage.at(-1).id, provenance: basis.provenance,
|
|
1180
|
-
publish: (next, transition, provenance, additions) => { acquire(); return publish(next, transition, provenance, additions); } }));
|
|
1181
|
-
} }, publish => { acquire(); publish(); return result; }, signal, true);
|
|
1182
|
-
}
|
|
1183
|
-
if (!branchStartsWithoutRuntime || forkInitialization || branchPolicy(ctx).forkPending)
|
|
1184
|
-
throw new Error("State Flow first authoring requires native independent origin authority");
|
|
1185
|
-
return await selected.withSelectedFirstPatchTransaction(wanted, snapshot, author, () => {
|
|
1240
|
+
if (!firstAuthoring)
|
|
1241
|
+
return await selected.withSelectedPatchTransaction(author, check, signal);
|
|
1186
1242
|
check();
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
if (admitted && !signal.aborted && memoryToolsAvailable()) {
|
|
1193
|
-
let attempted;
|
|
1194
|
-
try {
|
|
1195
|
-
attempted = structuredClone(params);
|
|
1243
|
+
const disposition = await selected.inspectSelectedLifecycle(wanted, check, signal);
|
|
1244
|
+
if (disposition && !wanted.includes("session")) {
|
|
1245
|
+
return await selected.withSelectedCurrentTransaction(wanted, (_current, _publish, transaction) => author(Object.freeze({
|
|
1246
|
+
...transaction, snapshot: { ...transaction.snapshot, config: { mode: receipt.policy.mode } },
|
|
1247
|
+
})), check, signal);
|
|
1196
1248
|
}
|
|
1197
|
-
|
|
1198
|
-
|
|
1249
|
+
if (disposition) {
|
|
1250
|
+
const acquire = () => {
|
|
1251
|
+
check();
|
|
1252
|
+
if (receipt.policy.mode === "off" || !wanted.includes("session") || disposition.privateAcquisition !== "unacquired"
|
|
1253
|
+
|| forkInitialization || branchPolicy(ctx).forkPending)
|
|
1254
|
+
throw new Error("State Flow first mutation requires independent unacquired Session participation");
|
|
1255
|
+
};
|
|
1256
|
+
acquire();
|
|
1257
|
+
const base = await loadSelectedFileCohort(ctx.cwd, selected.sessionId, disposition.selection, selected.root, selected.sessionKey, signal);
|
|
1258
|
+
acquire();
|
|
1259
|
+
if (!base)
|
|
1260
|
+
throw new Error("Unacquired State Flow first mutation source disappeared");
|
|
1261
|
+
let result;
|
|
1262
|
+
return await selected.withSelectedSessionAcquisitionTransaction({ kind: "unacquired", base, selection: wanted,
|
|
1263
|
+
snapshot: { ...disposition.snapshot, config: { mode: receipt.policy.mode } }, historyLimit: config.historyLimit,
|
|
1264
|
+
author: (basis, publish) => {
|
|
1265
|
+
acquire();
|
|
1266
|
+
result = author(Object.freeze({ selection: wanted,
|
|
1267
|
+
states: readTemporalScopes(basis.view, 0, config.historyLimit), snapshot: basis.snapshot,
|
|
1268
|
+
modules: Object.fromEntries(wanted.filter(scope => basis.view.scopes[scope]?.modules !== undefined).map(scope => [scope, structuredClone(basis.view.scopes[scope].modules)])),
|
|
1269
|
+
causalBasis: basis.view.lineage.at(-1).id, provenance: basis.provenance,
|
|
1270
|
+
publish: (next, transition, provenance, additions) => { acquire(); return publish(next, transition, provenance, additions); } }));
|
|
1271
|
+
} }, publish => { acquire(); publish(); return result; }, signal, true);
|
|
1199
1272
|
}
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1273
|
+
if (!branchStartsWithoutRuntime || forkInitialization || branchPolicy(ctx).forkPending)
|
|
1274
|
+
throw new Error("State Flow first authoring requires native independent origin authority");
|
|
1275
|
+
return await selected.withSelectedFirstPatchTransaction(wanted, snapshot, author, () => {
|
|
1276
|
+
check();
|
|
1277
|
+
if (!branchStartsWithoutRuntime || forkInitialization || branchPolicy(ctx).forkPending)
|
|
1278
|
+
throw new Error("State Flow origin authority changed");
|
|
1279
|
+
}, signal, true);
|
|
1204
1280
|
}
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1281
|
+
catch (error) {
|
|
1282
|
+
if (admitted && !signal.aborted && memoryToolsAvailable()) {
|
|
1283
|
+
let attempted;
|
|
1284
|
+
try {
|
|
1285
|
+
attempted = structuredClone(params);
|
|
1286
|
+
}
|
|
1287
|
+
catch {
|
|
1288
|
+
attempted = undefined;
|
|
1289
|
+
}
|
|
1290
|
+
const cause = diagnosticText(error);
|
|
1291
|
+
recordDiagnostic(cause, /concurrently|advanced/.test(cause) ? "publication-conflict" : "invalid-patch", ctx, {
|
|
1292
|
+
input: attempted, tool: name, toolCallId,
|
|
1293
|
+
});
|
|
1294
|
+
}
|
|
1295
|
+
throw separatedFailure(error);
|
|
1296
|
+
}
|
|
1297
|
+
},
|
|
1298
|
+
});
|
|
1299
|
+
}
|
|
1300
|
+
const patchStateTool = patchStateDefinition(PATCH_STATE_TOOL_NAME);
|
|
1301
|
+
const legacyPatchStateTool = { ...patchStateDefinition(LEGACY_PATCH_STATE_TOOL_NAME), promptSnippet: "", promptGuidelines: [] };
|
|
1209
1302
|
pi.registerTool({ ...patchStateTool });
|
|
1303
|
+
pi.registerTool({ ...legacyPatchStateTool });
|
|
1210
1304
|
function startStateFlow(ctx, reselect = false) {
|
|
1211
1305
|
if (shuttingDown)
|
|
1212
1306
|
return Promise.resolve({ ok: false, message: "State Flow is shutting down" });
|
|
@@ -1264,7 +1358,7 @@ export default function stateFlowExtension(pi, options = {}) {
|
|
|
1264
1358
|
}
|
|
1265
1359
|
}
|
|
1266
1360
|
/** Explicit Active or Passive accepts validated current same-session memory without claiming unavailable history. */
|
|
1267
|
-
async function activateCurrentState(ctx, pending, mode = "active", owns = () => startActivation.current?.controller === pending) {
|
|
1361
|
+
async function activateCurrentState(ctx, pending, mode = "active", owns = () => startActivation.current?.controller === pending, healing) {
|
|
1268
1362
|
let selected = runtime;
|
|
1269
1363
|
const wanted = nativeScopeSelection(ctx);
|
|
1270
1364
|
const sameSession = sessionIdentity(ctx);
|
|
@@ -1290,17 +1384,26 @@ export default function stateFlowExtension(pi, options = {}) {
|
|
|
1290
1384
|
const retained = selectRetainedCheckpoint(discovery.candidates, config.inactiveMode);
|
|
1291
1385
|
branchStartsWithoutRuntime = retained.kind === "pre-runtime" || (discovery.candidates.length === 0 && discovery.errors.length === 0);
|
|
1292
1386
|
}
|
|
1387
|
+
// After a failed attempt, a missing or reset session lifecycle restarts visibly from empty memory instead of blocking forever.
|
|
1388
|
+
const sessionReset = healing?.lifecycleAbsent === true && !forkInitialization && !branchPolicy(ctx).forkPending
|
|
1389
|
+
&& !(selected?.cwd === ctx.cwd && selected.sessionKey === activation.sessionKey && selected.selectedView()?.selection.includes("session"));
|
|
1390
|
+
if (sessionReset) {
|
|
1391
|
+
if (!branchStartsWithoutRuntime && !healing.healed.some(item => item.scope === "session")) {
|
|
1392
|
+
announceHealing(ctx, "State Flow self-healed: session memory files were missing and session memory restarts empty");
|
|
1393
|
+
}
|
|
1394
|
+
branchStartsWithoutRuntime = true;
|
|
1395
|
+
}
|
|
1293
1396
|
// Off activation owns one cancellable current-head publication, not an independent read-only restore.
|
|
1294
1397
|
const acceptActivation = (current, publish) => {
|
|
1295
1398
|
signal.throwIfAborted();
|
|
1296
1399
|
if (!isCurrent())
|
|
1297
1400
|
throw new Error("State Flow activation selection changed while awaiting publication");
|
|
1298
|
-
if (!current && (!active || !branchStartsWithoutRuntime))
|
|
1401
|
+
if (!current && (!(active || sessionReset) || !branchStartsWithoutRuntime))
|
|
1299
1402
|
throw new Error(snapshot.meta.validation?.error ?? "Current State Flow session memory is unavailable");
|
|
1300
1403
|
const boundary = deferred && retainsPhysicalSessionProjection(deferred.reason)
|
|
1301
1404
|
? branchPolicy(ctx).stop : undefined;
|
|
1302
1405
|
const bootstrap = hasPriorConversation(ctx.sessionManager.getBranch()) || passiveContinuation !== undefined || boundary !== undefined;
|
|
1303
|
-
const activated = !active ? deactivateEpisode(current, "passive")
|
|
1406
|
+
const activated = !active ? deactivateEpisode(current ?? startEpisode(false), "passive")
|
|
1304
1407
|
: current ? resumeEpisode(current, bootstrap) : startEpisode(bootstrap);
|
|
1305
1408
|
if (active) {
|
|
1306
1409
|
// Explicit Start accepts current memory, not the prior run's prompt or repair attempt.
|
|
@@ -1373,8 +1476,9 @@ export default function stateFlowExtension(pi, options = {}) {
|
|
|
1373
1476
|
acquiredResult = acceptActivation(basis.snapshot, activated => publish(activated));
|
|
1374
1477
|
} }, publish => { check(); publish(); return acquiredResult; }, signal, true);
|
|
1375
1478
|
}
|
|
1376
|
-
else if (active && branchStartsWithoutRuntime && !acceptedSession && !disposition) {
|
|
1377
|
-
const
|
|
1479
|
+
else if ((active || sessionReset) && branchStartsWithoutRuntime && !acceptedSession && !disposition) {
|
|
1480
|
+
const started = startEpisode(hasPriorConversation(ctx.sessionManager.getBranch()) || passiveContinuation !== undefined);
|
|
1481
|
+
const next = active ? started : deactivateEpisode(startEpisode(false), "passive");
|
|
1378
1482
|
result = await activation.withSelectedFirstPatchTransaction(wanted, next, transaction => {
|
|
1379
1483
|
check();
|
|
1380
1484
|
if (!branchStartsWithoutRuntime || forkInitialization)
|
|
@@ -1389,6 +1493,14 @@ export default function stateFlowExtension(pi, options = {}) {
|
|
|
1389
1493
|
catch (error) {
|
|
1390
1494
|
if (!isCurrent())
|
|
1391
1495
|
return superseded();
|
|
1496
|
+
if (!accepted && healing === undefined) {
|
|
1497
|
+
// Self-healing is lazy: healthy stores never pay for it, and one retry bounds convergence.
|
|
1498
|
+
const healed = await healCurrentStore(ctx, wanted, signal).catch(() => undefined);
|
|
1499
|
+
if (!isCurrent())
|
|
1500
|
+
return superseded();
|
|
1501
|
+
if (healed && (healed.healed.length > 0 || healed.lifecycleAbsent))
|
|
1502
|
+
return activateCurrentState(ctx, pending, mode, owns, healed);
|
|
1503
|
+
}
|
|
1392
1504
|
const message = conciseDiagnostic(`${accepted ? `State Flow ${mode}; lifecycle update failed` : active ? "State Flow activation failed" : "State Flow passive acceptance failed"}: ${diagnosticText(error)}`);
|
|
1393
1505
|
// An unaccepted activation cannot replace retained lifecycle or poison an independent Stop.
|
|
1394
1506
|
// Attachment owns required-proof unavailability; failed Passive acceptance reports through its caller's fence.
|
|
@@ -1846,7 +1958,9 @@ export default function stateFlowExtension(pi, options = {}) {
|
|
|
1846
1958
|
// Off removes the owned section, including one contributed before an in-flight mode change.
|
|
1847
1959
|
const protocol = isActive() ? stateFlowProtocol(snapshot.meta.bootstrap === true, nativeScopeSelection(ctx))
|
|
1848
1960
|
: passiveMemoryAvailable() ? passiveMemoryProtocol(nativeScopeSelection(ctx)) : undefined;
|
|
1849
|
-
|
|
1961
|
+
// Only a request that can carry the section consumes the reset notice.
|
|
1962
|
+
const notice = snapshot.config.mode !== "off" && event.messages.some(message => message.role === "system") ? healNotice.project() : undefined;
|
|
1963
|
+
return { messages: projectSystemProtocol(event.messages, [protocol, notice].filter(Boolean).join("\n\n") || undefined) };
|
|
1850
1964
|
});
|
|
1851
1965
|
// Optional transport checkpoint: no payload/header inspection or transformation.
|
|
1852
1966
|
pi.on("before_provider_request", (_event, ctx) => {
|
|
@@ -2050,10 +2164,10 @@ export default function stateFlowExtension(pi, options = {}) {
|
|
|
2050
2164
|
artifactReads.recordStart(event.toolCallId, event.toolName, event.args);
|
|
2051
2165
|
});
|
|
2052
2166
|
pi.on("tool_call", (event, ctx) => {
|
|
2053
|
-
const owned =
|
|
2167
|
+
const owned = STATE_FLOW_TOOL_NAMES.includes(event.toolName);
|
|
2054
2168
|
if (event.parentToolCallId) {
|
|
2055
|
-
if (event.toolName
|
|
2056
|
-
return { block: true, reason: "
|
|
2169
|
+
if (isPatchStateTool(event.toolName) && isActive())
|
|
2170
|
+
return { block: true, reason: "state_flow_patch requires a direct native assistant barrier, not a nested call" };
|
|
2057
2171
|
try {
|
|
2058
2172
|
nativeRequests.nested(event.toolCallId, event.toolName, event.parentToolCallId);
|
|
2059
2173
|
}
|
|
@@ -2073,15 +2187,15 @@ export default function stateFlowExtension(pi, options = {}) {
|
|
|
2073
2187
|
if (!isActive() || !currentNativeTool(event.toolCallId, event.toolName, ctx))
|
|
2074
2188
|
return;
|
|
2075
2189
|
const batch = findAssistantToolBatch(ctx.sessionManager, event.toolCallId);
|
|
2076
|
-
const patchCalls = batch?.filter(
|
|
2190
|
+
const patchCalls = batch?.filter(isPatchStateTool).length ?? 0;
|
|
2077
2191
|
if (patchCalls > 0) {
|
|
2078
2192
|
if (patchCalls !== 1) {
|
|
2079
|
-
const reason = "A State Flow barrier response must contain exactly one
|
|
2193
|
+
const reason = "A State Flow barrier response must contain exactly one state_flow_patch call";
|
|
2080
2194
|
recordDiagnostic(reason, "barrier-block", ctx, { tool: event.toolName, toolCallId: event.toolCallId, batchToolNames: batch });
|
|
2081
2195
|
return { block: true, reason };
|
|
2082
2196
|
}
|
|
2083
|
-
if (event.toolName
|
|
2084
|
-
const reason = "Blocked by the
|
|
2197
|
+
if (!isPatchStateTool(event.toolName)) {
|
|
2198
|
+
const reason = "Blocked by the state_flow_patch barrier; reconsider this action after State Flow rematerializes context";
|
|
2085
2199
|
recordDiagnostic(reason, "barrier-block", ctx, { tool: event.toolName, toolCallId: event.toolCallId, batchToolNames: batch });
|
|
2086
2200
|
return { block: true, reason };
|
|
2087
2201
|
}
|
|
@@ -2286,6 +2400,7 @@ export default function stateFlowExtension(pi, options = {}) {
|
|
|
2286
2400
|
}
|
|
2287
2401
|
});
|
|
2288
2402
|
pi.on("agent_settled", async (_event, ctx) => {
|
|
2403
|
+
healNotice.settle();
|
|
2289
2404
|
if (telegramStartPending && !isActive()) {
|
|
2290
2405
|
telegramStartPending = false;
|
|
2291
2406
|
await startStateFlow(ctx);
|