@llblab/pi-state-flow 0.26.5 → 0.27.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.
Files changed (121) hide show
  1. package/AGENTS.md +7 -3
  2. package/BACKLOG.md +679 -2
  3. package/CHANGELOG.md +13 -0
  4. package/README.md +30 -14
  5. package/api/modules.ts +11 -0
  6. package/dist/api/modules.d.ts +3 -0
  7. package/dist/api/modules.js +3 -0
  8. package/dist/lib/acquisition.d.ts +7 -4
  9. package/dist/lib/acquisition.js +77 -36
  10. package/dist/lib/artifact.d.ts +2 -0
  11. package/dist/lib/artifact.js +26 -27
  12. package/dist/lib/config.d.ts +3 -0
  13. package/dist/lib/config.js +13 -1
  14. package/dist/lib/context.d.ts +27 -21
  15. package/dist/lib/context.js +144 -46
  16. package/dist/lib/continuation.js +14 -18
  17. package/dist/lib/durable.d.ts +6 -0
  18. package/dist/lib/durable.js +60 -50
  19. package/dist/lib/extension.js +1043 -310
  20. package/dist/lib/history.d.ts +4 -4
  21. package/dist/lib/history.js +15 -3
  22. package/dist/lib/json.d.ts +2 -0
  23. package/dist/lib/json.js +2 -1
  24. package/dist/lib/memory.d.ts +3 -1
  25. package/dist/lib/memory.js +7 -7
  26. package/dist/lib/migration.d.ts +29 -0
  27. package/dist/lib/migration.js +186 -0
  28. package/dist/lib/model-interface.d.ts +17 -0
  29. package/dist/lib/model-interface.js +158 -0
  30. package/dist/lib/module-registry.d.ts +21 -0
  31. package/dist/lib/module-registry.js +108 -0
  32. package/dist/lib/operation.js +3 -2
  33. package/dist/lib/ownership.d.ts +4 -4
  34. package/dist/lib/ownership.js +5 -5
  35. package/dist/lib/planes.d.ts +29 -0
  36. package/dist/lib/planes.js +84 -0
  37. package/dist/lib/protocol.d.ts +6 -3
  38. package/dist/lib/protocol.js +33 -16
  39. package/dist/lib/query.d.ts +21 -4
  40. package/dist/lib/query.js +53 -13
  41. package/dist/lib/recovery.js +5 -2
  42. package/dist/lib/rehydration.d.ts +3 -0
  43. package/dist/lib/rehydration.js +10 -1
  44. package/dist/lib/runtime.d.ts +84 -5
  45. package/dist/lib/runtime.js +570 -20
  46. package/dist/lib/selection.d.ts +10 -0
  47. package/dist/lib/selection.js +32 -0
  48. package/dist/lib/semantic-module.d.ts +79 -0
  49. package/dist/lib/semantic-module.js +187 -0
  50. package/dist/lib/session.d.ts +98 -1
  51. package/dist/lib/session.js +398 -3
  52. package/dist/lib/skills.d.ts +7 -2
  53. package/dist/lib/skills.js +55 -3
  54. package/dist/lib/snapshot.d.ts +67 -14
  55. package/dist/lib/snapshot.js +129 -9
  56. package/dist/lib/state.d.ts +26 -14
  57. package/dist/lib/state.js +61 -19
  58. package/dist/lib/status.d.ts +14 -9
  59. package/dist/lib/status.js +59 -22
  60. package/dist/lib/storage.d.ts +111 -10
  61. package/dist/lib/storage.js +728 -11
  62. package/dist/lib/telegram.d.ts +10 -7
  63. package/dist/lib/telegram.js +50 -14
  64. package/dist/lib/temporal.d.ts +40 -4
  65. package/dist/lib/temporal.js +247 -43
  66. package/dist/lib/transition.d.ts +41 -8
  67. package/dist/lib/transition.js +132 -39
  68. package/dist/package.json +6 -1
  69. package/dist/skills/state-flow-guide/SKILL.md +28 -16
  70. package/dist/skills/state-flow-memory/SKILL.md +12 -8
  71. package/docs/README.md +9 -0
  72. package/docs/architecture.md +76 -43
  73. package/docs/compatibility.md +9 -1
  74. package/docs/fork-contract.md +6 -0
  75. package/docs/lazy-state.md +23 -19
  76. package/docs/protocol-composition-decision.md +66 -0
  77. package/docs/public-module-contract.md +73 -0
  78. package/docs/scope-selection-contract.md +814 -0
  79. package/docs/semantic-compatibility-decision.md +212 -0
  80. package/docs/semantic-extensibility-decision.md +75 -0
  81. package/docs/semantic-handoff-contract.md +174 -0
  82. package/docs/semantic-memory-evaluation.md +166 -0
  83. package/docs/semantic-module-contract.md +84 -0
  84. package/docs/single-scope-interface-contract.md +201 -0
  85. package/docs/temporal-acceptance.md +22 -1
  86. package/docs/usage.md +30 -18
  87. package/lib/acquisition.ts +68 -31
  88. package/lib/artifact.ts +21 -22
  89. package/lib/config.ts +14 -1
  90. package/lib/context.ts +142 -46
  91. package/lib/continuation.ts +14 -17
  92. package/lib/durable.ts +53 -44
  93. package/lib/extension.ts +892 -297
  94. package/lib/history.ts +16 -7
  95. package/lib/json.ts +2 -1
  96. package/lib/memory.ts +10 -9
  97. package/lib/migration.ts +189 -0
  98. package/lib/model-interface.ts +136 -0
  99. package/lib/module-registry.ts +119 -0
  100. package/lib/operation.ts +3 -2
  101. package/lib/ownership.ts +6 -6
  102. package/lib/planes.ts +98 -0
  103. package/lib/protocol.ts +37 -16
  104. package/lib/query.ts +59 -18
  105. package/lib/recovery.ts +5 -2
  106. package/lib/rehydration.ts +10 -1
  107. package/lib/runtime.ts +574 -21
  108. package/lib/selection.ts +39 -0
  109. package/lib/semantic-module.ts +239 -0
  110. package/lib/session.ts +387 -3
  111. package/lib/skills.ts +45 -4
  112. package/lib/snapshot.ts +156 -16
  113. package/lib/state.ts +69 -28
  114. package/lib/status.ts +65 -31
  115. package/lib/storage.ts +770 -18
  116. package/lib/telegram.ts +58 -20
  117. package/lib/temporal.ts +267 -50
  118. package/lib/transition.ts +184 -52
  119. package/package.json +6 -1
  120. package/skills/state-flow-guide/SKILL.md +28 -16
  121. package/skills/state-flow-memory/SKILL.md +12 -8
@@ -1,5 +1,5 @@
1
1
  import { StringEnum, Type } from "@earendil-works/pi-ai";
2
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
2
+ import { defineTool, getAgentDir } from "@earendil-works/pi-coding-agent";
3
3
  import { Text } from "@earendil-works/pi-tui";
4
4
  import { existsSync } from "node:fs";
5
5
  import { isAbsolute, join, resolve } from "node:path";
@@ -7,7 +7,7 @@ import { ArtifactAcquisitionState, missingArtifactRemovals } from "./acquisition
7
7
  import { inspectRegisteredArtifactPaths, sameArtifactSourceFingerprint } from "./artifact.js";
8
8
  import { hasCompactionSizedTranscript, planStateFlowCompaction, shouldRequestStateFlowCompaction, StateFlowCompactionRequests } from "./compaction.js";
9
9
  import { inactiveModeFor, loadStateFlowConfig } from "./config.js";
10
- import { ContextProjection, contextView, createPassiveContinuation, currentRunTrajectory, passiveContinuationMessages, projectSystemProtocol, runtimeContextHead, syntheticUser } from "./context.js";
10
+ import { ContextProjection, contextView, createPassiveContinuation, currentRunTrajectory, passiveContinuationMessages, projectSystemProtocol, runtimeContextHead, passiveContextHead, moduleConversationSource, projectModuleContext } from "./context.js";
11
11
  import { readNativeSessionHeader } from "./continuation.js";
12
12
  import { cwdScopeKey, resolveSessionAddress, sessionScopeKey, } from "./durable.js";
13
13
  import { completeRun, deactivateEpisode, prepareRun, resumeEpisode, startEpisode } from "./episode.js";
@@ -15,31 +15,47 @@ import { awaitInFlightBackupPushes, backupCurrentStateFlowFiles, SettledTurnBack
15
15
  import { projectRecentTransitionsWithLimit } from "./history.js";
16
16
  import { isObject, presentationJson, sameJson } from "./json.js";
17
17
  import { StateFlowDiagnosticWriter, stateFlowLogPath } from "./logging.js";
18
- import { assistantToolCallCount, conciseDiagnostic, diagnosticText, finalizedAssistantResponse, formatPatchStateArguments, PASSIVE_MEMORY_PROTOCOL, RESPONSE_PATCH_GUIDELINE, separatedFailure, separatedOutput, stateFlowProtocol } from "./protocol.js";
18
+ import { normalizeModelPatches, normalizeModelReadPath, projectModelReferences, projectModelArtifactTarget, projectModelMissingDeletion } from "./model-interface.js";
19
+ import { StateFlowModuleHost } from "./module-registry.js";
20
+ import { prepareModuleContext } from "./semantic-module.js";
21
+ import { assistantToolCallCount, conciseDiagnostic, diagnosticText, finalizedAssistantResponse, formatPatchStateArguments, passiveMemoryProtocol, RESPONSE_PATCH_GUIDELINE, SCOPE_PARTICIPATION_GUIDELINE, separatedFailure, separatedOutput, stateFlowProtocol } from "./protocol.js";
19
22
  import { OwnedOperationSlot, RenewableLifetime } from "./operation.js";
20
23
  import { readProjectedState, readStatePath } from "./query.js";
21
24
  import { selectedBoundaryFailure, selectRetainedCheckpoint, waitForRecovery } from "./recovery.js";
22
25
  import { TemporalRuntime } from "./runtime.js";
23
- import { discoverSnapshotData, findAssistantToolBatch, findBranchPolicy, findPassiveStopBoundary, hasPendingFork, hasPriorConversation, hasUncheckpointedConversation, isNewSession, retainsPhysicalSessionProjection, SNAPSHOT_ENTRY_TYPE } from "./session.js";
26
+ import { prepareSelectedBranchPolicy, captureSelectedNativeMarker, NativeToolRequestCorrelation, SelectedPolicyLifetime, discoverSnapshotData, findAssistantToolBatch, hasPriorConversation, hasUncheckpointedConversation, isNewSession, retainsPhysicalSessionProjection, SNAPSHOT_ENTRY_TYPE } from "./session.js";
24
27
  import { hasCompiledSkillArtifact, hashSkillSource, registeredSkillResolver, SkillReadTracker } from "./skills.js";
25
- import { emptySnapshot, isActiveRestorationBlocked, migrationFailure, preRuntimeCheckpoint } from "./snapshot.js";
28
+ import { emptySnapshot, isActiveRestorationBlocked, migrationFailure } from "./snapshot.js";
26
29
  import { emptyState, projectStateForModel } from "./state.js";
27
30
  import { compactStatus, detailedStatus, STATUS_KEY } from "./status.js";
28
- import { PublicationBusyError } from "./storage.js";
31
+ import { PublicationBusyError, loadSelectedFileCohort } from "./storage.js";
32
+ import { captureScopeSelection, DEFAULT_SCOPE_SELECTION, parseScopeSelectionArguments, scopeSelectionArgumentCompletions } from "./selection.js";
29
33
  import { createStateFlowTelegramAdapter } from "./telegram.js";
30
- import { temporalScopeRevisions } from "./temporal.js";
31
- import { commitScopedTransition, stageAtomicScopePatches, stageScopedTransition } from "./transition.js";
34
+ import { readTemporalScopes, temporalScopeRevisions } from "./temporal.js";
35
+ import { commitSelectedTransition, stageSelectedScopePatches, stageSelectedScopedTransition } from "./transition.js";
32
36
  export { formatPatchStateArguments };
33
37
  export const PATCH_STATE_TOOL_NAME = "patch_state";
34
38
  export const READ_STATE_TOOL_NAME = "read_state";
35
39
  const PASSIVE_STOP_ENTRY_TYPE = "state-flow-passive-stop";
40
+ const flatPatchParameters = Type.Object({
41
+ intents: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
42
+ strategy: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
43
+ tactics: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
44
+ artifacts: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
45
+ lazy: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
46
+ }, { additionalProperties: false, minProperties: 1 });
47
+ const scopedPatchParameters = Type.Object({
48
+ global: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
49
+ cwd: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
50
+ session: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
51
+ }, { additionalProperties: false, minProperties: 1 });
36
52
  export default function stateFlowExtension(pi, options = {}) {
37
53
  const agentDir = options.agentDir ?? getAgentDir();
38
54
  const loadedConfig = loadStateFlowConfig(agentDir, options.repositoryRoot);
39
55
  const config = options.mode === undefined ? loadedConfig
40
56
  : { ...loadedConfig, mode: options.mode, inactiveMode: inactiveModeFor(options.mode) };
41
57
  let snapshot = emptySnapshot(config.inactiveMode);
42
- let scopeStates = { global: emptyState(), cwd: emptyState(), session: emptyState() };
58
+ let scopeStates = {};
43
59
  let effectiveState = {};
44
60
  let branchStartsWithoutRuntime = false;
45
61
  let modePersistenceError;
@@ -52,6 +68,10 @@ export default function stateFlowExtension(pi, options = {}) {
52
68
  const responseReconciliation = new OwnedOperationSlot();
53
69
  const sharedInspectionLifetime = new RenewableLifetime();
54
70
  const memoryToolLifetime = new RenewableLifetime();
71
+ const requestPolicy = new SelectedPolicyLifetime();
72
+ const nativeRequests = new NativeToolRequestCorrelation();
73
+ const moduleHost = new StateFlowModuleHost();
74
+ let guardAbortedOperation;
55
75
  let completedRunAccepted = false;
56
76
  const compactionRequests = new StateFlowCompactionRequests();
57
77
  let passiveContinuation;
@@ -96,6 +116,22 @@ export default function stateFlowExtension(pi, options = {}) {
96
116
  // An asynchronous push attempt can outlive the Pi context that launched it.
97
117
  }
98
118
  }
119
+ function modeOperationSignal(ctx, owned) {
120
+ const ambient = ctx.signal;
121
+ if (!ambient || guardAbortedOperation === ambient)
122
+ return owned;
123
+ if (!nativeRequests.ownsOperation(ambient))
124
+ return AbortSignal.any([owned, ambient]);
125
+ // User Abort still cancels in-run commands; only this guard's obsolete-model Abort is unrelated.
126
+ const forwarded = new AbortController();
127
+ const abort = () => { if (guardAbortedOperation !== ambient)
128
+ forwarded.abort(ambient.reason); };
129
+ if (ambient.aborted)
130
+ abort();
131
+ else
132
+ ambient.addEventListener("abort", abort, { once: true, signal: owned });
133
+ return AbortSignal.any([owned, forwarded.signal]);
134
+ }
99
135
  function createRuntime(ctx) {
100
136
  return new TemporalRuntime(ctx.cwd, sessionAddress(ctx), repositoryRoot, undefined, config.historyLimit);
101
137
  }
@@ -108,8 +144,7 @@ export default function stateFlowExtension(pi, options = {}) {
108
144
  }
109
145
  }
110
146
  options.onRuntime?.({ read: (offset, scope) => {
111
- if (scope === "session")
112
- assertSelectedBranchAvailable();
147
+ assertSelectedBranchAvailable();
113
148
  if (!runtime)
114
149
  throw new Error("State Flow temporal runtime is unavailable");
115
150
  const { lazy: _lazy, ...defaults } = emptyState();
@@ -124,23 +159,74 @@ export default function stateFlowExtension(pi, options = {}) {
124
159
  function isActive() {
125
160
  return snapshot.config.mode === "active" && !isActiveRestorationBlocked(snapshot);
126
161
  }
127
- /** Pending acquisition has no accepted Active memory yet. */
128
- function inactiveSelection(mode) {
129
- return mode === "active" ? config.inactiveMode : mode;
162
+ function readableView(selected = runtime) {
163
+ return selected?.selectedView() ?? selected?.observedSelectedView();
164
+ }
165
+ function nativeScopeSelection(ctx = activeContext) {
166
+ const policy = requestPolicy.policy;
167
+ return ctx && policy?.owner === ctx.sessionManager.getSessionId() && policy.cwd === resolve(ctx.cwd)
168
+ ? policy.scopes : config.scopes;
169
+ }
170
+ function appendNativeMarker(value, ctx = activeContext) {
171
+ pi.appendEntry(PASSIVE_STOP_ENTRY_TYPE, captureSelectedNativeMarker({ version: 2,
172
+ owner: ctx.sessionManager.getSessionId(), mode: snapshot.config.mode, scopes: nativeScopeSelection(ctx), ...value }));
173
+ }
174
+ function assertNativeMemoryScopes(scopes) {
175
+ captureScopeSelection(scopes);
176
+ }
177
+ function branchPolicy(ctx, reason, memoryRequired = true) {
178
+ const branch = ctx.sessionManager.getBranch();
179
+ const policy = prepareSelectedBranchPolicy(branch, { owner: ctx.sessionManager.getSessionId(), markerEntryType: PASSIVE_STOP_ENTRY_TYPE,
180
+ defaults: { mode: isNewSession(reason, branch) ? config.mode : config.inactiveMode, scopes: config.scopes },
181
+ inactiveMode: config.inactiveMode, fork: reason === "fork" });
182
+ if (memoryRequired)
183
+ assertNativeMemoryScopes(policy.scopes);
184
+ return policy;
185
+ }
186
+ /** Failure-only denial evidence, never policy admission: inspect own known-epoch headers without getters or memory I/O. */
187
+ function failedNativePolicyMode(ctx, reason) {
188
+ const own = (value, key) => Object.getOwnPropertyDescriptor(value, key)?.value;
189
+ try {
190
+ const inherited = reason === "fork" || typeof ctx.sessionManager.getHeader()?.parentSession === "string";
191
+ for (const entry of [...ctx.sessionManager.getBranch()].reverse()) {
192
+ try {
193
+ if (own(entry, "type") !== "custom")
194
+ continue;
195
+ const type = own(entry, "customType"), data = own(entry, "data");
196
+ if ((type !== SNAPSHOT_ENTRY_TYPE && type !== PASSIVE_STOP_ENTRY_TYPE) || !isObject(data))
197
+ continue;
198
+ const epoch = Object.getOwnPropertyDescriptor(data, "version");
199
+ if (epoch && (!("value" in epoch) || epoch.value !== 2))
200
+ continue;
201
+ if (type === PASSIVE_STOP_ENTRY_TYPE && own(data, "owner") !== ctx.sessionManager.getSessionId() && !inherited)
202
+ continue;
203
+ const mode = own(data, "mode");
204
+ if (mode === "active" || mode === "passive" || mode === "off")
205
+ return mode;
206
+ if (!epoch && typeof own(data, "enabled") === "boolean")
207
+ return own(data, "enabled") ? "active" : config.inactiveMode;
208
+ }
209
+ catch { /* Unreadable headers grant no memory participation. */ }
210
+ }
211
+ }
212
+ catch { /* No failure-only mode evidence. */ }
213
+ return undefined;
130
214
  }
131
215
  function appendCheckpoint() {
132
- const checkpoint = branchStartsWithoutRuntime ? preRuntimeCheckpoint(snapshot.config.mode)
133
- : runtime?.view ? runtime.retainedCheckpoint(snapshot) : undefined;
134
- if (!checkpoint)
135
- throw new Error("State Flow cannot checkpoint an unproven branch; restore a valid checkpoint first");
136
- pi.appendEntry(SNAPSHOT_ENTRY_TYPE, checkpoint);
137
- if ("boundary" in checkpoint)
216
+ if (runtime?.selectedView()) {
217
+ pi.appendEntry(SNAPSHOT_ENTRY_TYPE, runtime.retainedSelectedCheckpoint(snapshot.config.mode));
138
218
  branchStartsWithoutRuntime = false;
219
+ }
220
+ else if (branchStartsWithoutRuntime) {
221
+ // A policy capture cannot turn read-only shared observation into accepted memory.
222
+ appendNativeMarker({});
223
+ }
224
+ else
225
+ throw new Error("State Flow cannot checkpoint an unproven branch; restore current memory first");
139
226
  }
140
227
  function scopeRevisions() {
141
- return runtime?.view
142
- ? temporalScopeRevisions(runtime.view)
143
- : { global: 0, cwd: 0, session: 0 };
228
+ const view = readableView();
229
+ return view ? temporalScopeRevisions(view) : {};
144
230
  }
145
231
  function updateUi(ctx) {
146
232
  ctx.ui.setStatus(STATUS_KEY, compactStatus(snapshot, scopeRevisions(), (color, text) => ctx.ui.theme.fg(color, text)));
@@ -164,14 +250,15 @@ export default function stateFlowExtension(pi, options = {}) {
164
250
  acquisition.clearInvalidations();
165
251
  }
166
252
  function refreshArtifactHints() {
167
- if (runtime?.view)
168
- acquisition.refresh(scopeStates, (scope) => runtime.artifactProvenance(scope));
253
+ const view = readableView();
254
+ if (view)
255
+ acquisition.refresh(scopeStates, (scope) => runtime.artifactProvenance(scope), view.selection);
169
256
  else
170
257
  acquisition.reset();
171
258
  }
172
259
  function installScopeStates() {
173
- scopeStates = runtime?.view ? runtime.states() : { global: emptyState(), cwd: emptyState(), session: emptyState() };
174
- effectiveState = runtime?.view ? runtime.readView() : {};
260
+ scopeStates = readableView() ? runtime.selectedStates().states : {};
261
+ effectiveState = readableView() ? runtime.readView() : {};
175
262
  }
176
263
  /** Active and passive expose both memory tools; Off exposes neither. */
177
264
  function memoryToolsAvailable() {
@@ -179,7 +266,7 @@ export default function stateFlowExtension(pi, options = {}) {
179
266
  }
180
267
  /** Passive memory context needs a loaded view; Off and Active never inject it. */
181
268
  function passiveMemoryAvailable() {
182
- return snapshot.config.mode === "passive" && runtime?.view !== undefined;
269
+ return snapshot.config.mode === "passive" && readableView() !== undefined && snapshot.meta.validation?.attempt !== 0;
183
270
  }
184
271
  async function inspectTelegramState(scope) {
185
272
  if (!activeContext || shuttingDown)
@@ -187,37 +274,59 @@ export default function stateFlowExtension(pi, options = {}) {
187
274
  const ctx = activeContext;
188
275
  const owner = sessionAddress(ctx).key;
189
276
  const cwd = ctx.cwd;
277
+ const wanted = captureScopeSelection(nativeScopeSelection(ctx));
278
+ if (scope === "effective" ? wanted.length < 2 : !wanted.includes(scope))
279
+ throw new Error("State Flow inspection scope is not available in this selection");
280
+ const inspected = captureScopeSelection(scope === "effective" ? wanted : [scope]);
190
281
  const off = snapshot.config.mode === "off";
191
- const privateScope = scope === "session" || scope === "effective";
282
+ const privateScope = inspected.includes("session");
192
283
  if (!off && privateScope)
193
284
  assertSelectedBranchAvailable();
194
285
  // Off operator reads are disposable: they confer no selected-branch/cache authority.
195
- const selected = off ? createRuntime(ctx) : runtime ??= createRuntime(ctx);
286
+ const selected = createRuntime(ctx);
196
287
  const signal = sharedInspectionLifetime.signal;
197
- let privateAvailable = true;
198
- if (off && privateScope)
199
- privateAvailable = await selected.refreshCurrentMemory(signal) !== undefined;
200
- else if (!selected.view || (scope !== "session" && !modePersistenceError))
201
- await selected.refreshShared(signal);
202
- signal.throwIfAborted();
203
- if (activeContext !== ctx || ctx.cwd !== cwd || sessionAddress(ctx).key !== owner || (!off && runtime !== selected)) {
204
- throw new Error("State Flow inspection selection changed; select the scope again");
205
- }
206
- if (!privateAvailable)
207
- throw new Error("Current State Flow session memory is unavailable");
208
- if (!off && privateScope)
209
- assertSelectedBranchAvailable();
210
- if (!selected.view)
288
+ const check = () => {
289
+ signal.throwIfAborted();
290
+ if (activeContext !== ctx || ctx.cwd !== cwd || sessionAddress(ctx).key !== owner || !sameJson(nativeScopeSelection(ctx), wanted))
291
+ throw new Error("State Flow inspection selection changed; select the scope again");
292
+ };
293
+ if (privateScope && (off || !branchStartsWithoutRuntime || scope === "session")) {
294
+ await selected.refreshSelectedCurrent(inspected, check, signal);
295
+ }
296
+ else
297
+ await selected.refreshSelectedShared(captureScopeSelection(inspected.filter(owner => owner !== "session")), check, signal);
298
+ check();
299
+ const view = selected.observedSelectedView();
300
+ if (!view)
211
301
  throw new Error("State Flow temporal runtime is unavailable");
212
- if (!off)
213
- installScopeStates();
214
302
  const state = selected.readView(0, scope === "effective" ? undefined : scope);
215
- return { state: { ...projectModelState(state), ...(state.lazy === undefined ? {} : { lazy: structuredClone(state.lazy) }) }, revisions: temporalScopeRevisions(selected.view), signal };
303
+ return { state: { ...projectModelState(state), ...(state.lazy === undefined ? {} : { lazy: structuredClone(state.lazy) }) }, revisions: temporalScopeRevisions(view), signal };
216
304
  }
217
- function syncStateFlowTools() {
305
+ function syncStateFlowTools(force = false) {
306
+ if (activeContext && !shuttingDown) {
307
+ const scopes = nativeScopeSelection(activeContext);
308
+ requestPolicy.select({ cwd: activeContext.cwd, owner: activeContext.sessionManager.getSessionId(), mode: snapshot.config.mode, scopes });
309
+ skillReads.select(scopes);
310
+ }
311
+ const available = memoryToolsAvailable();
312
+ if (available && activeContext) {
313
+ const external = moduleHost.captureIfBound()?.modules.filter(module => !module.immutable).map(module => module.id) ?? [];
314
+ const flat = nativeScopeSelection(activeContext).length === 1;
315
+ const desired = [...Object.keys(flatPatchParameters.properties), ...external];
316
+ const sameFlatShape = flat && desired.join("|") === Object.keys(patchStateTool.parameters.properties).join("|");
317
+ const parameters = !flat ? scopedPatchParameters : !external.length ? flatPatchParameters : sameFlatShape ? patchStateTool.parameters
318
+ : Type.Object({ ...flatPatchParameters.properties, ...Object.fromEntries(external.map(id => [id, Type.Optional(Type.Record(Type.String(), Type.Unknown()))])) }, { additionalProperties: false, minProperties: 1 });
319
+ // Cache only the desired shape on our unregistered template: host filtering can hide ToolInfo.
320
+ // Every SDK registration is a fresh copy, preserving old response-wrapper declarations.
321
+ if (force || patchStateTool.parameters !== parameters) {
322
+ patchStateTool.parameters = parameters;
323
+ pi.registerTool({ ...patchStateTool, ...(external.length ? {
324
+ promptGuidelines: [...(patchStateTool.promptGuidelines ?? []), `Registered mutable object planes: ${external.join(", ")}. Availability and matching retained schema/policy are revalidated at acceptance.`],
325
+ } : {}) });
326
+ }
327
+ }
218
328
  const active = pi.getActiveTools();
219
329
  const owned = [PATCH_STATE_TOOL_NAME, READ_STATE_TOOL_NAME];
220
- const available = memoryToolsAvailable();
221
330
  if (owned.every((name) => active.includes(name) === available))
222
331
  return;
223
332
  pi.setActiveTools(available
@@ -231,7 +340,7 @@ export default function stateFlowExtension(pi, options = {}) {
231
340
  backup.markPublished();
232
341
  }
233
342
  function skillReadIsCurrent(read) {
234
- return read.hash !== undefined && runtime?.view !== undefined && hasCompiledSkillArtifact(scopeStates[read.scope].artifacts, runtime.artifactProvenance(read.scope)[read.path], read.path, read.hash);
343
+ return read.hash !== undefined && readableView()?.selection.includes(read.scope) === true && hasCompiledSkillArtifact(scopeStates[read.scope].artifacts ?? {}, runtime.artifactProvenance(read.scope)[read.path], read.path, read.hash);
235
344
  }
236
345
  function dropCurrentSkillReads() {
237
346
  for (const read of skillReads.successful.values()) {
@@ -239,44 +348,76 @@ export default function stateFlowExtension(pi, options = {}) {
239
348
  skillReads.delete(read.path);
240
349
  }
241
350
  }
242
- function skillAcquisitionHint(read) {
351
+ function skillAcquisitionHint(read, wanted) {
243
352
  if (read.hash === undefined || skillReadIsCurrent(read))
244
353
  return undefined;
245
- const target = `${read.scope}.artifacts[${JSON.stringify(read.path)}]`;
354
+ const target = projectModelArtifactTarget(read.scope, read.path, wanted);
246
355
  return `State Flow acquisition: this registered Skill belongs at ${target}. If durable compiled guidance is useful, include a non-empty description, kind:"skill", and compilation object there. Unrelated semantic patches do not need to include it.`;
247
356
  }
248
357
  function clearAcceptedAcquisitions(acquiredArtifactPaths) {
249
358
  acquisition.acceptAcquired(acquiredArtifactPaths);
250
359
  dropCurrentSkillReads();
251
360
  }
252
- async function prepareInference(pending, selected, ctx, operationSignal) {
253
- const signal = AbortSignal.any([pending.controller.signal, operationSignal]);
361
+ async function prepareInference(pending, selected, ctx, operationSignal, request, messages = []) {
362
+ const signal = AbortSignal.any([pending.controller.signal, operationSignal, ...(request ? [request.signal] : [])]);
363
+ const sameSession = sessionIdentity(ctx);
364
+ const check = () => {
365
+ request?.revalidate();
366
+ if (ctx.signal !== operationSignal || !sameSession() || !currentNativeContextOwner(ctx))
367
+ throw new Error("State Flow preparation context owner changed");
368
+ };
254
369
  try {
255
- if (!selected?.view)
370
+ check();
371
+ if (!selected?.selectedView())
256
372
  throw new Error("Temporal State Flow runtime is unavailable; reload before publishing");
257
- await selected.withPatchTransaction((transaction) => {
373
+ pending.modules = await capturePublicModules(messages, ctx, signal);
374
+ pending.modules?.assertOriginal();
375
+ const replacements = [];
376
+ try {
377
+ const proposals = await Promise.all((pending.modules?.bindings ?? []).filter(binding => binding.module.produce).map(async (binding) => {
378
+ const content = await binding.prepared.produce();
379
+ return content === undefined ? undefined : { scope: binding.scope, id: binding.module.id, content };
380
+ }));
381
+ replacements.push(...proposals.filter((item) => item !== undefined));
382
+ }
383
+ catch {
384
+ throw new Error("State Flow registered module production failed");
385
+ }
386
+ pending.modules?.assertOriginal();
387
+ await selected.withSelectedPatchTransaction((transaction) => {
258
388
  signal.throwIfAborted();
389
+ check();
259
390
  if (runtime !== selected || !inferencePreparation.owns(pending) || !isActive() || shuttingDown) {
260
391
  throw new Error("State Flow inference selection changed while awaiting publication");
261
392
  }
262
393
  assertPublicationAvailable();
394
+ pending.modules?.assertOriginal();
395
+ for (const binding of pending.modules?.bindings ?? []) {
396
+ if (!sameJson(transaction.states[binding.scope]?.[binding.module.id] ?? null, binding.content ?? null)
397
+ || !sameJson(transaction.modules?.[binding.scope]?.[binding.module.id] ?? null, binding.descriptor ?? null))
398
+ throw new Error("State Flow producer content or descriptor basis changed");
399
+ }
263
400
  const nextSnapshot = structuredClone(snapshot);
264
401
  const rotatesRun = pending.prompt !== undefined && nextSnapshot.meta.specification !== undefined;
265
402
  if (pending.prompt !== undefined)
266
403
  prepareRun(nextSnapshot, pending.prompt);
267
404
  // Exact-path metadata validation belongs to the locked current head, including newly adopted registrations.
268
- const removals = missingArtifactRemovals(transaction.states);
405
+ const removals = missingArtifactRemovals(transaction.states, transaction.selection);
269
406
  let publication;
270
- if (Object.keys(removals).length > 0) {
271
- const stage = stageAtomicScopePatches(transaction.states, removals, [], transaction.causalBasis);
272
- commitScopedTransition(nextSnapshot, transaction.states, stage, (transition, next) => {
273
- publication = transaction.publish(next, transition);
407
+ if (Object.keys(removals).length > 0 || replacements.length > 0) {
408
+ const stage = stageSelectedScopePatches(transaction, removals, [], transaction.causalBasis, [], pending.modules?.definitions, replacements);
409
+ commitSelectedTransition(nextSnapshot, transaction, stage, (transition, next) => {
410
+ pending.modules?.assertCurrent();
411
+ publication = transaction.publish(next, transition, stage.provenanceUpdates, stage.moduleAdditions);
274
412
  pending.accepted = true;
413
+ pending.moduleAcceptance = selected.captureSelectedReadBasis();
275
414
  }, transaction.causalBasis, { finalizeRun: false });
276
415
  }
277
416
  else {
417
+ pending.modules?.assertCurrent();
278
418
  publication = transaction.publish(nextSnapshot);
279
419
  pending.accepted = true;
420
+ pending.moduleAcceptance = selected.captureSelectedReadBasis();
280
421
  }
281
422
  snapshot = nextSnapshot;
282
423
  installScopeStates();
@@ -289,13 +430,28 @@ export default function stateFlowExtension(pi, options = {}) {
289
430
  if (Object.keys(removals).length > 0)
290
431
  clearAcceptedAcquisitions();
291
432
  updateUi(ctx);
292
- }, signal);
433
+ }, () => {
434
+ check();
435
+ if (runtime !== selected || !inferencePreparation.owns(pending) || !isActive())
436
+ throw new Error("State Flow preparation superseded");
437
+ pending.modules?.assertCurrent();
438
+ }, signal, [...new Set(pending.modules?.bindings.map(binding => binding.scope) ?? [])]);
293
439
  }
294
440
  catch (error) {
441
+ if (!pending.accepted)
442
+ pending.modules?.cancel();
295
443
  if (signal.aborted || runtime !== selected || !inferencePreparation.owns(pending) || shuttingDown)
296
444
  return;
445
+ try {
446
+ check();
447
+ }
448
+ catch {
449
+ return;
450
+ }
451
+ if (!contextRequestCurrent(request, ctx, operationSignal))
452
+ return;
297
453
  // Pi reports context-hook exceptions and continues. Abort through its public port rather than infer from stale preparation.
298
- ctx.abort();
454
+ abortContext(ctx, operationSignal);
299
455
  const cause = diagnosticText(error);
300
456
  recordDiagnostic(cause, "publication-conflict", ctx);
301
457
  notifyProblem(ctx, pending.accepted
@@ -305,7 +461,7 @@ export default function stateFlowExtension(pi, options = {}) {
305
461
  }
306
462
  function statusDiagnostics(ctx) {
307
463
  const cwd = ctx.cwd;
308
- const view = runtime?.view;
464
+ const view = readableView();
309
465
  const diagnosticRecent = runtime?.recent() ?? [];
310
466
  const durableStateError = snapshot.meta.validation?.attempt === 0 ? snapshot.meta.validation.error
311
467
  : view ? undefined : "no temporal runtime is selected on this branch";
@@ -317,6 +473,8 @@ export default function stateFlowExtension(pi, options = {}) {
317
473
  repositoryRoot,
318
474
  cwdScopeKey: cwdScopeKey(cwd),
319
475
  sessionScopeKey: sessionScopeKey(session.key),
476
+ selection: view?.selection ?? nativeScopeSelection(ctx),
477
+ requestedSelection: nativeScopeSelection(ctx),
320
478
  scopeStates,
321
479
  effectiveState,
322
480
  recent: diagnosticRecent,
@@ -324,7 +482,7 @@ export default function stateFlowExtension(pi, options = {}) {
324
482
  ...(view === undefined ? {} : { temporal: {
325
483
  head: structuredClone(view.lineage.at(-1)),
326
484
  historyDepth: view.lineage.length - 1,
327
- tailCounts: { global: view.scopes.global.patches.length, cwd: view.scopes.cwd.patches.length, session: view.scopes.session.patches.length },
485
+ tailCounts: Object.fromEntries(view.selection.map(scope => [scope, view.scopes[scope].patches.length])),
328
486
  revisions: temporalScopeRevisions(view),
329
487
  } }),
330
488
  staleArtifacts,
@@ -344,6 +502,7 @@ export default function stateFlowExtension(pi, options = {}) {
344
502
  /** Select the active native branch under one owned restoration lifetime; only current accepted work installs memory. */
345
503
  function restoreActiveBranch(ctx, sessionStartReason, notifyRecovery = true, startOwner, requestedMode) {
346
504
  contextProjection.reset();
505
+ requestPolicy.invalidate();
347
506
  memoryToolLifetime.renew();
348
507
  branchRestoration.cancel();
349
508
  // Start-owned attachment/fork recovery keeps its owner; only accepted Start cancels Stop.
@@ -357,9 +516,29 @@ export default function stateFlowExtension(pi, options = {}) {
357
516
  acquisition.clearInvalidations();
358
517
  telegramStartPending = false;
359
518
  activeContext = ctx;
519
+ let nativePolicy;
520
+ try {
521
+ nativePolicy = branchPolicy(ctx, sessionStartReason, false);
522
+ requestPolicy.select({ cwd: ctx.cwd, owner: ctx.sessionManager.getSessionId(), mode: snapshot.config.mode, scopes: nativePolicy.scopes });
523
+ // Freeze admitted policy before accepting any selected memory.
524
+ // Policy-only capture grants no acquisition or semantic-boundary authority.
525
+ if (nativePolicy.requiresCapture)
526
+ pi.appendEntry(PASSIVE_STOP_ENTRY_TYPE, nativePolicy.capture);
527
+ if (nativePolicy.mode !== "off")
528
+ assertNativeMemoryScopes(nativePolicy.scopes);
529
+ }
530
+ catch (error) {
531
+ runtime = undefined;
532
+ branchStartsWithoutRuntime = false;
533
+ modePersistenceError = diagnosticText(error);
534
+ snapshot = selectedBoundaryFailure(modePersistenceError, nativePolicy?.mode ?? failedNativePolicyMode(ctx, sessionStartReason) ?? config.inactiveMode);
535
+ installScopeStates();
536
+ syncStateFlowTools();
537
+ updateUi(ctx);
538
+ return Promise.resolve();
539
+ }
360
540
  if (!startOwner) {
361
541
  let mode = config.inactiveMode;
362
- let adoptDefault = false;
363
542
  let withoutRuntime = false;
364
543
  let persistenceError;
365
544
  let pendingFork = false;
@@ -367,14 +546,9 @@ export default function stateFlowExtension(pi, options = {}) {
367
546
  const branch = ctx.sessionManager.getBranch();
368
547
  const discovery = discoverSnapshotData(branch);
369
548
  withoutRuntime = discovery.candidates.length === 0 && discovery.errors.length === 0;
370
- adoptDefault = withoutRuntime && isNewSession(sessionStartReason, branch);
371
- pendingFork = hasPendingFork(branch, ctx.sessionManager.getSessionId(), PASSIVE_STOP_ENTRY_TYPE);
372
- const inherited = sessionStartReason === "fork" || pendingFork;
373
- const policy = findBranchPolicy(branch, inherited ? undefined : ctx.sessionManager.getSessionId(), inherited || retainsPhysicalSessionProjection(sessionStartReason) ? PASSIVE_STOP_ENTRY_TYPE : undefined, config.inactiveMode);
374
- mode = policy?.mode ?? (adoptDefault ? config.mode : config.inactiveMode);
375
- persistenceError = inherited
376
- ? findBranchPolicy(branch, ctx.sessionManager.getSessionId(), PASSIVE_STOP_ENTRY_TYPE, config.inactiveMode)?.persistenceError
377
- : policy?.persistenceError;
549
+ pendingFork = nativePolicy.forkPending;
550
+ mode = nativePolicy.mode;
551
+ persistenceError = nativePolicy.persistenceError;
378
552
  }
379
553
  catch {
380
554
  // Off needs only policy; unavailable native evidence grants no memory authority.
@@ -385,7 +559,7 @@ export default function stateFlowExtension(pi, options = {}) {
385
559
  const reason = pendingFork || (deferredBranch?.owner === owner && deferredBranch.cwd === ctx.cwd && deferredBranch.reason === "fork"
386
560
  && retainsPhysicalSessionProjection(sessionStartReason)) ? "fork" : sessionStartReason;
387
561
  if (reason === "fork" && !pendingFork)
388
- pi.appendEntry(PASSIVE_STOP_ENTRY_TYPE, { owner: ctx.sessionManager.getSessionId(), forkPending: true });
562
+ appendNativeMarker({ mode: "off", forkPending: true });
389
563
  deferredBranch = { reason, owner, cwd: ctx.cwd };
390
564
  runtime = undefined;
391
565
  snapshot = emptySnapshot("off");
@@ -394,8 +568,6 @@ export default function stateFlowExtension(pi, options = {}) {
394
568
  forkInitialization = reason === "fork";
395
569
  installScopeStates();
396
570
  acquisition.reset();
397
- if (adoptDefault)
398
- appendCheckpoint();
399
571
  syncStateFlowTools();
400
572
  updateUi(ctx);
401
573
  return Promise.resolve();
@@ -407,16 +579,22 @@ export default function stateFlowExtension(pi, options = {}) {
407
579
  runtime = createRuntime(ctx);
408
580
  installScopeStates();
409
581
  branchStartsWithoutRuntime = false;
410
- forkInitialization = sessionStartReason === "fork";
582
+ forkInitialization = sessionStartReason === "fork" || nativePolicy.forkPending;
411
583
  let selection = { kind: "settled" };
412
584
  let skipped = 0;
413
585
  try {
414
586
  const branch = ctx.sessionManager.getBranch();
415
- const fence = retainsPhysicalSessionProjection(sessionStartReason)
416
- ? findPassiveStopBoundary(branch, ctx.sessionManager.getSessionId(), PASSIVE_STOP_ENTRY_TYPE)
417
- : undefined;
587
+ const fence = nativePolicy.stop;
418
588
  modePersistenceError = fence?.persistenceError ?? (startOwner ? modePersistenceError : undefined);
419
- if (fence?.persistenceError) {
589
+ if (forkInitialization) {
590
+ // Pending copy authority is independent of whether ancillary Pi checkpoint appends succeeded.
591
+ const selected = selectRetainedCheckpoint(discoverSnapshotData(branch).candidates, config.inactiveMode);
592
+ selection = { kind: "fork", checkpoint: {
593
+ mode: requestedMode ?? (nativePolicy.mode === "off" && startOwner ? "passive" : nativePolicy.mode),
594
+ ...(selected.kind === "boundary" && selected.checkpoint.bootstrap ? { bootstrap: true } : {}),
595
+ } };
596
+ }
597
+ else if (fence?.persistenceError) {
420
598
  // The native marker owns policy only: read proven memory, never replay or publish a stale selection.
421
599
  selection = { kind: "current", mode: fence.mode ?? config.inactiveMode };
422
600
  }
@@ -428,23 +606,13 @@ export default function stateFlowExtension(pi, options = {}) {
428
606
  if (discovery.candidates.length === 0 && discovery.errors.length > 0) {
429
607
  snapshot = migrationFailure({}, `Snapshot restoration failed: ${discovery.errors[0]}`, config.inactiveMode);
430
608
  }
431
- else if (selected.kind === "boundary" && forkInitialization) {
432
- try {
433
- // Native parent acquisition stays outside canonical exclusion.
434
- const source = forkSource(ctx);
435
- const sourceFence = findPassiveStopBoundary(branch, source.id, PASSIVE_STOP_ENTRY_TYPE);
436
- selection = { kind: "fork", source, checkpoint: sourceFence?.persistenceError !== undefined
437
- ? { ...selected.checkpoint, mode: sourceFence.mode ?? config.inactiveMode } : selected.checkpoint };
438
- }
439
- catch (error) {
440
- snapshot = selectedBoundaryFailure(diagnosticText(error), requestedMode ?? selected.checkpoint.mode);
441
- }
442
- }
443
609
  else if (selected.kind === "boundary") {
444
- selection = { kind: "attach", checkpoint: selected.checkpoint };
610
+ selection = { kind: "attach", checkpoint: { ...selected.checkpoint, mode: nativePolicy.mode } };
445
611
  }
446
612
  else if (selected.kind === "pre-runtime") {
447
- snapshot = emptySnapshot(selected.mode);
613
+ snapshot = emptySnapshot(nativePolicy.mode);
614
+ if (nativePolicy.mode === "active")
615
+ selection = { kind: "auto-start" };
448
616
  }
449
617
  else if (discovery.candidates.length > 0) {
450
618
  snapshot = selected.snapshot;
@@ -455,23 +623,28 @@ export default function stateFlowExtension(pi, options = {}) {
455
623
  selection = { kind: "auto-start" };
456
624
  else {
457
625
  snapshot = emptySnapshot(config.mode);
458
- // Adopt the default once without initializing semantic storage.
459
- appendCheckpoint();
626
+ // The native policy was captured before memory acquisition.
460
627
  }
461
628
  }
462
629
  else {
463
- snapshot = emptySnapshot(config.inactiveMode);
630
+ snapshot = emptySnapshot(nativePolicy.mode);
631
+ if (nativePolicy.mode === "active" && branchStartsWithoutRuntime)
632
+ selection = { kind: "auto-start" };
464
633
  }
465
634
  }
466
635
  }
467
636
  catch (error) {
468
637
  selection = { kind: "settled" };
469
- snapshot = selectedBoundaryFailure(diagnosticText(error), config.inactiveMode);
638
+ snapshot = selectedBoundaryFailure(diagnosticText(error), nativePolicy.mode);
639
+ }
640
+ const preRuntimeMode = requestedMode ?? snapshot.config.mode;
641
+ if (selection.kind === "settled" && branchStartsWithoutRuntime && snapshot.meta.validation?.attempt !== 0 && preRuntimeMode !== "off") {
642
+ selection = { kind: "pre-runtime", mode: preRuntimeMode };
470
643
  }
471
- // Pending selection grants neither private reads nor publication until its acceptance installs memory.
644
+ // Retain selected policy while validation blocks memory authority and Active inference until acceptance.
472
645
  if (selection.kind !== "settled") {
473
646
  snapshot = migrationFailure({}, "State Flow branch restoration is pending", selection.kind === "current" ? selection.mode
474
- : selection.kind === "auto-start" ? config.inactiveMode : inactiveSelection(selection.checkpoint.mode));
647
+ : selection.kind === "auto-start" ? "active" : selection.kind === "pre-runtime" ? selection.mode : selection.checkpoint.mode);
475
648
  }
476
649
  if (requestedMode)
477
650
  snapshot = deactivateEpisode(snapshot, requestedMode);
@@ -487,11 +660,11 @@ export default function stateFlowExtension(pi, options = {}) {
487
660
  async function attachBranch(ctx, pending, selection, reason, notifyRecovery, skipped) {
488
661
  const placeholder = runtime;
489
662
  let selected = runtime;
490
- const owner = ctx.sessionManager.getSessionId();
663
+ const wanted = nativeScopeSelection(ctx);
491
664
  const sameSession = sessionIdentity(ctx);
492
- const signal = AbortSignal.any([pending.controller.signal, ...(ctx.signal ? [ctx.signal] : [])]);
665
+ const signal = modeOperationSignal(ctx, pending.controller.signal);
493
666
  const isCurrent = () => branchRestoration.owns(pending) && !pending.controller.signal.aborted && !shuttingDown && runtime === selected
494
- && sameSession();
667
+ && sameSession() && sameJson(nativeScopeSelection(ctx), wanted);
495
668
  const assertCurrent = () => {
496
669
  signal.throwIfAborted();
497
670
  if (!isCurrent())
@@ -500,7 +673,7 @@ export default function stateFlowExtension(pi, options = {}) {
500
673
  let accepted = false;
501
674
  const failSelection = (error) => {
502
675
  const mode = pending.requestedMode ?? (selection.kind === "auto-start" ? "active"
503
- : selection.kind === "attach" || selection.kind === "fork" ? selection.checkpoint.mode : snapshot.config.mode);
676
+ : selection.kind === "pre-runtime" ? selection.mode : selection.kind === "attach" || selection.kind === "fork" ? selection.checkpoint.mode : snapshot.config.mode);
504
677
  snapshot = selectedBoundaryFailure(diagnosticText(error), mode);
505
678
  installScopeStates();
506
679
  };
@@ -525,68 +698,148 @@ export default function stateFlowExtension(pi, options = {}) {
525
698
  };
526
699
  try {
527
700
  if (selection.kind !== "settled") {
528
- // Local policy is already passive while the selection waits for exclusion.
701
+ // Selected policy is visible while memory remains unavailable during the exclusion wait.
529
702
  syncStateFlowTools();
530
703
  updateUi(ctx);
531
704
  const candidate = createRuntime(ctx);
532
705
  try {
533
706
  if (selection.kind === "current") {
534
- const current = await candidate.refreshCurrentMemory(signal);
707
+ const current = await candidate.refreshSelectedCurrent(wanted, assertCurrent, signal);
535
708
  assertCurrent();
536
- if (current)
537
- runtime = selected = candidate;
538
- snapshot = current ? deactivateEpisode(current, pending.requestedMode ?? selection.mode)
539
- : migrationFailure({}, "Current State Flow session memory is unavailable", pending.requestedMode ?? selection.mode);
709
+ runtime = selected = candidate;
710
+ snapshot = deactivateEpisode(current, pending.requestedMode ?? selection.mode);
540
711
  installScopeStates();
541
712
  }
542
713
  else if (selection.kind === "attach") {
543
- // Memory is the current same-session files; the Pi checkpoint supplies only mode and run lifecycle.
544
- await candidate.withStartTransaction((current, publish) => {
714
+ // A validated shared-only bookmark may precede a new requested Session selection.
715
+ const addsSession = wanted.includes("session") && "scopes" in selection.checkpoint
716
+ && !captureScopeSelection(selection.checkpoint.scopes).includes("session");
717
+ const disposition = addsSession ? await candidate.inspectSelectedLifecycle(wanted, assertCurrent, signal) : undefined;
718
+ assertCurrent();
719
+ if ((pending.requestedMode ?? selection.checkpoint.mode) === "passive" && disposition?.privateAcquisition === "unacquired") {
720
+ // Observation cannot turn the new policy or old bookmark into private acquisition.
721
+ const shared = wanted.filter(scope => scope !== "session");
722
+ if (shared.length)
723
+ await candidate.refreshSelectedShared(captureScopeSelection(shared), assertCurrent, signal);
545
724
  assertCurrent();
546
- if (!current)
547
- throw new Error("Current State Flow session memory is unavailable");
548
- const { checkpoint } = selection;
549
- const restored = { config: { mode: checkpoint.mode }, meta: {
550
- step: current.meta.step,
551
- ...(checkpoint.bootstrap ? { bootstrap: true } : {}),
552
- ...(checkpoint.specification === undefined ? {} : { specification: checkpoint.specification }),
553
- } };
554
- // Canceled preparation or boundary continuation may have no specification. Retain uncompiled native context.
555
- if (restored.config.mode === "active" && restored.meta.specification === undefined
556
- && retainsPhysicalSessionProjection(reason) && hasUncheckpointedConversation(ctx.sessionManager.getBranch()))
557
- restored.meta.bootstrap = true;
558
- const next = pending.requestedMode ? deactivateEpisode(restored, pending.requestedMode) : restored;
559
- publish(next);
560
- accept(candidate, next, appendCheckpoint);
561
- }, signal);
725
+ runtime = selected = candidate;
726
+ snapshot = emptySnapshot(pending.requestedMode ?? "passive");
727
+ installScopeStates();
728
+ }
729
+ else {
730
+ // Memory is the current same-session files; the Pi checkpoint supplies only mode and run lifecycle.
731
+ await candidate.withSelectedCurrentTransaction(wanted, (current, publish) => {
732
+ assertCurrent();
733
+ if (!current)
734
+ throw new Error("Current State Flow session memory is unavailable");
735
+ const { checkpoint } = selection;
736
+ const restored = { config: { mode: checkpoint.mode }, meta: {
737
+ step: current.meta.step,
738
+ ...(checkpoint.bootstrap ? { bootstrap: true } : {}),
739
+ ...(checkpoint.specification === undefined ? {} : { specification: checkpoint.specification }),
740
+ } };
741
+ // Canceled preparation or boundary continuation may have no specification. Retain uncompiled native context.
742
+ if (restored.config.mode === "active" && restored.meta.specification === undefined
743
+ && retainsPhysicalSessionProjection(reason) && hasUncheckpointedConversation(ctx.sessionManager.getBranch()))
744
+ restored.meta.bootstrap = true;
745
+ const next = pending.requestedMode ? deactivateEpisode(restored, pending.requestedMode) : restored;
746
+ publish(next);
747
+ accept(candidate, next, appendCheckpoint);
748
+ }, assertCurrent, signal);
749
+ }
562
750
  }
563
751
  else if (selection.kind === "fork") {
564
- // The runtime copies the parent's current memory; the checkpoint supplies only child mode/bootstrap.
565
- await candidate.withForkTransaction(selection.source, selection.checkpoint, (child, publish) => {
752
+ const disposition = await candidate.inspectSelectedLifecycle(wanted, assertCurrent, signal);
753
+ if (disposition && (!wanted.includes("session") || disposition.privateAcquisition === "acquired")) {
754
+ // Acquired child-current wins; a still-deferred shared child keeps its native pending fact.
755
+ await candidate.withSelectedCurrentTransaction(wanted, (current, publish) => {
756
+ assertCurrent();
757
+ const next = { ...current, config: { mode: pending.requestedMode ?? selection.checkpoint.mode } };
758
+ publish(next);
759
+ forkInitialization = false;
760
+ modePersistenceError = undefined;
761
+ accept(candidate, next, () => { if (disposition.privateAcquisition === "acquired")
762
+ appendNativeMarker({ reset: true }); appendCheckpoint(); });
763
+ }, assertCurrent, signal);
764
+ }
765
+ else if (!wanted.includes("session")) {
766
+ // Admit selected shared owners only; no parent header/session data or private acquisition.
767
+ await candidate.withSelectedDeferredForkTransaction(wanted, { mode: pending.requestedMode ?? selection.checkpoint.mode,
768
+ ...(selection.checkpoint.bootstrap ? { bootstrap: true } : {}) }, publish => {
769
+ assertCurrent();
770
+ publish();
771
+ forkInitialization = false;
772
+ modePersistenceError = undefined;
773
+ accept(candidate, candidate.selectedSnapshot(), appendCheckpoint);
774
+ }, signal, true, () => { assertCurrent(); return pending.requestedMode ?? selection.checkpoint.mode; });
775
+ }
776
+ else {
777
+ if (disposition?.privateAcquisition === "unacquired")
778
+ throw new Error("Fork child has no deferred private-copy authority");
779
+ const base = disposition ? await loadSelectedFileCohort(ctx.cwd, candidate.sessionId, disposition.selection, candidate.root, candidate.sessionKey, signal) : undefined;
566
780
  assertCurrent();
567
- // Mode is selected independently of creating the child's private memory.
568
- const next = pending.requestedMode ? deactivateEpisode(child, pending.requestedMode) : child;
569
- publish(next);
570
- forkInitialization = false;
571
- accept(candidate, next, () => {
572
- pi.appendEntry(PASSIVE_STOP_ENTRY_TYPE, { reset: true, owner });
573
- appendCheckpoint();
574
- });
575
- }, signal);
781
+ if (disposition && !base)
782
+ throw new Error("Deferred fork child authority disappeared");
783
+ // Direct-parent acquisition follows child classification and remains outside exclusion.
784
+ const source = forkSource(ctx), parentFile = ctx.sessionManager.getHeader()?.parentSession;
785
+ const next = { config: { mode: pending.requestedMode ?? selection.checkpoint.mode }, meta: disposition ? disposition.snapshot.meta : {
786
+ step: 0, ...(selection.checkpoint.bootstrap ? { bootstrap: true } : {})
787
+ } };
788
+ await candidate.withSelectedForkCopyTransaction({ ...(base ? { kind: "fork-deferred", base } : { kind: "fork-new" }), source,
789
+ selection: wanted, snapshot: next, historyLimit: config.historyLimit,
790
+ author: (_basis, publish) => {
791
+ assertCurrent();
792
+ publish({ ...next, config: { mode: pending.requestedMode ?? selection.checkpoint.mode } });
793
+ } }, publish => {
794
+ assertCurrent();
795
+ publish();
796
+ forkInitialization = false;
797
+ modePersistenceError = undefined;
798
+ accept(candidate, candidate.selectedSnapshot(), () => { appendNativeMarker({ reset: true }); appendCheckpoint(); });
799
+ }, (selectedSource, phase) => {
800
+ assertCurrent();
801
+ if (ctx.sessionManager.getHeader()?.parentSession !== parentFile)
802
+ throw new Error("Native fork parent changed");
803
+ if (phase === "prepare" && !sameJson(forkSource(ctx), selectedSource))
804
+ throw new Error("Native direct parent mismatch");
805
+ }, signal);
806
+ }
576
807
  }
577
808
  else {
578
- await candidate.withStartTransaction((current, publish) => {
809
+ const mode = pending.requestedMode ?? (selection.kind === "pre-runtime" ? selection.mode : "active");
810
+ const disposition = await candidate.inspectSelectedLifecycle(wanted, assertCurrent, signal);
811
+ assertCurrent();
812
+ // A pre-runtime Passive choice may observe shared owners, not acquire an explicitly unacquired Session.
813
+ const observesUnacquired = (pending.requestedMode ?? mode) === "passive" && wanted.includes("session") && disposition?.privateAcquisition === "unacquired";
814
+ if (disposition && !observesUnacquired) {
815
+ await candidate.withSelectedCurrentTransaction(wanted, (current, publish) => {
816
+ assertCurrent();
817
+ const next = { ...current, config: { mode: pending.requestedMode ?? mode } };
818
+ publish(next);
819
+ accept(candidate, next, appendCheckpoint);
820
+ }, assertCurrent, signal);
821
+ }
822
+ else if (mode === "passive" || observesUnacquired) {
823
+ const shared = wanted.filter(scope => scope !== "session");
824
+ if (shared.length)
825
+ await candidate.refreshSelectedShared(captureScopeSelection(shared), assertCurrent, signal);
579
826
  assertCurrent();
580
- // Truly new branch authority is rechecked after waiting; existing memory needs its own selection.
581
- const branch = ctx.sessionManager.getBranch();
582
- const discovery = discoverSnapshotData(branch);
583
- if (current || discovery.candidates.length > 0 || discovery.errors.length > 0)
584
- throw new Error("Existing session runtime requires retained-boundary restoration");
585
- const activated = startEpisode(hasPriorConversation(branch));
586
- const next = pending.requestedMode ? deactivateEpisode(activated, pending.requestedMode) : activated;
587
- publish(next);
588
- accept(candidate, next, appendCheckpoint);
589
- }, signal, true);
827
+ runtime = selected = candidate;
828
+ snapshot = emptySnapshot(pending.requestedMode ?? mode);
829
+ installScopeStates();
830
+ }
831
+ else {
832
+ const initial = startEpisode(hasPriorConversation(ctx.sessionManager.getBranch()));
833
+ await candidate.withSelectedFirstPatchTransaction(wanted, initial, transaction => {
834
+ assertCurrent();
835
+ if (!branchStartsWithoutRuntime || forkInitialization)
836
+ throw new Error("Existing session or pending fork requires current-memory acceptance");
837
+ // Bind the newest independent mode inside the existing atomic origin/lifecycle staging engine.
838
+ const next = pending.requestedMode ? deactivateEpisode(initial, pending.requestedMode) : initial;
839
+ transaction.publish(next);
840
+ accept(candidate, next, appendCheckpoint);
841
+ }, assertCurrent, signal, true);
842
+ }
590
843
  }
591
844
  }
592
845
  catch (error) {
@@ -606,15 +859,15 @@ export default function stateFlowExtension(pi, options = {}) {
606
859
  return;
607
860
  }
608
861
  settleSelection(ctx, reason, notifyRecovery, skipped, selected !== placeholder);
609
- if (snapshot.config.mode === "off" || isActive() || runtime?.view)
862
+ if (snapshot.config.mode === "off" || isActive() || readableView() || snapshot.meta.validation?.attempt === 0 || !branchStartsWithoutRuntime)
610
863
  return;
611
- // Unavailable Active memory may expose shared reads, never substitute private memory or model context.
864
+ // Only a proven pre-runtime Passive branch may observe shared owners without private acquisition.
612
865
  const passive = await loadPassiveView(ctx, signal, isCurrent, notifyRecovery);
613
866
  if (passive === undefined)
614
867
  return;
615
868
  assertCurrent();
616
869
  // An intervening passive patch or inspection owns its newer cache, even on the same physical branch.
617
- if (runtime?.view)
870
+ if (readableView())
618
871
  return;
619
872
  runtime = selected = passive;
620
873
  installScopeStates();
@@ -633,9 +886,15 @@ export default function stateFlowExtension(pi, options = {}) {
633
886
  }
634
887
  /** Load current shared memory for passive projection without initializing or publishing it. */
635
888
  async function loadPassiveView(ctx, signal, isCurrent, notify) {
889
+ const wanted = nativeScopeSelection(ctx), shared = wanted.filter(scope => scope !== "session");
890
+ if (!shared.length)
891
+ return undefined;
636
892
  const passive = createRuntime(ctx);
637
893
  try {
638
- await passive.refreshShared(signal);
894
+ await passive.refreshSelectedShared(captureScopeSelection(shared), () => {
895
+ if (!isCurrent() || !sameJson(nativeScopeSelection(ctx), wanted))
896
+ throw new Error("State Flow observation selection changed");
897
+ }, signal);
639
898
  }
640
899
  catch (error) {
641
900
  if (isCurrent() && !signal.aborted && notify && !modePersistenceError)
@@ -645,10 +904,10 @@ export default function stateFlowExtension(pi, options = {}) {
645
904
  return passive;
646
905
  }
647
906
  function selectedContinuation(ctx, reason) {
648
- if (!retainsPhysicalSessionProjection(reason) || !runtime?.view)
907
+ if (!retainsPhysicalSessionProjection(reason) || !readableView())
649
908
  return undefined;
650
- const boundary = findPassiveStopBoundary(ctx.sessionManager.getBranch(), ctx.sessionManager.getSessionId(), PASSIVE_STOP_ENTRY_TYPE);
651
- return boundary === undefined ? undefined : createPassiveContinuation(projectModelState(effectiveState), boundary.at, boundary.from, boundary.preserveContext);
909
+ const boundary = branchPolicy(ctx).stop;
910
+ return boundary === undefined ? undefined : createPassiveContinuation(projectModelState(effectiveState), boundary.at, boundary.from, boundary.preserveContext, nativeScopeSelection(ctx));
652
911
  }
653
912
  function settleSelection(ctx, reason, notifyRecovery, skipped, selectedMemory) {
654
913
  const failure = !isActive() && snapshot.meta.validation?.attempt === 0 ? snapshot.meta.validation.error : undefined;
@@ -673,47 +932,99 @@ export default function stateFlowExtension(pi, options = {}) {
673
932
  function recordDiagnostic(error, category, ctx, extras = {}) {
674
933
  diagnosticWriter.record(sessionAddress(ctx).id, ctx.cwd, error, category, extras);
675
934
  }
935
+ function nativeToolAdmission(id, name, ctx) {
936
+ if (nativeRequests.has(id))
937
+ return nativeRequests.take(id, name);
938
+ // Raw non-model domain invocations have no operation signal. Public SDK tool_call always gates.
939
+ if (ctx?.signal || nativeRequests.active)
940
+ throw new Error("State Flow tool batch has no current native request");
941
+ return undefined;
942
+ }
943
+ function currentNativeTool(id, name, ctx) {
944
+ try {
945
+ if (nativeRequests.has(id))
946
+ nativeRequests.check(id, name);
947
+ else if (nativeRequests.active || ctx.signal !== undefined)
948
+ return false;
949
+ const policy = requestPolicy.policy, selected = runtime;
950
+ return policy !== undefined && selected !== undefined && selected.sessionId === policy.owner
951
+ && policy.owner === ctx.sessionManager.getSessionId() && policy.cwd === ctx.cwd && selected.cwd === ctx.cwd
952
+ && selected.sessionKey === sessionAddress(ctx).key;
953
+ }
954
+ catch {
955
+ return false;
956
+ }
957
+ }
676
958
  pi.registerTool({
677
959
  name: READ_STATE_TOOL_NAME,
678
960
  label: "Read State",
679
- description: "Read exact State Flow values or historical semantic patches with one path or an ordered path list. Unscoped semantic paths read the effective overlay; effective makes that overlay explicit, while global, cwd, and session select ownership. Array selectors support zero-based indices and half-open [start..end] ranges. Projection value returns semantic 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.",
961
+ 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.",
680
962
  promptSnippet: "Read exact state values, structures, or historical semantic patches",
963
+ promptGuidelines: [SCOPE_PARTICIPATION_GUIDELINE],
681
964
  parameters: Type.Object({
682
- path: Type.Optional(Type.String({ description: "One semantic path; unscoped paths use effective, explicit roots may use effective/global/cwd/session and historical [N], and arrays support half-open [start..end] ranges" })),
965
+ 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." })),
683
966
  paths: Type.Optional(Type.Array(Type.String(), { minItems: 1, description: "Ordered query paths evaluated as one all-or-error read" })),
684
967
  projection: Type.Optional(StringEnum(["value", "keys", "patch"], { description: "Value snapshot by default, structural keys with minimal meta, or the selected historical semantic patch" })),
685
968
  }, { additionalProperties: false }),
686
- async execute(_toolCallId, params, signal) {
969
+ async execute(toolCallId, params, signal, _onUpdate, ctx) {
687
970
  try {
971
+ const admission = nativeToolAdmission(toolCallId, READ_STATE_TOOL_NAME, ctx);
972
+ admission?.revalidate();
973
+ if (admission)
974
+ signal = signal ? AbortSignal.any([signal, admission.signal]) : admission.signal;
688
975
  if (!memoryToolsAvailable())
689
976
  throw new Error("State Flow tools are off for this session");
690
977
  if (signal?.aborted)
691
978
  throw new Error("State Flow read was aborted");
692
- if (!runtime?.view)
979
+ assertSelectedBranchAvailable();
980
+ const selected = runtime;
981
+ if (!selected)
693
982
  throw new Error("State Flow temporal runtime is unavailable");
983
+ const receipt = admission ?? requestPolicy.capture();
984
+ const check = () => {
985
+ receipt.revalidate();
986
+ signal?.throwIfAborted();
987
+ if (!ctx || runtime !== selected || selected.sessionId !== receipt.policy.owner || receipt.policy.owner !== ctx.sessionManager.getSessionId() || receipt.policy.cwd !== ctx.cwd
988
+ || selected.cwd !== ctx.cwd || selected.sessionKey !== sessionAddress(ctx).key)
989
+ throw new Error("State Flow read selection owner changed");
990
+ };
991
+ check();
992
+ const wanted = captureScopeSelection(receipt.policy.scopes);
993
+ params = structuredClone(params);
994
+ check();
694
995
  if (params.path === undefined && params.paths === undefined)
695
996
  throw new Error("read_state requires path or paths");
696
997
  if (params.path !== undefined && params.paths !== undefined)
697
998
  throw new Error("read_state accepts path or paths, not both");
698
999
  {
699
- const paths = params.paths ?? [params.path];
1000
+ const requestedPaths = [...(params.paths ?? [params.path])];
1001
+ const paths = requestedPaths.map(path => normalizeModelReadPath(path, wanted, config.historyLimit));
1002
+ check();
1003
+ const view = readableView(selected);
1004
+ if (!view)
1005
+ throw new Error("State Flow temporal runtime is unavailable");
1006
+ check();
700
1007
  if (paths.some((path) => /^session(?:\.|\[|$)/.test(path)))
701
1008
  assertSelectedBranchAvailable();
702
1009
  if (paths.length === 1 && /^(?:global|cwd|session)\.patches(?:\[\d+\])?$/.test(paths[0])) {
703
1010
  if (params.projection !== undefined && params.projection !== "value")
704
1011
  throw new Error("Scope patch paths support only the value projection");
705
- const result = readStatePath(runtime.view, paths[0], config.historyLimit);
1012
+ const result = readStatePath(view, paths[0], config.historyLimit);
706
1013
  if (!("patch" in result))
707
1014
  throw new Error("Expected a scope patch path");
1015
+ const output = wanted.length === 1 ? projectModelReferences({ patch: result.patch }, wanted, wanted.flatMap(scope => Object.keys(view.scopes[scope]?.modules ?? {}))) : { patch: result.patch };
1016
+ check();
708
1017
  return {
709
- content: [{ type: "text", text: `\n${JSON.stringify({ patch: result.patch })}` }],
710
- details: { path: paths[0], transitionId: result.boundary.id },
1018
+ content: [{ type: "text", text: `\n${JSON.stringify(output)}` }],
1019
+ details: { path: requestedPaths[0], transitionId: result.boundary.id },
711
1020
  };
712
1021
  }
713
- const result = readProjectedState(runtime.view, paths, params.projection, config.historyLimit);
1022
+ const result = readProjectedState(view, paths, params.projection, config.historyLimit);
1023
+ const output = wanted.length === 1 ? projectModelReferences(result, wanted, wanted.flatMap(scope => Object.keys(view.scopes[scope]?.modules ?? {}))) : result;
1024
+ check();
714
1025
  return {
715
- content: [{ type: "text", text: `\n${JSON.stringify(result)}` }],
716
- details: { ...(params.path === undefined ? { paths } : { path: params.path }), projection: params.projection ?? "value" },
1026
+ content: [{ type: "text", text: `\n${JSON.stringify(output)}` }],
1027
+ details: { ...(params.path === undefined ? { paths: requestedPaths } : { path: requestedPaths[0] }), projection: params.projection ?? "value" },
717
1028
  };
718
1029
  }
719
1030
  }
@@ -722,23 +1033,20 @@ export default function stateFlowExtension(pi, options = {}) {
722
1033
  }
723
1034
  },
724
1035
  });
725
- pi.registerTool({
1036
+ const patchStateTool = defineTool({
726
1037
  name: PATCH_STATE_TOOL_NAME,
727
1038
  label: "Patch State",
728
- description: "The sole State Flow semantic mutation protocol. Supply one or more global, cwd, or session patches; all supplied scopes commit atomically. This call must be the only State Flow barrier in its assistant response. Deleting an intent also deletes same-scope working/lazy keys its {\"$ref\"} values own unless another intent refs them. Name keys in ASCII ([A-Za-z_$][A-Za-z0-9_$-]*) so read paths and refs resolve; values may use any language.",
729
- promptSnippet: "Atomically patch one or more global/cwd/session scopes",
1039
+ 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.",
1040
+ promptSnippet: "Atomically patch participating semantic memory in its declared flat or multi-owner form",
730
1041
  promptGuidelines: [
731
1042
  RESPONSE_PATCH_GUIDELINE,
1043
+ SCOPE_PARTICIPATION_GUIDELINE,
732
1044
  "Use patch_state only for material durable semantic changes; ordinary answers need no finalization call.",
733
1045
  "Use patch_state as reconciliation, not append-only notes: place new knowledge at the narrowest valid scope and remove superseded or completed state from touched branches.",
734
1046
  "Call patch_state alone in an assistant response; after its acknowledgement, further reasoning, tools, and later patch_state calls remain allowed.",
735
1047
  ],
736
1048
  executionMode: "sequential",
737
- parameters: Type.Object({
738
- global: Type.Optional(Type.Record(Type.String(), Type.Unknown(), { description: "Optional global semantic patch" })),
739
- cwd: Type.Optional(Type.Record(Type.String(), Type.Unknown(), { description: "Optional project semantic patch" })),
740
- session: Type.Optional(Type.Record(Type.String(), Type.Unknown(), { description: "Optional session semantic patch" })),
741
- }, { additionalProperties: false }),
1049
+ parameters: config.scopes.length === 1 ? flatPatchParameters : scopedPatchParameters,
742
1050
  renderCall(args, theme, context) {
743
1051
  const title = theme.fg("toolTitle", theme.bold(PATCH_STATE_TOOL_NAME));
744
1052
  if (!config.showSuccessfulPatches && !context.isError)
@@ -751,39 +1059,53 @@ export default function stateFlowExtension(pi, options = {}) {
751
1059
  },
752
1060
  async execute(toolCallId, params, signal, _onUpdate, ctx) {
753
1061
  signal = signal ? AbortSignal.any([signal, memoryToolLifetime.signal]) : memoryToolLifetime.signal;
1062
+ let admitted = false;
754
1063
  try {
1064
+ const admission = nativeToolAdmission(toolCallId, PATCH_STATE_TOOL_NAME, ctx);
1065
+ admission?.revalidate();
1066
+ if (admission)
1067
+ signal = AbortSignal.any([signal, admission.signal]);
755
1068
  if (!memoryToolsAvailable())
756
1069
  throw new Error("State Flow tools are off for this session");
757
1070
  assertPublicationAvailable();
758
1071
  if (signal?.aborted)
759
1072
  throw new Error("State Flow patch was aborted before materialization");
760
- if (!isObject(params))
761
- throw new Error("patch_state requires an object");
1073
+ if (!ctx)
1074
+ throw new Error("State Flow patch selection owner changed");
1075
+ const selected = runtime ??= createRuntime(ctx);
1076
+ const sameSession = sessionIdentity(ctx);
1077
+ const receipt = admission ?? requestPolicy.capture();
1078
+ const wanted = captureScopeSelection(receipt.policy.scopes);
1079
+ const catalog = moduleHost.captureIfBound();
1080
+ signal = AbortSignal.any([signal, receipt.signal, ...(catalog ? [catalog.signal] : [])]);
1081
+ const check = () => {
1082
+ receipt.revalidate();
1083
+ if (runtime !== selected || !sameSession() || selected.sessionId !== receipt.policy.owner || receipt.policy.owner !== ctx.sessionManager.getSessionId()
1084
+ || receipt.policy.cwd !== ctx.cwd || selected.cwd !== ctx.cwd || selected.sessionKey !== sessionAddress(ctx).key)
1085
+ throw new Error("State Flow patch selection owner changed");
1086
+ assertPublicationAvailable();
1087
+ catalog?.assertCurrent();
1088
+ };
1089
+ // Rehash and normalize only after caller admission, still before canonical exclusion.
1090
+ check();
1091
+ const excluded = isObject(params) && Object.keys(params).find(key => DEFAULT_SCOPE_SELECTION.includes(key) && !wanted.includes(key));
1092
+ if (excluded)
1093
+ throw new Error(`State Flow ${excluded} patch scope is excluded`);
762
1094
  params = structuredClone(params);
763
- const allowed = new Set(["global", "cwd", "session"]);
764
- for (const key of Object.keys(params)) {
765
- if (!allowed.has(key))
766
- throw new Error(`patch_state does not accept field ${key}`);
767
- }
768
- const patches = {};
769
- for (const scope of ["global", "cwd", "session"]) {
770
- if (!Object.hasOwn(params, scope))
771
- continue;
772
- const patch = params[scope];
773
- if (!isObject(patch))
774
- throw new Error(`patch_state ${scope} must be a semantic patch object`);
775
- if (Object.keys(patch).length === 0)
776
- throw new Error(`patch_state ${scope} cannot be empty; omit it when unchanged`);
777
- patches[scope] = patch;
778
- }
1095
+ check();
1096
+ admitted = true;
1097
+ const knownModules = [...new Set([...(catalog?.modules.map(module => module.id) ?? []),
1098
+ ...wanted.flatMap(scope => Object.keys(readableView(selected)?.scopes[scope]?.modules ?? {}))])];
1099
+ const patches = normalizeModelPatches(params, wanted, knownModules);
1100
+ check();
779
1101
  const scopes = Object.keys(patches);
780
- if (scopes.length === 0)
781
- throw new Error("patch_state requires at least one scope patch");
782
- const selected = runtime ??= createRuntime(ctx);
1102
+ const firstAuthoring = selected.selectedView() === undefined;
783
1103
  const acquiredArtifacts = structuredClone([...artifactReads.successful.values()]);
784
1104
  const acquiredSkills = structuredClone([...skillReads.successful.values()]);
785
1105
  const previousEffective = effectiveState;
786
- return await selected.withPatchTransaction((transaction) => {
1106
+ skillReads.validateCompilations(patches);
1107
+ const author = (transaction) => {
1108
+ check();
787
1109
  if (runtime !== selected)
788
1110
  throw new Error("State Flow session selection changed while awaiting publication");
789
1111
  if (!memoryToolsAvailable())
@@ -796,13 +1118,14 @@ export default function stateFlowExtension(pi, options = {}) {
796
1118
  throw new Error(`Artifact source changed after acquisition: ${acquired.path}`);
797
1119
  }
798
1120
  }
799
- const stage = stageAtomicScopePatches(transaction.states, patches, acquiredSkills, transaction.causalBasis, acquiredArtifacts);
800
- const changed = ["global", "cwd", "session"].some((scope) => !sameJson(transaction.states[scope], stage.nextStates[scope])
801
- || Object.entries(stage.provenanceUpdates[scope]).some(([path, evidence]) => !Object.hasOwn(transaction.provenance[scope], path) || !sameJson(transaction.provenance[scope][path], evidence)));
802
- const nextSnapshot = structuredClone(snapshot);
1121
+ const stage = stageSelectedScopePatches(transaction, patches, acquiredSkills, transaction.causalBasis, acquiredArtifacts, catalog?.modules);
1122
+ const changed = transaction.selection.some((scope) => !sameJson(transaction.states[scope], stage.nextStates[scope])
1123
+ || Object.entries(stage.provenanceUpdates[scope] ?? {}).some(([path, evidence]) => !Object.hasOwn(transaction.provenance[scope] ?? {}, path) || !sameJson(transaction.provenance[scope]?.[path], evidence)));
1124
+ const nextSnapshot = structuredClone(firstAuthoring ? transaction.snapshot : snapshot);
803
1125
  let publication;
804
- commitScopedTransition(nextSnapshot, transaction.states, stage, (accepted, next) => {
805
- publication = transaction.publish(next, accepted, stage.provenanceUpdates);
1126
+ commitSelectedTransition(nextSnapshot, transaction, stage, (accepted, next) => {
1127
+ catalog?.assertCurrent();
1128
+ publication = transaction.publish(next, accepted, stage.provenanceUpdates, stage.moduleAdditions);
806
1129
  }, transaction.causalBasis, { finalizeRun: false });
807
1130
  snapshot = nextSnapshot;
808
1131
  installScopeStates();
@@ -812,58 +1135,100 @@ export default function stateFlowExtension(pi, options = {}) {
812
1135
  }
813
1136
  clearAcceptedAcquisitions(new Set(acquiredArtifacts.map(({ path }) => path)));
814
1137
  updateUi(ctx);
815
- const updates = contextProjection.acceptPatch(previousEffective, effectiveState, patches, acquisition.hints, stage.cascades, isActive());
1138
+ const updates = contextProjection.acceptPatch(previousEffective, effectiveState, patches, acquisition.hints, stage.cascades, isActive(), wanted);
816
1139
  const acknowledgement = changed
817
1140
  ? `\nState materialized atomically at ${scopes.join("+")} scope${scopes.length === 1 ? "" : "s"}.`
818
1141
  : "\nState already current.";
819
1142
  return { content: [
820
- { type: "text", text: acknowledgement + stage.missingDeletions.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("") },
1143
+ { 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("") },
821
1144
  ...(updates ? [{ type: "text", text: `\n${presentationJson({ state_updates: updates })}` }] : []),
822
1145
  ], details: { scopes, step: snapshot.meta.step, changed, missingDeletions: stage.missingDeletions } };
823
- }, signal);
824
- }
825
- catch (error) {
826
- let attempted;
827
- try {
828
- attempted = structuredClone(params);
1146
+ };
1147
+ if (!firstAuthoring)
1148
+ return await selected.withSelectedPatchTransaction(author, check, signal);
1149
+ check();
1150
+ const disposition = await selected.inspectSelectedLifecycle(wanted, check, signal);
1151
+ if (disposition && !wanted.includes("session")) {
1152
+ return await selected.withSelectedCurrentTransaction(wanted, (_current, _publish, transaction) => author(Object.freeze({
1153
+ ...transaction, snapshot: { ...transaction.snapshot, config: { mode: receipt.policy.mode } },
1154
+ })), check, signal);
829
1155
  }
830
- catch {
831
- attempted = undefined;
1156
+ if (disposition) {
1157
+ const acquire = () => {
1158
+ check();
1159
+ if (receipt.policy.mode === "off" || !wanted.includes("session") || disposition.privateAcquisition !== "unacquired"
1160
+ || forkInitialization || branchPolicy(ctx).forkPending)
1161
+ throw new Error("State Flow first mutation requires independent unacquired Session participation");
1162
+ };
1163
+ acquire();
1164
+ const base = await loadSelectedFileCohort(ctx.cwd, selected.sessionId, disposition.selection, selected.root, selected.sessionKey, signal);
1165
+ acquire();
1166
+ if (!base)
1167
+ throw new Error("Unacquired State Flow first mutation source disappeared");
1168
+ let result;
1169
+ return await selected.withSelectedSessionAcquisitionTransaction({ kind: "unacquired", base, selection: wanted,
1170
+ snapshot: { ...disposition.snapshot, config: { mode: receipt.policy.mode } }, historyLimit: config.historyLimit,
1171
+ author: (basis, publish) => {
1172
+ acquire();
1173
+ result = author(Object.freeze({ selection: wanted,
1174
+ states: readTemporalScopes(basis.view, 0, config.historyLimit), snapshot: basis.snapshot,
1175
+ modules: Object.fromEntries(wanted.filter(scope => basis.view.scopes[scope]?.modules !== undefined).map(scope => [scope, structuredClone(basis.view.scopes[scope].modules)])),
1176
+ causalBasis: basis.view.lineage.at(-1).id, provenance: basis.provenance,
1177
+ publish: (next, transition, provenance, additions) => { acquire(); return publish(next, transition, provenance, additions); } }));
1178
+ } }, publish => { acquire(); publish(); return result; }, signal, true);
832
1179
  }
833
- const cause = diagnosticText(error);
834
- if (!signal.aborted && memoryToolsAvailable())
1180
+ if (!branchStartsWithoutRuntime || forkInitialization || branchPolicy(ctx).forkPending)
1181
+ throw new Error("State Flow first authoring requires native independent origin authority");
1182
+ return await selected.withSelectedFirstPatchTransaction(wanted, snapshot, author, () => {
1183
+ check();
1184
+ if (!branchStartsWithoutRuntime || forkInitialization || branchPolicy(ctx).forkPending)
1185
+ throw new Error("State Flow origin authority changed");
1186
+ }, signal, true);
1187
+ }
1188
+ catch (error) {
1189
+ if (admitted && !signal.aborted && memoryToolsAvailable()) {
1190
+ let attempted;
1191
+ try {
1192
+ attempted = structuredClone(params);
1193
+ }
1194
+ catch {
1195
+ attempted = undefined;
1196
+ }
1197
+ const cause = diagnosticText(error);
835
1198
  recordDiagnostic(cause, /concurrently|advanced/.test(cause) ? "publication-conflict" : "invalid-patch", ctx, {
836
- input: attempted,
837
- tool: PATCH_STATE_TOOL_NAME,
838
- toolCallId,
1199
+ input: attempted, tool: PATCH_STATE_TOOL_NAME, toolCallId,
839
1200
  });
1201
+ }
840
1202
  throw separatedFailure(error);
841
1203
  }
842
1204
  },
843
1205
  });
844
- function startStateFlow(ctx) {
1206
+ pi.registerTool({ ...patchStateTool });
1207
+ function startStateFlow(ctx, reselect = false) {
845
1208
  if (shuttingDown)
846
1209
  return Promise.resolve({ ok: false, message: "State Flow is shutting down" });
847
- if (startActivation.current?.operation)
1210
+ if (!reselect && startActivation.current?.operation)
848
1211
  return startActivation.current.operation;
849
1212
  telegramStartPending = false;
850
- if (activeContext && !branchRestoration.current && isActive()) {
1213
+ if (!reselect && activeContext && !branchRestoration.current && isActive()) {
851
1214
  return Promise.resolve({ ok: true, message: "State Flow is already active", signal: sharedInspectionLifetime.signal });
852
1215
  }
853
1216
  const pending = startActivation.claim({ controller: new AbortController() });
854
- return startActivation.track(pending, runStart(ctx, pending.controller));
1217
+ return startActivation.track(pending, runStart(ctx, pending.controller, reselect));
855
1218
  }
856
1219
  /** Await restoration-owned attachment and exact-source fork recovery before current-head activation. */
857
- async function runStart(ctx, pending) {
1220
+ async function runStart(ctx, pending, reselect) {
858
1221
  const sameSession = sessionIdentity(ctx);
859
- const signal = ctx.signal ? AbortSignal.any([pending.signal, ctx.signal]) : pending.signal;
1222
+ const signal = modeOperationSignal(ctx, pending.signal);
860
1223
  const isOwner = () => startActivation.current?.controller === pending && !signal.aborted && !shuttingDown && sameSession();
861
1224
  const superseded = () => {
862
1225
  pending.abort();
863
1226
  return { ok: false, message: "State Flow activation was superseded", signal: pending.signal };
864
1227
  };
865
1228
  try {
866
- if (deferredBranch?.reason === "fork")
1229
+ if (reselect)
1230
+ await waitForRecovery(restoreActiveBranch(ctx, undefined, false, pending), signal);
1231
+ else if (deferredBranch?.reason === "fork")
867
1232
  await waitForRecovery(restoreActiveBranch(ctx, "fork", false, pending), signal);
868
1233
  else if (!activeContext)
869
1234
  await waitForRecovery(restoreActiveBranch(ctx, undefined, false, pending), signal);
@@ -871,7 +1236,7 @@ export default function stateFlowExtension(pi, options = {}) {
871
1236
  await waitForRecovery(branchRestoration.current.operation, signal);
872
1237
  if (!isOwner())
873
1238
  return superseded();
874
- if (isActive())
1239
+ if (!reselect && isActive())
875
1240
  return { ok: true, message: "State Flow is already active", signal: sharedInspectionLifetime.signal };
876
1241
  if (forkInitialization) {
877
1242
  // Withdraw this join on cancellation without revoking the independently owned mode persistence.
@@ -898,7 +1263,7 @@ export default function stateFlowExtension(pi, options = {}) {
898
1263
  /** Explicit Active or Passive accepts validated current same-session memory without claiming unavailable history. */
899
1264
  async function activateCurrentState(ctx, pending, mode = "active", owns = () => startActivation.current?.controller === pending) {
900
1265
  let selected = runtime;
901
- const owner = ctx.sessionManager.getSessionId();
1266
+ const wanted = nativeScopeSelection(ctx);
902
1267
  const sameSession = sessionIdentity(ctx);
903
1268
  const policy = () => `${snapshot.config.mode}:${isActive()}`;
904
1269
  const initialPolicy = policy();
@@ -906,14 +1271,15 @@ export default function stateFlowExtension(pi, options = {}) {
906
1271
  const active = mode === "active";
907
1272
  let accepted = false;
908
1273
  let receipt = AbortSignal.any([pending.signal, sharedInspectionLifetime.signal]);
909
- const signal = ctx.signal ? AbortSignal.any([pending.signal, ctx.signal]) : pending.signal;
1274
+ const signal = modeOperationSignal(ctx, pending.signal);
910
1275
  const isCurrent = () => owns() && !signal.aborted && runtime === selected && !shuttingDown
911
- && sameSession() && policy() === (accepted ? acceptedPolicy : initialPolicy);
1276
+ && sameSession() && sameJson(nativeScopeSelection(ctx), wanted) && policy() === (accepted ? acceptedPolicy : initialPolicy);
912
1277
  const superseded = () => {
913
1278
  pending.abort();
914
1279
  return { ok: false, message: active ? "State Flow activation was superseded" : "State Flow mode change was superseded", signal: pending.signal };
915
1280
  };
916
1281
  try {
1282
+ assertNativeMemoryScopes(wanted);
917
1283
  const activation = createRuntime(ctx);
918
1284
  const deferred = deferredBranch;
919
1285
  if (deferred) {
@@ -922,17 +1288,22 @@ export default function stateFlowExtension(pi, options = {}) {
922
1288
  branchStartsWithoutRuntime = retained.kind === "pre-runtime" || (discovery.candidates.length === 0 && discovery.errors.length === 0);
923
1289
  }
924
1290
  // Off activation owns one cancellable current-head publication, not an independent read-only restore.
925
- const result = await activation.withStartTransaction((current, publish) => {
1291
+ const acceptActivation = (current, publish) => {
926
1292
  signal.throwIfAborted();
927
1293
  if (!isCurrent())
928
1294
  throw new Error("State Flow activation selection changed while awaiting publication");
929
1295
  if (!current && (!active || !branchStartsWithoutRuntime))
930
1296
  throw new Error(snapshot.meta.validation?.error ?? "Current State Flow session memory is unavailable");
931
1297
  const boundary = deferred && retainsPhysicalSessionProjection(deferred.reason)
932
- ? findPassiveStopBoundary(ctx.sessionManager.getBranch(), owner, PASSIVE_STOP_ENTRY_TYPE) : undefined;
1298
+ ? branchPolicy(ctx).stop : undefined;
933
1299
  const bootstrap = hasPriorConversation(ctx.sessionManager.getBranch()) || passiveContinuation !== undefined || boundary !== undefined;
934
1300
  const activated = !active ? deactivateEpisode(current, "passive")
935
1301
  : current ? resumeEpisode(current, bootstrap) : startEpisode(bootstrap);
1302
+ if (active) {
1303
+ // Explicit Start accepts current memory, not the prior run's prompt or repair attempt.
1304
+ delete activated.meta.specification;
1305
+ delete activated.meta.validation;
1306
+ }
936
1307
  const resumedWrites = modePersistenceError !== undefined;
937
1308
  publish(activated);
938
1309
  accepted = true;
@@ -958,7 +1329,7 @@ export default function stateFlowExtension(pi, options = {}) {
958
1329
  updateUi(ctx);
959
1330
  if (forkInitialization) {
960
1331
  forkInitialization = false;
961
- pi.appendEntry(PASSIVE_STOP_ENTRY_TYPE, { reset: true, owner });
1332
+ appendNativeMarker({ reset: true });
962
1333
  }
963
1334
  appendCheckpoint();
964
1335
  if (!active) {
@@ -970,14 +1341,54 @@ export default function stateFlowExtension(pi, options = {}) {
970
1341
  ? "State Flow active. The next complete agent run will migrate active context into state."
971
1342
  : "State Flow active. The next prompt starts a stateful agent run.", "info");
972
1343
  return { ok: true, message: "State Flow active", signal: receipt };
973
- }, signal, active && branchStartsWithoutRuntime);
1344
+ };
1345
+ const check = () => { signal.throwIfAborted(); if (!isCurrent())
1346
+ throw new Error("State Flow activation superseded"); };
1347
+ let result;
1348
+ const sameRuntimeOwner = selected?.cwd === ctx.cwd && selected.sessionKey === activation.sessionKey;
1349
+ // Known accepted Session can only take current acceptance, even if its live header is later downgraded.
1350
+ const acceptedSession = sameRuntimeOwner && selected?.selectedView()?.selection.includes("session");
1351
+ const disposition = active && !acceptedSession ? await activation.inspectSelectedLifecycle(wanted, check, signal) : undefined;
1352
+ // Explicit Start owns the grant; header data only selects the existing acquisition route.
1353
+ if (active && wanted.includes("session") && disposition?.privateAcquisition === "unacquired") {
1354
+ if (forkInitialization || branchPolicy(ctx).forkPending)
1355
+ throw new Error("Pending fork cannot use independent private acquisition");
1356
+ // Retain denial-only acquisition knowledge when an existing owner has cleared or excluded its cache.
1357
+ if (sameRuntimeOwner)
1358
+ await selected.inspectSelectedLifecycle(wanted, check, signal);
1359
+ const base = await loadSelectedFileCohort(ctx.cwd, activation.sessionId, disposition.selection, activation.root, activation.sessionKey, signal);
1360
+ check();
1361
+ if (!base)
1362
+ throw new Error("Unacquired State Flow source authority disappeared");
1363
+ let acquiredResult;
1364
+ result = await activation.withSelectedSessionAcquisitionTransaction({ kind: "unacquired", base, selection: wanted,
1365
+ snapshot: { ...disposition.snapshot, config: { mode: "active" } }, historyLimit: config.historyLimit,
1366
+ author: (basis, publish) => {
1367
+ check();
1368
+ if (forkInitialization || branchPolicy(ctx).forkPending)
1369
+ throw new Error("Pending fork cannot use independent private acquisition");
1370
+ acquiredResult = acceptActivation(basis.snapshot, activated => publish(activated));
1371
+ } }, publish => { check(); publish(); return acquiredResult; }, signal, true);
1372
+ }
1373
+ else if (active && branchStartsWithoutRuntime && !acceptedSession && !disposition) {
1374
+ const next = startEpisode(hasPriorConversation(ctx.sessionManager.getBranch()) || passiveContinuation !== undefined);
1375
+ result = await activation.withSelectedFirstPatchTransaction(wanted, next, transaction => {
1376
+ check();
1377
+ if (!branchStartsWithoutRuntime || forkInitialization)
1378
+ throw new Error("State Flow origin authority changed");
1379
+ return acceptActivation(undefined, activated => transaction.publish(activated));
1380
+ }, check, signal, true);
1381
+ }
1382
+ else
1383
+ result = await activation.withSelectedCurrentTransaction(wanted, (current, publish) => acceptActivation(current, publish), check, signal);
974
1384
  return isCurrent() ? result : superseded();
975
1385
  }
976
1386
  catch (error) {
977
1387
  if (!isCurrent())
978
1388
  return superseded();
979
1389
  const message = conciseDiagnostic(`${accepted ? `State Flow ${mode}; lifecycle update failed` : active ? "State Flow activation failed" : "State Flow passive acceptance failed"}: ${diagnosticText(error)}`);
980
- // Failed Passive acceptance falls back to its caller's write-fence report.
1390
+ // An unaccepted activation cannot replace retained lifecycle or poison an independent Stop.
1391
+ // Attachment owns required-proof unavailability; failed Passive acceptance reports through its caller's fence.
981
1392
  if (active || accepted)
982
1393
  notifyProblem(ctx, message, accepted ? "warning" : "error");
983
1394
  return { ok: accepted, message, signal: receipt };
@@ -989,14 +1400,40 @@ export default function stateFlowExtension(pi, options = {}) {
989
1400
  off: "Turn State Flow tools and context off on the current session branch",
990
1401
  };
991
1402
  /** Terminal commands and Telegram controls share these lifecycle owners. */
992
- function selectMode(ctx, mode) {
993
- return mode === "active" ? startStateFlow(ctx) : deactivateStateFlow(ctx, mode);
1403
+ function selectMode(ctx, mode, scopes) {
1404
+ if (!scopes || sameJson(scopes, nativeScopeSelection(ctx)))
1405
+ return mode === "active" ? startStateFlow(ctx) : deactivateStateFlow(ctx, mode);
1406
+ if (shuttingDown)
1407
+ return Promise.resolve({ ok: false, message: "State Flow is shutting down" });
1408
+ if (mode === "off")
1409
+ return selectOff(ctx, scopes);
1410
+ // The native choice is DATA, never a private/fork acquisition or a fence reset.
1411
+ appendNativeMarker({ mode, scopes }, ctx);
1412
+ if (mode === "active") {
1413
+ // A different selection revokes old-scope persistence, not an independent same-scope Stop.
1414
+ inactivePersistence.cancel();
1415
+ return startStateFlow(ctx, true);
1416
+ }
1417
+ const sameSession = sessionIdentity(ctx);
1418
+ const restoring = restoreActiveBranch(ctx, undefined, true, undefined, "passive");
1419
+ const signal = branchRestoration.current?.controller.signal;
1420
+ return restoring.then(() => {
1421
+ if (signal?.aborted || !sameSession() || !sameJson(scopes, nativeScopeSelection(ctx)) || snapshot.config.mode !== "passive") {
1422
+ return { ok: false, message: "State Flow mode change was superseded" };
1423
+ }
1424
+ return { ok: snapshot.meta.validation?.attempt !== 0, message: snapshot.meta.validation?.error ?? "State Flow passive" };
1425
+ });
994
1426
  }
995
1427
  for (const mode of ["active", "passive", "off"]) {
996
1428
  pi.registerCommand(`state-flow-${mode}`, {
997
- description: MODE_COMMAND_DESCRIPTIONS[mode],
998
- handler: async (_args, ctx) => {
999
- await selectMode(ctx, mode);
1429
+ description: `${MODE_COMMAND_DESCRIPTIONS[mode]} [global cwd session]`,
1430
+ getArgumentCompletions: prefix => {
1431
+ const values = scopeSelectionArgumentCompletions(prefix);
1432
+ return values.length ? values.map(value => ({ value, label: value })) : null;
1433
+ },
1434
+ handler: async (args, ctx) => {
1435
+ const scopes = parseScopeSelectionArguments(args);
1436
+ await selectMode(ctx, mode, scopes);
1000
1437
  },
1001
1438
  });
1002
1439
  }
@@ -1043,30 +1480,38 @@ export default function stateFlowExtension(pi, options = {}) {
1043
1480
  if (restoring?.awaitingAcceptance) {
1044
1481
  // Passive keeps independently owned restoration; Off withdraws it through selectOff.
1045
1482
  applyInactiveMode(ctx, mode);
1483
+ // A read-only observer may never write a checkpoint; retain the newer choice now.
1484
+ if (branchPolicy(ctx).mode !== mode)
1485
+ appendNativeMarker({ mode }, ctx);
1046
1486
  return Promise.resolve({ ok: true, message: `State Flow ${mode}; memory restoration continues` });
1047
1487
  }
1048
1488
  if (snapshot.config.mode === mode) {
1049
- const retained = selectRetainedCheckpoint(discoverSnapshotData(ctx.sessionManager.getBranch()).candidates, config.inactiveMode);
1050
- const recordedMode = retained.kind === "pre-runtime" ? retained.mode : retained.kind === "boundary" ? retained.checkpoint.mode : undefined;
1489
+ const recordedMode = branchPolicy(ctx).mode;
1051
1490
  if (!passiveRecoveryNeeded(mode) && (modePersistenceError || recordedMode === mode))
1052
1491
  return Promise.resolve({ ok: true, message: `State Flow is already ${mode}` });
1053
1492
  }
1054
1493
  inactivePersistence.cancel();
1055
1494
  const pending = inactivePersistence.claim({ controller: new AbortController() });
1056
- return inactivePersistence.track(pending, deferredBranch && mode === "passive" && !branchStartsWithoutRuntime
1495
+ return inactivePersistence.track(pending, deferredBranch && mode === "passive"
1057
1496
  ? acquirePassiveMode(ctx, pending, deferredBranch.reason)
1058
1497
  : persistInactiveMode(ctx, pending, mode));
1059
1498
  }
1060
1499
  /** Off owns cancellation and native policy only; no canonical transaction or semantic handoff. */
1061
- function selectOff(ctx) {
1500
+ function selectOff(ctx, scopes) {
1062
1501
  const address = sessionAddress(ctx);
1063
1502
  const owner = ctx.sessionManager.getSessionId();
1064
1503
  const branch = ctx.sessionManager.getBranch();
1065
1504
  const selected = runtime;
1066
1505
  const sameOwner = selected?.sessionKey === address.key && selected.cwd === ctx.cwd;
1067
- const forkRecorded = hasPendingFork(branch, owner, PASSIVE_STOP_ENTRY_TYPE);
1068
- const pendingFork = forkRecorded || (sameOwner && forkInitialization) || (deferredBranch?.owner === address.key && deferredBranch.cwd === ctx.cwd && deferredBranch.reason === "fork");
1069
- const policy = findBranchPolicy(branch, owner, PASSIVE_STOP_ENTRY_TYPE, config.inactiveMode);
1506
+ let policy;
1507
+ try {
1508
+ policy = branchPolicy(ctx, undefined, false);
1509
+ requestPolicy.select({ cwd: ctx.cwd, owner, mode: snapshot.config.mode, scopes: scopes ?? policy.scopes });
1510
+ }
1511
+ catch { /* Explicit Off denies memory even when the prior policy cannot be admitted. */ }
1512
+ const forkRecorded = policy?.forkPending ?? false;
1513
+ const pendingFork = forkRecorded || (sameOwner && forkInitialization) || (deferredBranch?.owner === address.key && deferredBranch.cwd === ctx.cwd && deferredBranch.reason === "fork")
1514
+ || (!policy && typeof ctx.sessionManager.getHeader()?.parentSession === "string");
1070
1515
  const sameDeferred = deferredBranch?.owner === address.key && deferredBranch.cwd === ctx.cwd;
1071
1516
  const current = sameOwner || sameDeferred ? snapshot : emptySnapshot("off");
1072
1517
  if (!sameOwner && !sameDeferred)
@@ -1082,8 +1527,8 @@ export default function stateFlowExtension(pi, options = {}) {
1082
1527
  const preRuntime = (sameOwner && branchStartsWithoutRuntime) || (discovery.candidates.length === 0 && discovery.errors.length === 0);
1083
1528
  let checkpoint;
1084
1529
  try {
1085
- checkpoint = !modePersistenceError && current.meta.validation?.attempt !== 0
1086
- ? preRuntime ? preRuntimeCheckpoint("off") : sameOwner && selected?.view ? selected.retainedCheckpoint(deactivateEpisode(current, "off")) : undefined
1530
+ checkpoint = !scopes && !modePersistenceError && current.meta.validation?.attempt !== 0
1531
+ ? sameOwner && selected?.selectedView() ? selected.retainedSelectedCheckpoint("off") : undefined
1087
1532
  : undefined;
1088
1533
  }
1089
1534
  catch {
@@ -1093,6 +1538,7 @@ export default function stateFlowExtension(pi, options = {}) {
1093
1538
  branchRestoration.cancel();
1094
1539
  inactivePersistence.cancel();
1095
1540
  backup.cancel();
1541
+ requestPolicy.invalidate();
1096
1542
  memoryToolLifetime.renew();
1097
1543
  clearRunTransient();
1098
1544
  contextProjection.reset();
@@ -1106,14 +1552,17 @@ export default function stateFlowExtension(pi, options = {}) {
1106
1552
  forkInitialization = pendingFork;
1107
1553
  deferredBranch = { owner: address.key, cwd: ctx.cwd, reason: pendingFork ? "fork" : undefined };
1108
1554
  activeContext = ctx;
1555
+ if (scopes)
1556
+ requestPolicy.select({ cwd: ctx.cwd, owner, mode: "off", scopes });
1109
1557
  installScopeStates();
1110
1558
  syncStateFlowTools();
1111
1559
  updateUi(ctx);
1112
1560
  try {
1113
- if (!alreadyOff || (pendingFork && !forkRecorded)) {
1561
+ if (scopes || !alreadyOff || (pendingFork && !forkRecorded)) {
1114
1562
  if (!checkpoint || !preRuntime || pendingFork || preserveContext || from !== undefined || modePersistenceError)
1115
- pi.appendEntry(PASSIVE_STOP_ENTRY_TYPE, {
1563
+ appendNativeMarker({
1116
1564
  owner, at, mode: "off", memoryDeferred: true,
1565
+ ...(scopes === undefined ? {} : { scopes }),
1117
1566
  ...(from === undefined ? {} : { from }),
1118
1567
  ...(preserveContext ? { preserveContext: true } : {}),
1119
1568
  ...(pendingFork ? { forkPending: true } : {}),
@@ -1141,6 +1590,7 @@ export default function stateFlowExtension(pi, options = {}) {
1141
1590
  let selected = runtime;
1142
1591
  const owner = ctx.sessionManager.getSessionId();
1143
1592
  const current = snapshot;
1593
+ const wanted = captureScopeSelection(nativeScopeSelection(ctx));
1144
1594
  const wasActive = current.config.mode === "active";
1145
1595
  let unfinished = current.meta.specification !== undefined
1146
1596
  || (inferencePreparation.current?.prompt !== undefined && !inferencePreparation.current.accepted);
@@ -1179,7 +1629,7 @@ export default function stateFlowExtension(pi, options = {}) {
1179
1629
  if (modePersistenceError) {
1180
1630
  // Writes stay paused; the native marker records only the newly selected inactive policy.
1181
1631
  pending.published = true;
1182
- pi.appendEntry(PASSIVE_STOP_ENTRY_TYPE, {
1632
+ appendNativeMarker({
1183
1633
  at: passiveContinuation?.startedAt ?? stoppedAt,
1184
1634
  ...(passiveContinuation?.activeRunStartedAt === undefined ? {} : { from: passiveContinuation.activeRunStartedAt }),
1185
1635
  preserveContext: true, owner, persistenceError: modePersistenceError, mode,
@@ -1194,8 +1644,8 @@ export default function stateFlowExtension(pi, options = {}) {
1194
1644
  const superseded = () => ({ ok: false, message: "State Flow mode change was superseded" });
1195
1645
  const freezeHandoff = () => {
1196
1646
  contextProjection.reset();
1197
- const handoff = (wasActive || modePersistenceError) && selected?.view && current.meta.validation?.attempt !== 0
1198
- ? createPassiveContinuation(projectModelState(effectiveState), incomingBoundary?.startedAt ?? stoppedAt, incomingBoundary ? incomingBoundary.activeRunStartedAt : !idle || unfinished ? anchor : undefined, modePersistenceError !== undefined || (incomingBoundary ? incomingBoundary.preserveContext : current.meta.bootstrap === true || (unfinished && anchor === undefined)))
1647
+ const handoff = (wasActive || modePersistenceError) && readableView(selected) && current.meta.validation?.attempt !== 0
1648
+ ? createPassiveContinuation(projectModelState(effectiveState), incomingBoundary?.startedAt ?? stoppedAt, incomingBoundary ? incomingBoundary.activeRunStartedAt : !idle || unfinished ? anchor : undefined, modePersistenceError !== undefined || (incomingBoundary ? incomingBoundary.preserveContext : current.meta.bootstrap === true || (unfinished && anchor === undefined)), wanted)
1199
1649
  : undefined;
1200
1650
  // Repeated Passive choices keep the already selected continuation boundary.
1201
1651
  passiveContinuation = handoff ?? (!wasActive ? passiveContinuation : undefined);
@@ -1206,7 +1656,7 @@ export default function stateFlowExtension(pi, options = {}) {
1206
1656
  const exitHandoff = freezeHandoff();
1207
1657
  const selectedMode = snapshot.config.mode;
1208
1658
  if (exitHandoff || modePersistenceError)
1209
- pi.appendEntry(PASSIVE_STOP_ENTRY_TYPE, {
1659
+ appendNativeMarker({
1210
1660
  at: exitHandoff?.startedAt ?? stoppedAt,
1211
1661
  ...(exitHandoff?.activeRunStartedAt === undefined ? {} : { from: exitHandoff.activeRunStartedAt }),
1212
1662
  ...(exitHandoff?.preserveContext || modePersistenceError ? { preserveContext: true } : {}),
@@ -1228,33 +1678,30 @@ export default function stateFlowExtension(pi, options = {}) {
1228
1678
  bootstrapContinuation = undefined;
1229
1679
  acquisition.clearInvalidations();
1230
1680
  assertPublicationAvailable();
1231
- const signal = ctx.signal ? AbortSignal.any([pending.controller.signal, ctx.signal]) : pending.controller.signal;
1232
- if (branchStartsWithoutRuntime || !selected?.view) {
1681
+ const signal = modeOperationSignal(ctx, pending.controller.signal);
1682
+ if (branchStartsWithoutRuntime || !selected?.selectedView()) {
1233
1683
  // A pre-runtime choice is native-only; Passive then loads shared memory without initializing storage.
1234
1684
  const result = complete();
1235
- if (snapshot.config.mode !== "passive" || runtime?.view)
1685
+ if (snapshot.config.mode !== "passive" || readableView())
1236
1686
  return result;
1237
1687
  const passive = await loadPassiveView(ctx, signal, isCurrent, true);
1238
- if (passive && isCurrent() && !signal.aborted && !runtime?.view) {
1688
+ if (passive && isCurrent() && !signal.aborted && !readableView()) {
1239
1689
  runtime = selected = passive;
1240
1690
  installScopeStates();
1241
1691
  updateUi(ctx);
1242
1692
  }
1243
1693
  return isCurrent() ? result : superseded();
1244
1694
  }
1245
- const result = await selected.withLifecycleTransaction((publish) => {
1695
+ await selected.persistSelectedPassive(() => {
1246
1696
  signal.throwIfAborted();
1247
1697
  if (!isCurrent())
1248
1698
  throw new Error("State Flow mode selection changed while awaiting publication");
1249
1699
  assertPublicationAvailable();
1250
- const next = structuredClone(snapshot);
1251
- publish(next);
1252
- accepted = true;
1253
- snapshot = next;
1254
- installScopeStates();
1255
- recordPublication();
1256
- return complete();
1257
1700
  }, signal);
1701
+ accepted = true;
1702
+ installScopeStates();
1703
+ recordPublication();
1704
+ const result = complete();
1258
1705
  return isCurrent() ? result : superseded();
1259
1706
  }
1260
1707
  catch (error) {
@@ -1277,6 +1724,7 @@ export default function stateFlowExtension(pi, options = {}) {
1277
1724
  port: {
1278
1725
  snapshot: () => ({
1279
1726
  mode: snapshot.config.mode,
1727
+ scopes: captureScopeSelection(nativeScopeSelection()),
1280
1728
  inferenceBlocked: isActiveRestorationBlocked(snapshot),
1281
1729
  step: snapshot.meta.step,
1282
1730
  revisions: scopeRevisions(),
@@ -1311,13 +1759,32 @@ export default function stateFlowExtension(pi, options = {}) {
1311
1759
  },
1312
1760
  });
1313
1761
  void telegram.ensure();
1314
- pi.on("before_agent_start", (event) => {
1762
+ function invalidateModuleModelContext(ctx) {
1763
+ if (!shuttingDown && snapshot.config.mode !== "off" && currentNativeContextOwner(ctx) && moduleHost.captureIfBound()?.modules.length)
1764
+ requestPolicy.invalidate();
1765
+ }
1766
+ pi.on("model_select", (event, ctx) => { if (event.previousModel !== event.model)
1767
+ invalidateModuleModelContext(ctx); });
1768
+ pi.on("thinking_level_select", (event, ctx) => { if (event.previousLevel !== event.level)
1769
+ invalidateModuleModelContext(ctx); });
1770
+ // turn_start/context/message_end are transport-independent; provider HTTP hooks are optional.
1771
+ pi.on("turn_start", (_event, ctx) => {
1772
+ if (shuttingDown)
1773
+ return;
1774
+ requestPolicy.select({ cwd: ctx.cwd, owner: ctx.sessionManager.getSessionId(), mode: snapshot.config.mode, scopes: nativeScopeSelection(ctx) });
1775
+ const catalog = snapshot.config.mode === "off" ? undefined : moduleHost.captureIfBound();
1776
+ const sameSession = sessionIdentity(ctx);
1777
+ nativeRequests.begin(snapshot.config.mode === "off" ? undefined : requestPolicy.capture(), ctx.signal, () => { catalog?.assertCurrent(); return sameSession(); }, catalog ? AbortSignal.any([requestPolicy.signal, catalog.signal]) : requestPolicy.signal);
1778
+ });
1779
+ pi.on("before_agent_start", (event, ctx) => {
1780
+ if (shuttingDown || !currentNativeContextOwner(ctx))
1781
+ return;
1315
1782
  // Native run identity is independent of semantic enablement and survives mode toggles.
1316
1783
  runAnchorTimestamp = undefined;
1317
1784
  if (!isActive()) {
1318
1785
  if (!passiveMemoryAvailable())
1319
1786
  return;
1320
- (event.systemPromptOptions.sections ??= {}).state_flow = PASSIVE_MEMORY_PROTOCOL;
1787
+ (event.systemPromptOptions.sections ??= {}).state_flow = passiveMemoryProtocol(nativeScopeSelection(ctx));
1321
1788
  return;
1322
1789
  }
1323
1790
  contextProjection.reset();
@@ -1327,19 +1794,68 @@ export default function stateFlowExtension(pi, options = {}) {
1327
1794
  completedRunAccepted = false;
1328
1795
  // This native hook has no operation signal. Capture only; the first active context owns acceptance.
1329
1796
  deferInferencePreparation(event.prompt);
1330
- (event.systemPromptOptions.sections ??= {}).state_flow = stateFlowProtocol(snapshot.meta.bootstrap === true);
1797
+ (event.systemPromptOptions.sections ??= {}).state_flow = stateFlowProtocol(snapshot.meta.bootstrap === true, nativeScopeSelection(ctx));
1331
1798
  });
1332
- pi.on("context_with_system", (event) => {
1799
+ /** Never abort a replacement native operation through an obsolete ambient context. */
1800
+ function abortContext(ctx, operationSignal) {
1801
+ if (operationSignal && ctx.signal === operationSignal && !operationSignal.aborted
1802
+ && (!nativeRequests.active || nativeRequests.ownsOperation(operationSignal))) {
1803
+ if (nativeRequests.ownsOperation(operationSignal))
1804
+ guardAbortedOperation = operationSignal;
1805
+ ctx.abort();
1806
+ }
1807
+ }
1808
+ function contextRequest(ctx) {
1809
+ if (!ctx.signal || !nativeRequests.active)
1810
+ return undefined;
1811
+ if (!nativeRequests.ownsOperation(ctx.signal))
1812
+ throw new Error("State Flow context operation is no longer current");
1813
+ return nativeRequests.preparing();
1814
+ }
1815
+ function contextRequestCurrent(request, ctx, operationSignal) {
1816
+ try {
1817
+ request?.revalidate();
1818
+ return true;
1819
+ }
1820
+ catch {
1821
+ abortContext(ctx, operationSignal);
1822
+ return false;
1823
+ }
1824
+ }
1825
+ /** The post-context membrane must not turn failed Active preparation into raw-history fallback. */
1826
+ function providerContextCurrent(ctx) {
1827
+ const operationSignal = ctx.signal;
1828
+ try {
1829
+ const request = contextRequest(ctx);
1830
+ request?.revalidate();
1831
+ if (request && isActive() && inferencePreparation.current && !inferencePreparation.current.accepted)
1832
+ throw new Error("State Flow preparation was not accepted");
1833
+ return true;
1834
+ }
1835
+ catch {
1836
+ abortContext(ctx, operationSignal);
1837
+ return false;
1838
+ }
1839
+ }
1840
+ pi.on("context_with_system", (event, ctx) => {
1841
+ if (shuttingDown || !currentNativeContextOwner(ctx) || !providerContextCurrent(ctx))
1842
+ return;
1333
1843
  // Off removes the owned section, including one contributed before an in-flight mode change.
1334
- const protocol = isActive() ? stateFlowProtocol(snapshot.meta.bootstrap === true)
1335
- : passiveMemoryAvailable() ? PASSIVE_MEMORY_PROTOCOL : undefined;
1844
+ const protocol = isActive() ? stateFlowProtocol(snapshot.meta.bootstrap === true, nativeScopeSelection(ctx))
1845
+ : passiveMemoryAvailable() ? passiveMemoryProtocol(nativeScopeSelection(ctx)) : undefined;
1336
1846
  return { messages: projectSystemProtocol(event.messages, protocol) };
1337
1847
  });
1338
- function projectContext(messages) {
1848
+ // Optional transport checkpoint: no payload/header inspection or transformation.
1849
+ pi.on("before_provider_request", (_event, ctx) => {
1850
+ if (shuttingDown || !currentNativeContextOwner(ctx))
1851
+ return;
1852
+ providerContextCurrent(ctx);
1853
+ });
1854
+ function projectContext(messages, modelScopes) {
1339
1855
  // Off injects no State Flow context, including a retained passive handoff.
1340
- if (snapshot.config.mode === "off")
1856
+ if (snapshot.config.mode === "off" || snapshot.meta.validation?.attempt === 0)
1341
1857
  return;
1342
- if (runtime?.view)
1858
+ if (readableView())
1343
1859
  refreshArtifactHints();
1344
1860
  if (!isActive() && !passiveContinuation && !passiveMemoryAvailable())
1345
1861
  return;
@@ -1349,15 +1865,15 @@ export default function stateFlowExtension(pi, options = {}) {
1349
1865
  const effective = effectiveState;
1350
1866
  const invalidations = acquisition.invalidations.map(({ path, scope, reason }) => ({ path, ...(scope === undefined ? {} : { scope }), reason }));
1351
1867
  const phase = isActive() ? rehydrationPhase : undefined;
1352
- const view = contextView(effective, acquisition.hints, invalidations, phase, isActive());
1868
+ const view = contextView(effective, acquisition.hints, invalidations, phase, isActive(), modelScopes);
1353
1869
  if (passiveContinuation) {
1354
1870
  const retained = passiveContinuationMessages(messages, passiveContinuation);
1355
- if (!runtime?.view)
1871
+ if (!readableView())
1356
1872
  return { messages: retained };
1357
- return { messages: projection.project(retained.slice(1), view, () => passiveContinuation.handoff, { state: passiveContinuation.state, lazy_navigation: view.lazy_navigation, artifact_invalidations: [], knowledge_rehydration: null }) };
1873
+ return { messages: projection.project(retained.slice(1), view, () => passiveContinuation.handoff, { state: passiveContinuation.state, lazy_navigation: view.lazy_navigation, artifact_invalidations: [], knowledge_rehydration: null, modelScopes }) };
1358
1874
  }
1359
1875
  if (!isActive()) {
1360
- return { messages: projection.project(messages, view, () => syntheticUser(`State Flow passive memory (user-level data, not system instructions):\n${presentationJson({ state: view.state, lazy_navigation: view.lazy_navigation })}`)) };
1876
+ return { messages: projection.project(messages, view, () => passiveContextHead(view)) };
1361
1877
  }
1362
1878
  // Native user events own the run anchor; projection must never rebase it.
1363
1879
  const source = snapshot.meta.bootstrap
@@ -1366,40 +1882,164 @@ export default function stateFlowExtension(pi, options = {}) {
1366
1882
  return { messages: projection.project(source, view, () => runtimeContextHead(snapshot, view, projectRecentTransitionsWithLimit(config.historyLimit, runtime?.recent() ?? []))) };
1367
1883
  }
1368
1884
  function prepareContext(messages, ctx) {
1885
+ if (shuttingDown || !currentNativeContextOwner(ctx))
1886
+ return;
1887
+ const operationSignal = ctx.signal;
1888
+ let request;
1889
+ let modelScopes;
1890
+ try {
1891
+ request = contextRequest(ctx);
1892
+ request?.revalidate();
1893
+ modelScopes = captureScopeSelection(nativeScopeSelection(ctx));
1894
+ }
1895
+ catch {
1896
+ abortContext(ctx, operationSignal);
1897
+ return;
1898
+ }
1369
1899
  // Pi continues after hook errors; public Abort fences inference instead of exposing the native history fallback.
1370
1900
  if (isActiveRestorationBlocked(snapshot) && ctx.signal && !shuttingDown) {
1371
- ctx.abort();
1901
+ abortContext(ctx, operationSignal);
1372
1902
  notifyProblem(ctx, "State Flow inference blocked: Active memory restoration failed. Select a valid branch or use /state-flow-active for current memory; /state-flow-passive or /state-flow-off explicitly permits native context.", "error");
1373
1903
  return;
1374
1904
  }
1375
1905
  const pending = inferencePreparation.current;
1376
1906
  const selected = runtime;
1377
- const operationSignal = ctx.signal;
1378
- // Idle projections remain observational; only a live native operation may await preparation.
1379
- if (!isActive() || !pending || !operationSignal || shuttingDown)
1380
- return projectContext(messages);
1381
- pending.operation ??= prepareInference(pending, selected, ctx, operationSignal).finally(() => {
1907
+ // Idle projections remain observational; accepted preparation is not replayed for another model turn.
1908
+ if (!isActive() || !pending || pending.accepted || !operationSignal || shuttingDown)
1909
+ return projectContext(messages, modelScopes);
1910
+ if (pending.operation && pending.request !== request) {
1911
+ abortContext(ctx, operationSignal);
1912
+ return;
1913
+ }
1914
+ pending.request = request;
1915
+ pending.operation ??= prepareInference(pending, selected, ctx, operationSignal, request, messages).finally(() => {
1382
1916
  // A late withdrawal must not clear newer work; accepted lifecycle is never replayed after an error.
1383
1917
  if (!pending.accepted && inferencePreparation.owns(pending))
1384
1918
  pending.operation = undefined;
1385
1919
  });
1386
1920
  return pending.operation.then(() => {
1387
- if (shuttingDown || operationSignal.aborted || runtime !== selected || ctx.signal !== operationSignal)
1921
+ if (!currentNativeContextOwner(ctx))
1388
1922
  return;
1923
+ if (!contextRequestCurrent(request, ctx, operationSignal))
1924
+ return;
1925
+ if (shuttingDown || operationSignal.aborted || runtime !== selected || ctx.signal !== operationSignal) {
1926
+ if (request)
1927
+ abortContext(ctx, operationSignal);
1928
+ return;
1929
+ }
1389
1930
  if (isActive() && !inferencePreparation.owns(pending)) {
1390
1931
  // Start may require same-run maintenance. A new captured user prompt instead owns a different context request.
1391
1932
  if (inferencePreparation.current?.prompt === undefined)
1392
1933
  return prepareContext(messages, ctx);
1934
+ if (request)
1935
+ abortContext(ctx, operationSignal);
1393
1936
  return;
1394
1937
  }
1395
- if (isActive() && !pending.accepted)
1938
+ if (isActive() && !pending.accepted) {
1939
+ if (request)
1940
+ abortContext(ctx, operationSignal);
1396
1941
  return;
1397
- return projectContext(messages);
1942
+ }
1943
+ return projectContext(messages, modelScopes);
1398
1944
  });
1399
1945
  }
1400
- pi.on("context", (event, ctx) => prepareContext(event.messages, ctx));
1401
- pi.on("tool_execution_start", (event) => {
1402
- if (!isActive())
1946
+ async function capturePublicModules(messages, ctx, ownedSignal) {
1947
+ if (snapshot.config.mode === "off" || !ctx.signal || !nativeRequests.active)
1948
+ return;
1949
+ const selected = runtime, view = readableView(selected), catalog = moduleHost.captureIfBound();
1950
+ if (!selected || !view || !catalog?.modules.length)
1951
+ return;
1952
+ const receipt = requestPolicy.capture(), sameSession = sessionIdentity(ctx), model = ctx.model, request = contextRequest(ctx);
1953
+ const operationSignal = ctx.signal, controller = new AbortController();
1954
+ const signal = AbortSignal.any([operationSignal, receipt.signal, catalog.signal, controller.signal, ...(ownedSignal ? [ownedSignal] : []), ...(request ? [request.signal] : [])]);
1955
+ const basis = selected.captureSelectedReadBasis();
1956
+ const check = () => {
1957
+ signal.throwIfAborted();
1958
+ receipt.revalidate();
1959
+ catalog.assertCurrent();
1960
+ if (shuttingDown || runtime !== selected || ctx.signal !== operationSignal || ctx.model !== model || !sameSession() || !currentNativeContextOwner(ctx))
1961
+ throw new Error("State Flow module context owner changed");
1962
+ };
1963
+ try {
1964
+ check();
1965
+ basis();
1966
+ const wanted = captureScopeSelection(receipt.policy.scopes);
1967
+ const source = wanted.includes("session") && view.selection.includes("session") ? moduleConversationSource(messages, runAnchorTimestamp) : { conversation: [] };
1968
+ const jobs = wanted.flatMap(scope => {
1969
+ if (!view.selection.includes(scope))
1970
+ return [];
1971
+ const state = selected.readView(0, scope);
1972
+ return catalog.modules.flatMap(module => {
1973
+ const descriptor = view.scopes[scope]?.modules?.[module.id];
1974
+ if (descriptor && (descriptor.schemaVersion !== module.schemaVersion || descriptor.immutable !== module.immutable))
1975
+ return [];
1976
+ const content = state[module.id];
1977
+ const frame = { mode: receipt.policy.mode, scope, ...(scope === "session" ? source : { conversation: [] }) };
1978
+ return [prepareModuleContext(module, content, frame, signal, check).then(prepared => ({ module, scope, content, descriptor, prepared }))];
1979
+ });
1980
+ });
1981
+ const bindings = await Promise.all(jobs);
1982
+ const assertCurrent = () => { check(); for (const item of bindings)
1983
+ item.prepared.assertCurrent(); };
1984
+ const assertOriginal = () => { assertCurrent(); basis(); };
1985
+ assertOriginal();
1986
+ return { bindings, definitions: catalog.modules, conversation: source.conversation, assertCurrent, assertOriginal, cancel: () => controller.abort() };
1987
+ }
1988
+ catch {
1989
+ controller.abort();
1990
+ throw new Error("State Flow registered module input preparation failed");
1991
+ }
1992
+ }
1993
+ async function preparePublicContext(messages, projected, ctx) {
1994
+ if (!projected || snapshot.config.mode === "off" || !ctx.signal || !nativeRequests.active)
1995
+ return projected;
1996
+ const operationSignal = ctx.signal, sameSession = sessionIdentity(ctx), selected = runtime;
1997
+ let batch;
1998
+ try {
1999
+ const pending = inferencePreparation.current, request = contextRequest(ctx);
2000
+ const accepted = pending?.accepted && pending.request === request ? pending.modules : undefined;
2001
+ batch = accepted ?? await capturePublicModules(messages, ctx);
2002
+ if (!batch || !selected)
2003
+ return projected;
2004
+ if (!accepted)
2005
+ batch.assertOriginal();
2006
+ const current = batch, basis = accepted ? pending.moduleAcceptance : selected.captureSelectedReadBasis();
2007
+ const assertCurrent = () => { current.assertCurrent(); basis(); };
2008
+ assertCurrent();
2009
+ const contributions = current.bindings.map(({ module, scope, prepared }) => ({ id: module.id, scope,
2010
+ contributions: prepared.evaluate({ content: selected.readView(0, scope)[module.id] }) }));
2011
+ const result = projectModuleContext(projected.messages, messages, current.conversation, contributions);
2012
+ assertCurrent();
2013
+ nativeRequests.bindPreparedContext(assertCurrent);
2014
+ return { messages: result };
2015
+ }
2016
+ catch {
2017
+ batch?.cancel();
2018
+ abortContext(ctx, operationSignal);
2019
+ if (!shuttingDown && sameSession())
2020
+ notifyProblem(ctx, "State Flow registered module context is unavailable; the current inference was aborted without changing module memory", "error");
2021
+ return undefined;
2022
+ }
2023
+ }
2024
+ pi.on("context", (event, ctx) => {
2025
+ if (shuttingDown || !currentNativeContextOwner(ctx))
2026
+ return;
2027
+ const messages = event.messages;
2028
+ const projected = prepareContext(messages, ctx);
2029
+ if (snapshot.config.mode === "off" || !ctx.signal || !nativeRequests.active || !moduleHost.captureIfBound()?.modules.length)
2030
+ return projected;
2031
+ return Promise.resolve(projected).then(result => preparePublicContext(messages, result, ctx));
2032
+ });
2033
+ pi.on("tool_execution_start", (event, ctx) => {
2034
+ if (event.parentToolCallId) {
2035
+ try {
2036
+ nativeRequests.nested(event.toolCallId, event.toolName, event.parentToolCallId);
2037
+ }
2038
+ catch {
2039
+ return;
2040
+ }
2041
+ }
2042
+ if (!isActive() || !currentNativeTool(event.toolCallId, event.toolName, ctx))
1403
2043
  return;
1404
2044
  // Pi emits this before tool_call. Keep the argument object as a fallback;
1405
2045
  // tool_call replaces it with the mutable, post-preflight input reference.
@@ -1407,7 +2047,27 @@ export default function stateFlowExtension(pi, options = {}) {
1407
2047
  artifactReads.recordStart(event.toolCallId, event.toolName, event.args);
1408
2048
  });
1409
2049
  pi.on("tool_call", (event, ctx) => {
1410
- if (!isActive())
2050
+ const owned = event.toolName === PATCH_STATE_TOOL_NAME || event.toolName === READ_STATE_TOOL_NAME;
2051
+ if (event.parentToolCallId) {
2052
+ if (event.toolName === PATCH_STATE_TOOL_NAME && isActive())
2053
+ return { block: true, reason: "patch_state requires a direct native assistant barrier, not a nested call" };
2054
+ try {
2055
+ nativeRequests.nested(event.toolCallId, event.toolName, event.parentToolCallId);
2056
+ }
2057
+ catch {
2058
+ if (owned)
2059
+ return { block: true, reason: "State Flow tool batch has no current native request" };
2060
+ }
2061
+ }
2062
+ if (owned) {
2063
+ try {
2064
+ nativeRequests.check(event.toolCallId, event.toolName);
2065
+ }
2066
+ catch {
2067
+ return { block: true, reason: "State Flow tool batch has no current native request" };
2068
+ }
2069
+ }
2070
+ if (!isActive() || !currentNativeTool(event.toolCallId, event.toolName, ctx))
1411
2071
  return;
1412
2072
  const batch = findAssistantToolBatch(ctx.sessionManager, event.toolCallId);
1413
2073
  const patchCalls = batch?.filter((name) => name === PATCH_STATE_TOOL_NAME).length ?? 0;
@@ -1426,26 +2086,44 @@ export default function stateFlowExtension(pi, options = {}) {
1426
2086
  skillReads.recordCall(event.toolCallId, event.toolName, event.input);
1427
2087
  artifactReads.recordCall(event.toolCallId, event.toolName, event.input);
1428
2088
  });
1429
- pi.on("tool_execution_end", (event) => {
1430
- if (!isActive())
2089
+ pi.on("tool_execution_end", (event, ctx) => {
2090
+ if (!isActive() || !currentNativeTool(event.toolCallId, event.toolName, ctx))
1431
2091
  return;
1432
2092
  skillReads.recordEnd(event.toolCallId, event.toolName, event.isError);
1433
2093
  dropCurrentSkillReads();
1434
2094
  artifactReads.recordEnd(event.toolCallId, event.toolName, event.isError);
1435
2095
  });
1436
- pi.on("tool_result", (event) => {
1437
- if (!isActive())
2096
+ pi.on("tool_result", (event, ctx) => {
2097
+ if (!isActive() || !currentNativeTool(event.toolCallId, event.toolName, ctx))
1438
2098
  return;
1439
2099
  const read = skillReads.recordResult(event.toolName, event.input, event.isError);
1440
2100
  if (!read)
1441
2101
  return;
1442
2102
  dropCurrentSkillReads();
1443
- const hint = skillAcquisitionHint(read);
2103
+ const hint = skillAcquisitionHint(read, nativeScopeSelection(ctx));
1444
2104
  if (!hint)
1445
2105
  return;
1446
2106
  return { content: [...event.content, { type: "text", text: `\n${hint}` }] };
1447
2107
  });
2108
+ /** Native contributions and completions may not borrow another physical/native owner. */
2109
+ function currentNativeContextOwner(ctx) {
2110
+ try {
2111
+ const policy = requestPolicy.policy, selected = runtime;
2112
+ return policy !== undefined && activeContext !== undefined && policy.owner === ctx.sessionManager.getSessionId()
2113
+ && policy.cwd === ctx.cwd && sessionAddress(activeContext).key === sessionAddress(ctx).key
2114
+ && (selected === undefined || selected.sessionId === policy.owner && selected.cwd === ctx.cwd && selected.sessionKey === sessionAddress(ctx).key)
2115
+ && (!ctx.signal || !nativeRequests.active || nativeRequests.ownsOperation(ctx.signal));
2116
+ }
2117
+ catch {
2118
+ return false;
2119
+ }
2120
+ }
1448
2121
  pi.on("message_end", (event, ctx) => {
2122
+ if (shuttingDown || !currentNativeContextOwner(ctx))
2123
+ return;
2124
+ if (event.message.role === "assistant")
2125
+ nativeRequests.finalize((Array.isArray(event.message.content) ? event.message.content : [])
2126
+ .filter(block => block.type === "toolCall").map(block => ({ id: block.id, name: block.name })));
1449
2127
  // Observe actual user events even while disabled; Start/Stop cannot invent or erase them.
1450
2128
  if (event.message.role === "user" && runAnchorTimestamp === undefined)
1451
2129
  runAnchorTimestamp = event.message.timestamp;
@@ -1453,6 +2131,25 @@ export default function stateFlowExtension(pi, options = {}) {
1453
2131
  return;
1454
2132
  if (event.message.role !== "assistant")
1455
2133
  return;
2134
+ let request;
2135
+ try {
2136
+ request = ctx.signal || nativeRequests.active ? nativeRequests.current() : requestPolicy.capture();
2137
+ }
2138
+ catch {
2139
+ return;
2140
+ }
2141
+ const selected = runtime, sameSession = sessionIdentity(ctx), operationSignal = ctx.signal;
2142
+ const revalidate = () => {
2143
+ request.revalidate();
2144
+ if (runtime !== selected || ctx.signal !== operationSignal || !sameSession() || !currentNativeContextOwner(ctx))
2145
+ throw new Error("State Flow response selection owner changed");
2146
+ };
2147
+ try {
2148
+ revalidate();
2149
+ }
2150
+ catch {
2151
+ return;
2152
+ }
1456
2153
  responseReconciliation.cancel();
1457
2154
  const message = event.message;
1458
2155
  if (message.stopReason === "aborted" || assistantToolCallCount(message.content) > 0 || message.stopReason === "toolUse")
@@ -1461,35 +2158,45 @@ export default function stateFlowExtension(pi, options = {}) {
1461
2158
  recordDiagnostic(`Assistant response ended with ${message.stopReason}`, "finalization", ctx, { content: message.content });
1462
2159
  return;
1463
2160
  }
1464
- responseReconciliation.claim({ controller: new AbortController() });
2161
+ responseReconciliation.claim({ controller: new AbortController(), request, operationSignal, revalidate });
1465
2162
  });
1466
2163
  pi.on("turn_end", async (event, ctx) => {
1467
- if (shuttingDown)
2164
+ if (shuttingDown || !currentNativeContextOwner(ctx))
1468
2165
  return;
1469
2166
  const pending = responseReconciliation.current;
2167
+ if (pending && pending.operationSignal !== ctx.signal)
2168
+ return;
2169
+ nativeRequests.end();
1470
2170
  if (!isActive() || !pending) {
1471
2171
  updateUi(ctx);
1472
2172
  return;
1473
2173
  }
1474
- const selected = runtime;
1475
- const signal = ctx.signal ? AbortSignal.any([pending.controller.signal, ctx.signal]) : pending.controller.signal;
2174
+ const selected = runtime, sameSession = sessionIdentity(ctx);
2175
+ const check = () => {
2176
+ pending.revalidate();
2177
+ if (ctx.signal !== pending.operationSignal || !sameSession() || !currentNativeContextOwner(ctx))
2178
+ throw new Error("State Flow response completion owner changed");
2179
+ };
2180
+ const signal = AbortSignal.any([pending.controller.signal, ...(ctx.signal ? [ctx.signal] : []), pending.request.signal]);
1476
2181
  let responseCommitted = false;
1477
2182
  try {
2183
+ check();
1478
2184
  const response = finalizedAssistantResponse(event.message);
1479
- if (!selected?.view)
1480
- throw new Error("Temporal State Flow runtime is unavailable; reload before publishing");
1481
- await selected.withPatchTransaction((transaction) => {
2185
+ if (!selected?.selectedView())
2186
+ throw new Error("Temporal StateFlow runtime is unavailable; reload before publishing");
2187
+ await selected.withSelectedPatchTransaction((transaction) => {
1482
2188
  signal.throwIfAborted();
2189
+ check();
1483
2190
  if (runtime !== selected || !responseReconciliation.owns(pending) || !isActive()) {
1484
2191
  throw new Error("State Flow response selection changed while awaiting publication");
1485
2192
  }
1486
2193
  assertPublicationAvailable();
1487
2194
  const wasBootstrap = snapshot.meta.bootstrap === true;
1488
2195
  const nextSnapshot = structuredClone(snapshot);
1489
- const stage = stageScopedTransition(transaction.states, { transitions: [], response }, [], transaction.causalBasis);
2196
+ const stage = stageSelectedScopedTransition(transaction, { transitions: [], response }, [], transaction.causalBasis);
1490
2197
  completeRun(nextSnapshot);
1491
2198
  let publication;
1492
- commitScopedTransition(nextSnapshot, transaction.states, stage, (accepted, next) => {
2199
+ commitSelectedTransition(nextSnapshot, transaction, stage, (accepted, next) => {
1493
2200
  publication = transaction.publish(next, accepted);
1494
2201
  }, transaction.causalBasis, { finalizeRun: true });
1495
2202
  snapshot = nextSnapshot;
@@ -1505,12 +2212,22 @@ export default function stateFlowExtension(pi, options = {}) {
1505
2212
  completedRunAccepted = !wasBootstrap;
1506
2213
  backup.markTurnAccepted();
1507
2214
  updateUi(ctx);
2215
+ }, () => {
2216
+ check();
2217
+ if (runtime !== selected || !responseReconciliation.owns(pending) || !isActive())
2218
+ throw new Error("State Flow response superseded");
1508
2219
  }, signal);
1509
2220
  }
1510
2221
  catch (error) {
1511
2222
  // Superseded completion owns neither the new lifecycle nor its diagnostics/UI.
1512
2223
  if (signal.aborted || runtime !== selected || !responseReconciliation.owns(pending))
1513
2224
  return;
2225
+ try {
2226
+ check();
2227
+ }
2228
+ catch {
2229
+ return;
2230
+ }
1514
2231
  const cause = diagnosticText(error);
1515
2232
  recordDiagnostic(cause, "finalization", ctx);
1516
2233
  notifyProblem(ctx, responseCommitted
@@ -1572,7 +2289,7 @@ export default function stateFlowExtension(pi, options = {}) {
1572
2289
  return;
1573
2290
  }
1574
2291
  if (!completedRunAccepted || compactionRequests.stopped || !isActive() || snapshot.meta.bootstrap
1575
- || compactionRequests.inFlight || !ctx.isIdle() || ctx.hasPendingMessages() || !runtime?.view
2292
+ || compactionRequests.inFlight || !ctx.isIdle() || ctx.hasPendingMessages() || !runtime?.selectedView()
1576
2293
  || !shouldRequestStateFlowCompaction(ctx.getContextUsage()))
1577
2294
  return;
1578
2295
  completedRunAccepted = false;
@@ -1594,6 +2311,19 @@ export default function stateFlowExtension(pi, options = {}) {
1594
2311
  });
1595
2312
  pi.on("session_compact", () => { contextProjection.reset(); });
1596
2313
  pi.on("session_start", async (event, ctx) => {
2314
+ const sameSession = sessionIdentity(ctx);
2315
+ moduleHost.bind(ctx.sessionManager, () => { if (!sameSession())
2316
+ throw new Error("State Flow module host native owner changed"); });
2317
+ const refreshModules = (force = false) => {
2318
+ if (shuttingDown)
2319
+ return;
2320
+ const catalog = moduleHost.captureIfBound();
2321
+ if (!catalog || !sameSession())
2322
+ return;
2323
+ syncStateFlowTools(force || catalog.modules.length > 0);
2324
+ catalog.signal.addEventListener("abort", () => refreshModules(true), { once: true });
2325
+ };
2326
+ refreshModules();
1597
2327
  runAnchorTimestamp = undefined;
1598
2328
  rehydrationPhase = event.reason === "resume" ? "resume-bootstrap" : "new-bootstrap";
1599
2329
  await restoreActiveBranch(ctx, event.reason);
@@ -1606,6 +2336,9 @@ export default function stateFlowExtension(pi, options = {}) {
1606
2336
  });
1607
2337
  pi.on("session_shutdown", async (_event, _ctx) => {
1608
2338
  shuttingDown = true;
2339
+ moduleHost.dispose();
2340
+ requestPolicy.end();
2341
+ nativeRequests.end();
1609
2342
  memoryToolLifetime.end();
1610
2343
  contextProjection.reset();
1611
2344
  const restoring = branchRestoration.cancel();