2121import io .github .agentic .ai .api .chat .ToolCall ;
2222import io .github .agentic .ai .api .tool .ToolRegistry ;
2323import io .github .agentic .ai .api .tool .ToolResult ;
24+ import io .github .agentic .ai .workflow .graph .KeyStrategy ;
2425import io .github .agentic .ai .workflow .graph .OverAllState ;
2526import io .github .agentic .ai .workflow .graph .RunnableConfig ;
2627import io .github .agentic .ai .workflow .graph .action .NodeActionWithConfig ;
3940import io .github .agentic .ai .agent .tool .patch .ToolContextPatchSpec ;
4041import io .github .agentic .ai .agent .tool .patch .ToolContextPatchValidator ;
4142import io .github .agentic .ai .agent .tool .patch .ToolContextPatchViolationException ;
43+ import io .github .agentic .ai .agent .tool .patch .strict .StateIsolation ;
44+ import io .github .agentic .ai .agent .tool .patch .strict .StrictMergeRules ;
45+ import io .github .agentic .ai .agent .tool .patch .strict .StrictPatchAdmission ;
46+ import io .github .agentic .ai .agent .tool .patch .strict .ToolUpdateUnit ;
4247import io .github .agentic .ai .agent .validation .ToolArgumentValidator ;
4348import io .github .agentic .ai .runtime .execution .ExecutionGuard ;
4449import io .github .agentic .ai .workflow .graph .checkpoint .lease .LeaseLostException ;
@@ -129,6 +134,8 @@ public class AgentToolNode implements NodeActionWithConfig {
129134
130135 private final ToolContextPatchPolicy toolContextPatchPolicy ;
131136
137+ private final boolean strictToolState ;
138+
132139 private final ThreadPoolExecutor neutralInvocationExecutor ;
133140
134141 public AgentToolNode (Builder builder ) {
@@ -154,6 +161,7 @@ public AgentToolNode(Builder builder) {
154161 this .throwOnToolError = builder .throwOnToolError ;
155162 this .businessOutcomeMappers = builder .businessOutcomeMappers ;
156163 this .toolContextPatchPolicy = builder .toolContextPatchPolicy ;
164+ this .strictToolState = builder .strictToolState ;
157165 }
158166
159167 public void setToolInterceptors (List <ToolInterceptor > toolInterceptors ) {
@@ -240,9 +248,10 @@ else if (lastMessage.role() == ChatRole.TOOL) {
240248 * </p>
241249 * <p>
242250 * Note: This differs from parallel execution mode, which respects
243- * {@link io.github.agentic.ai.workflow.graph.KeyStrategy} for merge operations. If you need
244- * deterministic merge behavior (e.g., APPEND for lists), use parallel execution mode
245- * instead.
251+ * {@link io.github.agentic.ai.workflow.graph.KeyStrategy} for merge operations - unless
252+ * {@code strictToolState(true)} is enabled, in which case sequential merges go through
253+ * the same KeyStrategy map and the divergence disappears. Without strict mode, use
254+ * parallel execution for deterministic merge behavior (e.g., APPEND for lists).
246255 * </p>
247256 *
248257 * @see #executeToolCallsParallel(List, OverAllState, RunnableConfig)
@@ -256,13 +265,14 @@ private Map<String, Object> executeToolCallsSequential(List<io.github.agentic.ai
256265 // successful tools
257266 List <ChatMessage > toolResponses = new ArrayList <>();
258267
268+ OverAllState toolState = toolVisibleState (state );
259269 Boolean returnDirect = null ;
260270 for (io .github .agentic .ai .api .chat .ToolCall toolCall : toolCalls ) {
261271 config .assertExecutionActive ();
262272 // Each tool gets its own isolated update map
263273 // If this tool times out, clear() only affects this map, not mergedUpdates
264274 Map <String , Object > toolSpecificUpdate = new ConcurrentHashMap <>();
265- ToolCallResponse response = executeToolCallWithInterceptors (toolCall , state , config , toolSpecificUpdate ,
275+ ToolCallResponse response = executeToolCallWithInterceptors (toolCall , toolState , config , toolSpecificUpdate ,
266276 false );
267277 config .assertExecutionActive ();
268278 toolResponses .add (response .toMessage ());
@@ -272,7 +282,12 @@ private Map<String, Object> executeToolCallsSequential(List<io.github.agentic.ai
272282 // data. A configured patch policy gates the merge boundary: patches of failed
273283 // calls and invalid patches never reach the next turn's state.
274284 if (admitsPatch (toolCall .name (), response , toolSpecificUpdate )) {
275- mergedUpdates .putAll (toolSpecificUpdate );
285+ if (strictToolState ) {
286+ mergeThroughStrategies (mergedUpdates , toolSpecificUpdate , state );
287+ }
288+ else {
289+ mergedUpdates .putAll (toolSpecificUpdate );
290+ }
276291 }
277292 }
278293 config .assertExecutionActive ();
@@ -297,7 +312,9 @@ private Map<String, Object> executeToolCallsSequential(List<io.github.agentic.ai
297312 * <b>Important:</b> The state snapshot created via {@code state.snapShot()} is a
298313 * shallow copy. Mutable objects within the state (like Lists) are shared. Tools
299314 * should NOT directly modify collections retrieved from the state. Use the
300- * {@code extraStateFromToolCall} map to write updates.
315+ * {@code extraStateFromToolCall} map to write updates. With
316+ * {@code strictToolState(true)} this advisory becomes structural: tools receive a
317+ * read-only view whose collections reject mutation.
301318 * </p>
302319 *
303320 * <h3>State Merge Semantics</h3>
@@ -335,7 +352,7 @@ private Map<String, Object> executeToolCallsParallel(List<io.github.agentic.ai.a
335352 // Create state snapshot for thread safety
336353 // Note: snapShot() is a shallow copy, shared mutable objects (like messages List)
337354 // should not be directly modified by tools
338- OverAllState stateSnapshot = state .snapShot ().orElse (state );
355+ OverAllState stateSnapshot = toolVisibleState ( state .snapShot ().orElse (state ) );
339356
340357 ToolStateCollector stateCollector = new ToolStateCollector (toolCalls .size (), state .keyStrategies ());
341358
@@ -466,6 +483,9 @@ private Map<String, Object> executeToolCallsParallel(List<io.github.agentic.ai.a
466483 // Same merge-boundary gate as sequential mode, applied per tool index: rejected
467484 // patches are discarded before mergeAll() so they cannot pollute the state.
468485 discardRejectedPatches (toolCalls , orderedResponses , stateCollector );
486+ if (strictToolState ) {
487+ enforceDeclaredMergeStrategies (toolCalls , stateCollector , state );
488+ }
469489 updatedState .putAll (stateCollector .mergeAll ());
470490
471491 if (enableActingLog ) {
@@ -775,11 +795,12 @@ private void propagateToolFailure(Throwable failure) {
775795
776796 /**
777797 * Applies the configured patch policy to every collected response before the parallel
778- * merge, discarding the update maps of rejected calls. No-op without a policy.
798+ * merge, discarding the update maps of rejected calls. No-op without a policy and
799+ * without strict mode; in strict mode the admission runs even without a policy.
779800 */
780801 private void discardRejectedPatches (List <io .github .agentic .ai .api .chat .ToolCall > toolCalls ,
781802 AtomicReferenceArray <ToolCallResponse > orderedResponses , ToolStateCollector stateCollector ) {
782- if (toolContextPatchPolicy == null ) {
803+ if (! strictToolState && toolContextPatchPolicy == null ) {
783804 return ;
784805 }
785806 for (int i = 0 ; i < orderedResponses .length (); i ++) {
@@ -793,6 +814,94 @@ private void discardRejectedPatches(List<io.github.agentic.ai.api.chat.ToolCall>
793814 }
794815 }
795816
817+ /**
818+ * The state a tool may read in strict mode: an {@link OverAllState} whose data map and
819+ * one-level-deep collections reject mutation, so state writes can escape only through
820+ * the patch channel. Without strict mode the state passes through untouched.
821+ * @param state the state the node was invoked with
822+ * @return the state a tool may read
823+ */
824+ private OverAllState toolVisibleState (OverAllState state ) {
825+ if (!strictToolState ) {
826+ return state ;
827+ }
828+ var view = new OverAllState (StateIsolation .readOnlyView (state .data ()), state .getStore ());
829+ view .registerKeyAndStrategy (state .keyStrategies ());
830+ return view ;
831+ }
832+
833+ /**
834+ * Merges one admitted patch into the accumulated sequential updates through the
835+ * declared {@link KeyStrategy} map - the same rules the parallel collector applies -
836+ * closing the historical sequential/parallel divergence for strict mode.
837+ * @param merged the accumulated updates of earlier tools
838+ * @param patch the admitted patch of the tool that just completed
839+ * @param state the node's state, source of the declared strategies
840+ */
841+ private void mergeThroughStrategies (Map <String , Object > merged , Map <String , Object > patch ,
842+ OverAllState state ) {
843+ Map <String , KeyStrategy > strategies = state .keyStrategies ();
844+ for (Map .Entry <String , Object > entry : patch .entrySet ()) {
845+ ToolStateCollector .mergeEntry (merged , strategies , entry .getKey (), entry .getValue ());
846+ }
847+ }
848+
849+ /**
850+ * Strict parallel merge rule: a key written by several tools without a declared
851+ * {@link KeyStrategy} is a policy violation, not a silent replace-last-in-tool-order.
852+ * ABORT runs throw the same violation exception as patch validation; DISCARD drops
853+ * every admitted patch touching the conflicting key, whole patches at a time.
854+ * @param toolCalls the calls of the parallel batch, in tool order
855+ * @param stateCollector the batch's admitted update maps
856+ * @param state the node's state, source of the declared strategies
857+ */
858+ private void enforceDeclaredMergeStrategies (List <io .github .agentic .ai .api .chat .ToolCall > toolCalls ,
859+ ToolStateCollector stateCollector , OverAllState state ) {
860+ // Re-check after every discard round: dropping a patch can resolve further
861+ // conflicts (or expose the next one), and each round discards at least one
862+ // non-empty patch, so the loop terminates.
863+ Map <String , KeyStrategy > strategies = state .keyStrategies ();
864+ while (true ) {
865+ var conflict = StrictMergeRules .checkUndeclaredConflicts (admittedPatches (toolCalls , stateCollector ),
866+ strategies .keySet ());
867+ if (conflict .isEmpty ()) {
868+ return ;
869+ }
870+ StrictMergeRules .ConflictFailure failure = conflict .get ();
871+ if (toolContextPatchPolicy != null
872+ && toolContextPatchPolicy .violationPolicy () == ToolContextPatchPolicy .ViolationPolicy .ABORT_RUN ) {
873+ throw new ToolContextPatchViolationException (new ToolContextPatchValidator .PatchValidationFailure (
874+ failure .errorCode (), failure .key (), failure .message ()));
875+ }
876+ logger .warn ("Discarding context patches writing state key '{}': written by several tools without a "
877+ + "declared merge strategy" , failure .key ());
878+ for (int i = 0 ; i < toolCalls .size (); i ++) {
879+ Map <String , Object > patch = stateCollector .toolUpdateMap (i );
880+ if (patch != null && patch .containsKey (failure .key ())) {
881+ stateCollector .discardToolUpdateMap (i );
882+ }
883+ }
884+ }
885+ }
886+
887+ /**
888+ * The update maps still admitted to the parallel merge, in tool order.
889+ * @param toolCalls the calls of the parallel batch, in tool order
890+ * @param stateCollector the batch's update maps
891+ * @return the non-empty admitted patches, never {@code null}
892+ */
893+ private List <Map <String , Object >> admittedPatches (List <io .github .agentic .ai .api .chat .ToolCall > toolCalls ,
894+ ToolStateCollector stateCollector ) {
895+ List <Map <String , Object >> patches = new ArrayList <>();
896+ for (int i = 0 ; i < toolCalls .size (); i ++) {
897+ Map <String , Object > patch = stateCollector .toolUpdateMap (i );
898+ if (patch != null && !patch .isEmpty ()) {
899+ patches .add (patch );
900+ }
901+ }
902+ return patches ;
903+ }
904+
796905 /**
797906 * Merge-boundary admission for one tool's context patch. Without a policy every patch
798907 * is admitted (legacy behavior). With a policy, patches of failed calls are discarded
@@ -805,6 +914,16 @@ private void discardRejectedPatches(List<io.github.agentic.ai.api.chat.ToolCall>
805914 * @return {@code true} when the patch may be merged into the next turn's state
806915 */
807916 private boolean admitsPatch (String toolName , ToolCallResponse response , Map <String , Object > patch ) {
917+ if (strictToolState ) {
918+ boolean admitted = StrictPatchAdmission .admit (toolContextPatchPolicy ,
919+ new ToolUpdateUnit (toolName , !response .isError (), patch ));
920+ if (!admitted ) {
921+ logger .warn (
922+ "Discarding context patch of tool {}: strict admission rejected the tool's update unit" ,
923+ toolName );
924+ }
925+ return admitted ;
926+ }
808927 if (toolContextPatchPolicy == null || patch == null || patch .isEmpty ()) {
809928 return true ;
810929 }
@@ -945,6 +1064,8 @@ public Builder toolRegistry(ToolRegistry toolRegistry) {
9451064
9461065 private ToolContextPatchPolicy toolContextPatchPolicy ;
9471066
1067+ private boolean strictToolState ;
1068+
9481069 /** Controls failure propagation for provider-neutral tool stages. */
9491070 public Builder throwOnToolError (boolean throwOnToolError ) {
9501071 this .throwOnToolError = throwOnToolError ;
@@ -963,6 +1084,20 @@ public Builder toolContextPatchPolicy(ToolContextPatchPolicy toolContextPatchPol
9631084 return this ;
9641085 }
9651086
1087+ /**
1088+ * Opt-in strict tool-state mode. Tools then see a read-only view of the state
1089+ * instead of the live map or a shallow snapshot, a failed call's patch is always
1090+ * discarded regardless of the patch policy, sequential merges honor the declared
1091+ * KeyStrategies, and parallel merges refuse keys written by several tools without
1092+ * a declared strategy. Default {@code false}: legacy behavior.
1093+ * @param strict true to enable strict tool-state semantics
1094+ * @return this builder
1095+ */
1096+ public Builder strictToolState (boolean strict ) {
1097+ this .strictToolState = strict ;
1098+ return this ;
1099+ }
1100+
9661101 private Builder () {
9671102 }
9681103
0 commit comments