@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/lib/extension.ts
CHANGED
|
@@ -40,7 +40,8 @@ import { compactStatus, detailedStatus, STATUS_KEY, type StatusDiagnostics } fro
|
|
|
40
40
|
import { PublicationBusyError, loadSelectedFileCohort, type SelectedFilePublication } from "./storage.ts";
|
|
41
41
|
import { captureScopeSelection, DEFAULT_SCOPE_SELECTION, parseScopeSelectionArguments, scopeSelectionArgumentCompletions, type ScopeSelection } from "./selection.ts";
|
|
42
42
|
import { createStateFlowTelegramAdapter, type StateFlowTelegramControlResult, type StateFlowTelegramInspection, type StateFlowTelegramLoader, type StateFlowTelegramScope } from "./telegram.ts";
|
|
43
|
-
import { readTemporalScopes, temporalScopeRevisions, type ScopeRevisions } from "./temporal.ts";
|
|
43
|
+
import { createSelectedTemporalState, readTemporalScopes, temporalScopeRevisions, type ScopeRevisions, type SelectedTemporalState } from "./temporal.ts";
|
|
44
|
+
import { describeHealedScopes, healSelectedStore, HealNotice, type HealResult } from "./healing.ts";
|
|
44
45
|
import { commitSelectedTransition, stageSelectedScopePatches, stageSelectedScopedTransition, type ModuleReplacement } from "./transition.ts";
|
|
45
46
|
|
|
46
47
|
export interface StateFlowExtensionOptions {
|
|
@@ -54,8 +55,12 @@ export interface StateFlowExtensionOptions {
|
|
|
54
55
|
|
|
55
56
|
export { formatPatchStateArguments };
|
|
56
57
|
|
|
57
|
-
export const PATCH_STATE_TOOL_NAME = "
|
|
58
|
-
export const READ_STATE_TOOL_NAME = "
|
|
58
|
+
export const PATCH_STATE_TOOL_NAME = "state_flow_patch";
|
|
59
|
+
export const READ_STATE_TOOL_NAME = "state_flow_read";
|
|
60
|
+
const LEGACY_PATCH_STATE_TOOL_NAME = "patch_state";
|
|
61
|
+
const LEGACY_READ_STATE_TOOL_NAME = "read_state";
|
|
62
|
+
const STATE_FLOW_TOOL_NAMES = [PATCH_STATE_TOOL_NAME, READ_STATE_TOOL_NAME, LEGACY_PATCH_STATE_TOOL_NAME, LEGACY_READ_STATE_TOOL_NAME];
|
|
63
|
+
const isPatchStateTool = (name: string) => name === PATCH_STATE_TOOL_NAME || name === LEGACY_PATCH_STATE_TOOL_NAME;
|
|
59
64
|
const PASSIVE_STOP_ENTRY_TYPE = "state-flow-passive-stop";
|
|
60
65
|
|
|
61
66
|
const flatPatchParameters = Type.Object({
|
|
@@ -125,6 +130,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
125
130
|
let effectiveState: SemanticState = {};
|
|
126
131
|
let branchStartsWithoutRuntime = false;
|
|
127
132
|
let modePersistenceError: string | undefined;
|
|
133
|
+
const healNotice = new HealNotice();
|
|
128
134
|
/** One pending inactive-mode persistence; later inactive choices coalesce until it publishes. */
|
|
129
135
|
const inactivePersistence = new OwnedOperationSlot<InactivePersistence>();
|
|
130
136
|
const startActivation = new OwnedOperationSlot<ModeOperation>();
|
|
@@ -177,6 +183,38 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
177
183
|
ctx.ui.notify(conciseDiagnostic(message), level);
|
|
178
184
|
}
|
|
179
185
|
|
|
186
|
+
/** Announce a reset to both operator and model; a reset is never silent. */
|
|
187
|
+
function announceHealing(ctx: ExtensionContext, message: string): void {
|
|
188
|
+
healNotice.announce(message);
|
|
189
|
+
diagnosticWriter.recordSelfHeal(sessionAddress(ctx).id, ctx.cwd, message);
|
|
190
|
+
ctx.ui.notify(message, "warning");
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Quarantine unrecoverable selected owners before acceptance; unhealable failures keep failing closed downstream. */
|
|
194
|
+
async function healCurrentStore(ctx: ExtensionContext, wanted: ScopeSelection, signal: AbortSignal): Promise<HealResult | undefined> {
|
|
195
|
+
const address = sessionAddress(ctx);
|
|
196
|
+
let result: HealResult;
|
|
197
|
+
try {
|
|
198
|
+
result = await healSelectedStore({ cwd: ctx.cwd, sessionId: address.id, sessionKey: address.key, selection: wanted,
|
|
199
|
+
historyLimit: config.historyLimit, root: repositoryRoot }, signal);
|
|
200
|
+
} catch (error) {
|
|
201
|
+
if (signal.aborted) throw error;
|
|
202
|
+
return undefined;
|
|
203
|
+
}
|
|
204
|
+
if (result.healed.length) announceHealing(ctx, `State Flow self-healed: ${describeHealedScopes(result.healed)}`);
|
|
205
|
+
return result;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** A pre-runtime branch with no stored cohort reads as empty memory instead of an unavailable runtime. */
|
|
209
|
+
function emptyPreRuntimeView(wanted: ScopeSelection): SelectedTemporalState | undefined {
|
|
210
|
+
if (!branchStartsWithoutRuntime || snapshot.config.mode === "off" || snapshot.meta.validation?.attempt === 0
|
|
211
|
+
|| branchRestoration.current?.awaitingAcceptance) return undefined;
|
|
212
|
+
// Shared absence is empty reality; unacquired Session keeps its explicit selected-unavailable diagnostic.
|
|
213
|
+
const shared = wanted.filter(scope => scope !== "session");
|
|
214
|
+
if (!shared.length) return undefined;
|
|
215
|
+
return createSelectedTemporalState(Object.fromEntries(shared.map(scope => [scope, {}])), captureScopeSelection(shared), "empty:pre-runtime", config.historyLimit);
|
|
216
|
+
}
|
|
217
|
+
|
|
180
218
|
function notifyActiveContext(message: string): void {
|
|
181
219
|
try {
|
|
182
220
|
if (activeContext) notifyProblem(activeContext, message, "warning");
|
|
@@ -381,13 +419,13 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
381
419
|
// Every SDK registration is a fresh copy, preserving old response-wrapper declarations.
|
|
382
420
|
if (force || patchStateTool.parameters !== parameters) {
|
|
383
421
|
patchStateTool.parameters = parameters;
|
|
384
|
-
pi.registerTool({ ...
|
|
422
|
+
for (const tool of [patchStateTool, legacyPatchStateTool]) pi.registerTool({ ...tool, parameters, ...(external.length && tool === patchStateTool ? {
|
|
385
423
|
promptGuidelines: [...(patchStateTool.promptGuidelines ?? []), `Registered mutable object planes: ${external.join(", ")}. Availability and matching retained schema/policy are revalidated at acceptance.`],
|
|
386
424
|
} : {}) });
|
|
387
425
|
}
|
|
388
426
|
}
|
|
389
427
|
const active = pi.getActiveTools();
|
|
390
|
-
const owned =
|
|
428
|
+
const owned = STATE_FLOW_TOOL_NAMES;
|
|
391
429
|
if (owned.every((name) => active.includes(name) === available)) return;
|
|
392
430
|
pi.setActiveTools(available
|
|
393
431
|
? [...new Set([...active, ...owned])]
|
|
@@ -691,9 +729,30 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
691
729
|
return branchRestoration.track(pending, attachBranch(ctx, pending, selection, sessionStartReason, notifyRecovery, skipped), false);
|
|
692
730
|
}
|
|
693
731
|
|
|
732
|
+
/**
|
|
733
|
+
* After a failed attachment, heal selected owners once. Returns the selection to retry, or undefined when healing
|
|
734
|
+
* changed nothing; expected-but-absent session memory restarts visibly from empty memory.
|
|
735
|
+
*/
|
|
736
|
+
async function healBranchSelection(ctx: ExtensionContext, selection: BranchSelection, requestedMode: InactiveMode | undefined, signal: AbortSignal): Promise<BranchSelection | undefined> {
|
|
737
|
+
if (selection.kind === "settled") return undefined;
|
|
738
|
+
const healing = await healCurrentStore(ctx, nativeScopeSelection(ctx), signal).catch(() => undefined);
|
|
739
|
+
if (!healing || signal.aborted || shuttingDown) return undefined;
|
|
740
|
+
if (healing.lifecycleAbsent && (selection.kind === "attach" || selection.kind === "current")) {
|
|
741
|
+
const mode = requestedMode ?? (selection.kind === "current" ? selection.mode : selection.checkpoint.mode);
|
|
742
|
+
if (mode === "off") return undefined;
|
|
743
|
+
if (!healing.healed.some(item => item.scope === "session")) {
|
|
744
|
+
announceHealing(ctx, "State Flow self-healed: session memory files were missing and session memory restarts empty");
|
|
745
|
+
}
|
|
746
|
+
branchStartsWithoutRuntime = true;
|
|
747
|
+
modePersistenceError = undefined;
|
|
748
|
+
return mode === "active" ? { kind: "auto-start" } : { kind: "pre-runtime", mode };
|
|
749
|
+
}
|
|
750
|
+
return healing.healed.length > 0 ? selection : undefined;
|
|
751
|
+
}
|
|
752
|
+
|
|
694
753
|
async function attachBranch(
|
|
695
754
|
ctx: ExtensionContext, pending: BranchRestoration, selection: BranchSelection,
|
|
696
|
-
reason: unknown, notifyRecovery: boolean, skipped: number,
|
|
755
|
+
reason: unknown, notifyRecovery: boolean, skipped: number, healed = false,
|
|
697
756
|
): Promise<void> {
|
|
698
757
|
const placeholder = runtime;
|
|
699
758
|
let selected = runtime;
|
|
@@ -853,6 +912,12 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
853
912
|
return;
|
|
854
913
|
}
|
|
855
914
|
if (!isCurrent()) return;
|
|
915
|
+
const retry = healed ? undefined : await healBranchSelection(ctx, selection, pending.requestedMode, signal);
|
|
916
|
+
if (retry && isCurrent()) {
|
|
917
|
+
pending.awaitingAcceptance = retry.kind !== "settled" && retry.kind !== "current";
|
|
918
|
+
return await attachBranch(ctx, pending, retry, reason, notifyRecovery, skipped, true);
|
|
919
|
+
}
|
|
920
|
+
if (!isCurrent()) return;
|
|
856
921
|
failSelection(error);
|
|
857
922
|
} finally {
|
|
858
923
|
pending.awaitingAcceptance = false;
|
|
@@ -862,7 +927,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
862
927
|
settleSelection(ctx, reason, notifyRecovery, skipped, selected !== placeholder);
|
|
863
928
|
if (snapshot.config.mode === "off" || isActive() || readableView() || snapshot.meta.validation?.attempt === 0 || !branchStartsWithoutRuntime) return;
|
|
864
929
|
// Only a proven pre-runtime Passive branch may observe shared owners without private acquisition.
|
|
865
|
-
const passive = await loadPassiveView(ctx, signal, isCurrent, notifyRecovery);
|
|
930
|
+
const passive = await loadPassiveView(ctx, signal, isCurrent, notifyRecovery, !healed);
|
|
866
931
|
if (passive === undefined) return;
|
|
867
932
|
assertCurrent();
|
|
868
933
|
// An intervening passive patch or inspection owns its newer cache, even on the same physical branch.
|
|
@@ -881,14 +946,21 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
881
946
|
}
|
|
882
947
|
|
|
883
948
|
/** Load current shared memory for passive projection without initializing or publishing it. */
|
|
884
|
-
async function loadPassiveView(ctx: ExtensionContext, signal: AbortSignal, isCurrent: () => boolean, notify: boolean): Promise<TemporalRuntime | undefined> {
|
|
949
|
+
async function loadPassiveView(ctx: ExtensionContext, signal: AbortSignal, isCurrent: () => boolean, notify: boolean, heal = true): Promise<TemporalRuntime | undefined> {
|
|
885
950
|
const wanted = nativeScopeSelection(ctx), shared = wanted.filter(scope => scope !== "session");
|
|
886
951
|
if (!shared.length) return undefined;
|
|
887
952
|
const passive = createRuntime(ctx);
|
|
953
|
+
const observe = () => passive.refreshSelectedShared(captureScopeSelection(shared), () => {
|
|
954
|
+
if (!isCurrent() || !sameJson(nativeScopeSelection(ctx), wanted)) throw new Error("State Flow observation selection changed");
|
|
955
|
+
}, signal);
|
|
888
956
|
try {
|
|
889
|
-
await
|
|
890
|
-
|
|
891
|
-
|
|
957
|
+
try { await observe(); }
|
|
958
|
+
catch (error) {
|
|
959
|
+
if (!heal || signal.aborted || !isCurrent()) throw error;
|
|
960
|
+
const healing = await healCurrentStore(ctx, captureScopeSelection(shared), signal).catch(() => undefined);
|
|
961
|
+
if (!healing?.healed.length) throw error;
|
|
962
|
+
await observe();
|
|
963
|
+
}
|
|
892
964
|
} catch (error) {
|
|
893
965
|
if (isCurrent() && !signal.aborted && notify && !modePersistenceError) notifyProblem(ctx, `State Flow passive memory is unavailable: ${diagnosticText(error)}`, "warning");
|
|
894
966
|
return undefined;
|
|
@@ -944,8 +1016,10 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
944
1016
|
} catch { return false; }
|
|
945
1017
|
}
|
|
946
1018
|
|
|
947
|
-
|
|
948
|
-
|
|
1019
|
+
function readStateDefinition(name: string) {
|
|
1020
|
+
return defineTool({
|
|
1021
|
+
name,
|
|
1022
|
+
...(name === LEGACY_READ_STATE_TOOL_NAME ? { prepareLoadout: () => ({ hiddenDeclarations: [name] }) } : {}),
|
|
949
1023
|
label: "Read State",
|
|
950
1024
|
description: "Read exact State Flow values or historical semantic patches with one path or an ordered path list. With one participating owner, semantic paths and structured references are scope-free, effective[N] selects that owner's historical boundary, and patches[N] selects its retained owner patch. With multiple owners, unscoped paths use the effective overlay and owner patch history requires an explicit owner. Optional global/cwd/session roots may address only participating available owners. Array selectors are zero-based indices or half-open [start..end] ranges, never temporal offsets inside a semantic value. Projection value returns data; keys returns minimal structure; patch intersects the selected path at its boundary. Path object keys must be ASCII identifiers ([A-Za-z_$][A-Za-z0-9_$-]*); non-ASCII keys cannot be addressed.",
|
|
951
1025
|
promptSnippet: "Read exact state values, structures, or historical semantic patches",
|
|
@@ -957,7 +1031,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
957
1031
|
}, { additionalProperties: false }),
|
|
958
1032
|
async execute(toolCallId, params, signal, _onUpdate, ctx) {
|
|
959
1033
|
try {
|
|
960
|
-
const admission = nativeToolAdmission(toolCallId,
|
|
1034
|
+
const admission = nativeToolAdmission(toolCallId, name, ctx);
|
|
961
1035
|
admission?.revalidate();
|
|
962
1036
|
if (admission) signal = signal ? AbortSignal.any([signal, admission.signal]) : admission.signal;
|
|
963
1037
|
type ReadDetails = { path?: string; paths?: string[]; projection?: string; transitionId?: string };
|
|
@@ -977,17 +1051,18 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
977
1051
|
const wanted = captureScopeSelection(receipt.policy.scopes);
|
|
978
1052
|
params = structuredClone(params);
|
|
979
1053
|
check();
|
|
980
|
-
if (params.path === undefined && params.paths === undefined) throw new Error("
|
|
981
|
-
if (params.path !== undefined && params.paths !== undefined) throw new Error("
|
|
1054
|
+
if (params.path === undefined && params.paths === undefined) throw new Error("state_flow_read requires path or paths");
|
|
1055
|
+
if (params.path !== undefined && params.paths !== undefined) throw new Error("state_flow_read accepts path or paths, not both");
|
|
982
1056
|
{
|
|
983
1057
|
const requestedPaths = [...(params.paths ?? [params.path!])];
|
|
984
1058
|
const paths = requestedPaths.map(path => normalizeModelReadPath(path, wanted, config.historyLimit));
|
|
985
1059
|
check();
|
|
986
|
-
const view = readableView(selected);
|
|
1060
|
+
const view = readableView(selected) ?? emptyPreRuntimeView(wanted);
|
|
987
1061
|
// Wanted policy was checked by normalization; an observational subset is not an exclusion.
|
|
988
1062
|
for (const path of paths) {
|
|
989
1063
|
const owner = /^(global|cwd|session)(?=\.|\[|$)/.exec(path)?.[1] as StateScope | undefined;
|
|
990
|
-
if (owner && !view?.selection.includes(owner)) throw new Error(`State Flow ${owner}: selected, unavailable
|
|
1064
|
+
if (owner && !view?.selection.includes(owner)) throw new Error(`State Flow ${owner}: selected, unavailable${branchStartsWithoutRuntime
|
|
1065
|
+
? "; no memory is stored for it yet, and an accepted state_flow_patch creates it" : ""}`);
|
|
991
1066
|
}
|
|
992
1067
|
if (!view) throw new Error("State Flow temporal runtime is unavailable");
|
|
993
1068
|
check();
|
|
@@ -1017,22 +1092,28 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
1017
1092
|
},
|
|
1018
1093
|
});
|
|
1019
1094
|
|
|
1020
|
-
|
|
1021
|
-
|
|
1095
|
+
}
|
|
1096
|
+
pi.registerTool(readStateDefinition(READ_STATE_TOOL_NAME));
|
|
1097
|
+
pi.registerTool({ ...readStateDefinition(LEGACY_READ_STATE_TOOL_NAME), promptSnippet: "", promptGuidelines: [] });
|
|
1098
|
+
|
|
1099
|
+
function patchStateDefinition(name: string) {
|
|
1100
|
+
return defineTool({
|
|
1101
|
+
name,
|
|
1102
|
+
...(name === LEGACY_PATCH_STATE_TOOL_NAME ? { prepareLoadout: () => ({ hiddenDeclarations: [name] }) } : {}),
|
|
1022
1103
|
label: "Patch State",
|
|
1023
1104
|
description: "The sole State Flow semantic mutation protocol. With one participating owner, supply intents/strategy/tactics/artifacts/lazy planes directly, without an owner wrapper. With multiple owners, supply one or more global, cwd, or session patches for participating owners; all supplied owners commit atomically. This call must be the only State Flow barrier in its assistant response. Intent updates run first, then clear owned same-scope strategy/tactics/lazy keys unless a remaining or new intent refs them, then other fields apply. Later writes can recreate cleared paths without old fields. Name keys in ASCII ([A-Za-z_$][A-Za-z0-9_$-]*) so read paths and refs resolve; values may use any language.",
|
|
1024
1105
|
promptSnippet: "Atomically patch participating semantic memory in its declared flat or multi-owner form",
|
|
1025
1106
|
promptGuidelines: [
|
|
1026
1107
|
RESPONSE_PATCH_GUIDELINE,
|
|
1027
1108
|
SCOPE_PARTICIPATION_GUIDELINE,
|
|
1028
|
-
"Use
|
|
1029
|
-
"Use
|
|
1030
|
-
"Call
|
|
1109
|
+
"Use state_flow_patch only for material durable semantic changes; ordinary answers need no finalization call.",
|
|
1110
|
+
"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.",
|
|
1111
|
+
"Call state_flow_patch alone in an assistant response; after its acknowledgement, further reasoning, tools, and later state_flow_patch calls remain allowed.",
|
|
1031
1112
|
],
|
|
1032
1113
|
executionMode: "sequential",
|
|
1033
1114
|
parameters: config.scopes.length === 1 ? flatPatchParameters : scopedPatchParameters,
|
|
1034
1115
|
renderCall(args, theme, context) {
|
|
1035
|
-
const title = theme.fg("toolTitle", theme.bold(
|
|
1116
|
+
const title = theme.fg("toolTitle", theme.bold(name));
|
|
1036
1117
|
if (!config.showSuccessfulPatches && !context.isError) return new Text(title, 0, 0);
|
|
1037
1118
|
return new Text(`${title}\n${separatedOutput(theme.fg("dim", formatPatchStateArguments(args)))}`, 0, 0);
|
|
1038
1119
|
},
|
|
@@ -1044,7 +1125,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
1044
1125
|
signal = signal ? AbortSignal.any([signal, memoryToolLifetime.signal]) : memoryToolLifetime.signal;
|
|
1045
1126
|
let admitted = false;
|
|
1046
1127
|
try {
|
|
1047
|
-
const admission = nativeToolAdmission(toolCallId,
|
|
1128
|
+
const admission = nativeToolAdmission(toolCallId, name, ctx);
|
|
1048
1129
|
admission?.revalidate();
|
|
1049
1130
|
if (admission) signal = AbortSignal.any([signal, admission.signal]);
|
|
1050
1131
|
if (!memoryToolsAvailable()) throw new Error("State Flow tools are off for this session");
|
|
@@ -1164,7 +1245,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
1164
1245
|
try { attempted = structuredClone(params); } catch { attempted = undefined; }
|
|
1165
1246
|
const cause = diagnosticText(error);
|
|
1166
1247
|
recordDiagnostic(cause, /concurrently|advanced/.test(cause) ? "publication-conflict" : "invalid-patch", ctx, {
|
|
1167
|
-
input: attempted, tool:
|
|
1248
|
+
input: attempted, tool: name, toolCallId,
|
|
1168
1249
|
});
|
|
1169
1250
|
}
|
|
1170
1251
|
throw separatedFailure(error);
|
|
@@ -1172,7 +1253,11 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
1172
1253
|
},
|
|
1173
1254
|
});
|
|
1174
1255
|
|
|
1256
|
+
}
|
|
1257
|
+
const patchStateTool = patchStateDefinition(PATCH_STATE_TOOL_NAME);
|
|
1258
|
+
const legacyPatchStateTool = { ...patchStateDefinition(LEGACY_PATCH_STATE_TOOL_NAME), promptSnippet: "", promptGuidelines: [] };
|
|
1175
1259
|
pi.registerTool({ ...patchStateTool });
|
|
1260
|
+
pi.registerTool({ ...legacyPatchStateTool });
|
|
1176
1261
|
|
|
1177
1262
|
function startStateFlow(ctx: ExtensionContext, reselect = false): Promise<StateFlowTelegramControlResult> {
|
|
1178
1263
|
if (shuttingDown) return Promise.resolve({ ok: false, message: "State Flow is shutting down" });
|
|
@@ -1223,6 +1308,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
1223
1308
|
async function activateCurrentState(
|
|
1224
1309
|
ctx: ExtensionContext, pending: AbortController, mode: "active" | "passive" = "active",
|
|
1225
1310
|
owns = () => startActivation.current?.controller === pending,
|
|
1311
|
+
healing?: HealResult,
|
|
1226
1312
|
): Promise<StateFlowTelegramControlResult> {
|
|
1227
1313
|
let selected = runtime;
|
|
1228
1314
|
const wanted = nativeScopeSelection(ctx);
|
|
@@ -1249,15 +1335,24 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
1249
1335
|
const retained = selectRetainedCheckpoint(discovery.candidates, config.inactiveMode);
|
|
1250
1336
|
branchStartsWithoutRuntime = retained.kind === "pre-runtime" || (discovery.candidates.length === 0 && discovery.errors.length === 0);
|
|
1251
1337
|
}
|
|
1338
|
+
// After a failed attempt, a missing or reset session lifecycle restarts visibly from empty memory instead of blocking forever.
|
|
1339
|
+
const sessionReset = healing?.lifecycleAbsent === true && !forkInitialization && !branchPolicy(ctx).forkPending
|
|
1340
|
+
&& !(selected?.cwd === ctx.cwd && selected.sessionKey === activation.sessionKey && selected.selectedView()?.selection.includes("session"));
|
|
1341
|
+
if (sessionReset) {
|
|
1342
|
+
if (!branchStartsWithoutRuntime && !healing!.healed.some(item => item.scope === "session")) {
|
|
1343
|
+
announceHealing(ctx, "State Flow self-healed: session memory files were missing and session memory restarts empty");
|
|
1344
|
+
}
|
|
1345
|
+
branchStartsWithoutRuntime = true;
|
|
1346
|
+
}
|
|
1252
1347
|
// Off activation owns one cancellable current-head publication, not an independent read-only restore.
|
|
1253
1348
|
const acceptActivation = (current: Snapshot | undefined, publish: (next: Snapshot) => SelectedFilePublication) => {
|
|
1254
1349
|
signal.throwIfAborted();
|
|
1255
1350
|
if (!isCurrent()) throw new Error("State Flow activation selection changed while awaiting publication");
|
|
1256
|
-
if (!current && (!active || !branchStartsWithoutRuntime)) throw new Error(snapshot.meta.validation?.error ?? "Current State Flow session memory is unavailable");
|
|
1351
|
+
if (!current && (!(active || sessionReset) || !branchStartsWithoutRuntime)) throw new Error(snapshot.meta.validation?.error ?? "Current State Flow session memory is unavailable");
|
|
1257
1352
|
const boundary = deferred && retainsPhysicalSessionProjection(deferred.reason)
|
|
1258
1353
|
? branchPolicy(ctx).stop : undefined;
|
|
1259
1354
|
const bootstrap = hasPriorConversation(ctx.sessionManager.getBranch()) || passiveContinuation !== undefined || boundary !== undefined;
|
|
1260
|
-
const activated = !active ? deactivateEpisode(current
|
|
1355
|
+
const activated = !active ? deactivateEpisode(current ?? startEpisode(false), "passive")
|
|
1261
1356
|
: current ? resumeEpisode(current, bootstrap) : startEpisode(bootstrap);
|
|
1262
1357
|
if (active) {
|
|
1263
1358
|
// Explicit Start accepts current memory, not the prior run's prompt or repair attempt.
|
|
@@ -1321,8 +1416,9 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
1321
1416
|
if (forkInitialization || branchPolicy(ctx).forkPending) throw new Error("Pending fork cannot use independent private acquisition");
|
|
1322
1417
|
acquiredResult = acceptActivation(basis.snapshot, activated => publish(activated));
|
|
1323
1418
|
} }, publish => { check(); publish(); return acquiredResult; }, signal, true);
|
|
1324
|
-
} else if (active && branchStartsWithoutRuntime && !acceptedSession && !disposition) {
|
|
1325
|
-
const
|
|
1419
|
+
} else if ((active || sessionReset) && branchStartsWithoutRuntime && !acceptedSession && !disposition) {
|
|
1420
|
+
const started = startEpisode(hasPriorConversation(ctx.sessionManager.getBranch()) || passiveContinuation !== undefined);
|
|
1421
|
+
const next = active ? started : deactivateEpisode(startEpisode(false), "passive");
|
|
1326
1422
|
result = await activation.withSelectedFirstPatchTransaction(wanted, next, transaction => {
|
|
1327
1423
|
check();
|
|
1328
1424
|
if (!branchStartsWithoutRuntime || forkInitialization) throw new Error("State Flow origin authority changed");
|
|
@@ -1333,6 +1429,12 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
1333
1429
|
return isCurrent() ? result : superseded();
|
|
1334
1430
|
} catch (error) {
|
|
1335
1431
|
if (!isCurrent()) return superseded();
|
|
1432
|
+
if (!accepted && healing === undefined) {
|
|
1433
|
+
// Self-healing is lazy: healthy stores never pay for it, and one retry bounds convergence.
|
|
1434
|
+
const healed = await healCurrentStore(ctx, wanted, signal).catch(() => undefined);
|
|
1435
|
+
if (!isCurrent()) return superseded();
|
|
1436
|
+
if (healed && (healed.healed.length > 0 || healed.lifecycleAbsent)) return activateCurrentState(ctx, pending, mode, owns, healed);
|
|
1437
|
+
}
|
|
1336
1438
|
const message = conciseDiagnostic(`${accepted ? `State Flow ${mode}; lifecycle update failed` : active ? "State Flow activation failed" : "State Flow passive acceptance failed"}: ${diagnosticText(error)}`);
|
|
1337
1439
|
// An unaccepted activation cannot replace retained lifecycle or poison an independent Stop.
|
|
1338
1440
|
// Attachment owns required-proof unavailability; failed Passive acceptance reports through its caller's fence.
|
|
@@ -1766,7 +1868,9 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
1766
1868
|
// Off removes the owned section, including one contributed before an in-flight mode change.
|
|
1767
1869
|
const protocol = isActive() ? stateFlowProtocol(snapshot.meta.bootstrap === true, nativeScopeSelection(ctx))
|
|
1768
1870
|
: passiveMemoryAvailable() ? passiveMemoryProtocol(nativeScopeSelection(ctx)) : undefined;
|
|
1769
|
-
|
|
1871
|
+
// Only a request that can carry the section consumes the reset notice.
|
|
1872
|
+
const notice = snapshot.config.mode !== "off" && event.messages.some(message => message.role === "system") ? healNotice.project() : undefined;
|
|
1873
|
+
return { messages: projectSystemProtocol(event.messages, [protocol, notice].filter(Boolean).join("\n\n") || undefined) };
|
|
1770
1874
|
});
|
|
1771
1875
|
|
|
1772
1876
|
// Optional transport checkpoint: no payload/header inspection or transformation.
|
|
@@ -1925,9 +2029,9 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
1925
2029
|
});
|
|
1926
2030
|
|
|
1927
2031
|
pi.on("tool_call", (event, ctx) => {
|
|
1928
|
-
const owned =
|
|
2032
|
+
const owned = STATE_FLOW_TOOL_NAMES.includes(event.toolName);
|
|
1929
2033
|
if (event.parentToolCallId) {
|
|
1930
|
-
if (event.toolName
|
|
2034
|
+
if (isPatchStateTool(event.toolName) && isActive()) return { block: true, reason: "state_flow_patch requires a direct native assistant barrier, not a nested call" };
|
|
1931
2035
|
try { nativeRequests.nested(event.toolCallId, event.toolName, event.parentToolCallId); }
|
|
1932
2036
|
catch { if (owned) return { block: true, reason: "State Flow tool batch has no current native request" }; }
|
|
1933
2037
|
}
|
|
@@ -1937,15 +2041,15 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
1937
2041
|
}
|
|
1938
2042
|
if (!isActive() || !currentNativeTool(event.toolCallId, event.toolName, ctx)) return;
|
|
1939
2043
|
const batch = findAssistantToolBatch(ctx.sessionManager, event.toolCallId);
|
|
1940
|
-
const patchCalls = batch?.filter(
|
|
2044
|
+
const patchCalls = batch?.filter(isPatchStateTool).length ?? 0;
|
|
1941
2045
|
if (patchCalls > 0) {
|
|
1942
2046
|
if (patchCalls !== 1) {
|
|
1943
|
-
const reason = "A State Flow barrier response must contain exactly one
|
|
2047
|
+
const reason = "A State Flow barrier response must contain exactly one state_flow_patch call";
|
|
1944
2048
|
recordDiagnostic(reason, "barrier-block", ctx, { tool: event.toolName, toolCallId: event.toolCallId, batchToolNames: batch });
|
|
1945
2049
|
return { block: true, reason };
|
|
1946
2050
|
}
|
|
1947
|
-
if (event.toolName
|
|
1948
|
-
const reason = "Blocked by the
|
|
2051
|
+
if (!isPatchStateTool(event.toolName)) {
|
|
2052
|
+
const reason = "Blocked by the state_flow_patch barrier; reconsider this action after State Flow rematerializes context";
|
|
1949
2053
|
recordDiagnostic(reason, "barrier-block", ctx, { tool: event.toolName, toolCallId: event.toolCallId, batchToolNames: batch });
|
|
1950
2054
|
return { block: true, reason };
|
|
1951
2055
|
}
|
|
@@ -2113,6 +2217,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
2113
2217
|
});
|
|
2114
2218
|
|
|
2115
2219
|
pi.on("agent_settled", async (_event, ctx) => {
|
|
2220
|
+
healNotice.settle();
|
|
2116
2221
|
if (telegramStartPending && !isActive()) {
|
|
2117
2222
|
telegramStartPending = false;
|
|
2118
2223
|
await startStateFlow(ctx);
|
package/lib/healing.ts
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
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.ts";
|
|
7
|
+
import { sessionRuntimePaths, temporalScopePaths } from "./durable.ts";
|
|
8
|
+
import { captureScopeSelection, type ScopeSelection } from "./selection.ts";
|
|
9
|
+
import { RevisionUnavailableError } from "./snapshot.ts";
|
|
10
|
+
import type { StateScope } from "./state.ts";
|
|
11
|
+
import { assertStorageDirectory, PublicationBusyError, withStorageTransaction, type StorageTransaction } from "./storage.ts";
|
|
12
|
+
|
|
13
|
+
/** One visible reset: the scope became wholly absent after its exact bytes were quarantined. */
|
|
14
|
+
export interface HealedScope {
|
|
15
|
+
scope: StateScope;
|
|
16
|
+
reason: string;
|
|
17
|
+
quarantine: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Healing outcome; `lifecycleAbsent` means this session owns no lifecycle after healing. */
|
|
21
|
+
export interface HealResult {
|
|
22
|
+
healed: HealedScope[];
|
|
23
|
+
lifecycleAbsent: boolean;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface HealRequest {
|
|
27
|
+
cwd: string;
|
|
28
|
+
sessionId: string;
|
|
29
|
+
sessionKey: string;
|
|
30
|
+
selection: ScopeSelection;
|
|
31
|
+
historyLimit: number;
|
|
32
|
+
root: string;
|
|
33
|
+
/** Wall-clock source for deterministic tests. */
|
|
34
|
+
now?: () => Date;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Only semantic decoding/validation failures are healable. Filesystem, lock, cancellation and
|
|
39
|
+
* foreign-owner identity failures keep failing closed because resetting cannot fix them safely.
|
|
40
|
+
*/
|
|
41
|
+
export function isHealableCorruption(error: unknown): boolean {
|
|
42
|
+
if (!(error instanceof Error)) return false;
|
|
43
|
+
if (error instanceof RevisionUnavailableError || error instanceof PublicationBusyError) return false;
|
|
44
|
+
if (error.name === "AbortError") return false;
|
|
45
|
+
if (typeof (error as NodeJS.ErrnoException).code === "string") return false;
|
|
46
|
+
if (/identity mismatch/i.test(error.message)) return false;
|
|
47
|
+
if (error instanceof AggregateError) return error.errors.every(isHealableCorruption);
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function scopeFiles(request: HealRequest, scope: StateScope): string[] {
|
|
52
|
+
const paths = temporalScopePaths(request.cwd, request.sessionId, scope, request.root, request.sessionKey);
|
|
53
|
+
const semantic = [paths.checkpoint, paths.patches, paths.meta, resolve(paths.directory, "state.json")];
|
|
54
|
+
if (scope !== "session") return semantic;
|
|
55
|
+
const runtime = sessionRuntimePaths(request.cwd, request.sessionId, request.root, request.sessionKey);
|
|
56
|
+
return [...semantic, runtime.config, runtime.runtime];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function readPresent(path: string): Buffer | undefined {
|
|
60
|
+
const stat = lstatSync(path, { throwIfNoEntry: false });
|
|
61
|
+
if (!stat) return undefined;
|
|
62
|
+
if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`State Flow quarantine refuses a non-regular file: ${JSON.stringify(path)}`);
|
|
63
|
+
return readFileSync(path, { flag: constants.O_RDONLY | constants.O_NOFOLLOW });
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Exact-byte private record first; canonical files are removed only after the record verifies. */
|
|
67
|
+
function quarantineScope(request: HealRequest, scope: StateScope, reason: string): HealedScope | undefined {
|
|
68
|
+
const root = resolve(request.root);
|
|
69
|
+
const files = scopeFiles(request, scope).map(path => ({ path, bytes: readPresent(path) })).filter(file => file.bytes !== undefined);
|
|
70
|
+
if (files.length === 0) return undefined;
|
|
71
|
+
const at = (request.now?.() ?? new Date()).toISOString();
|
|
72
|
+
const content = `${canonicalJson({ version: 1, kind: "state-flow-quarantine", at, root, cwd: resolve(request.cwd),
|
|
73
|
+
sessionId: request.sessionId, sessionKey: request.sessionKey, scope, reason,
|
|
74
|
+
files: files.map(file => ({ path: relative(root, file.path), bytes: file.bytes!.toString("base64") })) })}\n`;
|
|
75
|
+
const directory = resolve(dirname(root), `${basename(root)}-quarantine`);
|
|
76
|
+
assertStorageDirectory(directory);
|
|
77
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
78
|
+
const directoryStat = lstatSync(directory);
|
|
79
|
+
if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink() || (directoryStat.mode & 0o077) !== 0) {
|
|
80
|
+
throw new Error("State Flow quarantine directory must be private; canonical files preserved");
|
|
81
|
+
}
|
|
82
|
+
const digest = createHash("sha256").update(content).digest("hex").slice(0, 16);
|
|
83
|
+
const path = resolve(directory, `${at.replace(/[:.]/g, "-")}-${scope}-${digest}.json`);
|
|
84
|
+
try { writeFileSync(path, content, { flag: "wx", mode: 0o600 }); }
|
|
85
|
+
catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }
|
|
86
|
+
if (readFileSync(path, { encoding: "utf8", flag: constants.O_RDONLY | constants.O_NOFOLLOW }) !== content) {
|
|
87
|
+
throw new Error("State Flow quarantine record changed; canonical files preserved");
|
|
88
|
+
}
|
|
89
|
+
for (const file of files) rmSync(file.path);
|
|
90
|
+
return { scope, reason, quarantine: path };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function probe(action: () => unknown, signal?: AbortSignal): Error | undefined {
|
|
94
|
+
try { action(); return undefined; }
|
|
95
|
+
catch (error) {
|
|
96
|
+
// Cancellation reasons are arbitrary values; they never prove corruption.
|
|
97
|
+
signal?.throwIfAborted();
|
|
98
|
+
if (!isHealableCorruption(error)) throw error;
|
|
99
|
+
return error as Error;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Converge the selected owners to a loadable store: decode each owner independently, then the
|
|
105
|
+
* complete selected cohort. A broken owner is quarantined and becomes wholly absent, which the
|
|
106
|
+
* normal lifecycle treats as empty memory. Healthy stores are never written.
|
|
107
|
+
*/
|
|
108
|
+
export function healSelectedStoreLocked(storage: StorageTransaction, request: HealRequest, signal?: AbortSignal): HealResult {
|
|
109
|
+
const wanted = captureScopeSelection(request.selection);
|
|
110
|
+
const { cwd, sessionId, sessionKey, root, historyLimit } = request;
|
|
111
|
+
const healed: HealedScope[] = [];
|
|
112
|
+
const reset = (scope: StateScope, error: Error) => {
|
|
113
|
+
const result = quarantineScope(request, scope, error.message);
|
|
114
|
+
if (result) healed.push(result);
|
|
115
|
+
};
|
|
116
|
+
for (const scope of wanted.filter(owner => owner !== "session")) {
|
|
117
|
+
const failure = probe(() => storage.observeSelectedShared(cwd, captureScopeSelection([scope]), root), signal);
|
|
118
|
+
if (failure) reset(scope, failure);
|
|
119
|
+
}
|
|
120
|
+
let lifecycle: ReturnType<StorageTransaction["inspectSelectedLifecycle"]>;
|
|
121
|
+
const lifecycleFailure = probe(() => { lifecycle = storage.inspectSelectedLifecycle(cwd, sessionId, wanted, root, sessionKey); }, signal);
|
|
122
|
+
if (lifecycleFailure) {
|
|
123
|
+
reset("session", lifecycleFailure);
|
|
124
|
+
return { healed, lifecycleAbsent: true };
|
|
125
|
+
}
|
|
126
|
+
if (!lifecycle) return { healed, lifecycleAbsent: true };
|
|
127
|
+
if (wanted.includes("session") && lifecycle.runtime.meta.privateAcquisition !== "acquired") return { healed, lifecycleAbsent: false };
|
|
128
|
+
// The session lifecycle anchors cross-owner lineage, so a contradictory cohort resets that private anchor.
|
|
129
|
+
const cohortFailure = probe(() => storage.prepareSelectedCurrent(cwd, sessionId, wanted, historyLimit, root, sessionKey), signal);
|
|
130
|
+
if (cohortFailure) reset("session", cohortFailure);
|
|
131
|
+
return { healed, lifecycleAbsent: cohortFailure !== undefined };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Never waits behind a live writer: a busy store is being used, so healing defers to a later attempt. */
|
|
135
|
+
export async function healSelectedStore(request: HealRequest, signal?: AbortSignal): Promise<HealResult> {
|
|
136
|
+
const root = resolve(request.root);
|
|
137
|
+
if (!lstatSync(root, { throwIfNoEntry: false })) return { healed: [], lifecycleAbsent: true };
|
|
138
|
+
return withStorageTransaction(root, storage => healSelectedStoreLocked(storage, { ...request, root }, signal), signal, false);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** One pending reset notice: projected to the model until an agent run settles after seeing it. */
|
|
142
|
+
export class HealNotice {
|
|
143
|
+
#message: string | undefined;
|
|
144
|
+
#projected = false;
|
|
145
|
+
|
|
146
|
+
announce(message: string): void {
|
|
147
|
+
this.#message = message;
|
|
148
|
+
this.#projected = false;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Model-facing text for the current request, marking it as seen. */
|
|
152
|
+
project(): string | undefined {
|
|
153
|
+
if (this.#message === undefined) return undefined;
|
|
154
|
+
this.#projected = true;
|
|
155
|
+
return `${this.#message}. Tell the user about this State Flow memory reset in your next answer.`;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** A settled run that saw the notice consumes it; an unseen notice survives. */
|
|
159
|
+
settle(): void {
|
|
160
|
+
if (!this.#projected) return;
|
|
161
|
+
this.#message = undefined;
|
|
162
|
+
this.#projected = false;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function describeHealedScopes(healed: readonly HealedScope[]): string {
|
|
167
|
+
return healed.map(item => `${item.scope} memory was unreadable (${item.reason}) and was reset to empty; original bytes quarantined at ${item.quarantine}`).join("; ");
|
|
168
|
+
}
|
package/lib/logging.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { appendFileSync, closeSync, constants, fstatSync, lstatSync, mkdirSync,
|
|
|
3
3
|
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
4
4
|
import { isObject } from "./json.ts";
|
|
5
5
|
|
|
6
|
-
export type StateFlowDiagnosticCategory = "invalid-patch" | "publication-conflict" | "finalization" | "barrier-block";
|
|
6
|
+
export type StateFlowDiagnosticCategory = "invalid-patch" | "publication-conflict" | "finalization" | "barrier-block" | "self-heal";
|
|
7
7
|
|
|
8
8
|
/** Minimal structural block; only ordinary text keeps its exact content. */
|
|
9
9
|
export interface StateFlowDiagnosticBlock {
|
|
@@ -92,6 +92,11 @@ export class StateFlowDiagnosticWriter {
|
|
|
92
92
|
return this.write(sessionId, cwd, error, "publication-conflict", {}, false);
|
|
93
93
|
}
|
|
94
94
|
|
|
95
|
+
/** Memory resets are always recorded locally, independently of opt-in logging. */
|
|
96
|
+
recordSelfHeal(sessionId: string, cwd: string, error: string): boolean {
|
|
97
|
+
return this.write(sessionId, cwd, error, "self-heal", {});
|
|
98
|
+
}
|
|
99
|
+
|
|
95
100
|
private write(sessionId: string, cwd: string, error: string, category: StateFlowDiagnosticCategory, extras: DiagnosticExtras, reportFailure = true): boolean {
|
|
96
101
|
try {
|
|
97
102
|
const fromRepository = relative(this.repositoryRoot, this.path);
|
package/lib/ownership.ts
CHANGED
|
@@ -11,7 +11,7 @@ export interface OwnedPath {
|
|
|
11
11
|
}
|
|
12
12
|
|
|
13
13
|
const OWNED_PLANES = new Set<string>(["strategy", "tactics", "lazy"]);
|
|
14
|
-
// Same key grammar as
|
|
14
|
+
// Same key grammar as state_flow_read value paths; array selectors never parse.
|
|
15
15
|
const OBJECT_KEY = /^[A-Za-z_$][A-Za-z0-9_$-]*$/;
|
|
16
16
|
|
|
17
17
|
/**
|
|
@@ -106,7 +106,7 @@ export function cascadeDeletionPatch(paths: readonly OwnedPath[]): JsonObject {
|
|
|
106
106
|
return patch;
|
|
107
107
|
}
|
|
108
108
|
|
|
109
|
-
/** Render an ownership target as its scoped `
|
|
109
|
+
/** Render an ownership target as its scoped `state_flow_read` path. */
|
|
110
110
|
export function formatOwnedPath(scope: StateScope, path: OwnedPath): string {
|
|
111
111
|
return [scope, path.plane, ...path.keys].join(".");
|
|
112
112
|
}
|
package/lib/protocol.ts
CHANGED
|
@@ -11,9 +11,9 @@ const PATCH_RESULT_PROTOCOL = "Head state/recent transitions are frozen at proje
|
|
|
11
11
|
export const RESPONSE_PATCH_GUIDELINE = "Never patch response in global, cwd or session, including clearing/deleting it; State Flow captures your final answer automatically in Active mode only when Session participates.";
|
|
12
12
|
export const SCOPE_PARTICIPATION_GUIDELINE = "Use only participating memory owners from the current protocol/view; scope names and examples describe grammar, not participation grants.";
|
|
13
13
|
|
|
14
|
-
export const PASSIVE_MEMORY_PROTOCOL = `State Flow passive memory is available.
|
|
14
|
+
export const PASSIVE_MEMORY_PROTOCOL = `State Flow passive memory is available. state_flow_read and state_flow_patch access durable memory without starting an active episode. ${RESPONSE_PATCH_GUIDELINE} Passive turns never trigger State Flow continuation or compaction. ${TASK_DRIVEN_HISTORY} ${PATCH_RESULT_PROTOCOL}`;
|
|
15
15
|
|
|
16
|
-
const FLAT_INTERFACE_PROTOCOL = 'One-owner interface:
|
|
16
|
+
const FLAT_INTERFACE_PROTOCOL = 'One-owner interface: state_flow_patch takes intents/strategy/tactics/artifacts/lazy object planes directly; never add an owner wrapper. state_flow_read accepts flat semantic paths, effective[N] history and a scalar patches[N] retained-patch alias; nested array[N] stays an array index. Current same-owner structured refs may use {"$ref":"lazy.plan"}; canonical ownership is retained internally. Explicit different-owner, historical/effective refs, source/resource paths and ordinary text keep their meaning, never become local permission.';
|
|
17
17
|
|
|
18
18
|
function scopeGuidance(selection: ScopeSelection): string {
|
|
19
19
|
const meanings = { session: "session=branch/run continuation by default", cwd: "cwd=project knowledge", global: "global=cross-project/user/environment knowledge" };
|
|
@@ -106,7 +106,7 @@ export function stateFlowProtocol(bootstrap: boolean, scopes: ScopeSelection = D
|
|
|
106
106
|
const response = selected.includes("session") ? 'read-only prior answer; never patch it in any scope. Auto-stored at turn_end (empty="").'
|
|
107
107
|
: "read-only selected legacy data; never patch it in any scope. Session excluded: new answers are delivered, not stored or backfilled.";
|
|
108
108
|
const bootstrapProtocol = bootstrap
|
|
109
|
-
? `BOOTSTRAP RUN: Reconcile all relevant ${all ? "state" : "participating state"} and continuation through
|
|
109
|
+
? `BOOTSTRAP RUN: Reconcile all relevant ${all ? "state" : "participating state"} and continuation through state_flow_patch before completion.\n\n`
|
|
110
110
|
: "";
|
|
111
111
|
return `State Flow is enabled. It owns durable memory.
|
|
112
112
|
|
|
@@ -120,13 +120,13 @@ ${bootstrapProtocol}STATE:
|
|
|
120
120
|
|
|
121
121
|
SCOPES: ${all ? "Use the narrowest scope: session=branch/run continuation by default; cwd=project knowledge; global=cross-project/user/environment knowledge." : scopeGuidance(selected)}${single ? `\nINTERFACE: ${FLAT_INTERFACE_PROTOCOL}` : ""}
|
|
122
122
|
|
|
123
|
-
READ: Use
|
|
123
|
+
READ: Use state_flow_read for concrete ${single ? "semantic" : "scope"}/retained-history gaps. lazy_navigation lists bounded effective lazy keys, not bodies. ${TASK_DRIVEN_HISTORY}
|
|
124
124
|
|
|
125
|
-
WRITE:
|
|
125
|
+
WRITE: state_flow_patch is the sole model-authored semantic mutation mechanism; ${single ? "the supplied planes are validated and durably accepted for the captured owner as one atomic transition. Updates use current canonical values after cancelable lock waiting." : "all supplied scopes are validated and durably accepted as one atomic transition. Global/CWD use current canonical values after cancelable lock waiting."} Correct repeats succeed without new revisions. ${PATCH_RESULT_PROTOCOL}
|
|
126
126
|
|
|
127
127
|
PATCH: Use ${single ? "flat semantic plane object patches for material updates, not acknowledgments. Omit unchanged planes; do not wrap them in an owner object." : `${names} object patches for material updates, not acknowledgments. Omit empty scopes.`} ${single ? "artifacts/strategy/tactics/intents/lazy are objects; nested values are ordinary JSON." : "artifacts/strategy/tactics/intents are objects; lazy is ordinary JSON."} Omitted fields persist. Never patch runtime config/meta/response. Objects merge recursively; arrays/primitives replace. An object containing only canonical "[N]" keys recursively patches array elements. Indexed deletion is forbidden; nested object null deletes; materialized null is forbidden.
|
|
128
128
|
|
|
129
|
-
MEMORY: Proposals are not commitments. Treat every patch as reconciliation rather than append-only notes: merge superseded fragments, remove obsolete progress. Preserve commitments, open questions, consequential results and exact continuation; distinguish requirements, decisions, observations, conclusions and hypotheses. Exclude secrets, raw history, transient progress, speculation and unsupported claims; retain decision-relevant uncertainty. Curate touched state; cleanup and scope reviews require an explicit user request. ${single ? "A cross-owner move requires both owners to participate; this one-owner interface cannot perform it or broaden selection. Preserve data and report the unavailable destination." : "Proven moves use targeted
|
|
129
|
+
MEMORY: Proposals are not commitments. Treat every patch as reconciliation rather than append-only notes: merge superseded fragments, remove obsolete progress. Preserve commitments, open questions, consequential results and exact continuation; distinguish requirements, decisions, observations, conclusions and hypotheses. Exclude secrets, raw history, transient progress, speculation and unsupported claims; retain decision-relevant uncertainty. Curate touched state; cleanup and scope reviews require an explicit user request. ${single ? "A cross-owner move requires both owners to participate; this one-owner interface cannot perform it or broaden selection. Preserve data and report the unavailable destination." : "Proven moves use targeted state_flow_read and one atomic multi-scope patch, then verify both owners."} External transfers need verified acceptance before deletion. Never invent memory changes.
|
|
130
130
|
|
|
131
131
|
REFS: State refs use {"$ref":"${referencePath}"} or \`$${referencePath}\` in text. Intent $ref owns same-scope strategy/tactics/lazy keys; text refs only use. Fixed phases, not JSON order: intents, cleanup, other planes, compile/normalize. Remaining/new intents keep targets/ancestors/descendants. Rewrite same/new path: fresh, no old fields; unowned legal. Resolve only when needed; infer no authority, hydration, execution, or completion. Hint paths are current reference owners, not relocated targets or proof of staleness. Fix proven stale refs only as needed; never scan refs or history offsets.
|
|
132
132
|
|