deepclause-sdk 0.4.0 → 0.6.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 (131) hide show
  1. package/README.md +134 -2
  2. package/dist/agent.d.ts.map +1 -1
  3. package/dist/agent.js +154 -28
  4. package/dist/agent.js.map +1 -1
  5. package/dist/cli/config.d.ts +150 -140
  6. package/dist/cli/config.d.ts.map +1 -1
  7. package/dist/cli/config.js +3 -0
  8. package/dist/cli/config.js.map +1 -1
  9. package/dist/cli/login.d.ts +2 -1
  10. package/dist/cli/login.d.ts.map +1 -1
  11. package/dist/cli/login.js +15 -2
  12. package/dist/cli/login.js.map +1 -1
  13. package/dist/cli/repl.d.ts +54 -1
  14. package/dist/cli/repl.d.ts.map +1 -1
  15. package/dist/cli/repl.js +437 -54
  16. package/dist/cli/repl.js.map +1 -1
  17. package/dist/cli/set-backend.d.ts +2 -2
  18. package/dist/cli/set-backend.d.ts.map +1 -1
  19. package/dist/cli/set-backend.js +54 -8
  20. package/dist/cli/set-backend.js.map +1 -1
  21. package/dist/cli/work.d.ts +16 -0
  22. package/dist/cli/work.d.ts.map +1 -0
  23. package/dist/cli/work.js +45 -0
  24. package/dist/cli/work.js.map +1 -0
  25. package/dist/index.d.ts +8 -6
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +4 -3
  28. package/dist/index.js.map +1 -1
  29. package/dist/prolog-src/deepclause_mi.pl +2426 -253
  30. package/dist/prolog-src/deepclause_strings.pl +36 -3
  31. package/dist/repl/agent.d.ts +5 -0
  32. package/dist/repl/agent.d.ts.map +1 -1
  33. package/dist/repl/agent.js +19 -7
  34. package/dist/repl/agent.js.map +1 -1
  35. package/dist/repl/auth.d.ts +6 -3
  36. package/dist/repl/auth.d.ts.map +1 -1
  37. package/dist/repl/auth.js +55 -5
  38. package/dist/repl/auth.js.map +1 -1
  39. package/dist/repl/backend.d.ts +24 -0
  40. package/dist/repl/backend.d.ts.map +1 -1
  41. package/dist/repl/backend.js +292 -12
  42. package/dist/repl/backend.js.map +1 -1
  43. package/dist/repl/compaction.d.ts +2 -0
  44. package/dist/repl/compaction.d.ts.map +1 -1
  45. package/dist/repl/compaction.js +9 -0
  46. package/dist/repl/compaction.js.map +1 -1
  47. package/dist/repl/event-history.d.ts +4 -0
  48. package/dist/repl/event-history.d.ts.map +1 -0
  49. package/dist/repl/event-history.js +33 -0
  50. package/dist/repl/event-history.js.map +1 -0
  51. package/dist/repl/harness-tools.d.ts +25 -18
  52. package/dist/repl/harness-tools.d.ts.map +1 -1
  53. package/dist/repl/harness-tools.js +103 -34
  54. package/dist/repl/harness-tools.js.map +1 -1
  55. package/dist/repl/history.d.ts +52 -2
  56. package/dist/repl/history.d.ts.map +1 -1
  57. package/dist/repl/history.js +113 -4
  58. package/dist/repl/history.js.map +1 -1
  59. package/dist/repl/index.d.ts +27 -5
  60. package/dist/repl/index.d.ts.map +1 -1
  61. package/dist/repl/index.js +27 -0
  62. package/dist/repl/index.js.map +1 -1
  63. package/dist/repl/reference.d.ts +31 -0
  64. package/dist/repl/reference.d.ts.map +1 -0
  65. package/dist/repl/reference.js +143 -0
  66. package/dist/repl/reference.js.map +1 -0
  67. package/dist/repl/render.d.ts +3 -1
  68. package/dist/repl/render.d.ts.map +1 -1
  69. package/dist/repl/render.js +7 -0
  70. package/dist/repl/render.js.map +1 -1
  71. package/dist/repl/session.d.ts +128 -23
  72. package/dist/repl/session.d.ts.map +1 -1
  73. package/dist/repl/session.js +895 -196
  74. package/dist/repl/session.js.map +1 -1
  75. package/dist/repl/tui/autocomplete.d.ts.map +1 -1
  76. package/dist/repl/tui/autocomplete.js +5 -1
  77. package/dist/repl/tui/autocomplete.js.map +1 -1
  78. package/dist/repl/tui/renderer.d.ts +2 -1
  79. package/dist/repl/tui/renderer.d.ts.map +1 -1
  80. package/dist/repl/tui/renderer.js +20 -3
  81. package/dist/repl/tui/renderer.js.map +1 -1
  82. package/dist/repl/tui/status-bar.d.ts +5 -2
  83. package/dist/repl/tui/status-bar.d.ts.map +1 -1
  84. package/dist/repl/tui/status-bar.js +8 -3
  85. package/dist/repl/tui/status-bar.js.map +1 -1
  86. package/dist/repl/tui/tool-pane.d.ts +1 -1
  87. package/dist/repl/tui/tool-pane.d.ts.map +1 -1
  88. package/dist/repl/tui/tool-pane.js +13 -7
  89. package/dist/repl/tui/tool-pane.js.map +1 -1
  90. package/dist/repl/tui/work-view.d.ts +10 -0
  91. package/dist/repl/tui/work-view.d.ts.map +1 -0
  92. package/dist/repl/tui/work-view.js +28 -0
  93. package/dist/repl/tui/work-view.js.map +1 -0
  94. package/dist/runner.d.ts.map +1 -1
  95. package/dist/runner.js +50 -19
  96. package/dist/runner.js.map +1 -1
  97. package/dist/runtime-identity.json +10 -0
  98. package/dist/system/assets/docs/AGENT_PROMPT.md +265 -3008
  99. package/dist/system/assets/docs/DML_AUTHORING.md +81 -299
  100. package/dist/system/assets/docs/DML_BASICS.md +93 -0
  101. package/dist/system/assets/docs/DML_DEBUGGING.md +73 -0
  102. package/dist/system/assets/docs/DML_FORMS.md +94 -728
  103. package/dist/system/assets/docs/DML_MEDIA.md +63 -0
  104. package/dist/system/assets/docs/DML_PROCESSES.md +100 -0
  105. package/dist/system/assets/docs/DML_PYTHON.md +74 -0
  106. package/dist/system/assets/docs/DML_REFERENCE.md +224 -1971
  107. package/dist/system/assets/docs/DML_SHELL.md +107 -0
  108. package/dist/system/assets/docs/DML_TASKS.md +112 -0
  109. package/dist/system/assets/docs/HARNESS_EXAMPLES.md +255 -179
  110. package/dist/system/assets/docs/HARNESS_PATTERNS.md +65 -538
  111. package/dist/system/assets/docs/LOCAL_AGENT_PROMPT.md +186 -0
  112. package/dist/system/assets/docs/PROLOG_SNIPPETS.md +61 -154
  113. package/dist/system/assets/index.d.ts +1 -1
  114. package/dist/system/assets/index.d.ts.map +1 -1
  115. package/dist/system/assets/index.js +7 -0
  116. package/dist/system/assets/index.js.map +1 -1
  117. package/dist/system/environment.d.ts +1 -1
  118. package/dist/system/environment.d.ts.map +1 -1
  119. package/dist/system/environment.js +10 -6
  120. package/dist/system/environment.js.map +1 -1
  121. package/dist/system/runtime/shell-manager.d.ts +1 -1
  122. package/dist/system/runtime/shell-manager.d.ts.map +1 -1
  123. package/dist/types.d.ts +49 -2
  124. package/dist/types.d.ts.map +1 -1
  125. package/dist/work/index.d.ts +82 -0
  126. package/dist/work/index.d.ts.map +1 -0
  127. package/dist/work/index.js +232 -0
  128. package/dist/work/index.js.map +1 -0
  129. package/package.json +12 -3
  130. package/src/prolog-src/deepclause_mi.pl +2426 -253
  131. package/src/prolog-src/deepclause_strings.pl +36 -3
@@ -58,11 +58,29 @@
58
58
  repl_retract/3,
59
59
  repl_define/4,
60
60
  repl_delete_predicate/4,
61
+ repl_delete_doc/4,
62
+ repl_delete_schema/3,
63
+ repl_delete_script/3,
64
+ repl_delete_annotation_entry/4,
65
+ repl_trace_json/2,
66
+ repl_trace_clear/1,
67
+ repl_add_harness_import/5,
68
+ repl_set_harness_exports/3,
69
+ repl_trace_tool_start/4,
70
+ repl_trace_tool_end/3,
71
+ repl_load_harness_module/6,
72
+ repl_hs_register_exports/2,
73
+ repl_hs_register_module_exports/2,
74
+ repl_hs_register_imports/5,
75
+ parse_harness_module_string/3,
76
+ process_harness_term/3,
77
+ repl_harness_module_info_json/2,
61
78
  repl_edit_touched/2,
62
79
  repl_edit_touched_text/2,
63
80
  repl_edit_touched_clear/1,
64
81
  repl_validate_tools/2,
65
82
  repl_validate_docs/2,
83
+ repl_validate_complexity/2,
66
84
  schema_fill_fields/3,
67
85
  schema_fields_of/3,
68
86
  repl_unhandled_directives/2,
@@ -71,6 +89,8 @@
71
89
  repl_set_dml_reference/2,
72
90
  repl_set_authoring_examples/2,
73
91
  repl_manifest/2,
92
+ repl_display_harness/2,
93
+ repl_shell_json/2,
74
94
  repl_history_load/2,
75
95
  repl_history_record/2,
76
96
  repl_history_summary/2,
@@ -128,9 +148,18 @@
128
148
  %% `process_engine_result/4`, which is intentional.
129
149
  :- discontiguous process_engine_result/4.
130
150
  :- discontiguous process_directive/2.
151
+ %% `repl_register_tool/6` sits between the tool clauses of process_clause/2.
152
+ :- discontiguous process_clause/2.
153
+ %% Tool/workflow conversion helpers sit between the workflow_from/2 clauses.
154
+ :- discontiguous workflow_from/2.
155
+ %% Harness-local dispatch sits near mi_call/3; the fallbacks live much later.
156
+ :- discontiguous mi_call_dispatch/3.
131
157
 
132
158
  %% Dynamic predicates for session state (engine management only, not memory!)
133
159
  :- dynamic session_engine/2. % session_engine(SessionId, Engine) - legacy default engine handle
160
+ :- dynamic mi_cut_class/3. % mi_cut_class(SessionId, Name/Arity, native|interpreted)
161
+ :- dynamic mi_purity/3. % mi_purity(SessionId, Name/Arity, pure|impure|in_progress)
162
+ :- dynamic mi_cut_done/1. % mi_cut_done(CallId) - non-backtrackable clause commit
134
163
  :- dynamic session_frame/4. % session_frame(FrameId, SessionId, Kind, Depth)
135
164
  :- dynamic session_frame_engine/2. % session_frame_engine(FrameId, Engine)
136
165
  :- dynamic session_default_frame/2. % session_default_frame(SessionId, FrameId)
@@ -153,13 +182,23 @@
153
182
  :- dynamic session_params/2. % session_params(SessionId, ParamsDict)
154
183
  :- dynamic session_user_tools/2. % session_user_tools(SessionId, ToolName)
155
184
  :- dynamic session_user_tool_schema/3. % session_user_tool_schema(SessionId, ToolName, Schema)
185
+ :- dynamic session_source_view/3. % session_source_view(SessionId, Name/Arity, SourceText)
156
186
  :- dynamic session_pending_input/2. % session_pending_input(SessionId, Input)
157
187
  :- dynamic session_agent_result/2. % session_agent_result(SessionId, Result)
158
188
  :- dynamic session_exec_result/2. % session_exec_result(SessionId, Result)
159
189
  :- dynamic session_sample_token_result/2. % session_sample_token_result(SessionId, Result)
160
190
  :- dynamic session_llm_result/2. % session_llm_result(SessionId, Result)
161
191
  :- dynamic session_judgment_result/2. % session_judgment_result(SessionId, Result)
162
- :- dynamic session_trace_log/2. % session_trace_log(SessionId, TraceLog) - accumulated trace entries
192
+ :- dynamic session_trace_entry/3. % session_trace_entry(SessionId, Index, Entry) - bounded trace
193
+ :- dynamic session_trace_scope/2. % session_trace_scope(SessionId, [ToolId|...]) - nested tool scope stack
194
+ :- dynamic session_harness_module/5. % SessionId, Name, Version, Hash, ModuleId
195
+ :- dynamic harness_module_owner/4. % ModuleId, Name, Version, Hash
196
+ :- dynamic harness_module_export/3. % ModuleId, Name, Arity
197
+ :- dynamic harness_module_import/4. % ModuleId, Name/Arity, TargetModule, TargetName/Arity
198
+ :- dynamic session_harness_export/3. % SessionId, Name, Arity
199
+ :- dynamic session_harness_import/4. % SessionId, Name/Arity, TargetModule, TargetName/Arity
200
+ :- dynamic session_trace_count/2. % session_trace_count(SessionId, Count)
201
+ :- dynamic session_trace_log/2. % legacy list; retained for compatibility
163
202
  :- dynamic session_trace_enabled/2. % session_trace_enabled(SessionId, true/false)
164
203
  :- dynamic session_pending_signal/2. % session_pending_signal(SessionId, Signal) - fallback for engine_fetch
165
204
  :- dynamic session_proc_result/3. % session_proc_result(SessionId, Key, Value) - process primitive results
@@ -202,12 +241,35 @@ assert_params(SessionId, Params) :-
202
241
  ; true
203
242
  ).
204
243
 
244
+ %% Validate that every exported predicate actually exists. Export directives can
245
+ %% appear before the definitions, so this runs after the whole source is loaded.
246
+ repl_validate_session_exports(SessionId) :-
247
+ findall(Name/Arity, session_harness_export(SessionId, Name, Arity), Exports),
248
+ repl_validate_export_list(Exports, SessionId, session).
249
+
250
+ repl_validate_module_exports(ModuleId) :-
251
+ findall(Name/Arity, harness_module_export(ModuleId, Name, Arity), Exports),
252
+ repl_validate_export_list(Exports, ModuleId, module).
253
+
254
+ repl_validate_export_list([], _, _).
255
+ repl_validate_export_list([Name/Arity|Rest], Owner, Kind) :-
256
+ ( module_local_predicate(Owner, Name, Arity)
257
+ -> true
258
+ ; throw(error(existence_error(export, Name/Arity),
259
+ context(export/1, 'exported predicate is not defined in this harness')))
260
+ ),
261
+ repl_validate_export_list(Rest, Owner, Kind).
262
+
205
263
  %% parse_dml_string(+Code, +SessionId)
206
264
  %% Parse DML code from a string
207
265
  parse_dml_string(Code, SessionId) :-
266
+ retractall(session_harness_export(SessionId, _, _)),
267
+ retractall(session_harness_import(SessionId, _, _, _)),
208
268
  open_string(Code, Stream),
209
269
  parse_clauses(Stream, SessionId),
210
- close(Stream).
270
+ close(Stream),
271
+ repl_source_views(SessionId, Code, Views),
272
+ repl_store_source_views(SessionId, Views, append).
211
273
 
212
274
  %% parse_clauses(+Stream, +SessionId)
213
275
  %% Read and process all clauses from a stream
@@ -215,7 +277,8 @@ parse_dml_string(Code, SessionId) :-
215
277
  parse_clauses(Stream, SessionId) :-
216
278
  read_term(Stream, Term, [module(SessionId), variable_names(Bindings)]),
217
279
  ( Term == end_of_file
218
- -> install_builtin_tools(SessionId)
280
+ -> install_builtin_tools(SessionId),
281
+ repl_validate_session_exports(SessionId)
219
282
  ; preprocess_loaded_term(Term, Bindings, PreparedTerms),
220
283
  forall(member(PreparedTerm, PreparedTerms), process_clause(PreparedTerm, SessionId)),
221
284
  parse_clauses(Stream, SessionId)
@@ -229,7 +292,29 @@ parse_clauses(Stream, SessionId) :-
229
292
  preprocess_loaded_term(Term, Bindings, PreparedTerms) :-
230
293
  transform_task_calls(Term, Bindings, TransformedTerm),
231
294
  expand_interpolations(TransformedTerm, Bindings, InterpolatedTerm),
232
- expand_loaded_term(InterpolatedTerm, PreparedTerms).
295
+ expand_loaded_term(InterpolatedTerm, ExpandedTerms),
296
+ annotate_tool_names_list(ExpandedTerms, Bindings, PreparedTerms).
297
+
298
+ %% annotate_tool_names(+Term, +Bindings, -Annotated)
299
+ %% A `tool(...)` clause is wrapped with the source names of its head variables.
300
+ %% Asserting the clause loses them (the listing prints A, B, C), and the schema
301
+ %% is what the nested agent reads: `arg1` says nothing, `Path` does.
302
+ annotate_tool_names(Term, Bindings, '$dc_tool'(Term, Names)) :-
303
+ tool_clause_head(Term, Head),
304
+ !,
305
+ term_variables(Head, HeadVars),
306
+ findall(Name, (member(Var, HeadVars), member(Name=Var, Bindings)), Names0),
307
+ list_to_set(Names0, Names).
308
+ annotate_tool_names(Term, _Bindings, Term).
309
+
310
+ annotate_tool_names_list([], _, []).
311
+ annotate_tool_names_list([Term|Terms], Bindings, [Annotated|Annotateds]) :-
312
+ annotate_tool_names(Term, Bindings, Annotated),
313
+ annotate_tool_names_list(Terms, Bindings, Annotateds).
314
+
315
+ tool_clause_head((tool(Head, _) :- _), Head).
316
+ tool_clause_head((tool(Head, _, _) :- _), Head).
317
+ tool_clause_head((tool(Head) :- _), Head).
233
318
 
234
319
  %% expand_loaded_term(+Term, -ExpandedTerms)
235
320
  %% Runs SWI term expansion and normalizes the result to a list of terms.
@@ -397,12 +482,44 @@ wrapper_type(dict, object).
397
482
  %% clean_clause_body(+Body, -CleanBody)
398
483
  clean_clause_body(Body, Clean) :-
399
484
  conj_list(Body, Goals),
400
- clean_goal_list(Goals, CleanGoals),
485
+ % `{Var}` interpolation is rewritten to a render goal plus a `~s` format; put
486
+ % the original variables back so the source reads `task("…{X}…")` again.
487
+ fold_interp_renders(Goals, FoldedGoals),
488
+ clean_goal_list(FoldedGoals, CleanGoals),
401
489
  ( CleanGoals = [Single]
402
490
  -> Clean = Single
403
491
  ; list_to_conjunction(CleanGoals, Clean)
404
492
  ).
405
493
 
494
+ %% fold_interp_renders(+Goals, -Folded)
495
+ %% Drop `dc_interp_value(Original, Rendered)` goals and put `Original` back into
496
+ %% the argument list of the `format/3` they feed.
497
+ fold_interp_renders(Goals, Folded) :-
498
+ fold_interp_renders(Goals, [], Folded).
499
+
500
+ fold_interp_renders([], _, []).
501
+ fold_interp_renders([Goal|Rest], Map, Out) :-
502
+ ( interp_render_goal(Goal, Original, Rendered)
503
+ -> fold_interp_renders(Rest, [Rendered-Original|Map], Out)
504
+ ; ( Goal = format(string(TextVar), Template, Args),
505
+ is_list(Args)
506
+ -> swap_interp_vars(Args, Map, Args2),
507
+ Out = [format(string(TextVar), Template, Args2)|Out2]
508
+ ; Out = [Goal|Out2]
509
+ ),
510
+ fold_interp_renders(Rest, Map, Out2)
511
+ ).
512
+
513
+ interp_render_goal(deepclause_strings:dc_interp_value(Original, Rendered), Original, Rendered).
514
+
515
+ swap_interp_vars([], _, []).
516
+ swap_interp_vars([Arg|Args], Map, [Swapped|SwappedArgs]) :-
517
+ ( member(Arg-Original, Map)
518
+ -> Swapped = Original
519
+ ; Swapped = Arg
520
+ ),
521
+ swap_interp_vars(Args, Map, SwappedArgs).
522
+
406
523
  conj_list((A, B), List) :-
407
524
  !,
408
525
  conj_list(A, LA),
@@ -525,14 +642,25 @@ typed_arg_type(string, Var, _, Var) :- !.
525
642
  typed_arg_type(integer, Var, _, integer(Var)) :- !.
526
643
  typed_arg_type(number, Var, _, number(Var)) :- !.
527
644
  typed_arg_type(boolean, Var, _, boolean(Var)) :- !.
528
- typed_arg_type(object, Var, _, object(Var)) :- !.
645
+ typed_arg_type(object, Var, Info, Wrapped) :-
646
+ !,
647
+ % `schema(name, X)` is an object with a declared shape. Dropping the name
648
+ % here made listing and export show `object(X)`, so an edit made from the
649
+ % listing silently lost the schema.
650
+ ( get_dict(schema, Info, SchemaName)
651
+ -> Wrapped = schema(SchemaName, Var)
652
+ ; Wrapped = object(Var)
653
+ ).
529
654
  typed_arg_type(array, Var, Info, list(Wrapped)) :-
530
655
  !,
531
656
  ( get_dict(itemType, Info, ItemType)
532
657
  -> true
533
658
  ; ItemType = string
534
659
  ),
535
- Wrapped =.. [ItemType, Var].
660
+ ( get_dict(schema, Info, SchemaName)
661
+ -> Wrapped = schema(SchemaName, Var)
662
+ ; Wrapped =.. [ItemType, Var]
663
+ ).
536
664
  typed_arg_type(_, Var, _, Var).
537
665
 
538
666
  %% interpolate_template(+Template, +Args, -Description)
@@ -547,7 +675,8 @@ interpolate_template(Template, Args, Description) :-
547
675
  interpolate_codes([], [], []) :- !.
548
676
  %% A {Var} placeholder consumes one argument; require Args to be exhausted
549
677
  %% exactly (the []/[] base case above fails if either side has leftovers).
550
- interpolate_codes([0'~, 0'w | Rest], [Arg | Args], Out) :-
678
+ interpolate_codes([0'~, Directive | Rest], [Arg | Args], Out) :-
679
+ ( Directive =:= 0'w ; Directive =:= 0's ),
551
680
  !,
552
681
  named_var(Arg),
553
682
  term_string(Arg, Name, [numbervars(true)]),
@@ -573,6 +702,57 @@ var_to_name(Bindings, Var, Name) :-
573
702
  ; Name = 'Var' % Fallback if not found
574
703
  ).
575
704
 
705
+ repl_script_predicate_conflict(SessionId, Name) :-
706
+ current_predicate(SessionId:script_file/2),
707
+ SessionId:script_file(Name, _),
708
+ current_predicate(SessionId:Name/Arity),
709
+ repl_user_predicate(SessionId, Name, Arity).
710
+
711
+ repl_reject_existing_predicate_for_script(SessionId, Name) :-
712
+ ( current_predicate(SessionId:Name/Arity),
713
+ repl_user_predicate(SessionId, Name, Arity)
714
+ -> format(atom(Message),
715
+ '~w is already a predicate. Rename the predicate or use a distinct script link name (for example ~w_py); script link names and predicate names must not overlap.',
716
+ [Name, Name]),
717
+ throw(error(permission_error(modify, script_predicate_collision, Name),
718
+ context(script_file/2, Message)))
719
+ ; true
720
+ ).
721
+
722
+ repl_reject_script_predicate_collision(SessionId, Name, Where) :-
723
+ ( repl_script_predicate_conflict(SessionId, Name)
724
+ -> format(atom(Message),
725
+ '~w is already a script_file/2 link name. Rename the link (for example ~w_py) or rename the predicate; script link names and predicate names must not overlap.',
726
+ [Name, Name]),
727
+ throw(error(permission_error(modify, script_predicate_collision, Name),
728
+ context(Where, Message)))
729
+ ; true
730
+ ).
731
+
732
+ repl_check_script_name_for_head(SessionId, Head) :-
733
+ ( catch(repl_head_of(Head, H), _, fail),
734
+ callable(H),
735
+ functor(H, Name, Arity)
736
+ -> ( session_harness_import(SessionId, Name/Arity, TargetModule, _)
737
+ -> format(atom(Message),
738
+ '~w/~w is imported read-only from ~w. Define a different local wrapper instead of redefining it.',
739
+ [Name, Arity, TargetModule]),
740
+ throw(error(permission_error(modify, imported_predicate, Name/Arity),
741
+ context(process_clause/2, Message)))
742
+ ; true
743
+ ),
744
+ ( current_predicate(SessionId:script_file/2),
745
+ SessionId:script_file(Name, _)
746
+ -> format(atom(Message),
747
+ '~w is already a script_file/2 link name. Rename the link (for example ~w_py) or rename the predicate; script link names and predicate names must not overlap.',
748
+ [Name, Name]),
749
+ throw(error(permission_error(modify, script_predicate_collision, Name),
750
+ context(process_clause/2, Message)))
751
+ ; true
752
+ )
753
+ ; true
754
+ ).
755
+
576
756
  %% process_clause(+Term, +SessionId)
577
757
  %% Process a single clause and add to session.
578
758
  %% Reject reserved-name definitions (third place of the reserved guard, so
@@ -592,43 +772,88 @@ process_clause((:- Directive), SessionId) :-
592
772
  %% The leading args are inputs (typed from the list); the last arg is the output.
593
773
  process_clause((tool(ToolHead, Description, Types) :- Body), SessionId) :-
594
774
  !,
595
- (catch(expand_dict_dots(Body, ExpandedBody), _, fail) -> true ; ExpandedBody = Body),
596
- extract_tool_schema(ToolHead, Description, Types, ToolName, Schema),
597
- assertz(session_user_tools(SessionId, ToolName)),
598
- assertz(session_user_tool_schema(SessionId, ToolName, Schema)),
599
- format_tool_source(ToolHead, Description, Types, Body, SourceCode),
600
- assertz(SessionId:tool_source(ToolName, SourceCode)),
601
- assertz(SessionId:(tool(ToolHead) :- ExpandedBody)).
775
+ repl_register_tool(SessionId, ToolHead, Description, Types, Body, []).
602
776
 
603
777
  %% Handle tool/2 with description: tool(Head, Description) :- Body
604
778
  process_clause((tool(ToolHead, Description) :- Body), SessionId) :-
605
779
  !,
606
- (catch(expand_dict_dots(Body, ExpandedBody), _, fail) -> true ; ExpandedBody = Body),
607
- extract_tool_schema(ToolHead, Description, ToolName, Schema),
608
- assertz(session_user_tools(SessionId, ToolName)),
609
- assertz(session_user_tool_schema(SessionId, ToolName, Schema)),
610
- % Store the source code for the tool description. Reverses the load-time
611
- % task/prompt rewrites and normalizes variables for deterministic export.
612
- format_tool_source(ToolHead, Description, Body, SourceCode),
613
- assertz(SessionId:tool_source(ToolName, SourceCode)),
614
- % Assert the tool implementation (use just ToolHead for execution)
615
- assertz(SessionId:(tool(ToolHead) :- ExpandedBody)).
780
+ repl_register_tool(SessionId, ToolHead, Description, none, Body, []).
616
781
 
617
782
  %% Handle tool/1 without description: tool(Head) :- Body
618
783
  process_clause((tool(ToolHead) :- Body), SessionId) :-
619
784
  !,
785
+ repl_register_tool(SessionId, ToolHead, none, none, Body, []).
786
+
787
+ %% A tool clause annotated with the source variable names of its head, so the
788
+ %% schema tells the model `Path` rather than `arg1`. `preprocess_loaded_term/3`
789
+ %% wraps tool clauses because the names are lost once the clause is asserted.
790
+ process_clause('$dc_tool'(Term, Names), SessionId) :-
791
+ !,
792
+ ( Term = (tool(Head, Description, Types) :- Body)
793
+ -> repl_register_tool(SessionId, Head, Description, Types, Body, Names)
794
+ ; Term = (tool(Head, Description) :- Body)
795
+ -> repl_register_tool(SessionId, Head, Description, none, Body, Names)
796
+ ; Term = (tool(Head) :- Body)
797
+ -> repl_register_tool(SessionId, Head, none, none, Body, Names)
798
+ ; true
799
+ ).
800
+
801
+ %% A tool written as a *fact* is not an annotation. It used to be asserted as a
802
+ %% plain `tool/2` (or `tool/3`) fact that nothing reads: the model got no tool,
803
+ %% no error at edit time, and "Tool not found" only when a nested agent called
804
+ %% it. Refuse it and name the shape that works.
805
+ process_clause(tool(_, _), _SessionId) :-
806
+ !,
807
+ throw(error(domain_error(tool_clause, tool/2),
808
+ context(process_clause/2,
809
+ 'a tool needs a body: tool(Head, "what it does") :- Delegate.'))).
810
+ process_clause(tool(_, _, _), _SessionId) :-
811
+ !,
812
+ throw(error(domain_error(tool_clause, tool/3),
813
+ context(process_clause/2,
814
+ 'a tool needs a body: tool(Head, "what it does", [InputTypes]) :- Delegate.'))).
815
+
816
+ %% repl_register_tool(+SessionId, +Head, +Description, +TypesOrNone, +Body, +Names)
817
+ %%
818
+ %% One tool per name. A second registration used to be accepted silently, so the
819
+ %% same tool appeared twice to the model and an old implementation could stay
820
+ %% live while the export carried the new one. Replacing is `define`'s job, whose
821
+ %% block may carry the tool clause next to the predicate.
822
+ repl_register_tool(SessionId, ToolHead, Description, Types, Body, Names) :-
823
+ repl_check_script_name_for_head(SessionId, ToolHead),
824
+ ToolHead =.. [ToolName|ToolArgs],
825
+ length(ToolArgs, Arity),
826
+ ( session_user_tools(SessionId, ToolName)
827
+ -> format(atom(Message),
828
+ 'tool ~w is already registered. Replace it with define, putting the predicate and its tool(...) clause in the same block.',
829
+ [ToolName]),
830
+ throw(error(permission_error(modify, existing_tool, ToolName),
831
+ context(process_clause/2, Message)))
832
+ ; true
833
+ ),
620
834
  (catch(expand_dict_dots(Body, ExpandedBody), _, fail) -> true ; ExpandedBody = Body),
621
- extract_tool_schema(ToolHead, none, ToolName, Schema),
835
+ extract_tool_schema(ToolHead, Description, Types, Names, ToolName, Schema),
622
836
  assertz(session_user_tools(SessionId, ToolName)),
623
837
  assertz(session_user_tool_schema(SessionId, ToolName, Schema)),
624
- % Store the source code for the tool description (reverses task rewrites).
625
- format_tool_source(ToolHead, none, Body, SourceCode),
838
+ assertz(session_user_tool_arity(SessionId, ToolName, Arity)),
839
+ assertz(session_user_tool_head(SessionId, ToolName, ToolHead)),
840
+ assertz(session_user_tool_desc(SessionId, ToolName, Description)),
841
+ assertz(session_user_tool_names(SessionId, ToolName, Names)),
842
+ ( is_list(Types) -> assertz(session_user_tool_types(SessionId, ToolName, Types)) ; true ),
843
+ assertz(session_user_tool_body(SessionId, ToolName, ExpandedBody)),
844
+ % The export source reverses the load-time task/prompt rewrites and
845
+ % normalizes variables, so an export round-trips deterministically.
846
+ ( Types == none
847
+ -> format_tool_source(ToolHead, Description, Body, SourceCode)
848
+ ; format_tool_source(ToolHead, Description, Types, Body, SourceCode)
849
+ ),
626
850
  assertz(SessionId:tool_source(ToolName, SourceCode)),
627
- % Assert the tool implementation
851
+ % Assert the tool implementation (just the head; the body is the delegate).
628
852
  assertz(SessionId:(tool(ToolHead) :- ExpandedBody)).
629
853
 
630
854
  process_clause((Head :- Body), SessionId) :-
631
855
  !,
856
+ repl_check_script_name_for_head(SessionId, Head),
632
857
  % Expand dict dot-notation (Dict.Key → get_dict), then assert
633
858
  ( catch(expand_dict_dots(Body, ExpandedBody), _, fail)
634
859
  -> true
@@ -636,6 +861,18 @@ process_clause((Head :- Body), SessionId) :-
636
861
  ),
637
862
  assertz(SessionId:(Head :- ExpandedBody)).
638
863
 
864
+ %% A script link is a keyed annotation, not a predicate. Refuse a name that is
865
+ %% already a user predicate; a later predicate definition checks the reverse in
866
+ %% process_clause and repl_register_tool.
867
+ process_clause(script_file(Name, Path), SessionId) :-
868
+ !,
869
+ ( atom(Name)
870
+ -> true
871
+ ; throw(error(type_error(atom, Name), context(script_file/2, 'the link name must be an atom')))
872
+ ),
873
+ repl_reject_existing_predicate_for_script(SessionId, Name),
874
+ assertz(SessionId:script_file(Name, Path)).
875
+
639
876
  %% repl_delete/1 is a load-time directive that removes a predicate. It must
640
877
  %% be handled before the generic fact clause so it is never asserted itself.
641
878
  process_clause(repl_delete(Name/Arity), SessionId) :-
@@ -647,6 +884,7 @@ process_clause(repl_delete(Name/Arity), SessionId) :-
647
884
 
648
885
  process_clause(Fact, SessionId) :-
649
886
  % Simple fact
887
+ repl_check_script_name_for_head(SessionId, Fact),
650
888
  assertz(SessionId:Fact).
651
889
 
652
890
  %% ============================================================
@@ -720,64 +958,64 @@ expand_dict_expr(Expr, Expr).
720
958
 
721
959
  %% extract_tool_schema(+ToolHead, +Description, -ToolName, -Schema)
722
960
  extract_tool_schema(ToolHead, Description, ToolName, Schema) :-
723
- extract_tool_schema(ToolHead, Description, [], ToolName, Schema).
961
+ extract_tool_schema(ToolHead, Description, [], [], ToolName, Schema).
724
962
 
725
- %% extract_tool_schema(+Head, +Description, +Types, -ToolName, -Schema)
963
+ %% extract_tool_schema(+Head, +Description, +Types, +Names, -ToolName, -Schema)
726
964
  %% `Types` is an optional list giving the type of each input (the leading args,
727
965
  %% in order); a missing entry defaults to `string`. This is what lets a tool take
728
- %% an object, an array or a number rather than only a string.
729
- extract_tool_schema(ToolHead, Description, Types, ToolName, Schema) :-
966
+ %% an object, an array or a number rather than only a string. `Names` are the
967
+ %% head's source variable names (`Path`, `Question`), so the model sees what an
968
+ %% argument means instead of `arg1`.
969
+ extract_tool_schema(ToolHead, Description, Types, Names, ToolName, Schema) :-
730
970
  ToolHead =.. [ToolName|Args],
731
971
  length(Args, Arity),
732
- tool_type_warning(ToolName, Arity, Types),
733
- extract_params(Args, 1, Arity, Types, Inputs, Outputs),
972
+ extract_params(Args, Names, 1, Arity, Types, Inputs, Outputs),
734
973
  (Description == none -> Desc = "" ; Desc = Description),
735
974
  Schema = schema{
736
975
  name: ToolName,
976
+ arity: Arity,
737
977
  description: Desc,
738
978
  inputs: Inputs,
739
979
  outputs: Outputs
740
980
  }.
741
981
 
742
- %% extract_params(+Args, +Index, +Arity, +Types, -Inputs, -Outputs)
982
+ %% extract_params(+Args, +Names, +Index, +Arity, +Types, -Inputs, -Outputs)
743
983
  %% The last argument is the output; the rest are inputs, typed from `Types`.
744
- extract_params([], _, _, _, [], []) :- !.
745
- extract_params([_Arg|Rest], Index, Arity, Types, Inputs, Outputs) :-
746
- format(atom(Name), 'arg~w', [Index]),
984
+ extract_params([], _, _, _, _, [], []) :- !.
985
+ extract_params([Arg|Rest], Names, Index, Arity, Types, Inputs, Outputs) :-
986
+ param_name(Arg, Names, Index, Name, Label),
747
987
  NextIndex is Index + 1,
748
- extract_params(Rest, NextIndex, Arity, Types, RestInputs, RestOutputs),
988
+ extract_params(Rest, Names, NextIndex, Arity, Types, RestInputs, RestOutputs),
749
989
  ( Index == Arity
750
990
  -> IsOutput = true, Type = string
751
991
  ; IsOutput = false, input_type(Index, Types, Type)
752
992
  ),
753
- Param = param{name: Name, type: Type},
993
+ Param = param{name: Name, type: Type, description: Label},
754
994
  ( IsOutput == true
755
995
  -> Inputs = RestInputs, Outputs = [Param|RestOutputs]
756
996
  ; Inputs = [Param|RestInputs], Outputs = RestOutputs
757
997
  ).
758
998
 
999
+ %% param_name(+HeadArg, +Names, +Index, -Name, -Label)
1000
+ %% The wire name stays `argN` (a model bridge and existing harnesses use it);
1001
+ %% the head's variable name becomes the parameter description, so the model
1002
+ %% reads `Path` and `Question` instead of an unexplained `arg1`.
1003
+ param_name(_Arg, Names, Index, Name, Label) :-
1004
+ format(atom(Name), 'arg~w', [Index]),
1005
+ ( nth1(Index, Names, Candidate),
1006
+ atom(Candidate)
1007
+ -> Label = Candidate
1008
+ ; Label = Name
1009
+ ).
1010
+
759
1011
  %% input_type(+Index, +Types, -Type): the Index-th input's declared type.
1012
+ input_type(_, Types, string) :-
1013
+ \+ is_list(Types),
1014
+ !.
760
1015
  input_type(1, [T|_], T) :- !.
761
1016
  input_type(N, [_|Rest], T) :- N > 1, N1 is N - 1, input_type(N1, Rest, T).
762
1017
  input_type(_, [], string).
763
1018
 
764
- %% tool_type_warning(+Name, +Arity, +Types)
765
- %% The last argument of a tool head is the output, so a type list should label
766
- %% the other (Arity - 1) inputs. When it does not, the author has almost
767
- %% certainly written a tool whose second input was taken for its output — the
768
- %% `tool(fs_write(Path, Content), …)` shape, which silently writes nothing.
769
- tool_type_warning(ToolName, Arity, Types) :-
770
- is_list(Types),
771
- Types \== [],
772
- length(Types, Declared),
773
- Inputs is Arity - 1,
774
- Declared =\= Inputs,
775
- !,
776
- format(user_error,
777
- 'Warning: tool ~w/~w declares ~w input type(s) but has ~w input argument(s). The last argument of a tool head is the output; a tool with another input needs a result argument (e.g. fs_write(Path, Content, ok)).~n',
778
- [ToolName, Arity, Declared, Inputs]).
779
- tool_type_warning(_, _, _).
780
-
781
1019
  module_reference_string(Module, ModuleStr) :-
782
1020
  atom(Module),
783
1021
  !,
@@ -817,6 +1055,295 @@ import_library_into_mi(library(Name)) :-
817
1055
  catch(deepclause_mi:use_module(library(Name)), _, true).
818
1056
  import_library_into_mi(_).
819
1057
 
1058
+ %% ============================================================
1059
+ %% Harness modules (export / use_harness)
1060
+ %% ============================================================
1061
+
1062
+ harness_indicator_list(Spec, List) :-
1063
+ ( is_list(Spec)
1064
+ -> List = Spec
1065
+ ; Spec = (A, B)
1066
+ -> harness_indicator_list(A, LA),
1067
+ harness_indicator_list(B, LB),
1068
+ append(LA, LB, List)
1069
+ ; List = [Spec]
1070
+ ).
1071
+
1072
+ valid_harness_indicator(Name/Arity) :-
1073
+ atom(Name), integer(Arity), Arity >= 0,
1074
+ \+ repl_reserved_name(Name).
1075
+
1076
+ repl_hs_register_exports(SessionId, Spec) :-
1077
+ harness_indicator_list(Spec, Exports),
1078
+ repl_hs_export_list(Exports, SessionId).
1079
+
1080
+ repl_hs_export_list([], _SessionId).
1081
+ repl_hs_export_list([Indicator|Rest], SessionId) :-
1082
+ ( valid_harness_indicator(Indicator)
1083
+ -> Indicator = Name/Arity,
1084
+ assertz(session_harness_export(SessionId, Name, Arity))
1085
+ ; throw(error(domain_error(predicate_indicator, Indicator),
1086
+ context(export/1, 'export expects Name/Arity')))
1087
+ ),
1088
+ repl_hs_export_list(Rest, SessionId).
1089
+
1090
+ repl_hs_register_module_exports(ModuleId, Spec) :-
1091
+ harness_indicator_list(Spec, Exports),
1092
+ repl_hs_module_export_list(Exports, ModuleId).
1093
+
1094
+ repl_hs_module_export_list([], _ModuleId).
1095
+ repl_hs_module_export_list([Indicator|Rest], ModuleId) :-
1096
+ ( valid_harness_indicator(Indicator)
1097
+ -> Indicator = Name/Arity,
1098
+ assertz(harness_module_export(ModuleId, Name, Arity))
1099
+ ; throw(error(domain_error(predicate_indicator, Indicator),
1100
+ context(export/1, 'export expects Name/Arity')))
1101
+ ),
1102
+ repl_hs_module_export_list(Rest, ModuleId).
1103
+
1104
+ %% repl_hs_register_imports(+Owner, +SessionId, +Name, +VersionOpt, +Spec)
1105
+ %% Owner is a harness module id, or the session id for the caller.
1106
+ repl_hs_register_imports(Owner, SessionId, Name, VersionOpt, Spec) :-
1107
+ harness_indicator_list(Spec, Exports),
1108
+ repl_hs_find_target(SessionId, Name, VersionOpt, TargetModule),
1109
+ repl_hs_import_list(Exports, Owner, SessionId, TargetModule).
1110
+
1111
+ repl_hs_find_target(SessionId, Name, none, TargetModule) :-
1112
+ findall(ModuleId,
1113
+ session_harness_module(SessionId, Name, _, _, ModuleId),
1114
+ Modules0),
1115
+ sort(Modules0, Modules),
1116
+ ( Modules = [TargetModule|_]
1117
+ -> true
1118
+ ; throw(error(existence_error(harness_module, Name),
1119
+ context(use_harness/2, 'harness module is not available in this session')))
1120
+ ).
1121
+ repl_hs_find_target(SessionId, Name, version(Version0), TargetModule) :-
1122
+ normalize_harness_version(Version0, Version),
1123
+ findall(ModuleId,
1124
+ session_harness_module(SessionId, Name, Version, _, ModuleId),
1125
+ Modules0),
1126
+ sort(Modules0, Modules),
1127
+ ( Modules = [TargetModule|_]
1128
+ -> true
1129
+ ; throw(error(existence_error(harness_module, Name),
1130
+ context(use_harness/2, 'harness module is not available in this session')))
1131
+ ).
1132
+
1133
+ normalize_harness_version(Value, Normalized) :-
1134
+ ( number(Value)
1135
+ -> number_string(Value, Normalized)
1136
+ ; atom(Value)
1137
+ -> atom_string(Value, Normalized)
1138
+ ; string(Value)
1139
+ -> Normalized = Value
1140
+ ; term_string(Value, Normalized)
1141
+ ).
1142
+
1143
+ harness_import_conflicts(Owner, SessionId, Indicator) :-
1144
+ ( Owner == SessionId
1145
+ -> ( session_harness_import(SessionId, Indicator, _, _)
1146
+ ; session_harness_export(SessionId, Name, Arity),
1147
+ Indicator = Name/Arity
1148
+ )
1149
+ ; harness_module_import(Owner, Indicator, _, _)
1150
+ ; Indicator = Name/Arity,
1151
+ module_local_predicate(Owner, Name, Arity)
1152
+ ).
1153
+
1154
+ repl_hs_import_list([], _Owner, _SessionId, _TargetModule).
1155
+ repl_hs_import_list([Indicator|Rest], Owner, SessionId, TargetModule) :-
1156
+ ( Indicator = ExportName/ExportArity
1157
+ -> true
1158
+ ; throw(error(domain_error(predicate_indicator, Indicator),
1159
+ context(use_harness/2, 'imports must be Name/Arity')))
1160
+ ),
1161
+ ( harness_module_export(TargetModule, ExportName, ExportArity)
1162
+ -> true
1163
+ ; throw(error(existence_error(export, Indicator),
1164
+ context(use_harness/2, 'the imported harness does not export this predicate')))
1165
+ ),
1166
+ ( harness_import_conflicts(Owner, SessionId, Indicator)
1167
+ -> throw(error(permission_error(import, duplicate_predicate, Indicator),
1168
+ context(use_harness/2, 'name is already present in the importing harness')))
1169
+ ; true
1170
+ ),
1171
+ ( Owner == SessionId
1172
+ -> assertz(session_harness_import(SessionId, Indicator, TargetModule, Indicator))
1173
+ ; assertz(harness_module_import(Owner, Indicator, TargetModule, Indicator))
1174
+ ),
1175
+ repl_hs_import_list(Rest, Owner, SessionId, TargetModule).
1176
+
1177
+ %% repl_add_harness_import(+SessionId, +Name, +VersionOpt, +Predicates, -Result)
1178
+ %% Adds a use_harness directive to the living module inside the current edit
1179
+ %% transaction. The caller must have preloaded the target module.
1180
+ repl_add_harness_import(SessionId, Name, VersionOpt, Predicates, Result) :-
1181
+ catch(
1182
+ ( guard_not_frozen(SessionId),
1183
+ ( VersionOpt == none
1184
+ -> Directive = use_harness(Name, Predicates)
1185
+ ; Directive = use_harness(Name, VersionOpt, Predicates)
1186
+ ),
1187
+ process_directive(Directive, SessionId),
1188
+ Result = ok
1189
+ ),
1190
+ ImportError,
1191
+ format(atom(Result), 'error(~w)', [ImportError])
1192
+ ).
1193
+
1194
+ %% process_directive(export(...), +SessionId)
1195
+ process_directive(export(Spec), SessionId) :-
1196
+ !,
1197
+ repl_hs_register_exports(SessionId, Spec),
1198
+ record_directive(SessionId, export(Spec)).
1199
+
1200
+ %% process_directive(use_harness(Name, Imports), +SessionId)
1201
+ process_directive(use_harness(Name, Imports), SessionId) :-
1202
+ !,
1203
+ repl_hs_register_imports(SessionId, SessionId, Name, none, Imports),
1204
+ record_directive(SessionId, use_harness(Name, Imports)).
1205
+ process_directive(use_harness(Name, version(Version), Imports), SessionId) :-
1206
+ !,
1207
+ repl_hs_register_imports(SessionId, SessionId, Name, version(Version), Imports),
1208
+ record_directive(SessionId, use_harness(Name, version(Version), Imports)).
1209
+
1210
+ %% repl_harness_module_info_json(+SessionId, -Json)
1211
+ %% Provenance for the UI: imported modules, exported predicates and the local
1212
+ %% caller's exports. Never exposes private predicates.
1213
+ repl_harness_module_info_json(SessionId, Json) :-
1214
+ findall(ModuleDict,
1215
+ ( session_harness_module(SessionId, Name, Version, Hash, ModuleId),
1216
+ findall(ExportName/ExportArity,
1217
+ harness_module_export(ModuleId, ExportName, ExportArity),
1218
+ ExportIndicators),
1219
+ maplist(indicator_text, ExportIndicators, Exports),
1220
+ findall(ImportDict,
1221
+ ( harness_module_import(ModuleId, FromName/FromArity, Target, TargetName/TargetArity),
1222
+ indicator_text(FromName/FromArity, From),
1223
+ indicator_text(TargetName/TargetArity, As),
1224
+ ImportDict = _{from: From, as: As, module: Target}
1225
+ ),
1226
+ Imports),
1227
+ ModuleDict = _{name: Name, version: Version, hash: Hash, module: ModuleId,
1228
+ exports: Exports, imports: Imports}
1229
+ ),
1230
+ Modules),
1231
+ findall(IndicatorText,
1232
+ ( session_harness_export(SessionId, Name, Arity),
1233
+ indicator_text(Name/Arity, IndicatorText)
1234
+ ),
1235
+ LocalExports),
1236
+ Json =_{modules: Modules, exports: LocalExports}.
1237
+
1238
+ indicator_text(Name/Arity, Text) :-
1239
+ format(atom(Text), '~w/~w', [Name, Arity]).
1240
+
1241
+ %% repl_set_harness_exports(+SessionId, +Predicates, -Result)
1242
+ %% Replace the current export contract within the open edit transaction.
1243
+ repl_set_harness_exports(SessionId, Predicates, Result) :-
1244
+ catch(
1245
+ ( guard_not_frozen(SessionId),
1246
+ repl_validate_export_selection(SessionId, Predicates),
1247
+ retractall(session_directive(SessionId, export(_))),
1248
+ retractall(session_harness_export(SessionId, _, _)),
1249
+ ( Predicates == []
1250
+ -> true
1251
+ ; process_directive(export(Predicates), SessionId)
1252
+ ),
1253
+ Result = ok
1254
+ ),
1255
+ ExportError,
1256
+ format(atom(Result), 'error(~w)', [ExportError])
1257
+ ).
1258
+
1259
+ repl_validate_export_selection(_SessionId, []).
1260
+ repl_validate_export_selection(SessionId, [Name/Arity|Rest]) :-
1261
+ ( atom(Name), integer(Arity), Arity >= 0, module_local_predicate(SessionId, Name, Arity)
1262
+ -> repl_validate_export_selection(SessionId, Rest)
1263
+ ; throw(error(existence_error(export, Name/Arity),
1264
+ context(export/1, 'can only export predicates defined by this harness')))
1265
+ ).
1266
+
1267
+ %% ============================================================
1268
+ %% Module loading (preloaded by the embedding before the main source)
1269
+ %% ============================================================
1270
+
1271
+ ensure_harness_module(ModuleId) :-
1272
+ ( current_module(ModuleId)
1273
+ -> true
1274
+ ; assertz(ModuleId:harness_module_marker)
1275
+ ).
1276
+
1277
+ %% repl_load_harness_module(+SessionId, +ModuleId, +Name, +Version, +Hash, +Code)
1278
+ %% Loads one dependency into its own SWI module. The module is immutable at the
1279
+ %% public boundary: only exported predicates are registered as imports.
1280
+ repl_load_harness_module(SessionId, ModuleId, Name, Version0, Hash, Code) :-
1281
+ atom(ModuleId),
1282
+ atom(Name),
1283
+ normalize_harness_version(Version0, Version),
1284
+ ( session_harness_module(SessionId, Name, Version, Hash, _Instance)
1285
+ -> true
1286
+ ; format(atom(Instance), '~w_~w', [ModuleId, SessionId]),
1287
+ ( harness_module_owner(Instance, Name, Version, Hash)
1288
+ -> true
1289
+ ; assertz(harness_module_owner(Instance, Name, Version, Hash)),
1290
+ ensure_harness_module(Instance),
1291
+ parse_harness_module_string(Code, Instance, SessionId)
1292
+ ),
1293
+ assertz(session_harness_module(SessionId, Name, Version, Hash, Instance))
1294
+ ).
1295
+
1296
+ parse_harness_module_string(Code, ModuleId, SessionId) :-
1297
+ open_string(Code, Stream),
1298
+ parse_harness_module_clauses(Stream, ModuleId, SessionId),
1299
+ close(Stream),
1300
+ repl_validate_module_exports(ModuleId).
1301
+
1302
+ parse_harness_module_clauses(Stream, ModuleId, SessionId) :-
1303
+ read_term(Stream, RawTerm, [module(ModuleId), variable_names(Bindings)]),
1304
+ ( RawTerm == end_of_file
1305
+ -> true
1306
+ ; preprocess_loaded_term(RawTerm, Bindings, PreparedTerms),
1307
+ forall(member(Term, PreparedTerms),
1308
+ process_harness_term(Term, ModuleId, SessionId)),
1309
+ parse_harness_module_clauses(Stream, ModuleId, SessionId)
1310
+ ).
1311
+
1312
+ process_harness_term((:- export(Spec)), ModuleId, _SessionId) :-
1313
+ !, repl_hs_register_module_exports(ModuleId, Spec).
1314
+ process_harness_term((:- use_harness(Name, Imports)), ModuleId, SessionId) :-
1315
+ !, repl_hs_register_imports(ModuleId, SessionId, Name, none, Imports).
1316
+ process_harness_term((:- use_harness(Name, version(Version), Imports)), ModuleId, SessionId) :-
1317
+ !, repl_hs_register_imports(ModuleId, SessionId, Name, version(Version), Imports).
1318
+ process_harness_term((:- use_module(Module)), ModuleId, _SessionId) :-
1319
+ !, catch(ModuleId:use_module(Module), _, true).
1320
+ process_harness_term((:- ModuleSpec), ModuleId, _SessionId) :-
1321
+ !,
1322
+ ( ModuleSpec = use_module(Module, _)
1323
+ -> catch(ModuleId:use_module(Module), _, true)
1324
+ ; true
1325
+ ).
1326
+ process_harness_term('$dc_tool'(_, _), _ModuleId, _SessionId) :- !.
1327
+ process_harness_term((tool(_, _) :- _), _ModuleId, _SessionId) :- !.
1328
+ process_harness_term((tool(_, _, _) :- _), _ModuleId, _SessionId) :- !.
1329
+ process_harness_term((tool(_) :- _), _ModuleId, _SessionId) :- !.
1330
+ process_harness_term((Head :- Body), ModuleId, _SessionId) :-
1331
+ !,
1332
+ ( catch(expand_dict_dots(Body, ExpandedBody), _, fail)
1333
+ -> true
1334
+ ; ExpandedBody = Body
1335
+ ),
1336
+ assertz(ModuleId:(Head :- ExpandedBody)).
1337
+ process_harness_term(Fact, ModuleId, _SessionId) :-
1338
+ ( Fact = script_file(_, _)
1339
+ -> true
1340
+ ; Fact = tool(_, _)
1341
+ -> true
1342
+ ; Fact = tool(_, _, _)
1343
+ -> true
1344
+ ; assertz(ModuleId:Fact)
1345
+ ).
1346
+
820
1347
  %% process_directive(+Directive, +SessionId)
821
1348
  process_directive(param(Key, Desc), SessionId) :-
822
1349
  !,
@@ -1056,7 +1583,13 @@ create_engine(SessionId, _MemoryId, Args, Params, InitialMemory, Engine) :-
1056
1583
  % Check if tracing is enabled and store in session state
1057
1584
  (get_dict(trace, Params, true) -> TraceEnabled = true ; TraceEnabled = false),
1058
1585
  assertz(session_trace_enabled(SessionId, TraceEnabled)),
1059
- assertz(session_trace_log(SessionId, [])),
1586
+ % Keep the session trace across turns: create_engine runs once per turn,
1587
+ % and a Work session can execute several workflows. Only create_session/
1588
+ % explicit clear resets the store.
1589
+ ( session_trace_count(SessionId, _)
1590
+ -> true
1591
+ ; assertz(session_trace_count(SessionId, 0))
1592
+ ),
1060
1593
  % Check for gas limit in params
1061
1594
  (get_dict(gas_limit, Params, GasLimit) -> true ; GasLimit = -1),
1062
1595
  % Create initial state with provided memory, params, context stack, trace depth and gas
@@ -1128,9 +1661,9 @@ step_engine_handle(SessionId, Engine, Status, Content, Payload) :-
1128
1661
  ; % Engine finished - return trace if enabled
1129
1662
  Status = finished,
1130
1663
  Content = '',
1131
- ( session_trace_enabled(SessionId, true),
1132
- session_trace_log(SessionId, TraceLog)
1133
- -> Payload = payload{trace: TraceLog}
1664
+ ( session_trace_enabled(SessionId, true)
1665
+ -> session_trace_list(SessionId, TraceLog),
1666
+ Payload = payload{trace: TraceLog}
1134
1667
  ; Payload = none
1135
1668
  )
1136
1669
  ),
@@ -1142,9 +1675,9 @@ step_engine_handle(SessionId, Engine, Status, Content, Payload) :-
1142
1675
  ; format(atom(ErrMsg), 'Engine error: ~w', [Error]),
1143
1676
  Status = error,
1144
1677
  Content = ErrMsg,
1145
- ( session_trace_enabled(SessionId, true),
1146
- session_trace_log(SessionId, TraceLog)
1147
- -> Payload = payload{trace: TraceLog}
1678
+ ( session_trace_enabled(SessionId, true)
1679
+ -> session_trace_list(SessionId, TraceLog),
1680
+ Payload = payload{trace: TraceLog}
1148
1681
  ; Payload = none
1149
1682
  )
1150
1683
  )
@@ -1184,8 +1717,7 @@ create_session(SessionId, Params, HarnessMemory, MetaMemory) :-
1184
1717
  ),
1185
1718
  retractall(session_trace_enabled(SessionId, _)),
1186
1719
  assertz(session_trace_enabled(SessionId, TraceEnabled)),
1187
- retractall(session_trace_log(SessionId, _)),
1188
- assertz(session_trace_log(SessionId, [])),
1720
+ reset_trace_store(SessionId),
1189
1721
  retractall(session_repl_memory(SessionId, _)),
1190
1722
  assertz(session_repl_memory(SessionId, HarnessMemory)),
1191
1723
  retractall(session_meta_memory(SessionId, _)),
@@ -1244,7 +1776,10 @@ clear_session(SessionId) :-
1244
1776
  retractall(repl_snapshot(SessionId, _)),
1245
1777
  retractall(session_user_tools(SessionId, _)),
1246
1778
  retractall(session_user_tool_schema(SessionId, _, _)),
1779
+ retractall(session_source_view(SessionId, _, _)),
1247
1780
  retractall(session_builtin_tool(SessionId, _)),
1781
+ retractall(session_harness_export(SessionId, _, _)),
1782
+ retractall(session_harness_import(SessionId, _, _, _)),
1248
1783
  repl_abolish_user_predicates(SessionId),
1249
1784
  install_builtin_tools(SessionId).
1250
1785
 
@@ -1269,14 +1804,17 @@ destroy_session(SessionId) :-
1269
1804
  retractall(repl_snapshot(SessionId, _)),
1270
1805
  retractall(session_params(SessionId, _)),
1271
1806
  retractall(session_trace_enabled(SessionId, _)),
1272
- retractall(session_trace_log(SessionId, _)).
1807
+ reset_trace_store(SessionId).
1273
1808
 
1274
1809
  %% load_code(+SessionId, +Code, -Error)
1275
1810
  %% Parses DML source into the session module, running the normal source
1276
1811
  %% preprocessing (task/prompt rewrite, interpolation, expand_term).
1277
1812
  load_code(SessionId, Code, Error) :-
1278
1813
  catch(
1279
- ( guard_not_frozen(SessionId),
1814
+ ( mi_clear_cut_classes(SessionId),
1815
+ guard_not_frozen(SessionId),
1816
+ retractall(session_harness_export(SessionId, _, _)),
1817
+ retractall(session_harness_import(SessionId, _, _, _)),
1280
1818
  parse_dml_string(Code, SessionId),
1281
1819
  Error = none
1282
1820
  ),
@@ -1375,6 +1913,14 @@ trim_trailing_ws(Str, Len0, Len) :-
1375
1913
  %% Names is the read_term variable_names list (Name=Var), used to render
1376
1914
  %% bindings for solution events.
1377
1915
  read_repl_goal(SessionId, Text, Goal, Names) :-
1916
+ catch(read_repl_goal_once(SessionId, Text, Goal, Names), ReadError,
1917
+ ( repl_clp_operator_error(ReadError),
1918
+ repl_install_clp_operators(SessionId)
1919
+ -> read_repl_goal_once(SessionId, Text, Goal, Names)
1920
+ ; throw(ReadError)
1921
+ )).
1922
+
1923
+ read_repl_goal_once(SessionId, Text, Goal, Names) :-
1378
1924
  % read_term/3 requires a full stop; REPL callers may omit it (`-g "p(X)"`).
1379
1925
  ensure_full_stop(Text, Text1),
1380
1926
  open_string(Text1, Stream),
@@ -1392,9 +1938,33 @@ read_repl_goal(SessionId, Text, Goal, Names) :-
1392
1938
  % hoisted into a goal *before* the goal that uses it. expand_term_interp
1393
1939
  % embeds the interpolation term in the argument position instead, which is
1394
1940
  % wrong for a raw goal such as verify(X, "Is {X} > 0?", V).
1395
- expand_body_interp(Transformed, Names0, Goal),
1941
+ expand_body_interp(Transformed, Names0, Interpolated),
1942
+ % `Dict.key` is expanded when a clause is asserted, but an `execute` goal is
1943
+ % read and called directly, so it used to reach `'.'/2` and silently return
1944
+ % the term `_{a:1}.a` instead of 1.
1945
+ ( catch(expand_dict_dots(Interpolated, Expanded), _, fail)
1946
+ -> Goal = Expanded
1947
+ ; Goal = Interpolated
1948
+ ),
1396
1949
  Names = Names0.
1397
1950
 
1951
+ %% repl_clp_operator_error(+Error)
1952
+ %% `X #> 3` in a goal is a *syntax* error until the CLP operators are declared
1953
+ %% in the session module: the docs tell the agent to run CLP with `execute`, and
1954
+ %% without this it got `syntax_error(operator_expected)` and no hint.
1955
+ repl_clp_operator_error(error(syntax_error(operator_expected), _)).
1956
+
1957
+ repl_install_clp_operators(SessionId) :-
1958
+ % Import predicates *and* operators, into the session module and the
1959
+ % meta-interpreter's module: the goal is read against the session and run
1960
+ % through `deepclause_mi`.
1961
+ forall(member(Library, [clpfd, clpr, clpq]),
1962
+ catch(repl_load_clp_library(SessionId, Library), _, true)).
1963
+
1964
+ repl_load_clp_library(SessionId, Library) :-
1965
+ catch(SessionId:use_module(library(Library)), _, true),
1966
+ catch(import_library_into_mi(library(Library)), _, true).
1967
+
1398
1968
  %% repl_solve(+Goal, +Names, +SessionId, +State)
1399
1969
  %% Enumerating goal-mode solver. Yields one solution(Bindings, Deterministic)
1400
1970
  %% per answer and fails so engine_next/2 backtracks for the next solution.
@@ -1417,7 +1987,13 @@ repl_solve(Goal, Names, SessionId, State) :-
1417
1987
  ).
1418
1988
 
1419
1989
  repl_solve_loop(Goal, Names, SessionId, State) :-
1420
- mi_call(Goal, State, StateOut),
1990
+ ( mi_native_query(SessionId, Goal)
1991
+ -> % A cut in a query commits the query itself. A pure query has no
1992
+ % state to thread, so it can run natively and get real cut semantics.
1993
+ call(SessionId:Goal),
1994
+ StateOut = State
1995
+ ; mi_call(Goal, State, StateOut)
1996
+ ),
1421
1997
  collect_bindings(Names, Bindings),
1422
1998
  store_memory_for_state(SessionId, StateOut),
1423
1999
  engine_yield(solution(Bindings, false)),
@@ -1464,12 +2040,11 @@ repl_listing(Filter, Text) :-
1464
2040
 
1465
2041
  repl_listing_output(SessionId, Filter) :-
1466
2042
  ( Filter == tools
1467
- -> forall(session_user_tool_schema(SessionId, Name, Schema),
1468
- ( SessionId:tool_source(Name, Source)
1469
- -> format("~w - ~w~n~w~n~n", [Name, Schema, Source])
1470
- ; format("~w - ~w~n~n", [Name, Schema])
1471
- )
1472
- )
2043
+ -> repl_listing_tools(SessionId, false)
2044
+ ; Filter == 'tools:all'
2045
+ -> repl_listing_tools(SessionId, true)
2046
+ ; Filter == scripts
2047
+ -> repl_listing_scripts(SessionId)
1473
2048
  ; Filter == history
1474
2049
  -> repl_history_listing(SessionId)
1475
2050
  ; ( current_predicate(SessionId:module_doc/1),
@@ -1484,18 +2059,116 @@ repl_listing_output(SessionId, Filter) :-
1484
2059
  Preds0),
1485
2060
  sort(Preds0, Preds),
1486
2061
  forall(member(Name/Arity, Preds),
1487
- ( repl_listing_match(Filter, Name, Arity)
2062
+ ( repl_listing_match(Filter, Name, Arity),
2063
+ \+ repl_annotation_predicate(Name, Arity)
1488
2064
  -> format("~w/~w~n", [Name, Arity]),
1489
2065
  ( current_predicate(SessionId:doc/2),
1490
2066
  SessionId:doc(Name/Arity, DocText)
1491
2067
  -> format(" % ~w~n", [DocText])
1492
2068
  ; true
1493
2069
  ),
1494
- functor(Head, Name, Arity),
1495
- forall(clause(SessionId:Head, ClauseBody), print_user_clause(Head, ClauseBody))
2070
+ repl_listing_tool_line(SessionId, Name, Arity),
2071
+ ( session_source_view(SessionId, Name/Arity, SourceView)
2072
+ -> format("~w", [SourceView])
2073
+ ; functor(Head, Name, Arity),
2074
+ forall(clause(SessionId:Head, ClauseBody), print_user_clause(Head, ClauseBody))
2075
+ )
1496
2076
  ; true
1497
2077
  )
2078
+ ),
2079
+ findall(Name/Arity-TargetModule,
2080
+ ( session_harness_import(SessionId, Name/Arity, TargetModule, _),
2081
+ repl_listing_match(Filter, Name, Arity)
2082
+ ),
2083
+ Imports0),
2084
+ sort(Imports0, Imports),
2085
+ forall(member(Name/Arity-TargetModule, Imports),
2086
+ format("~w/~w [imported from ~w, read-only]~n", [Name, Arity, TargetModule])
2087
+ ),
2088
+ repl_listing_tool_summary(SessionId)
2089
+ ).
2090
+
2091
+ %% repl_listing_scripts(+SessionId): the linked script files, which are
2092
+ %% annotations rather than predicates.
2093
+ repl_listing_scripts(SessionId) :-
2094
+ ( current_predicate(SessionId:script_file/2)
2095
+ -> findall(Name-Path,
2096
+ ( SessionId:script_file(Name, Path),
2097
+ ( atom(Path) ; string(Path) )
2098
+ ),
2099
+ Links0),
2100
+ sort(Links0, Links),
2101
+ ( Links == []
2102
+ -> format("no script_file/2 links.~n")
2103
+ ; forall(member(Name-Path, Links), format("~w -> ~w~n", [Name, Path]))
1498
2104
  )
2105
+ ; format("no script_file/2 links.~n")
2106
+ ).
2107
+
2108
+ %% repl_listing_tool_line(+SessionId, +Name, +Arity)
2109
+ %% A tool annotation is stored outside the clause database, so `listing` used to
2110
+ %% show a predicate with no hint that a nested agent can call it — an agent that
2111
+ %% had just added a tool could not confirm it from the listing, and added it
2112
+ %% again.
2113
+ repl_listing_tool_line(SessionId, Name, Arity) :-
2114
+ session_user_tools(SessionId, Name),
2115
+ session_user_tool_arity(SessionId, Name, Arity),
2116
+ !,
2117
+ session_user_tool_head(SessionId, Name, Head),
2118
+ ( session_user_tool_types(SessionId, Name, Types) -> true ; Types = none ),
2119
+ ( session_user_tool_desc(SessionId, Name, Desc), Desc \== none -> true ; Desc = "" ),
2120
+ ( Types == none
2121
+ -> format(" % tool ~q — ~w~n", [Head, Desc])
2122
+ ; format(" % tool ~q ~w — ~w~n", [Head, Types, Desc])
2123
+ ).
2124
+ repl_listing_tool_line(_, _, _).
2125
+
2126
+ %% repl_listing_tool_summary(+SessionId): one line at the end of `all`.
2127
+ repl_listing_tool_summary(SessionId) :-
2128
+ findall(ToolName/Arity,
2129
+ ( session_user_tools(SessionId, ToolName),
2130
+ \+ session_builtin_tool(SessionId, ToolName),
2131
+ session_user_tool_arity(SessionId, ToolName, Arity)
2132
+ ),
2133
+ Tools0),
2134
+ sort(Tools0, Tools),
2135
+ ( Tools == []
2136
+ -> true
2137
+ ; format("~ntools: ~w~n", [Tools])
2138
+ ).
2139
+
2140
+ %% repl_listing_tools(+SessionId, +IncludeBuiltins)
2141
+ %% User tools first and compact; the built-in form tools only on request. The
2142
+ %% old listing led with seven built-ins as raw schema dicts, which buried the
2143
+ %% harness's own tools.
2144
+ repl_listing_tools(SessionId, IncludeBuiltins) :-
2145
+ findall(ToolName/Arity,
2146
+ ( session_user_tools(SessionId, ToolName),
2147
+ session_user_tool_arity(SessionId, ToolName, Arity),
2148
+ ( IncludeBuiltins == true
2149
+ -> true
2150
+ ; \+ session_builtin_tool(SessionId, ToolName)
2151
+ )
2152
+ ),
2153
+ Tools0),
2154
+ sort(Tools0, Tools),
2155
+ ( Tools == []
2156
+ -> format("no tools registered. A tool is tool(Head, \"description\", [InputTypes]) :- Delegate.~n")
2157
+ ; forall(member(ToolName/Arity, Tools),
2158
+ ( session_user_tool_head(SessionId, ToolName, Head),
2159
+ ( session_user_tool_types(SessionId, ToolName, Types) -> true ; Types = none ),
2160
+ ( session_user_tool_desc(SessionId, ToolName, Desc), Desc \== none -> true ; Desc = "" ),
2161
+ format("~w/~w~n % tool ~q", [ToolName, Arity, Head]),
2162
+ ( Types == none
2163
+ -> true
2164
+ ; format(" ~w", [Types])
2165
+ ),
2166
+ format(" — ~w~n", [Desc]),
2167
+ ( SessionId:tool_source(ToolName, Source)
2168
+ -> format("~w~n", [Source])
2169
+ ; true
2170
+ )
2171
+ ))
1499
2172
  ).
1500
2173
 
1501
2174
  %% A filter either names a predicate (`name/arity`), names a prefix, or is `all`.
@@ -1687,6 +2360,222 @@ record_directive(SessionId, Directive) :-
1687
2360
  export_harness(SessionId, Header, Text) :-
1688
2361
  with_output_to(string(Text), export_harness_output(SessionId, Header)).
1689
2362
 
2363
+ %% repl_shell_json(+SessionId, -Json)
2364
+ %%
2365
+ %% How the harness wants to be presented in Work mode. Two shapes are accepted:
2366
+ %%
2367
+ %% shell(agent([system("…"), host_tools(show_image, execute)]),
2368
+ %% workflows([name("Check mail"), predicate([goal(check_mail), args([(string:"Account")])])]),
2369
+ %% welcome("## …")).
2370
+ %%
2371
+ %% shell(workflow([goal(entry_point), args([(string:"Param 1")])])).
2372
+ %%
2373
+ %% A `shell(_{...})` dict is the third form. Everything is normalized to one
2374
+ %% JSON object; a harness without a shell is `null` and Work keeps its old view.
2375
+ repl_shell_json(SessionId, Json) :-
2376
+ ( repl_shell_spec(SessionId, Spec)
2377
+ -> atom_json_dict(Json, Spec, [])
2378
+ ; Json = "null"
2379
+ ).
2380
+
2381
+ repl_shell_spec(SessionId, Spec) :-
2382
+ ( clause(SessionId:shell(One), true)
2383
+ -> shell_from_one(One, Spec)
2384
+ ; clause(SessionId:shell(Agent, Workflows, Welcome), true)
2385
+ -> shell_from_parts(Agent, Workflows, Welcome, Spec)
2386
+ ).
2387
+
2388
+ shell_from_one(workflow(Items), Spec) :-
2389
+ !,
2390
+ workflow_from(workflow(Items), Workflow),
2391
+ Spec = shell_spec{kind: workflow, system: "", hostTools: [], tools: [], workflows: [Workflow], welcome: ""}.
2392
+ shell_from_one(Dict, Spec) :-
2393
+ is_dict(Dict),
2394
+ !,
2395
+ shell_from_dict(Dict, Spec).
2396
+ shell_from_one(agent(Items), Spec) :-
2397
+ !,
2398
+ agent_items(Items, System, Tools),
2399
+ Spec = shell_spec{kind: agent, system: System, hostTools: Tools, tools: [], workflows: [], welcome: ""}.
2400
+
2401
+ shell_from_parts(AgentTerm, WorkflowsTerm, WelcomeTerm, Spec) :-
2402
+ agent_term(AgentTerm, System, Tools),
2403
+ workflows_term(WorkflowsTerm, Workflows),
2404
+ ( WelcomeTerm = welcome(Welcome0)
2405
+ -> text_value(Welcome0, Welcome)
2406
+ ; text_value(WelcomeTerm, Welcome)
2407
+ ),
2408
+ Spec = shell_spec{kind: agent, system: System, hostTools: Tools, tools: [], workflows: Workflows, welcome: Welcome}.
2409
+
2410
+ shell_from_dict(Dict, Spec) :-
2411
+ ( get_dict(kind, Dict, Kind0)
2412
+ -> text_value(Kind0, Kind)
2413
+ ; shell_infer_kind(Dict, Kind)
2414
+ ),
2415
+ ( get_dict(system, Dict, Sys0) -> text_value(Sys0, System) ; System = "" ),
2416
+ ( get_dict(host_tools, Dict, Tools0)
2417
+ -> host_tools_value(Tools0, Tools)
2418
+ ; get_dict(hostTools, Dict, Tools1)
2419
+ -> host_tools_value(Tools1, Tools)
2420
+ ; Tools = ["show_image", "execute"]
2421
+ ),
2422
+ ( get_dict(tools, Dict, ToolsList0) -> tools_term(ToolsList0, ToolSpecs) ; ToolSpecs = [] ),
2423
+ ( get_dict(workflows, Dict, Wfs0) -> workflows_term(Wfs0, Workflows) ; Workflows = [] ),
2424
+ ( get_dict(welcome, Dict, Welcome0) -> text_value(Welcome0, Welcome) ; Welcome = "" ),
2425
+ Spec = shell_spec{kind: Kind, system: System, hostTools: Tools, tools: ToolSpecs, workflows: Workflows, welcome: Welcome}.
2426
+
2427
+ shell_infer_kind(Dict, Kind) :-
2428
+ ( get_dict(system, Dict, _)
2429
+ ; get_dict(host_tools, Dict, _)
2430
+ ; get_dict(hostTools, Dict, _)
2431
+ ),
2432
+ !,
2433
+ Kind = agent.
2434
+ shell_infer_kind(_, workflow).
2435
+
2436
+ agent_term(agent(Items), System, Tools) :- !, agent_items(Items, System, Tools).
2437
+ agent_term(Items, System, Tools) :- is_list(Items), !, agent_items(Items, System, Tools).
2438
+ agent_term(_, "", ["show_image", "execute"]).
2439
+
2440
+ agent_items(Items, System, Tools) :-
2441
+ ( member(system(S), Items) -> text_value(S, System) ; System = "" ),
2442
+ ( member(Term, Items),
2443
+ compound(Term),
2444
+ ( compound_name_arity(Term, host_tools, _) ; compound_name_arity(Term, hostTools, _) )
2445
+ -> Term =.. [_|Args],
2446
+ host_tools_args(Args, Tools)
2447
+ ; Tools = ["show_image", "execute"]
2448
+ ).
2449
+
2450
+ host_tools_args([Single], Tools) :-
2451
+ is_list(Single),
2452
+ !,
2453
+ host_tools_value(Single, Tools).
2454
+ host_tools_args(Args, Tools) :-
2455
+ maplist(text_value, Args, Tools).
2456
+
2457
+ host_tools_value(Tools, Normalized) :-
2458
+ ( is_list(Tools)
2459
+ -> maplist(text_value, Tools, Normalized)
2460
+ ; Normalized = []
2461
+ ).
2462
+
2463
+ workflows_term(workflows(Items), Workflows) :- !, workflows_list(Items, Workflows).
2464
+ workflows_term(Items, Workflows) :- is_list(Items), !, workflows_list(Items, Workflows).
2465
+ workflows_term(Item, [Workflow]) :- workflow_from(Item, Workflow).
2466
+
2467
+ workflows_list([], []).
2468
+ workflows_list([name(Name), predicate(Pred)|Rest], [Workflow|Workflows]) :-
2469
+ !,
2470
+ text_value(Name, N),
2471
+ workflow_from_parts(N, Pred, Workflow),
2472
+ workflows_list(Rest, Workflows).
2473
+ workflows_list([name(Name), workflow(Pred)|Rest], [Workflow|Workflows]) :-
2474
+ !,
2475
+ text_value(Name, N),
2476
+ workflow_from_parts(N, Pred, Workflow),
2477
+ workflows_list(Rest, Workflows).
2478
+ workflows_list([Item|Rest], [Workflow|Workflows]) :-
2479
+ workflow_from(Item, Workflow),
2480
+ workflows_list(Rest, Workflows).
2481
+
2482
+ workflow_from(Dict, Workflow) :-
2483
+ is_dict(Dict),
2484
+ !,
2485
+ workflow_dict_parts(Dict, Name, Goal, Inputs, Outputs),
2486
+ Workflow = shell_workflow{name: Name, goal: Goal, inputs: Inputs, outputs: Outputs}.
2487
+
2488
+ workflow_dict_parts(Dict, Name, Goal, Inputs, Outputs) :-
2489
+ ( get_dict(name, Dict, Name0) -> text_value(Name0, Name) ; Name = "" ),
2490
+ ( get_dict(goal, Dict, Goal0) -> text_value(Goal0, Goal) ; Goal = "" ),
2491
+ ( get_dict(inputs, Dict, In0) -> workflow_args(In0, Inputs)
2492
+ ; get_dict(args, Dict, Args0) -> workflow_args(Args0, Inputs)
2493
+ ; Inputs = []
2494
+ ),
2495
+ ( get_dict(outputs, Dict, Out0) -> workflow_args(Out0, Outputs) ; Outputs = [] ).
2496
+
2497
+ tool_from(Dict, Tool) :-
2498
+ is_dict(Dict),
2499
+ !,
2500
+ workflow_dict_parts(Dict, Name, Goal, Inputs, Outputs),
2501
+ ( get_dict(description, Dict, Desc0) -> text_value(Desc0, Description) ; Description = "" ),
2502
+ Tool = shell_tool{name: Name, goal: Goal, inputs: Inputs, outputs: Outputs, description: Description}.
2503
+
2504
+ tools_term(Tools, ToolsOut) :-
2505
+ ( is_list(Tools) -> maplist(tool_from, Tools, ToolsOut) ; ToolsOut = [] ).
2506
+ workflow_from(workflow(Name, Pred), Workflow) :- !, text_value(Name, N), workflow_from_parts(N, Pred, Workflow).
2507
+ workflow_from(workflow(Pred), Workflow) :- !, workflow_from_parts("", Pred, Workflow).
2508
+ workflow_from(predicate(Pred), Workflow) :- !, workflow_from_parts("", Pred, Workflow).
2509
+
2510
+ workflow_from_parts(Name, Pred, Workflow) :-
2511
+ ( Pred = predicate(Items) -> true ; Items = Pred ),
2512
+ ( is_list(Items)
2513
+ -> ( member(goal(Goal0), Items) -> text_value(Goal0, Goal) ; Goal = "" ),
2514
+ ( member(inputs(Inputs0), Items) -> workflow_args(Inputs0, Inputs)
2515
+ ; member(args(Args0), Items) -> workflow_args(Args0, Inputs)
2516
+ ; Inputs = []
2517
+ ),
2518
+ ( member(outputs(Outputs0), Items) -> workflow_args(Outputs0, Outputs) ; Outputs = [] )
2519
+ ; text_value(Pred, Goal), Inputs = [], Outputs = []
2520
+ ),
2521
+ ( Name == "" -> WorkflowName = Goal ; WorkflowName = Name ),
2522
+ Workflow = shell_workflow{name: WorkflowName, goal: Goal, inputs: Inputs, outputs: Outputs}.
2523
+
2524
+ workflow_args(Args, Normalized) :-
2525
+ ( Args = args(Inner) -> true ; Inner = Args ),
2526
+ ( is_list(Inner) -> maplist(workflow_arg, Inner, Normalized) ; Normalized = [] ).
2527
+
2528
+ workflow_arg(Type:Label, shell_arg{name: Name, type: TypeText}) :-
2529
+ !,
2530
+ text_value(Label, Name),
2531
+ text_value(Type, TypeText).
2532
+ workflow_arg(Dict, shell_arg{name: Name, type: TypeText}) :-
2533
+ is_dict(Dict),
2534
+ !,
2535
+ ( get_dict(name, Dict, N0) -> text_value(N0, Name) ; Name = "" ),
2536
+ ( get_dict(type, Dict, T0) -> text_value(T0, TypeText) ; TypeText = "string" ).
2537
+ workflow_arg(arg(Name0, Type0), shell_arg{name: Name, type: TypeText}) :-
2538
+ !,
2539
+ text_value(Name0, Name),
2540
+ text_value(Type0, TypeText).
2541
+ workflow_arg(Value, shell_arg{name: Value, type: "string"}) :- atom(Value), !.
2542
+ workflow_arg(Value, shell_arg{name: Value, type: "string"}) :- string(Value), !.
2543
+ workflow_arg(_, shell_arg{name: "", type: "string"}).
2544
+
2545
+ text_value(Value, Text) :-
2546
+ ( string(Value) -> Text = Value
2547
+ ; atom(Value) -> atom_string(Value, Text)
2548
+ ; number(Value) -> number_string(Value, Text)
2549
+ ; Text = ""
2550
+ ).
2551
+
2552
+ %% repl_display_harness(+SessionId, -Text)
2553
+ %% The same module as `export_harness/3`, but for humans: clauses come from the
2554
+ %% stored source view, so variable names, `{Var}` and `schema(...)` are the ones
2555
+ %% the author wrote. Export keeps its deterministic A/B numbering for hashing and
2556
+ %% byte-stable round-trips.
2557
+ repl_display_harness(SessionId, Text) :-
2558
+ with_output_to(string(Text), repl_display_output(SessionId)).
2559
+
2560
+ repl_display_output(SessionId) :-
2561
+ export_directives(SessionId),
2562
+ export_tools(SessionId),
2563
+ repl_display_clauses(SessionId).
2564
+
2565
+ repl_display_clauses(SessionId) :-
2566
+ findall(Name/Arity,
2567
+ ( current_predicate(SessionId:Name/Arity),
2568
+ export_user_predicate(SessionId, Name, Arity)
2569
+ ),
2570
+ Preds0),
2571
+ sort(Preds0, Preds),
2572
+ forall(member(Name/Arity, Preds),
2573
+ ( session_source_view(SessionId, Name/Arity, SourceView)
2574
+ -> format("~w~n", [SourceView])
2575
+ ; functor(Head, Name, Arity),
2576
+ forall(clause(SessionId:Head, Body), export_clause(Head, Body))
2577
+ )).
2578
+
1690
2579
  export_harness_output(SessionId, Header) :-
1691
2580
  ( Header == none
1692
2581
  -> true
@@ -1949,6 +2838,8 @@ repl_assert(SessionId, ClauseText, Result) :-
1949
2838
  repl_require_new_predicate(SessionId, PreparedTerm)),
1950
2839
  forall(member(PreparedTerm, PreparedTerms),
1951
2840
  repl_assert_clause(PreparedTerm, SessionId)),
2841
+ repl_source_views(SessionId, ClauseText, Views),
2842
+ repl_store_source_views(SessionId, Views, append),
1952
2843
  Result = ok
1953
2844
  ),
1954
2845
  AssertError,
@@ -1990,10 +2881,77 @@ repl_set_prolog_snippets(SessionId, Text) :-
1990
2881
  %% repl_parse_clauses(+SessionId, +ClausesText, -Terms)
1991
2882
  %% Parse and preprocess a block of DML clauses without asserting them.
1992
2883
  repl_parse_clauses(SessionId, ClausesText, Terms) :-
2884
+ repl_parse_clauses(SessionId, ClausesText, Terms, _Views).
2885
+
2886
+ %% repl_parse_clauses/4 also returns the source view: the block as written, with
2887
+ %% the author's variable names, before task/N rewriting. Asserting a clause loses
2888
+ %% those names (listing used to show A, B, C), so the view is what listing prints.
2889
+ repl_parse_clauses(SessionId, ClausesText, Terms, Views) :-
1993
2890
  ensure_full_stop(ClausesText, Text1),
1994
2891
  open_string(Text1, Stream),
1995
2892
  repl_read_prepared_terms(Stream, SessionId, Terms),
1996
- close(Stream).
2893
+ close(Stream),
2894
+ repl_source_views(SessionId, ClausesText, Views).
2895
+
2896
+ %% repl_source_views(+Text, -Views): Indicator-Source pairs, one per clause.
2897
+ %% A source view is best-effort: it only improves `listing`. Read the text as it
2898
+ %% is first — a comment-only harness (the export header) and an empty string are
2899
+ %% both valid, and `ensure_full_stop` would append a lone `.` after the comment,
2900
+ %% which the reader rejects with `end_of_clause`. Only when the final clause
2901
+ %% lacks a full stop does a retry with one make sense.
2902
+ repl_source_views(SessionId, Text, Views) :-
2903
+ ( catch(repl_source_views_raw(SessionId, Text, Views0), _, fail)
2904
+ -> Views = Views0
2905
+ ; catch(( ensure_full_stop(Text, Text1),
2906
+ repl_source_views_raw(SessionId, Text1, Views)
2907
+ ), _, Views = [])
2908
+ ).
2909
+
2910
+ repl_source_views_raw(SessionId, Text, Views) :-
2911
+ open_string(Text, Stream),
2912
+ call_cleanup(repl_source_views_loop(Stream, SessionId, Views), close(Stream)).
2913
+
2914
+ repl_source_views_loop(Stream, SessionId, Views) :-
2915
+ read_term(Stream, Term, [module(SessionId), variable_names(Bindings)]),
2916
+ ( Term == end_of_file
2917
+ -> Views = []
2918
+ ; ( repl_term_indicator(Term, Indicator)
2919
+ -> with_output_to(string(Body),
2920
+ write_term(Term, [variable_names(Bindings), quoted(true)])),
2921
+ format(string(Source), "~w.~n", [Body]),
2922
+ Views = [Indicator-Source|Rest]
2923
+ ; Views = Rest
2924
+ ),
2925
+ repl_source_views_loop(Stream, SessionId, Rest)
2926
+ ).
2927
+
2928
+ %% repl_store_source_views(+SessionId, +Views, +Mode)
2929
+ %% Mode is `replace` (define) or `append` (assert).
2930
+ repl_store_source_views(SessionId, Views, Mode) :-
2931
+ keysort(Views, Sorted),
2932
+ repl_store_view_groups(SessionId, Sorted, Mode).
2933
+
2934
+ repl_store_view_groups(_, [], _).
2935
+ repl_store_view_groups(SessionId, [Indicator-Source|Rest], Mode) :-
2936
+ repl_same_indicator(Indicator, Rest, [Source], Sources, Remaining),
2937
+ atomic_list_concat(Sources, '', NewText),
2938
+ ( Mode == append,
2939
+ session_source_view(SessionId, Indicator, Existing)
2940
+ -> atomic_list_concat([Existing, NewText], '', Text)
2941
+ ; retractall(session_source_view(SessionId, Indicator, _)),
2942
+ Text = NewText
2943
+ ),
2944
+ assertz(session_source_view(SessionId, Indicator, Text)),
2945
+ repl_store_view_groups(SessionId, Remaining, Mode).
2946
+
2947
+ repl_same_indicator(Indicator, [Indicator-Source|Rest], Acc, [Source|Same], Remaining) :-
2948
+ !,
2949
+ repl_same_indicator(Indicator, Rest, Acc, Same, Remaining).
2950
+ repl_same_indicator(_, Rest, Acc, Acc, Rest).
2951
+
2952
+ %% repl_drop_source_view(+SessionId, +Indicator)
2953
+ repl_drop_source_view(SessionId, Indicator) :-
2954
+ retractall(session_source_view(SessionId, Indicator, _)).
1997
2955
 
1998
2956
  repl_read_prepared_terms(Stream, SessionId, Terms) :-
1999
2957
  read_term(Stream, Term, [module(SessionId), variable_names(Bindings)]),
@@ -2042,9 +3000,21 @@ repl_commit_terms(SessionId, Terms) :-
2042
3000
  ( repl_protected_clause(PreparedTerm)
2043
3001
  -> throw(error(permission_error(modify, reserved_name, PreparedTerm),
2044
3002
  context(repl_assert_many/3, 'cannot define a reserved predicate')))
3003
+ ; repl_replace_annotation(SessionId, PreparedTerm)
3004
+ -> process_clause(PreparedTerm, SessionId)
2045
3005
  ; process_clause(PreparedTerm, SessionId)
2046
3006
  )).
2047
3007
 
3008
+ %% repl_replace_annotation(+SessionId, +Term)
3009
+ %% Remove the existing entry with the same key before asserting the new one.
3010
+ repl_replace_annotation(SessionId, Term) :-
3011
+ repl_annotation_key(Term, AnnotationName, Key),
3012
+ current_predicate(SessionId:AnnotationName/2),
3013
+ functor(Template, AnnotationName, 2),
3014
+ arg(1, Template, Key),
3015
+ retractall(SessionId:Template),
3016
+ !.
3017
+
2048
3018
  %% repl_assert_many(+SessionId, +ClausesText, -Result)
2049
3019
  %% Parses a block of clauses and asserts them in the order written. Prefer this
2050
3020
  %% for defining a predicate: clause order matters for backtracking, so asserting
@@ -2052,12 +3022,13 @@ repl_commit_terms(SessionId, Terms) :-
2052
3022
  repl_assert_many(SessionId, ClausesText, Result) :-
2053
3023
  catch(
2054
3024
  ( guard_not_frozen(SessionId),
2055
- repl_parse_clauses(SessionId, ClausesText, Terms),
3025
+ repl_parse_clauses(SessionId, ClausesText, Terms, SourceViews),
2056
3026
  % assert appends; against an existing predicate that leaves both
2057
3027
  % versions live with their clauses interleaved.
2058
3028
  forall(member(Term, Terms), repl_require_new_predicate(SessionId, Term)),
2059
3029
  repl_commit_terms(SessionId, Terms),
2060
3030
  repl_note_touched(SessionId, Terms),
3031
+ repl_store_source_views(SessionId, SourceViews, append),
2061
3032
  Result = ok
2062
3033
  ),
2063
3034
  AssertError,
@@ -2068,6 +3039,7 @@ repl_assert_many(SessionId, ClausesText, Result) :-
2068
3039
  %% The plain predicate a parsed clause defines. Directives and tool/2 wrappers
2069
3040
  %% have no plain indicator here (process_clause owns them).
2070
3041
  repl_term_indicator((:- _), _) :- !, fail.
3042
+ repl_term_indicator('$dc_tool'(_, _), _) :- !, fail.
2071
3043
  repl_term_indicator((tool(_, _) :- _), _) :- !, fail.
2072
3044
  repl_term_indicator((tool(_, _, _) :- _), _) :- !, fail.
2073
3045
  repl_term_indicator((tool(_) :- _), _) :- !, fail.
@@ -2093,80 +3065,129 @@ repl_note_indicator(SessionId, Name/Arity) :-
2093
3065
  %% that mixes the old and the new version — both stay live, clause order
2094
3066
  %% interleaves them, and nothing says so. Refuse instead, and name the remedy.
2095
3067
  repl_require_new_predicate(SessionId, Term) :-
2096
- repl_term_indicator(Term, Name/Arity),
2097
- findall(x,
3068
+ % Annotation facts (`doc/2`, `schema/2`, `script_file/2`) are keyed records,
3069
+ % not appendable clauses: a new key is fine, an existing key must be replaced.
3070
+ ( repl_annotation_key(Term, AnnotationName, Key)
3071
+ -> ( functor(AnnotationTemplate, AnnotationName, 2),
3072
+ clause(SessionId:AnnotationTemplate, Body),
3073
+ repl_annotation_clause_key(AnnotationName, Body, Key)
3074
+ -> format(atom(AnnotationMessage),
3075
+ '~w(~w, …) already exists. Use define("~w", "…") to replace that entry (other entries are kept).',
3076
+ [AnnotationName, Key, AnnotationName]),
3077
+ throw(error(permission_error(modify, existing_annotation, AnnotationName),
3078
+ context(repl_require_new_predicate/2, AnnotationMessage)))
3079
+ ; true
3080
+ )
3081
+ ; repl_term_indicator(Term, Name/Arity),
3082
+ findall(x,
2098
3083
  ( functor(Head, Name, Arity),
2099
3084
  clause(SessionId:Head, _)
2100
3085
  ),
2101
3086
  Existing),
2102
- Existing \== [],
2103
- !,
2104
- length(Existing, Count),
2105
- format(atom(Message),
2106
- '~w/~w already has ~w clause(s). assert appends, so the old and the new clauses would both be present and clause order would interleave them. Use define("~w/~w", "...") to replace the predicate, or delete("~w/~w") first.',
2107
- [Name, Arity, Count, Name, Arity, Name, Arity]),
2108
- throw(error(permission_error(modify, existing_predicate, Name/Arity),
2109
- context(repl_require_new_predicate/2, Message))).
3087
+ Existing \== [],
3088
+ !,
3089
+ length(Existing, Count),
3090
+ format(atom(Message),
3091
+ '~w/~w already has ~w clause(s). assert appends, so the old and the new clauses would both be present and clause order would interleave them. Use define("~w/~w", "...") to replace the predicate, or delete("~w/~w") first.',
3092
+ [Name, Arity, Count, Name, Arity, Name, Arity]),
3093
+ throw(error(permission_error(modify, existing_predicate, Name/Arity),
3094
+ context(repl_require_new_predicate/2, Message)))
3095
+ ).
2110
3096
  repl_require_new_predicate(_SessionId, _Term).
2111
3097
 
3098
+ %% repl_annotation_key(+Term, -Name, -Key)
3099
+ %% The annotation predicates whose entries are keyed: one per documented
3100
+ %% predicate, schema or linked script. Defining one entry must not delete the
3101
+ %% others, which is exactly what "replace the whole predicate" used to do.
3102
+ repl_annotation_key(doc(Key, _), doc, Key) :- !.
3103
+ repl_annotation_key(schema(Key, _), schema, Key) :- !.
3104
+ repl_annotation_key(script_file(Key, _), script_file, Key).
3105
+ repl_annotation_key((Head :- _), Name, Key) :- !, repl_annotation_key(Head, Name, Key).
3106
+
3107
+ repl_annotation_clause_key(doc, doc(Key, _), Key) :- !.
3108
+ repl_annotation_clause_key(schema, schema(Key, _), Key) :- !.
3109
+ repl_annotation_clause_key(script_file, script_file(Key, _), Key).
3110
+
3111
+ repl_annotation_predicate(doc, 2).
3112
+ repl_annotation_predicate(schema, 2).
3113
+ repl_annotation_predicate(script_file, 2).
3114
+
2112
3115
  %% repl_forget_tool(+SessionId, +Name)
2113
- %% Drop the tool annotation that belonged to a predicate being removed.
3116
+ %% Drop the tool annotation that belonged to a predicate being removed, and the
3117
+ %% `tool/1` implementation clause that carried it. Leaving the implementation
3118
+ %% behind meant a later `task/N` still offered the old body while the export
3119
+ %% carried the new one, so the live session and the exported harness disagreed.
2114
3120
  repl_forget_tool(SessionId, Name) :-
2115
3121
  ( session_user_tools(SessionId, Name)
2116
3122
  -> retractall(session_user_tools(SessionId, Name)),
2117
3123
  retractall(session_user_tool_schema(SessionId, Name, _)),
3124
+ retractall(session_user_tool_arity(SessionId, Name, _)),
3125
+ retractall(session_user_tool_head(SessionId, Name, _)),
3126
+ retractall(session_user_tool_desc(SessionId, Name, _)),
3127
+ retractall(session_user_tool_names(SessionId, Name, _)),
3128
+ retractall(session_user_tool_types(SessionId, Name, _)),
3129
+ retractall(session_user_tool_body(SessionId, Name, _)),
2118
3130
  catch(retractall(SessionId:tool_source(Name, _)), _, true)
2119
3131
  ; true
2120
- ).
3132
+ ),
3133
+ repl_forget_tool_clauses(SessionId, Name).
3134
+
3135
+ %% repl_forget_tool_clauses(+SessionId, +Name)
3136
+ %% Every `tool(Head) :- Body` whose head is this tool. The clause lives in the
3137
+ %% module's `tool/1` predicate, so it cannot be abolished by name/arity.
3138
+ repl_forget_tool_clauses(SessionId, Name) :-
3139
+ forall(( clause(SessionId:tool(Head), Body), compound(Head), functor(Head, Name, _) ),
3140
+ ( Body == true
3141
+ -> retract(SessionId:tool(Head))
3142
+ ; retract(SessionId:(tool(Head) :- Body))
3143
+ )).
2121
3144
 
2122
3145
  %% repl_capture_predicates(+SessionId, +Indicators, -Captured)
2123
3146
  %% Copy the clauses and tool bookkeeping a replacement is about to destroy, so
2124
3147
  %% a failure part-way through can put them back.
2125
3148
  repl_capture_predicates(SessionId, Indicators, Captured) :-
2126
- findall(indicator(Name, Arity, Clauses, tool(IsTool, Schema, Source)),
3149
+ findall(indicator(Name, Arity, Clauses, ToolInfo),
2127
3150
  ( member(Name/Arity, Indicators),
2128
- findall(Stored,
2129
- ( functor(Head, Name, Arity),
2130
- clause(SessionId:Head, Body),
2131
- ( Body == true
2132
- -> Stored = Head
2133
- ; Stored = (Head :- Body)
2134
- )
2135
- ),
2136
- Clauses),
2137
- ( session_user_tools(SessionId, Name)
2138
- -> IsTool = true
2139
- ; IsTool = false
2140
- ),
2141
- ( session_user_tool_schema(SessionId, Name, Found)
2142
- -> Schema = Found
2143
- ; Schema = none
2144
- ),
2145
- ( current_predicate(SessionId:tool_source/2),
2146
- SessionId:tool_source(Name, FoundSource)
2147
- -> Source = FoundSource
2148
- ; Source = none
2149
- )
3151
+ findall(Stored, capture_clause(SessionId, Name, Arity, Stored), Clauses),
3152
+ capture_tool_info(SessionId, Name, ToolInfo)
2150
3153
  ),
2151
3154
  Captured).
2152
3155
 
3156
+ capture_clause(SessionId, Name, Arity, Stored) :-
3157
+ functor(Head, Name, Arity),
3158
+ clause(SessionId:Head, Body),
3159
+ ( Body == true
3160
+ -> Stored = Head
3161
+ ; Stored = (Head :- Body)
3162
+ ).
3163
+
3164
+ capture_tool_info(SessionId, Name, ToolInfo) :-
3165
+ ( session_user_tools(SessionId, Name),
3166
+ \+ session_builtin_tool(SessionId, Name),
3167
+ % Head and Body must come from the *same* clause: reading the stored head
3168
+ % and body separately gives two copies with unrelated variables, and the
3169
+ % restored tool then delegates to an unbound goal.
3170
+ clause(SessionId:tool(Head), Body),
3171
+ compound(Head),
3172
+ functor(Head, Name, _),
3173
+ session_user_tool_desc(SessionId, Name, Desc)
3174
+ -> ( session_user_tool_names(SessionId, Name, Names) -> true ; Names = [] ),
3175
+ ( session_user_tool_types(SessionId, Name, Types) -> true ; Types = none ),
3176
+ ToolInfo = tool(true, tool_meta(Head, Desc, Names, Types, Body))
3177
+ ; ToolInfo = none
3178
+ ).
3179
+
2153
3180
  %% repl_restore_captured(+SessionId, +Captured)
2154
3181
  repl_restore_captured(SessionId, Captured) :-
2155
- forall(member(indicator(Name, Arity, Clauses, tool(IsTool, Schema, Source)), Captured),
2156
- ( catch(abolish(SessionId:Name/Arity), _, true),
3182
+ forall(member(indicator(Name, Arity, Clauses, ToolInfo), Captured),
3183
+ ( % Only the arity this transaction touched: other arities of the same
3184
+ % name were never part of it.
3185
+ catch(abolish(SessionId:Name/Arity), _, true),
2157
3186
  repl_forget_tool(SessionId, Name),
2158
3187
  forall(member(Clause, Clauses), assertz(SessionId:Clause)),
2159
- ( IsTool == true
2160
- -> assertz(session_user_tools(SessionId, Name))
3188
+ ( ToolInfo = tool(true, tool_meta(Head, Desc, Names, Types, Body))
3189
+ -> catch(repl_register_tool(SessionId, Head, Desc, Types, Body, Names), _, true)
2161
3190
  ; true
2162
- ),
2163
- ( Schema == none
2164
- -> true
2165
- ; assertz(session_user_tool_schema(SessionId, Name, Schema))
2166
- ),
2167
- ( Source == none
2168
- -> true
2169
- ; assertz(SessionId:tool_source(Name, Source))
2170
3191
  )
2171
3192
  )).
2172
3193
 
@@ -2174,7 +3195,12 @@ repl_restore_captured(SessionId, Captured) :-
2174
3195
  %% The destructive half of define: abolish the targets, then assert the block.
2175
3196
  repl_replace_predicates(SessionId, Indicators, Terms) :-
2176
3197
  forall(member(Name/Arity, Indicators),
2177
- ( catch(abolish(SessionId:Name/Arity), _, true),
3198
+ ( % Annotation predicates merge per key (repl_commit_terms replaces the
3199
+ % entry the block defines); abolishing them deleted every other
3200
+ % predicate's doc/schema/script link.
3201
+ repl_annotation_predicate(Name, Arity)
3202
+ -> true
3203
+ ; catch(abolish(SessionId:Name/Arity), _, true),
2178
3204
  repl_forget_tool(SessionId, Name)
2179
3205
  )),
2180
3206
  repl_commit_terms(SessionId, Terms).
@@ -2220,58 +3246,110 @@ repl_retract(SessionId, ClauseText, Result) :-
2220
3246
  catch(
2221
3247
  ( guard_not_frozen(SessionId),
2222
3248
  repl_read_clause(SessionId, ClauseText, Pattern),
2223
- repl_head_of(Pattern, Clause),
2224
- repl_callable_indicator(Clause, Name, Arity),
2225
- ( repl_protected_clause(Clause)
2226
- -> throw(error(permission_error(modify, reserved_name, Clause),
2227
- context(repl_retract/3, 'cannot retract a reserved predicate')))
2228
- ; true
2229
- ),
2230
- findall(x, retract(SessionId:Pattern), Removed),
2231
- length(Removed, RemovedCount),
2232
- ( RemovedCount =:= 0
2233
- -> format(atom(Message),
2234
- 'no clause of ~w/~w matched ~w, so nothing was removed',
2235
- [Name, Arity, Clause]),
2236
- throw(error(existence_error(clause, Clause),
2237
- context(repl_retract/3, Message)))
2238
- ; true
2239
- ),
2240
- % Only drop the tool annotation when the predicate is really gone;
2241
- % other clauses of it may still be live.
2242
- ( functor(Head, Name, Arity),
2243
- clause(SessionId:Head, _)
2244
- -> true
2245
- ; repl_forget_tool(SessionId, Name)
2246
- ),
2247
- repl_note_indicator(SessionId, Name/Arity),
2248
- ( RemovedCount =:= 1
2249
- -> Suffix = ''
2250
- ; Suffix = 's'
2251
- ),
2252
- format(atom(Result), 'ok(removed ~w clause~w)', [RemovedCount, Suffix])
3249
+ ( repl_tool_pattern_name(Pattern, ToolName)
3250
+ -> repl_forget_tool(SessionId, ToolName),
3251
+ format(atom(Result), 'ok(removed tool ~w)', [ToolName])
3252
+ ; repl_retract_predicate_clause(SessionId, Pattern, Result)
3253
+ )
2253
3254
  ),
2254
3255
  RetractError,
2255
3256
  format(atom(Result), 'error(~w)', [RetractError])
2256
3257
  ).
2257
3258
 
3259
+ %% A `tool(...)` pattern names an annotation, not a module clause. The
3260
+ %% implementation lives in `tool/1` and the metadata outside the module, so the
3261
+ %% generic retract found nothing and reported "no clause of tool/2 matched" —
3262
+ %% while the tool stayed registered and the agent had no way to remove it.
3263
+ repl_tool_pattern_name(Pattern, Name) :-
3264
+ repl_tool_pattern_head(Pattern, Head),
3265
+ compound(Head),
3266
+ functor(Head, Name, _),
3267
+ \+ Name == tool_source.
3268
+
3269
+ repl_tool_pattern_head((tool(Head) :- _), Head) :- !.
3270
+ repl_tool_pattern_head((tool(Head, _) :- _), Head) :- !.
3271
+ repl_tool_pattern_head((tool(Head, _, _) :- _), Head) :- !.
3272
+ repl_tool_pattern_head(tool(Head), Head) :- !.
3273
+ repl_tool_pattern_head(tool(Head, _), Head) :- !.
3274
+ repl_tool_pattern_head(tool(Head, _, _), Head).
3275
+
3276
+ repl_retract_predicate_clause(SessionId, Pattern, Result) :-
3277
+ repl_head_of(Pattern, Clause),
3278
+ repl_callable_indicator(Clause, Name, Arity),
3279
+ ( session_harness_import(SessionId, Name/Arity, TargetModule, _)
3280
+ -> format(atom(ImportMessage),
3281
+ '~w/~w is imported read-only from ~w and cannot be retracted here.',
3282
+ [Name, Arity, TargetModule]),
3283
+ throw(error(permission_error(modify, imported_predicate, Name/Arity),
3284
+ context(repl_retract/3, ImportMessage)))
3285
+ ; true
3286
+ ),
3287
+ ( repl_protected_clause(Clause)
3288
+ -> throw(error(permission_error(modify, reserved_name, Clause),
3289
+ context(repl_retract/3, 'cannot retract a reserved predicate')))
3290
+ ; true
3291
+ ),
3292
+ findall(x, retract(SessionId:Pattern), Removed),
3293
+ length(Removed, RemovedCount),
3294
+ ( RemovedCount =:= 0
3295
+ -> format(atom(Message),
3296
+ 'no clause of ~w/~w matched ~w, so nothing was removed',
3297
+ [Name, Arity, Clause]),
3298
+ throw(error(existence_error(clause, Clause),
3299
+ context(repl_retract/3, Message)))
3300
+ ; true
3301
+ ),
3302
+ % Only drop the tool annotation when the predicate is really gone;
3303
+ % other clauses of it may still be live.
3304
+ ( functor(Head, Name, Arity),
3305
+ clause(SessionId:Head, _)
3306
+ -> true
3307
+ ; repl_forget_tool(SessionId, Name)
3308
+ ),
3309
+ repl_note_indicator(SessionId, Name/Arity),
3310
+ ( RemovedCount =:= 1
3311
+ -> Suffix = ''
3312
+ ; Suffix = 's'
3313
+ ),
3314
+ format(atom(Result), 'ok(removed ~w clause~w)', [RemovedCount, Suffix]).
3315
+
2258
3316
  %% repl_delete_predicate(+SessionId, +Name, +Arity, -Result)
2259
3317
  %% Fully remove a predicate. Unlike retract (which only removes matching
2260
3318
  %% clauses and can leave an empty predicate behind), this abolishes it.
2261
3319
  repl_delete_predicate(SessionId, Name, Arity, Result) :-
2262
3320
  catch(
2263
- ( guard_not_frozen(SessionId),
3321
+ ( mi_clear_cut_classes(SessionId),
3322
+ guard_not_frozen(SessionId),
2264
3323
  atom(Name), integer(Arity), Arity >= 0,
3324
+ ( session_harness_import(SessionId, Name/Arity, TargetModule, _)
3325
+ -> format(atom(ImportMessage),
3326
+ '~w/~w is imported read-only from ~w and cannot be deleted here.',
3327
+ [Name, Arity, TargetModule]),
3328
+ throw(error(permission_error(modify, imported_predicate, Name/Arity),
3329
+ context(repl_delete_predicate/4, ImportMessage)))
3330
+ ; true
3331
+ ),
2265
3332
  ( repl_protected_name(Name)
2266
3333
  -> throw(error(permission_error(modify, reserved_name, Name/Arity),
2267
3334
  context(repl_delete_predicate/4, 'cannot delete a reserved predicate')))
2268
3335
  ; true
2269
3336
  ),
3337
+ ( repl_annotation_predicate(Name, Arity)
3338
+ -> throw(error(permission_error(modify, annotation_predicate, Name/Arity),
3339
+ context(repl_delete_predicate/4,
3340
+ 'doc/2, schema/2 and script_file/2 are keyed annotations, not skills. Remove one entry with retract("doc(name/arity, _)") / retract("schema(name, _)") / retract("script_file(name, _)"), or replace it with define.')))
3341
+ ; true
3342
+ ),
3343
+ ( Name == tool
3344
+ -> throw(error(domain_error(delete_target, tool/Arity),
3345
+ context(repl_delete_predicate/4,
3346
+ 'tool/2 and tool/1 are the annotation mechanism, not a predicate to delete. To remove one tool use delete("tool:Name/Arity") or retract("tool(Head, _)").')))
3347
+ ; true
3348
+ ),
2270
3349
  catch(abolish(SessionId:Name/Arity), _, true),
3350
+ repl_drop_source_view(SessionId, Name/Arity),
2271
3351
  ( session_user_tools(SessionId, Name)
2272
- -> retractall(session_user_tools(SessionId, Name)),
2273
- retractall(session_user_tool_schema(SessionId, Name, _)),
2274
- retractall(SessionId:tool_source(Name, _))
3352
+ -> repl_forget_tool(SessionId, Name)
2275
3353
  ; true
2276
3354
  ),
2277
3355
  ( session_edit_touched(SessionId, Name/Arity)
@@ -2284,6 +3362,76 @@ repl_delete_predicate(SessionId, Name, Arity, Result) :-
2284
3362
  format(atom(Result), 'error(~w)', [DeleteError])
2285
3363
  ).
2286
3364
 
3365
+ %% repl_delete_doc(+SessionId, +Name, +Arity, -Result)
3366
+ %% Remove one keyed doc/2 entry, leaving every other doc entry alone.
3367
+ repl_delete_doc(SessionId, Name, Arity, Result) :-
3368
+ catch(
3369
+ ( guard_not_frozen(SessionId),
3370
+ integer(Arity),
3371
+ Key = Name/Arity,
3372
+ repl_delete_annotation_entry(SessionId, doc, Key, Result)
3373
+ ),
3374
+ DeleteError,
3375
+ format(atom(Result), 'error(~w)', [DeleteError])
3376
+ ).
3377
+
3378
+ %% repl_delete_schema(+SessionId, +Key, -Result)
3379
+ %% Remove one keyed schema/2 entry.
3380
+ repl_delete_schema(SessionId, Key, Result) :-
3381
+ catch(
3382
+ ( guard_not_frozen(SessionId),
3383
+ atom(Key),
3384
+ repl_delete_annotation_entry(SessionId, schema, Key, Result)
3385
+ ),
3386
+ DeleteError,
3387
+ format(atom(Result), 'error(~w)', [DeleteError])
3388
+ ).
3389
+
3390
+ %% repl_delete_script(+SessionId, +Key, -Result)
3391
+ %% Remove one keyed script_file/2 link.
3392
+ repl_delete_script(SessionId, Key, Result) :-
3393
+ catch(
3394
+ ( guard_not_frozen(SessionId),
3395
+ atom(Key),
3396
+ repl_delete_annotation_entry(SessionId, script_file, Key, Result)
3397
+ ),
3398
+ DeleteError,
3399
+ format(atom(Result), 'error(~w)', [DeleteError])
3400
+ ).
3401
+
3402
+ repl_delete_annotation_entry(SessionId, Kind, Key, Result) :-
3403
+ functor(Template, Kind, 2),
3404
+ arg(1, Template, Key),
3405
+ ( current_predicate(SessionId:Kind/2),
3406
+ clause(SessionId:Template, _)
3407
+ -> retractall(SessionId:Template),
3408
+ format(atom(Result), 'ok(removed ~w(~w))', [Kind, Key])
3409
+ ; format(atom(Annotation), '~w(~w)', [Kind, Key]),
3410
+ throw(error(existence_error(annotation, Annotation),
3411
+ context(repl_delete_annotation_entry/4,
3412
+ 'no such keyed annotation entry; check the key exactly')))
3413
+ ).
3414
+
3415
+ %% repl_delete_tool(+SessionId, +ToolName, -Result)
3416
+ %% `delete("tool:name/arity")`. Removes the annotation and its implementation,
3417
+ %% and leaves the delegate predicate alone — that is a skill in its own right.
3418
+ repl_delete_tool(SessionId, ToolName, Result) :-
3419
+ catch(
3420
+ ( guard_not_frozen(SessionId),
3421
+ atom(ToolName),
3422
+ ( session_user_tools(SessionId, ToolName)
3423
+ -> repl_forget_tool(SessionId, ToolName),
3424
+ Result = ok
3425
+ ; format(atom(Message),
3426
+ 'no tool named ~w is registered, so nothing was removed', [ToolName]),
3427
+ throw(error(existence_error(tool, ToolName),
3428
+ context(repl_delete_tool/3, Message)))
3429
+ )
3430
+ ),
3431
+ DeleteToolError,
3432
+ format(atom(Result), 'error(~w)', [DeleteToolError])
3433
+ ).
3434
+
2287
3435
  %% repl_define(+SessionId, +HeadPatternText, +ClausesText, -Result)
2288
3436
  %% Replace every predicate the clause block defines, all or nothing.
2289
3437
  %%
@@ -2295,13 +3443,16 @@ repl_delete_predicate(SessionId, Name, Arity, Result) :-
2295
3443
  %% clauses being replaced are copied first so a failure can still put them back.
2296
3444
  repl_define(SessionId, HeadPatternText, ClausesText, Result) :-
2297
3445
  catch(
2298
- ( guard_not_frozen(SessionId),
3446
+ ( mi_clear_cut_classes(SessionId),
3447
+ guard_not_frozen(SessionId),
2299
3448
  repl_define_target(SessionId, HeadPatternText, HeadName, HeadArity),
2300
- repl_parse_clauses(SessionId, ClausesText, Terms),
3449
+ repl_parse_clauses(SessionId, ClausesText, Terms, SourceViews),
2301
3450
  findall(Name/Arity,
2302
3451
  ( member(Term, Terms), repl_term_indicator(Term, Name/Arity) ),
2303
3452
  BlockIndicators0),
2304
3453
  sort(BlockIndicators0, BlockIndicators),
3454
+ forall(member(Term, Terms), repl_check_script_name_for_head(SessionId, Term)),
3455
+ repl_reject_script_predicate_collision(SessionId, HeadName, repl_define/4),
2305
3456
  % The head names the predicate being replaced. If it is not one of
2306
3457
  % them the target is almost certainly a typo, and silently replacing
2307
3458
  % a *different* predicate is worse than refusing.
@@ -2325,12 +3476,34 @@ repl_define(SessionId, HeadPatternText, ClausesText, Result) :-
2325
3476
  ))
2326
3477
  ),
2327
3478
  repl_note_touched(SessionId, Terms),
3479
+ repl_restore_kept_tools(SessionId, Captured),
3480
+ repl_store_source_views(SessionId, SourceViews, replace),
2328
3481
  Result = ok
2329
3482
  ),
2330
3483
  DefineError,
2331
3484
  format(atom(Result), 'error(~w)', [DefineError])
2332
3485
  ).
2333
3486
 
3487
+ %% repl_restore_kept_tools(+SessionId, +Captured)
3488
+ %%
3489
+ %% `define` replaces a predicate; the tool annotation is separate bookkeeping.
3490
+ %% It used to be dropped whenever the new block did not repeat the tool clause,
3491
+ %% so a perfectly good capability silently disappeared from the next `task/N`.
3492
+ %% Keep it when the delegate still exists at the same arity; a block that
3493
+ %% re-declares the tool has already registered it.
3494
+ repl_restore_kept_tools(SessionId, Captured) :-
3495
+ forall(member(indicator(Name, _Arity, _Clauses, ToolInfo), Captured),
3496
+ ( ToolInfo = tool(true, tool_meta(Head, Desc, Names, Types, Body)),
3497
+ \+ session_user_tools(SessionId, Name)
3498
+ -> Head =.. [Name|Args],
3499
+ length(Args, HeadArity),
3500
+ ( current_predicate(SessionId:Name/HeadArity)
3501
+ -> catch(repl_register_tool(SessionId, Head, Desc, Types, Body, Names), _, true)
3502
+ ; true
3503
+ )
3504
+ ; true
3505
+ )).
3506
+
2334
3507
  %% repl_define_target(+SessionId, +HeadText, -Name, -Arity)
2335
3508
  %% The first argument of `define` names the predicate being replaced, written as
2336
3509
  %% an indicator (`f/1`) or as a clause head (`f(_)`).
@@ -2349,22 +3522,47 @@ repl_define_target(SessionId, HeadText, Name, Arity) :-
2349
3522
  Arity = IndicatorArity
2350
3523
  ; repl_head_of(Pattern, HeadClause),
2351
3524
  repl_callable_indicator(HeadClause, Name, Arity)
3525
+ ),
3526
+ ( Name == tool
3527
+ -> throw(error(domain_error(define_target, tool/Arity),
3528
+ context(repl_define/4,
3529
+ 'define the predicate the tool delegates to, and put the tool(...) clause in the same block: define("up/2", "up(X, Y) :- ... . tool(up(X, Y), \"…\") :- up(X, Y).")')))
3530
+ ; true
2352
3531
  ).
2353
3532
 
2354
3533
  %% repl_require_committable(+SessionId, +Term)
2355
- repl_require_committable(_SessionId, Term) :-
3534
+ repl_require_committable(SessionId, Term) :-
2356
3535
  ( repl_protected_clause(Term)
2357
3536
  -> throw(error(permission_error(modify, reserved_name, Term),
2358
3537
  context(repl_define/4, 'cannot define a reserved predicate')))
2359
3538
  ; true
3539
+ ),
3540
+ ( catch(repl_head_of(Term, Head), _, fail),
3541
+ callable(Head),
3542
+ functor(Head, Name, Arity),
3543
+ session_harness_import(SessionId, Name/Arity, TargetModule, _)
3544
+ -> format(atom(ImportMessage),
3545
+ '~w/~w is imported read-only from ~w and cannot be redefined here.',
3546
+ [Name, Arity, TargetModule]),
3547
+ throw(error(permission_error(modify, imported_predicate, Name/Arity),
3548
+ context(repl_define/4, ImportMessage)))
3549
+ ; true
2360
3550
  ).
2361
3551
 
2362
3552
  %% repl_require_not_reserved(+SessionId, +Indicator)
2363
- repl_require_not_reserved(_SessionId, Name/Arity) :-
3553
+ repl_require_not_reserved(SessionId, Name/Arity) :-
2364
3554
  ( repl_protected_name(Name)
2365
3555
  -> throw(error(permission_error(modify, reserved_name, Name/Arity),
2366
3556
  context(repl_define/4, 'cannot define a reserved predicate')))
2367
3557
  ; true
3558
+ ),
3559
+ ( session_harness_import(SessionId, Name/Arity, TargetModule, _)
3560
+ -> format(atom(ImportMessage),
3561
+ '~w/~w is imported read-only from ~w and cannot be redefined here.',
3562
+ [Name, Arity, TargetModule]),
3563
+ throw(error(permission_error(modify, imported_predicate, Name/Arity),
3564
+ context(repl_define/4, ImportMessage)))
3565
+ ; true
2368
3566
  ).
2369
3567
 
2370
3568
  %% repl_extract_code(+Text, -Source)
@@ -2398,6 +3596,10 @@ repl_manifest(SessionId, Manifest) :-
2398
3596
  sort(Tools0, Tools),
2399
3597
  findall(Directive, session_directive(SessionId, Directive), Directives0),
2400
3598
  sort(Directives0, Directives),
3599
+ findall(Name/Arity-TargetModule,
3600
+ session_harness_import(SessionId, Name/Arity, TargetModule, _),
3601
+ Imports0),
3602
+ sort(Imports0, Imports),
2401
3603
  ( current_predicate(SessionId:module_doc/1),
2402
3604
  SessionId:module_doc(Summary0)
2403
3605
  -> Summary = Summary0
@@ -2415,6 +3617,7 @@ repl_manifest(SessionId, Manifest) :-
2415
3617
  ),
2416
3618
  format("- predicates: ~w~n", [Preds]),
2417
3619
  format("- tools: ~w~n", [Tools]),
3620
+ format("- imports: ~w~n", [Imports]),
2418
3621
  format("- directives: ~w~n", [Directives]),
2419
3622
  ( Docs0 == []
2420
3623
  -> format("- docs: (none; add doc(Name/Arity, Text) facts)~n")
@@ -2523,8 +3726,10 @@ repl_history_assert_term(Term, SessionId) :-
2523
3726
  %% memory is preserved.
2524
3727
  repl_rollback(SessionId, Source, Result) :-
2525
3728
  catch(
2526
- ( guard_not_frozen(SessionId),
3729
+ ( mi_clear_cut_classes(SessionId),
3730
+ guard_not_frozen(SessionId),
2527
3731
  repl_abolish_user_predicates(SessionId),
3732
+ retractall(session_source_view(SessionId, _, _)),
2528
3733
  retractall(session_directive(SessionId, _)),
2529
3734
  retractall(session_user_tools(SessionId, _)),
2530
3735
  retractall(session_user_tool_schema(SessionId, _, _)),
@@ -2562,7 +3767,13 @@ repl_harness_view(SessionId, Rows) :-
2562
3767
  ),
2563
3768
  format(atom(Row), "~w/~w|~w|~w", [Name, Arity, Clauses, FlagText])
2564
3769
  ),
2565
- Rows).
3770
+ OwnRows),
3771
+ findall(Row,
3772
+ ( session_harness_import(SessionId, Name/Arity, TargetModule, _),
3773
+ format(atom(Row), "~w/~w|0|imported,read-only,~w", [Name, Arity, TargetModule])
3774
+ ),
3775
+ ImportedRows),
3776
+ append(OwnRows, ImportedRows, Rows).
2566
3777
 
2567
3778
  repl_predicate_clause_count(SessionId, Name, Arity, Count) :-
2568
3779
  functor(Head, Name, Arity),
@@ -2598,9 +3809,15 @@ repl_user_predicates(SessionId, Preds) :-
2598
3809
  %% repl_user_predicates_text(+SessionId, -Text)
2599
3810
  %% Rendered "name/arity, name/arity" for change diffing on the host side.
2600
3811
  repl_user_predicates_text(SessionId, Text) :-
2601
- repl_user_predicates(SessionId, Preds),
3812
+ repl_user_predicates(SessionId, Preds0),
3813
+ % doc/2, schema/2 and script_file/2 are annotations. Reporting them as
3814
+ % changed predicates invited `delete(doc/2)`, which wipes every doc at once.
3815
+ exclude(repl_annotation_indicator, Preds0, Preds),
2602
3816
  with_output_to(string(Text), print_pred_list(Preds)).
2603
3817
 
3818
+ repl_annotation_indicator(Name/Arity) :-
3819
+ repl_annotation_predicate(Name, Arity).
3820
+
2604
3821
  %% repl_predicate_arities(+SessionId, +Name, -Arities)
2605
3822
  %% Sorted arities of a user predicate, e.g. agent_main -> [0,1,2]. Used by
2606
3823
  %% `deepclause run` to pick the agent_main/N to call for the given arguments.
@@ -2676,16 +3893,40 @@ repl_predicate_pure(SessionId, Name, Arity) :-
2676
3893
 
2677
3894
  %% repl_validate_tools(+SessionId, -Warnings)
2678
3895
  repl_validate_tools(SessionId, Warnings) :-
2679
- findall(W, tool_contract_violation(SessionId, W), Raw),
3896
+ findall(W,
3897
+ ( tool_contract_violation(SessionId, W)
3898
+ ; tool_shape_violation(SessionId, W)
3899
+ ),
3900
+ Raw),
2680
3901
  list_to_set(Raw, Warnings).
2681
3902
 
3903
+ %% tool_shape_violation(+SessionId, -Warning)
3904
+ %%
3905
+ %% A tool head has exactly one output, and it is the last argument. The type
3906
+ %% list labels only the inputs, so a mismatch means the author's `Content` is
3907
+ %% being offered to the model as an output — the `fs_write(Path, Content)` shape,
3908
+ %% which a nested agent cannot fill in. This used to be printed to stderr at
3909
+ %% registration time, where the agent never saw it.
3910
+ tool_shape_violation(SessionId, Warning) :-
3911
+ session_user_tools(SessionId, ToolName),
3912
+ \+ session_builtin_tool(SessionId, ToolName),
3913
+ session_user_tool_arity(SessionId, ToolName, Arity),
3914
+ session_user_tool_types(SessionId, ToolName, Types),
3915
+ is_list(Types),
3916
+ length(Types, Declared),
3917
+ Inputs is Arity - 1,
3918
+ Declared =\= Inputs,
3919
+ !,
3920
+ format(string(Warning),
3921
+ 'tool ~w/~w declares ~w input type(s) but has ~w input argument(s). The last argument of a tool head is its output; put several values in one dict or JSON string, or add an explicit result argument.',
3922
+ [ToolName, Arity, Declared, Inputs]).
3923
+
2682
3924
  %% repl_validate_docs(+SessionId, -Warnings)
2683
3925
  %%
2684
- %% `doc(Name/Arity, Text)` is an annotation: it documents a predicate, it does not
2685
- %% create one. A `doc/2` whose predicate has no clauses therefore names a goal that
2686
- %% fails silently when called — the failure surfaces far away as an empty result,
2687
- %% and the name still appears in the manifest, so the listing looks healthy.
2688
- %% Reported at `end_turn`, where the author can still see what they just wrote.
3926
+ %% `doc(Name/Arity, Text)` is an annotation: it documents a predicate, it does
3927
+ %% not create one. A `doc/2` whose predicate has no clauses names a goal that
3928
+ %% fails silently when called, and the name still appears in the manifest, so the
3929
+ %% listing looks healthy. Reported at `end_turn`.
2689
3930
  repl_validate_docs(SessionId, Warnings) :-
2690
3931
  findall(W, doc_without_clauses(SessionId, W), Raw),
2691
3932
  list_to_set(Raw, Warnings).
@@ -2704,6 +3945,9 @@ doc_without_clauses(SessionId, Warning) :-
2704
3945
  'doc(~w/~w) documents a predicate with no clauses, so calling it fails silently and yields an empty result. Define ~w/~w, or remove the doc/2.',
2705
3946
  [Name, Arity, Name, Arity]).
2706
3947
 
3948
+ %% tool_contract_violation(+SessionId, -Warning)
3949
+ %% A nested agent calls the tool body, so it must reach real logic with the same
3950
+ %% name and arity as its head.
2707
3951
  tool_contract_violation(SessionId, Warning) :-
2708
3952
  clause(SessionId:tool(Head), Body),
2709
3953
  compound(Head),
@@ -2717,8 +3961,8 @@ tool_contract_violation(SessionId, Warning) :-
2717
3961
  length(Args, CalleeArity),
2718
3962
  ( Callee == Name, CalleeArity == Arity, \+ repl_user_predicate(SessionId, Name, Arity)
2719
3963
  -> format(string(Warning),
2720
- 'tool ~w/~w calls the tool itself, so a nested agent recurses forever. Define ~w/~w separately and delegate to it: tool(~w(A,B), "…") :- ~w(A,B).',
2721
- [Name, Arity, Name, Name, Name, Name])
3964
+ 'tool ~w/~w calls ~w/~w, which does not exist, so a nested agent gets "Tool not found". Define ~w/~w and delegate to it: tool(~w(A, B), "…") :- ~w(A, B).',
3965
+ [Name, Arity, Callee, CalleeArity, Name, Arity, Name, Name])
2722
3966
  ; Callee == Name, CalleeArity \== Arity
2723
3967
  -> format(string(Warning),
2724
3968
  'tool ~w/~w declares a different arity than its body calls (~w/~w). A tool head and its delegate must match, with the output argument last.',
@@ -2749,9 +3993,78 @@ tool_body_goal(Body, Call) :-
2749
3993
  F \== (',').
2750
3994
 
2751
3995
  %% tool_first_goal(+Body, -Call): the first call in a conjunction body.
2752
- tool_first_goal((A, _), Call) :- !, tool_first_goal(A, Call).
3996
+ %% tool_first_goal((A, _), Call) :- !, tool_first_goal(A, Call).
2753
3997
  tool_first_goal(Call, Call).
2754
3998
 
3999
+ %% ============================================================
4000
+ %% Complexity advisories
4001
+ %% ============================================================
4002
+ %%
4003
+ %% The goal is many small composable skills, not one clever predicate. These
4004
+ %% checks catch the shapes a model falls into when it reaches for Prolog instead
4005
+ %% of composition: a long clause, inline Python long enough to belong in a
4006
+ %% script, and an `agent_main` that returns a value instead of answering.
4007
+ repl_validate_complexity(SessionId, Warnings) :-
4008
+ findall(W, complexity_violation(SessionId, W), Raw),
4009
+ list_to_set(Raw, Warnings).
4010
+
4011
+ complexity_violation(SessionId, Warning) :-
4012
+ current_predicate(SessionId:Name/Arity),
4013
+ integer(Arity),
4014
+ repl_user_predicate(SessionId, Name, Arity),
4015
+ functor(Head, Name, Arity),
4016
+ clause(SessionId:Head, Body),
4017
+ Body \== true,
4018
+ ( Name == agent_main,
4019
+ Arity > 0,
4020
+ \+ body_calls_predicate(Body, answer, 1)
4021
+ -> format(string(Warning),
4022
+ 'agent_main/~w has arguments but never calls answer/1. `agent_main/N` takes the run inputs; return the result with answer/1, not as an extra output argument.',
4023
+ [Arity])
4024
+ ; body_goal_count(Body, Count),
4025
+ Count > 12
4026
+ -> format(string(Warning),
4027
+ '~w/~w has ~w goals in one clause. Split it into named skills and compose them (A, B) or with maplist/3; a clause this long is where a harness stops being reviewable.',
4028
+ [Name, Arity, Count])
4029
+ ; body_inline_python_lines(Body, Lines),
4030
+ Lines > 3
4031
+ -> format(string(Warning),
4032
+ '~w/~w embeds ~w lines of Python in a DML string. Put the script in a workspace file, link it with script_file/2, and call run_script(Name, Args, Value).',
4033
+ [Name, Arity, Lines])
4034
+ ; fail
4035
+ ).
4036
+
4037
+ body_calls_predicate(Body, Name, Arity) :-
4038
+ sub_term(Sub, Body),
4039
+ compound(Sub),
4040
+ compound_name_arity(Sub, Name, Arity).
4041
+
4042
+ body_goal_count(Body, Count) :-
4043
+ conj_list(Body, Goals),
4044
+ length(Goals, Count).
4045
+
4046
+ body_inline_python_lines(Body, Lines) :-
4047
+ sub_term(Sub, Body),
4048
+ compound(Sub),
4049
+ compound_name_arity(Sub, python, _Arity),
4050
+ Sub =.. [_|Options],
4051
+ python_option(code, Options, Code),
4052
+ string(Code),
4053
+ split_string(Code, "\n", "", Lines0),
4054
+ length(Lines0, Lines).
4055
+
4056
+ %% python_option(+Key, +Options, -Value)
4057
+ %% `exec(python(code: "…"))` reaches Prolog as `python(:(code, "…"))`; a dict is
4058
+ %% also accepted. Both spell the same option.
4059
+ python_option(Key, Options, Value) :-
4060
+ member(Option, Options),
4061
+ ( is_dict(Option)
4062
+ -> get_dict(Key, Option, Value)
4063
+ ; compound_name_arity(Option, :, 2),
4064
+ arg(1, Option, Key),
4065
+ arg(2, Option, Value)
4066
+ ).
4067
+
2755
4068
  %% True when the predicate has at least one clause with a real body (not a fact).
2756
4069
  repl_predicate_has_rule(SessionId, Name, Arity) :-
2757
4070
  functor(Head, Name, Arity),
@@ -3012,6 +4325,8 @@ repl_snapshot_save(SessionId) :-
3012
4325
  ; ToolSources = []
3013
4326
  ),
3014
4327
  findall(Directive, session_directive(SessionId, Directive), Directives),
4328
+ findall(Name/Arity, session_harness_export(SessionId, Name, Arity), Exports),
4329
+ findall(import(Import, Target, TargetImport), session_harness_import(SessionId, Import, Target, TargetImport), Import0),
3015
4330
  ( session_repl_memory(SessionId, Memory) -> true ; Memory = [] ),
3016
4331
  assertz(repl_snapshot(SessionId, snapshot{
3017
4332
  clauses: Clauses,
@@ -3019,11 +4334,14 @@ repl_snapshot_save(SessionId) :-
3019
4334
  schemas: Schemas,
3020
4335
  tool_sources: ToolSources,
3021
4336
  directives: Directives,
4337
+ exports: Exports,
4338
+ imports: Import0,
3022
4339
  memory: Memory
3023
4340
  })).
3024
4341
 
3025
4342
  %% repl_snapshot_restore(+SessionId)
3026
4343
  repl_snapshot_restore(SessionId) :-
4344
+ mi_clear_cut_classes(SessionId),
3027
4345
  ( repl_snapshot(SessionId, Snapshot)
3028
4346
  -> retract(repl_snapshot(SessionId, Snapshot)),
3029
4347
  findall(Name/Arity,
@@ -3048,6 +4366,19 @@ repl_snapshot_restore(SessionId) :-
3048
4366
  retractall(session_directive(SessionId, _)),
3049
4367
  forall(member(Directive, Snapshot.directives),
3050
4368
  assertz(session_directive(SessionId, Directive))),
4369
+ retractall(session_harness_export(SessionId, _, _)),
4370
+ ( get_dict(exports, Snapshot, SnapshotExports)
4371
+ -> forall(member(ExportName/ExportArity, SnapshotExports),
4372
+ assertz(session_harness_export(SessionId, ExportName, ExportArity)))
4373
+ ; true
4374
+ ),
4375
+ retractall(session_harness_import(SessionId, _, _, _)),
4376
+ ( get_dict(imports, Snapshot, SnapshotImports)
4377
+ -> true
4378
+ ; SnapshotImports = []
4379
+ ),
4380
+ forall(member(import(Import, Target, TargetImport), SnapshotImports),
4381
+ assertz(session_harness_import(SessionId, Import, Target, TargetImport))),
3051
4382
  retractall(session_repl_memory(SessionId, _)),
3052
4383
  assertz(session_repl_memory(SessionId, Snapshot.memory))
3053
4384
  ; true
@@ -3322,6 +4653,7 @@ destroy_engine(SessionId) :-
3322
4653
  retractall(session_params(SessionId, _)),
3323
4654
  retractall(session_user_tools(SessionId, _)),
3324
4655
  retractall(session_user_tool_schema(SessionId, _, _)),
4656
+ retractall(session_source_view(SessionId, _, _)),
3325
4657
  retractall(session_pending_input(SessionId, _)),
3326
4658
  retractall(session_input_cancelled(SessionId)),
3327
4659
  retractall(session_agent_result(SessionId, _)),
@@ -3329,7 +4661,7 @@ destroy_engine(SessionId) :-
3329
4661
  retractall(session_sample_token_result(SessionId, _)),
3330
4662
  retractall(session_llm_result(SessionId, _)),
3331
4663
  retractall(session_judgment_result(SessionId, _)),
3332
- retractall(session_trace_log(SessionId, _)),
4664
+ reset_trace_store(SessionId),
3333
4665
  retractall(session_trace_enabled(SessionId, _)),
3334
4666
  ( current_module(SessionId)
3335
4667
  -> catch(
@@ -3619,34 +4951,255 @@ get_depth(State, Depth) :-
3619
4951
  set_depth(StateIn, Depth, StateOut) :-
3620
4952
  StateOut = StateIn.put(depth, Depth).
3621
4953
 
4954
+ %% get_harness_context(+State, -Module)
4955
+ %% The module whose local predicates are currently being resolved. `session`
4956
+ %% means the caller's live harness module.
4957
+ get_harness_context(State, Module) :-
4958
+ ( is_dict(State), get_dict(harness_module, State, Module)
4959
+ -> true
4960
+ ; get_session_id(SessionId),
4961
+ Module = SessionId
4962
+ ).
4963
+
4964
+ set_harness_context(StateIn, Module, StateOut) :-
4965
+ StateOut = StateIn.put(harness_module, Module).
4966
+
4967
+ harness_module_loaded(Module) :-
4968
+ harness_module_owner(Module, _, _, _).
4969
+
4970
+ import_target(Owner, Name, Arity, TargetModule, TargetName) :-
4971
+ ( harness_module_loaded(Owner)
4972
+ -> harness_module_import(Owner, Name/Arity, TargetModule, TargetName/Arity)
4973
+ ; session_harness_import(Owner, Name/Arity, TargetModule, TargetName/Arity)
4974
+ ).
4975
+
4976
+ module_local_predicate(Module, Name, Arity) :-
4977
+ functor(Head, Name, Arity),
4978
+ predicate_property(Module:Head, defined),
4979
+ \+ predicate_property(Module:Head, imported_from(_)),
4980
+ \+ predicate_property(Module:Head, built_in),
4981
+ \+ predicate_property(Module:Head, foreign).
4982
+
4983
+ is_harness_module(Module) :-
4984
+ harness_module_owner(Module, _, _, _).
4985
+
4986
+ retarget_goal(Goal, Name, TargetGoal) :-
4987
+ Goal =.. [_|Args],
4988
+ TargetGoal =.. [Name|Args].
4989
+
4990
+ mi_call_harness_goal(Module, Goal, StateIn, StateOut) :-
4991
+ get_session_id(SessionId),
4992
+ get_harness_context(StateIn, Previous),
4993
+ ( Previous == Module
4994
+ -> true
4995
+ ; functor(Goal, Name, Arity),
4996
+ ( harness_module_export(Module, Name, Arity)
4997
+ -> true
4998
+ ; throw(error(permission_error(access, private_predicate, Module:Goal),
4999
+ context(use_harness/2, 'only exported predicates are callable from another harness')))
5000
+ )
5001
+ ),
5002
+ get_depth(StateIn, Depth),
5003
+ NextDepth is Depth + 1,
5004
+ State1 = StateIn.put(depth, NextDepth),
5005
+ set_harness_context(State1, Module, State2),
5006
+ trace_goal_call(SessionId, Goal, Depth),
5007
+ ( clause(Module:Goal, Body)
5008
+ *-> ( Body == true
5009
+ -> trace_goal_exit(SessionId, Goal, Depth),
5010
+ State3 = State2
5011
+ ; mi_call(Body, State2, State3),
5012
+ trace_goal_exit(SessionId, Goal, Depth)
5013
+ ),
5014
+ State4 = State3.put(depth, Depth),
5015
+ set_harness_context(State4, Previous, StateOut)
5016
+ ; trace_goal_fail(SessionId, Goal, Depth),
5017
+ fail
5018
+ ).
5019
+
5020
+ %% mi_call_dispatch for an unqualified goal inside a harness module. Local
5021
+ %% predicates win; otherwise resolve that module's imports. Never fall through
5022
+ %% to the caller's session module, which would leak private caller predicates.
5023
+ mi_call_dispatch(Goal, StateIn, StateOut) :-
5024
+ get_session_id(SessionId),
5025
+ get_harness_context(StateIn, Current),
5026
+ Current \== SessionId,
5027
+ callable(Goal),
5028
+ \+ predicate_property(Goal, built_in),
5029
+ functor(Goal, Name, Arity),
5030
+ !,
5031
+ ( module_local_predicate(Current, Name, Arity)
5032
+ -> mi_call_harness_goal(Current, Goal, StateIn, StateOut)
5033
+ ; import_target(Current, Name, Arity, TargetModule, TargetName)
5034
+ -> retarget_goal(Goal, TargetName, TargetGoal),
5035
+ mi_call_harness_goal(TargetModule, TargetGoal, StateIn, StateOut)
5036
+ ; predicate_property(Current:Goal, defined)
5037
+ -> get_depth(StateIn, Depth),
5038
+ trace_goal_call(SessionId, Goal, Depth),
5039
+ ( catch(call(Current:Goal), _, fail)
5040
+ -> trace_goal_exit(SessionId, Goal, Depth), StateOut = StateIn
5041
+ ; trace_goal_fail(SessionId, Goal, Depth), fail
5042
+ )
5043
+ ; fail
5044
+ ).
5045
+
3622
5046
  %% add_trace_entry(+SessionId, +Type, +Predicate, +Args, +Depth)
3623
5047
  %% Add a trace entry if tracing is enabled
3624
5048
  add_trace_entry(SessionId, Type, Predicate, Args, Depth) :-
5049
+ add_trace_entry_result(SessionId, Type, Predicate, Args, none, Depth).
5050
+
5051
+ %% add_trace_entry_result(+SessionId, +Type, +Predicate, +Args, +ResultOrNone, +Depth)
5052
+ %% Indexed, constant-time append with a hard cap. The list-backed log was
5053
+ %% quadratic for long loops; this keeps a bounded store and can still be
5054
+ %% serialized in order.
5055
+ add_trace_entry_result(SessionId, Type, Predicate, Args, ResultOpt, Depth) :-
3625
5056
  ( session_trace_enabled(SessionId, true)
3626
5057
  -> get_time(Now),
3627
- Timestamp is round(Now * 1000), % Convert to milliseconds
3628
- Entry = trace{timestamp: Timestamp, type: Type, predicate: Predicate, args: Args, depth: Depth},
3629
- session_trace_log(SessionId, OldLog),
3630
- retract(session_trace_log(SessionId, OldLog)),
3631
- append(OldLog, [Entry], NewLog),
3632
- assertz(session_trace_log(SessionId, NewLog))
5058
+ Timestamp is round(Now * 1000),
5059
+ ( ResultOpt = none
5060
+ -> Entry0 = trace{timestamp: Timestamp, type: Type, predicate: Predicate, args: Args, depth: Depth}
5061
+ ; ResultOpt = some(Result),
5062
+ Entry0 = trace{timestamp: Timestamp, type: Type, predicate: Predicate, args: Args, result: Result, depth: Depth}
5063
+ ),
5064
+ add_trace_scope(Entry0, Entry),
5065
+ append_trace_entry(SessionId, Entry)
3633
5066
  ; true
3634
5067
  ).
3635
5068
 
3636
- %% add_trace_with_result(+SessionId, +Type, +Predicate, +Args, +Result, +Depth)
3637
- %% Add a trace entry with a result field
3638
- add_trace_with_result(SessionId, Type, Predicate, Args, Result, Depth) :-
5069
+ %% add_trace_scope(+EntryIn, -EntryOut)
5070
+ %% Attach the current tool/workflow scope, so the UI can nest MI calls under
5071
+ %% the host tool invocation that produced them.
5072
+ add_trace_scope(Entry, EntryOut) :-
5073
+ get_session_id(SessionId),
5074
+ ( session_trace_scope(SessionId, [Scope|_])
5075
+ -> put_dict(scope, Entry, Scope, EntryOut)
5076
+ ; EntryOut = Entry
5077
+ ).
5078
+
5079
+ %% append_trace_entry(+SessionId, +Entry)
5080
+ %% Bounded, indexed append used by normal MI entries and host tool roots.
5081
+ append_trace_entry(SessionId, Entry) :-
5082
+ ( session_trace_count(SessionId, Count)
5083
+ -> true
5084
+ ; Count = 0,
5085
+ assertz(session_trace_count(SessionId, 0))
5086
+ ),
5087
+ Max = 50000,
5088
+ ( Count < Max
5089
+ -> assertz(session_trace_entry(SessionId, Count, Entry)),
5090
+ Next is Count + 1,
5091
+ retractall(session_trace_count(SessionId, _)),
5092
+ assertz(session_trace_count(SessionId, Next))
5093
+ ; true
5094
+ ).
5095
+
5096
+ %% repl_trace_tool_start(+SessionId, +Id, +Name, +ArgsJson)
5097
+ repl_trace_tool_start(SessionId, Id, Name, ArgsJson) :-
3639
5098
  ( session_trace_enabled(SessionId, true)
3640
5099
  -> get_time(Now),
3641
5100
  Timestamp is round(Now * 1000),
3642
- Entry = trace{timestamp: Timestamp, type: Type, predicate: Predicate, args: Args, result: Result, depth: Depth},
3643
- session_trace_log(SessionId, OldLog),
3644
- retract(session_trace_log(SessionId, OldLog)),
3645
- append(OldLog, [Entry], NewLog),
3646
- assertz(session_trace_log(SessionId, NewLog))
5101
+ ( session_trace_scope(SessionId, [Parent|_])
5102
+ -> put_dict(scope, trace{timestamp: Timestamp, type: tool, predicate: Name,
5103
+ args: [ArgsJson], depth: 0, id: Id, scope: Parent}, Entry)
5104
+ ; Entry = trace{timestamp: Timestamp, type: tool, predicate: Name,
5105
+ args: [ArgsJson], depth: 0, id: Id}
5106
+ ),
5107
+ append_trace_entry(SessionId, Entry),
5108
+ ( session_trace_scope(SessionId, Stack)
5109
+ -> retractall(session_trace_scope(SessionId, _)),
5110
+ assertz(session_trace_scope(SessionId, [Id|Stack]))
5111
+ ; assertz(session_trace_scope(SessionId, [Id]))
5112
+ )
5113
+ ; true
5114
+ ).
5115
+
5116
+ %% repl_trace_tool_end(+SessionId, +Id, +ResultJson)
5117
+ repl_trace_tool_end(SessionId, Id, ResultJson) :-
5118
+ ( session_trace_enabled(SessionId, true)
5119
+ -> ( session_trace_scope(SessionId, Stack),
5120
+ select(Id, Stack, Rest)
5121
+ -> retractall(session_trace_scope(SessionId, _)),
5122
+ ( Rest = [] -> true ; assertz(session_trace_scope(SessionId, Rest)) )
5123
+ ; true
5124
+ ),
5125
+ get_time(Now),
5126
+ Timestamp is round(Now * 1000),
5127
+ Entry = trace{timestamp: Timestamp, type: exit, predicate: tool,
5128
+ args: [], result: ResultJson, depth: 0, scope: Id},
5129
+ append_trace_entry(SessionId, Entry)
3647
5130
  ; true
3648
5131
  ).
3649
5132
 
5133
+ %% reset_trace_store(+SessionId)
5134
+ reset_trace_store(SessionId) :-
5135
+ retractall(session_trace_entry(SessionId, _, _)),
5136
+ retractall(session_trace_count(SessionId, _)),
5137
+ retractall(session_trace_scope(SessionId, _)),
5138
+ retractall(session_trace_log(SessionId, _)).
5139
+
5140
+ %% session_trace_list(+SessionId, -Entries)
5141
+ session_trace_list(SessionId, Entries) :-
5142
+ findall(Entry, session_trace_entry(SessionId, _, Entry), Entries).
5143
+
5144
+ %% add_trace_with_result(+SessionId, +Type, +Predicate, +Args, +Result, +Depth)
5145
+ %% Add a trace entry with a result field
5146
+ add_trace_with_result(SessionId, Type, Predicate, Args, Result, Depth) :-
5147
+ add_trace_entry_result(SessionId, Type, Predicate, Args, some(Result), Depth).
5148
+
5149
+ %% goal_trace_parts(+Goal, -Predicate, -Args)
5150
+ goal_trace_parts(Goal, Predicate, Args) :-
5151
+ ( compound(Goal)
5152
+ -> Goal =.. [Predicate|Args]
5153
+ ; Predicate = Goal, Args = []
5154
+ ).
5155
+
5156
+ trace_goal_call(SessionId, Goal, Depth) :-
5157
+ goal_trace_parts(Goal, Predicate, Args),
5158
+ add_trace_entry(SessionId, call, Predicate, Args, Depth).
5159
+
5160
+ trace_goal_exit(SessionId, Goal, Depth) :-
5161
+ goal_trace_parts(Goal, Predicate, Args),
5162
+ copy_term(Goal, GoalOut),
5163
+ add_trace_with_result(SessionId, exit, Predicate, Args, GoalOut, Depth).
5164
+
5165
+ trace_goal_fail(SessionId, Goal, Depth) :-
5166
+ goal_trace_parts(Goal, Predicate, Args),
5167
+ add_trace_entry(SessionId, fail, Predicate, Args, Depth).
5168
+
5169
+ %% repl_trace_clear(+SessionId)
5170
+ repl_trace_clear(SessionId) :-
5171
+ reset_trace_store(SessionId).
5172
+
5173
+ %% JSON-safe trace. Terms are rendered as text; arbitrary DML terms/variables
5174
+ %% are not JSON values.
5175
+ repl_trace_json(SessionId, Json) :-
5176
+ session_trace_list(SessionId, Log),
5177
+ maplist(trace_entry_json, Log, Entries),
5178
+ atom_json_dict(Json, Entries, []).
5179
+
5180
+ trace_entry_json(Trace, Dict) :-
5181
+ is_dict(Trace),
5182
+ get_dict(timestamp, Trace, Timestamp),
5183
+ get_dict(type, Trace, Type),
5184
+ get_dict(predicate, Trace, Predicate),
5185
+ get_dict(args, Trace, Args),
5186
+ get_dict(depth, Trace, Depth),
5187
+ term_string(Args, ArgsText),
5188
+ Base = _{timestamp: Timestamp, type: Type, predicate: Predicate, depth: Depth, argsText: ArgsText},
5189
+ ( get_dict(result, Trace, Result)
5190
+ -> term_string(Result, ResultText),
5191
+ put_dict(resultText, Base, ResultText, WithResult)
5192
+ ; WithResult = Base
5193
+ ),
5194
+ ( get_dict(id, Trace, Id0)
5195
+ -> put_dict(id, WithResult, Id0, WithId)
5196
+ ; WithId = WithResult
5197
+ ),
5198
+ ( get_dict(scope, Trace, Scope)
5199
+ -> put_dict(scope, WithId, Scope, Dict)
5200
+ ; Dict = WithId
5201
+ ).
5202
+
3650
5203
  %% ============================================================
3651
5204
  %% Agent Signal Loop - SIMPLIFIED
3652
5205
  %% ============================================================
@@ -3726,8 +5279,9 @@ call_tool_inline(SessionId, ToolName, Args, StateIn, StateOut, Result) :-
3726
5279
  ToolHead = ToolPattern,
3727
5280
  % Execute the tool body through MI
3728
5281
  % Wrap in catch to handle answer() commits - answer() yields and then throws
5282
+ mi_lower_cut_body(Body, LoweredBody),
3729
5283
  catch(
3730
- ( mi_call(Body, StateIn, StateOut)
5284
+ ( mi_call(LoweredBody, StateIn, StateOut)
3731
5285
  -> % Collect result from result/1 facts or output args
3732
5286
  % Use catch to handle case where result/2 doesn't exist
3733
5287
  ( catch(SessionId:result(ToolNameAtom, R), _, fail)
@@ -3784,10 +5338,13 @@ create_tool_engine(SessionId, ToolName, Args, ToolEngineId) :-
3784
5338
  (session_params(SessionId, Params) -> true ; Params = params{}),
3785
5339
  InitialState = state{memory: [], params: Params, context_stack: [], depth: 0},
3786
5340
  % Create goal that will yield the result
5341
+ % A tool body is interpreted (it may call exec/exec-free host code); lower
5342
+ % any cut so it commits the body's prefix instead of doing nothing.
5343
+ mi_lower_cut_body(Body, LoweredBody),
3787
5344
  Goal = (
3788
5345
  nb_setval(current_session_id, SessionId),
3789
5346
  catch(
3790
- ( mi_call(Body, InitialState, _FinalState),
5347
+ ( mi_call(LoweredBody, InitialState, _FinalState),
3791
5348
  % A tool that declares an output but leaves it unbound has no
3792
5349
  % result. `extract_tool_result_simple/4` maps that to `true`, which
3793
5350
  % is how a `tool(fs_write(Path, Content), …)` (content taken for the
@@ -3984,6 +5541,7 @@ mi_call(task(Desc), StateIn, StateOut) :-
3984
5541
  interpolate_desc(Desc, Params, InterpDesc),
3985
5542
  get_session_id(SessionId),
3986
5543
  get_depth(StateIn, Depth),
5544
+ add_trace_entry(SessionId, call, task, [InterpDesc], Depth),
3987
5545
  add_trace_entry(SessionId, llm_call, task, [InterpDesc], Depth),
3988
5546
  collect_user_tools(SessionId, UserTools),
3989
5547
  get_memory(StateIn, Memory),
@@ -4004,6 +5562,7 @@ mi_call(task(Desc), StateIn, StateOut) :-
4004
5562
  -> format(atom(WarnMsg), 'Warning: task/1 failed: ~w', [ErrorMsg])
4005
5563
  ; format(atom(WarnMsg), 'Warning: task/1 failed (success=false)', [])
4006
5564
  ),
5565
+ add_trace_entry(SessionId, fail, task, [InterpDesc], Depth),
4007
5566
  engine_yield(output(WarnMsg)),
4008
5567
  fail
4009
5568
  ),
@@ -4060,6 +5619,7 @@ mi_call(prompt(Desc), StateIn, StateOut) :-
4060
5619
  interpolate_desc(Desc, Params, InterpDesc),
4061
5620
  get_session_id(SessionId),
4062
5621
  get_depth(StateIn, Depth),
5622
+ add_trace_entry(SessionId, call, prompt, [InterpDesc], Depth),
4063
5623
  add_trace_entry(SessionId, llm_call, prompt, [InterpDesc], Depth),
4064
5624
  % prompt/N is a simple LLM call - no tools, no tool scope
4065
5625
  get_model_spec(StateIn, ModelSpec),
@@ -4145,6 +5705,7 @@ mi_call(chat(Message, Reply), StateIn, StateOut) :-
4145
5705
  interpolate_desc(Message, Params, InterpMessage),
4146
5706
  get_session_id(SessionId),
4147
5707
  get_depth(StateIn, Depth),
5708
+ add_trace_entry(SessionId, call, chat, [InterpMessage], Depth),
4148
5709
  add_trace_entry(SessionId, llm_call, chat, [InterpMessage], Depth),
4149
5710
  collect_user_tools(SessionId, UserTools),
4150
5711
  % The message is NOT added to memory here: the loop appends it as the turn's
@@ -4480,6 +6041,7 @@ mi_call_task_n(Desc, Vars, VarNames, StateIn, StateOut) :-
4480
6041
  interpolate_desc(Desc, Params, InterpDesc),
4481
6042
  get_session_id(SessionId),
4482
6043
  get_depth(StateIn, Depth),
6044
+ add_trace_entry(SessionId, call, task, [InterpDesc], Depth),
4483
6045
  add_trace_entry(SessionId, llm_call, task, [InterpDesc], Depth),
4484
6046
  collect_user_tools(SessionId, UserTools),
4485
6047
  get_memory(StateIn, Memory),
@@ -4502,6 +6064,7 @@ mi_call_task_n(Desc, Vars, VarNames, StateIn, StateOut) :-
4502
6064
  -> format(atom(WarnMsg), 'Warning: task/~w failed: ~w', [ActualArity, ErrorMsg])
4503
6065
  ; format(atom(WarnMsg), 'Warning: task/~w failed (success=false)', [ActualArity])
4504
6066
  ),
6067
+ add_trace_entry(SessionId, fail, task, [InterpDesc], Depth),
4505
6068
  engine_yield(output(WarnMsg)),
4506
6069
  fail
4507
6070
  ),
@@ -4546,12 +6109,22 @@ mi_call_task_n(Desc, Vars, VarNames, StateIn, StateOut) :-
4546
6109
  %%
4547
6110
  %% task("From the front matter extract every author: {Text}",
4548
6111
  %% list(schema(author, Authors))).
4549
- %% schema_fill(+Fields, +Value, -Filled): the pure part, so it is testable and
4550
- %% usable without a session. The session predicate schema_fill/3 looks the fields
4551
- %% up from `schema/2`.
6112
+ %% schema_fill(+Fields, +Value, -Filled): the pure part (primitive field types),
6113
+ %% so it is testable and usable without a session. The session predicate
6114
+ %% schema_fill/3 looks the fields up from `schema/2`.
4552
6115
  schema_fill_fields(Fields, Value, Filled) :-
6116
+ schema_fill_fields(none, Fields, Value, Filled).
6117
+
6118
+ %% schema_fill_fields(+SessionOrNone, +Fields, +Value, -Filled)
6119
+ %%
6120
+ %% Field types: a primitive (`string`, `integer`, `number`, `boolean`, `object`,
6121
+ %% `array`), `list(Type)`, or `schema(Name)` / `schema(Name, _)` for a nested
6122
+ %% object. Nested schemas are filled and validated recursively; before this,
6123
+ %% `list(schema(part, _))` was an unknown type and every value was rejected —
6124
+ %% including `[]`.
6125
+ schema_fill_fields(Session, Fields, Value, Filled) :-
4553
6126
  is_dict(Value),
4554
- ( member(field(Field, Type, required), Fields),
6127
+ ( member(field(Field, _Type, required), Fields),
4555
6128
  \+ dict_field(Value, Field, _),
4556
6129
  !,
4557
6130
  format(atom(Msg), 'schema: required field "~w" is missing', [Field]),
@@ -4560,7 +6133,7 @@ schema_fill_fields(Fields, Value, Filled) :-
4560
6133
  ),
4561
6134
  ( member(field(Field, Type, _), Fields),
4562
6135
  dict_field(Value, Field, Found),
4563
- \+ schema_value_ok(Type, Found),
6136
+ \+ schema_value_ok(Session, Type, Found),
4564
6137
  !,
4565
6138
  format(atom(Msg), 'schema: field "~w" is not ~w (~w)', [Field, Type, Found]),
4566
6139
  throw(error(schema_error(Msg), schema_fill/3))
@@ -4569,10 +6142,9 @@ schema_fill_fields(Fields, Value, Filled) :-
4569
6142
  dict_pairs(Value, _, Pairs),
4570
6143
  findall(Key-NewValue,
4571
6144
  ( member(Key-Old, Pairs),
4572
- ( member(field(Key, _, Option), Fields)
4573
- -> ( Option = default(Default), Old == "" -> NewValue = Default
4574
- ; NewValue = Old
4575
- )
6145
+ ( member(field(Key, Type, Option), Fields)
6146
+ -> ( Option = default(Default), Old == "" -> Base = Default ; Base = Old ),
6147
+ schema_fill_value(Session, Type, Base, NewValue)
4576
6148
  ; NewValue = Old % undeclared: kept, so it stays visible
4577
6149
  )
4578
6150
  ),
@@ -4585,15 +6157,57 @@ schema_fill_fields(Fields, Value, Filled) :-
4585
6157
  append(Updated, Missing, All),
4586
6158
  dict_pairs(Filled, _, All).
4587
6159
 
6160
+ %% schema_fill_value(+SessionOrNone, +Type, +Value, -Filled)
6161
+ schema_fill_value(Session, list(Inner), Value, Filled) :-
6162
+ !,
6163
+ ( is_list(Value)
6164
+ -> maplist(schema_fill_value(Session, Inner), Value, Filled)
6165
+ ; Filled = Value
6166
+ ).
6167
+ schema_fill_value(Session, schema(Name), Value, Filled) :-
6168
+ !,
6169
+ schema_fill_nested(Session, Name, Value, Filled).
6170
+ schema_fill_value(Session, schema(Name, _), Value, Filled) :-
6171
+ !,
6172
+ schema_fill_nested(Session, Name, Value, Filled).
6173
+ schema_fill_value(_, _, Value, Value).
6174
+
6175
+ schema_fill_nested(none, _, Value, Value) :- !.
6176
+ schema_fill_nested(Session, Name, Value, Filled) :-
6177
+ ( is_dict(Value)
6178
+ -> schema_fields_of(Session, Name, Fields),
6179
+ schema_fill_fields(Session, Fields, Value, Filled)
6180
+ ; Filled = Value
6181
+ ).
6182
+
4588
6183
  %% A declared type accepts its own shape; anything coarser (a number for a string
4589
6184
  %% field, for instance) fails, because silently coercing hides the model's error.
4590
- schema_value_ok(string, V) :- ( string(V) ; atom(V) ), !.
4591
- schema_value_ok(integer, V) :- integer(V), !.
4592
- schema_value_ok(number, V) :- number(V), !.
4593
- schema_value_ok(boolean, V) :- ( V == true ; V == false ; V == yes ; V == no ), !.
4594
- schema_value_ok(object, V) :- is_dict(V), !.
4595
- schema_value_ok(array, V) :- is_list(V), !.
4596
- schema_value_ok(_, _) :- fail.
6185
+ schema_value_ok(_, string, V) :- ( string(V) ; atom(V) ), !.
6186
+ schema_value_ok(_, integer, V) :- integer(V), !.
6187
+ schema_value_ok(_, number, V) :- number(V), !.
6188
+ schema_value_ok(_, boolean, V) :- ( V == true ; V == false ; V == yes ; V == no ), !.
6189
+ schema_value_ok(_, object, V) :- is_dict(V), !.
6190
+ schema_value_ok(_, array, V) :- is_list(V), !.
6191
+ schema_value_ok(Session, list(Inner), V) :-
6192
+ !,
6193
+ is_list(V),
6194
+ maplist(schema_value_ok(Session, Inner), V).
6195
+ schema_value_ok(Session, schema(Name), V) :-
6196
+ !,
6197
+ schema_value_ok_nested(Session, Name, V).
6198
+ schema_value_ok(Session, schema(Name, _), V) :-
6199
+ !,
6200
+ schema_value_ok_nested(Session, Name, V).
6201
+ schema_value_ok(none, list(_), V) :- is_list(V), !.
6202
+ schema_value_ok(none, schema(_), V) :- is_dict(V), !.
6203
+ schema_value_ok(none, schema(_, _), V) :- is_dict(V), !.
6204
+ schema_value_ok(_, _, _) :- fail.
6205
+
6206
+ schema_value_ok_nested(none, _, V) :- is_dict(V), !.
6207
+ schema_value_ok_nested(Session, Name, V) :-
6208
+ is_dict(V),
6209
+ schema_fields_of(Session, Name, Fields),
6210
+ catch((schema_fill_fields(Session, Fields, V, _), true), _, fail).
4597
6211
 
4598
6212
  %% bind_task_variables(+VarsDict, +Names, -Values)
4599
6213
  bind_task_variables(_, _, [], []) :- !.
@@ -4609,8 +6223,8 @@ bind_task_variables(SessionId, VarsDict, [N|Names], [Value|Values]) :-
4609
6223
  ( is_dict(N), get_dict(schema, N, SchemaName), nonvar(Raw)
4610
6224
  -> schema_fields_of(SessionId, SchemaName, Fields),
4611
6225
  ( is_list(Raw)
4612
- -> maplist(schema_filled(Fields), Raw, Value)
4613
- ; schema_fill_fields(Fields, Raw, Value)
6226
+ -> schema_fill_list(SessionId, Fields, Raw, Value)
6227
+ ; schema_fill_fields(SessionId, Fields, Raw, Value)
4614
6228
  )
4615
6229
  ; Value = Raw
4616
6230
  ),
@@ -4643,18 +6257,36 @@ resolve_schema_field(SessionId, VarName, Resolved) :-
4643
6257
 
4644
6258
  %% Field descriptors as dicts, so they cross the bridge without a decoder.
4645
6259
  %% `required` is 1/0 rather than an atom: the atom `false` arrives as the string
4646
- %% "false", which is truthy in JavaScript.
6260
+ %% "false", which is truthy in JavaScript. A nested schema carries its own
6261
+ %% `fields`, so the description the nested agent reads includes them.
4647
6262
  schema_field_dicts(SessionId, SchemaName, Dicts) :-
4648
6263
  catch(clause(SessionId:schema(SchemaName, Fields), true), _, fail),
4649
- findall(x{name: Field, type: Type, required: Required, default: Default},
4650
- ( member(field(Field, Type, Option), Fields),
6264
+ findall(x{name: Field, type: Type, itemType: ItemType, required: Required,
6265
+ default: Default, fields: Nested},
6266
+ ( member(field(Field, TypeTerm, Option), Fields),
6267
+ field_type_dict(SessionId, TypeTerm, Type, ItemType, Nested),
4651
6268
  ( Option == required -> Required = 1 ; Required = 0 ),
4652
6269
  ( Option = default(D) -> Default = D ; Default = no_default )
4653
6270
  ),
4654
6271
  Dicts).
4655
6272
 
4656
- schema_filled(Fields, Raw, Filled) :-
4657
- ( is_dict(Raw) -> schema_fill_fields(Fields, Raw, Filled) ; Filled = Raw ).
6273
+ %% field_type_dict(+Session, +TypeTerm, -Type, -ItemType, -Fields)
6274
+ field_type_dict(Session, list(Inner), array, ItemType, Nested) :-
6275
+ !,
6276
+ field_type_dict(Session, Inner, ItemType, _, Nested).
6277
+ field_type_dict(Session, schema(Name), object, none, Nested) :-
6278
+ !,
6279
+ schema_field_dicts(Session, Name, Nested).
6280
+ field_type_dict(Session, schema(Name, _), object, none, Nested) :-
6281
+ !,
6282
+ schema_field_dicts(Session, Name, Nested).
6283
+ field_type_dict(_, Type, Type, none, []).
6284
+
6285
+ %% schema_fill_list(+Session, +Fields, +Values, -Filled)
6286
+ schema_fill_list(_, _, [], []).
6287
+ schema_fill_list(Session, Fields, [Raw|Raws], [Value|Values]) :-
6288
+ schema_fill_fields(Session, Fields, Raw, Value),
6289
+ schema_fill_list(Session, Fields, Raws, Values).
4658
6290
 
4659
6291
  %% ============================================================
4660
6292
  %% Exec Handling
@@ -4678,7 +6310,92 @@ mi_call(exec(ToolCall, Output), StateIn, StateOut) :-
4678
6310
  add_trace_with_result(SessionId, exit, ToolName, Args, Output, Depth),
4679
6311
  StateOut = State0
4680
6312
  ; add_trace_entry(SessionId, fail, ToolName, Args, Depth),
4681
- fail
6313
+ % A failed host call used to be a plain failure. `exec(bash(...))` in the
6314
+ % browser therefore produced no bindings and no message at all: the goal
6315
+ % just failed, which reads like "the predicate did not match" instead of
6316
+ % "there is no such host tool". Surface the host's reason as an error.
6317
+ % post_exec_result/3 stores the reason under `result`, not `error`.
6318
+ % Only a *missing* tool becomes an error: that is the case that used to
6319
+ % fail with no explanation at all (`exec(bash(...))` in the browser).
6320
+ % A tool that ran and failed stays a plain failure, so `catch/3` and
6321
+ % `\+` around `exec` keep working.
6322
+ ( catch(get_dict(result, Result, Reason0), _, fail),
6323
+ format(string(Reason), '~w', [Reason0]),
6324
+ sub_string(Reason, _, _, _, "Tool not found")
6325
+ -> throw(error(tool_error(ToolName, Reason), context(exec/2, Reason)))
6326
+ ; fail
6327
+ )
6328
+ ).
6329
+
6330
+ %% ============================================================
6331
+ %% Scripts: one helper instead of five goals of glue
6332
+ %% ============================================================
6333
+ %%
6334
+ %% run_script(+ScriptName, +Args, -Value)
6335
+ %%
6336
+ %% Resolve a `script_file(Name, Path)` link, convert the arguments to the strings
6337
+ %% `argv` takes, run it, check `exitCode`, and parse stdout as JSON when it is
6338
+ %% JSON. Every Python-backed skill otherwise repeats `script_file`, a numeric
6339
+ %% conversion, `exec`, `get_dict(exitCode)`, `get_dict(stdout)` and
6340
+ %% `atom_json_dict` — and the version that forgets the exit-code check is the one
6341
+ %% that reports fabricated results.
6342
+ mi_call(run_script(Name, Args, Value), StateIn, StateOut) :-
6343
+ !,
6344
+ get_session_id(SessionId),
6345
+ ( atom(Name),
6346
+ current_predicate(SessionId:script_file/2),
6347
+ SessionId:script_file(Name, Path)
6348
+ -> true
6349
+ ; atom(Name)
6350
+ -> throw(error(existence_error(script, Name),
6351
+ context(run_script/3,
6352
+ 'no script_file(Name, Path) links that name; declare script_file/2 and create the file first')))
6353
+ ; throw(error(type_error(atom, Name), context(run_script/3, 'the script name must be an atom')))
6354
+ ),
6355
+ ( is_list(Args)
6356
+ -> maplist(script_arg_string, Args, Argv)
6357
+ ; throw(error(type_error(list, Args),
6358
+ context(run_script/3, 'pass the script arguments as a list')))
6359
+ ),
6360
+ script_exec(Path, Argv, Result, StateIn, State1),
6361
+ ( catch(get_dict(exitCode, Result, 0), _, fail)
6362
+ -> get_dict(stdout, Result, Out),
6363
+ ( catch(atom_json_dict(Out, Parsed, []), _, fail)
6364
+ -> Value = Parsed
6365
+ ; Value = Out
6366
+ ),
6367
+ StateOut = State1
6368
+ ; ( catch(get_dict(stderr, Result, Err), _, fail) -> true ; Err = "script failed" ),
6369
+ throw(error(script_failed(Name, Err), context(run_script/3, Err)))
6370
+ ).
6371
+
6372
+ %% script_exec(+Path, +Argv, -Result, +StateIn, -StateOut)
6373
+ %% The capability tool differs by embedding: the browser registers `python`, the
6374
+ %% CLI has a shell. Try Python first and fall back to running the file, so one
6375
+ %% `run_script/3` works in both places. A missing tool is the catchable
6376
+ %% `tool_error` raised by `exec/2`; anything else is the script's own failure.
6377
+ script_exec(Path, Argv, Result, StateIn, State1) :-
6378
+ ( catch(mi_call(exec(python(script: Path, argv: Argv), Result), StateIn, State1),
6379
+ error(tool_error(_, _), _), fail)
6380
+ -> true
6381
+ ; script_shell_command(Path, Argv, Command),
6382
+ mi_call(exec(bash(argv: Command), Result), StateIn, State1)
6383
+ ).
6384
+
6385
+ %% script_shell_command(+Path, +Argv, -Command): execute a .py with python3,
6386
+ %% anything else directly (it needs a shebang or to be a shell script).
6387
+ script_shell_command(Path, Argv, [python3, Path|Argv]) :-
6388
+ sub_atom(Path, _, _, 0, '.py'),
6389
+ !.
6390
+ script_shell_command(Path, Argv, [Path|Argv]).
6391
+
6392
+ %% script_arg_string(+Value, -String): argv entries are strings.
6393
+ script_arg_string(Value, String) :-
6394
+ ( string(Value) -> String = Value
6395
+ ; atom(Value) -> atom_string(Value, String)
6396
+ ; number(Value) -> number_string(Value, String)
6397
+ ; throw(error(type_error(atomic, Value),
6398
+ context(run_script/3, 'script arguments must be atoms, strings or numbers')))
4682
6399
  ).
4683
6400
 
4684
6401
  %% ============================================================
@@ -5391,7 +7108,7 @@ mi_call(output(Media), StateIn, StateIn) :-
5391
7108
  nonvar(Media),
5392
7109
  ( Media = media(_, _)
5393
7110
  ; Media = media(_)
5394
- ; is_dict(Media)
7111
+ ; is_dict(Media), media_dict_keys(Media)
5395
7112
  ),
5396
7113
  media_dict(Media, Dict),
5397
7114
  !,
@@ -5404,6 +7121,10 @@ mi_call(output(Media), StateIn, StateIn) :-
5404
7121
  add_trace_entry(SessionId, media, media, [Path], Depth),
5405
7122
  engine_yield(media(media{path: Path, mimeType: Mime, kind: Kind, data: Data})).
5406
7123
 
7124
+ %% media_dict_keys(+Dict): a dict shaped like a media reference.
7125
+ media_dict_keys(Dict) :-
7126
+ ( get_dict(mime, Dict, _) ; get_dict(svg, Dict, _) ; get_dict(path, Dict, _) ; get_dict(data, Dict, _) ).
7127
+
5407
7128
  %% mi_call(output(html(Path)), +StateIn, -StateOut)
5408
7129
  %% Present a workspace HTML file as an interactive miniapp.
5409
7130
  mi_call(output(html(Path)), StateIn, StateIn) :-
@@ -5420,6 +7141,14 @@ mi_call(output(html(Path)), StateIn, StateIn) :-
5420
7141
  !,
5421
7142
  engine_yield(html(html{path: HtmlPath})).
5422
7143
 
7144
+ %% A plain dict is not text. `output(R)` on an exec result used to reach the media
7145
+ %% path and fail inside sub_atom with `type_error(atom, dict{...})`.
7146
+ mi_call(output(Value), _StateIn, _StateOut) :-
7147
+ is_dict(Value),
7148
+ !,
7149
+ throw(error(type_error(text, Value), context(output/1,
7150
+ 'output/1 expects text or media; read a field first, e.g. get_dict(stdout, R, Text), output(Text)'))).
7151
+
5423
7152
  %% mi_call(output(Text), +StateIn, -StateOut)
5424
7153
  mi_call(output(Text), StateIn, StateIn) :-
5425
7154
  get_params(StateIn, Params),
@@ -5721,6 +7450,39 @@ mi_call(\+(Goal), StateIn, StateIn) :-
5721
7450
  mi_call(!, StateIn, StateIn) :-
5722
7451
  !.
5723
7452
 
7453
+ %% mi_call('$dc_cut_flag', +StateIn, -StateOut)
7454
+ %% A cut whose only remaining effect is committing the clause.
7455
+ mi_call('$dc_cut_flag', StateIn, StateOut) :- !,
7456
+ mi_cut_mark(StateIn),
7457
+ StateOut = StateIn.
7458
+
7459
+ %% mi_call('$dc_cut_commit'(Goal), +StateIn, -StateOut)
7460
+ %% Commit the goals to the left of a cut, then the clause. once/1 is
7461
+ %% interpreter-aware, so bindings and state are kept.
7462
+ mi_call('$dc_cut_commit'(Goal), StateIn, StateOut) :- !,
7463
+ once(mi_call(Goal, StateIn, State1)),
7464
+ mi_cut_mark(State1),
7465
+ StateOut = State1.
7466
+
7467
+ %% mi_call('$dc_cut_guard'(Goal), +StateIn, -StateOut)
7468
+ %% The right branch of a disjunction whose left branch was cut.
7469
+ mi_call('$dc_cut_guard'(Goal), StateIn, StateOut) :- !,
7470
+ ( mi_cut_committed(StateIn)
7471
+ -> fail
7472
+ ; mi_call(Goal, StateIn, StateOut)
7473
+ ).
7474
+
7475
+ %% mi_call('$dc_cut_scope'(Goal), +StateIn, -StateOut)
7476
+ %% A nested cut scope: call/1, \+/1, findall/3, an if-then-else condition.
7477
+ mi_call('$dc_cut_scope'(Goal), StateIn, StateOut) :- !,
7478
+ ( get_dict(call_id, StateIn, Outer) -> true ; Outer = none ),
7479
+ mi_fresh_call_id(CallId),
7480
+ call_cleanup(
7481
+ mi_call(Goal, StateIn.put(call_id, CallId), StateOut0),
7482
+ mi_clear_cut_mark(CallId)
7483
+ ),
7484
+ StateOut = StateOut0.put(call_id, Outer).
7485
+
5724
7486
  %% mi_call(true, +StateIn, -StateOut)
5725
7487
  mi_call(true, StateIn, StateIn).
5726
7488
 
@@ -5766,17 +7528,30 @@ repl_reserved_clause(Head) :-
5766
7528
  functor(Head, Name, _),
5767
7529
  repl_protected_name(Name).
5768
7530
 
7531
+ guard_harness_mutation(StateIn, What) :-
7532
+ get_session_id(SessionId),
7533
+ get_harness_context(StateIn, Module),
7534
+ ( Module == SessionId
7535
+ -> true
7536
+ ; throw(error(permission_error(modify, imported_module, What),
7537
+ context(mi_call/3, 'imported harness modules are read-only')))
7538
+ ).
7539
+
5769
7540
  mi_call(assertz(Head), StateIn, StateIn) :-
5770
7541
  get_session_id(SessionId),
7542
+ guard_harness_mutation(StateIn, Head),
5771
7543
  guard_not_frozen(SessionId),
5772
7544
  guard_reserved_clause(Head),
5773
- assertz(SessionId:Head).
7545
+ assertz(SessionId:Head),
7546
+ mi_clear_cut_classes(SessionId).
5774
7547
 
5775
7548
  mi_call(asserta(Head), StateIn, StateIn) :-
5776
7549
  get_session_id(SessionId),
7550
+ guard_harness_mutation(StateIn, Head),
5777
7551
  guard_not_frozen(SessionId),
5778
7552
  guard_reserved_clause(Head),
5779
- asserta(SessionId:Head).
7553
+ asserta(SessionId:Head),
7554
+ mi_clear_cut_classes(SessionId).
5780
7555
 
5781
7556
  guard_reserved_clause(Head) :-
5782
7557
  ( repl_reserved_clause(Head)
@@ -5787,13 +7562,17 @@ guard_reserved_clause(Head) :-
5787
7562
 
5788
7563
  mi_call(retract(Head), StateIn, StateIn) :-
5789
7564
  get_session_id(SessionId),
7565
+ guard_harness_mutation(StateIn, Head),
5790
7566
  guard_not_frozen(SessionId),
5791
- retract(SessionId:Head).
7567
+ retract(SessionId:Head),
7568
+ mi_clear_cut_classes(SessionId).
5792
7569
 
5793
7570
  mi_call(retractall(Head), StateIn, StateIn) :-
5794
7571
  get_session_id(SessionId),
7572
+ guard_harness_mutation(StateIn, Head),
5795
7573
  guard_not_frozen(SessionId),
5796
- retractall(SessionId:Head).
7574
+ retractall(SessionId:Head),
7575
+ mi_clear_cut_classes(SessionId).
5797
7576
 
5798
7577
  %% ============================================================
5799
7578
  %% List Predicates - Interpreted for proper state threading
@@ -6413,7 +8192,7 @@ workspace_predicate_clause(S, (S:json_gets(D, P, Vs) :- deepclause_mi:json_gets(
6413
8192
  workspace_predicate_clause(S, (S:json_put(D, P, V, D2) :- deepclause_mi:json_put(D, P, V, D2))).
6414
8193
  workspace_predicate_clause(S, (S:json_text(D, T) :- deepclause_mi:json_text(D, T))).
6415
8194
  workspace_predicate_clause(S, (S:schema_fill(N, V, F) :-
6416
- deepclause_mi:schema_fields_of(S, N, Fields), deepclause_mi:schema_fill_fields(Fields, V, F))).
8195
+ deepclause_mi:schema_fields_of(S, N, Fields), deepclause_mi:schema_fill_fields(S, Fields, V, F))).
6417
8196
  workspace_predicate_clause(S, (S:pattern(T, Text, B) :- deepclause_mi:pattern(T, Text, B))).
6418
8197
 
6419
8198
  workspace_predicate_clause(S, (S:time_file(F, T) :-
@@ -6690,6 +8469,37 @@ mi_call(_Module:Goal, StateIn, StateOut) :-
6690
8469
  !,
6691
8470
  mi_call(Goal, StateIn, StateOut).
6692
8471
 
8472
+ % A goal qualified with a module other than the session's runs natively. Its
8473
+ % body must resolve its own unqualified helpers in *its* module: interpreting it
8474
+ % here called `interp_json/2` (and any other helper) as `deepclause_mi:…`.
8475
+ % Session-qualified goals still need the interpreter so task/N and exec/2 work.
8476
+ mi_call(Module:Goal, StateIn, StateOut) :-
8477
+ is_harness_module(Module),
8478
+ !,
8479
+ mi_call_harness_goal(Module, Goal, StateIn, StateOut).
8480
+
8481
+ mi_call(Module:Goal, StateIn, StateIn) :-
8482
+ external_callable_module(Module),
8483
+ !,
8484
+ call(Module:Goal).
8485
+
8486
+ %% external_callable_module(+Module)
8487
+ %% Modules whose predicates must run natively rather than be re-interpreted
8488
+ %% here. Deliberately a whitelist: a session module (a generated `repl_*`) must
8489
+ %% keep going through the interpreter, or `task/N` and `exec/2` inside a
8490
+ %% qualified goal would not be intercepted.
8491
+ external_callable_module(deepclause_strings).
8492
+ external_callable_module(deepclause_memory).
8493
+ external_callable_module(deepclause_analysis).
8494
+ external_callable_module(json).
8495
+ external_callable_module(clpfd).
8496
+ external_callable_module(clpr).
8497
+ external_callable_module(clpq).
8498
+ external_callable_module(lists).
8499
+ external_callable_module(apply).
8500
+ external_callable_module(system).
8501
+ external_callable_module(user).
8502
+
6693
8503
  % For regular module-qualified goals, use clause/2 for backtracking
6694
8504
  mi_call(Module:Goal, StateIn, StateOut) :-
6695
8505
  predicate_property(Module:Goal, defined),
@@ -6729,6 +8539,7 @@ is_mi_special_predicate(task_named(_,_,_)). %% Transformed form of task/N
6729
8539
  is_mi_special_predicate(sample_token(_,_)).
6730
8540
  is_mi_special_predicate(sample_token(_,_,_)).
6731
8541
  is_mi_special_predicate(exec(_,_)).
8542
+ is_mi_special_predicate(run_script(_,_,_)).
6732
8543
  is_mi_special_predicate(spawn(_,_)).
6733
8544
  is_mi_special_predicate(spawn_opt(_,_,_)).
6734
8545
  is_mi_special_predicate(self(_)).
@@ -6821,6 +8632,10 @@ is_mi_special_predicate(\+(_)).
6821
8632
  is_mi_special_predicate(catch(_,_,_)).
6822
8633
  is_mi_special_predicate(throw(_)).
6823
8634
  is_mi_special_predicate(!).
8635
+ is_mi_special_predicate('$dc_cut_flag').
8636
+ is_mi_special_predicate('$dc_cut_commit'(_)).
8637
+ is_mi_special_predicate('$dc_cut_guard'(_)).
8638
+ is_mi_special_predicate('$dc_cut_scope'(_)).
6824
8639
  is_mi_special_predicate(true).
6825
8640
  is_mi_special_predicate(fail).
6826
8641
  is_mi_special_predicate(false).
@@ -7011,18 +8826,60 @@ consume_gas(StateIn, StateOut) :-
7011
8826
  %% mi_call_dispatch(+Goal, +StateIn, -StateOut)
7012
8827
  %% Dispatch user-defined vs built-in predicates
7013
8828
  %% Uses separate clauses instead of if-then-else to preserve backtracking
7014
- mi_call_dispatch(Goal, StateIn, StateIn) :-
8829
+ %%
8830
+ %% A goal qualified with another module (for example
8831
+ %% `deepclause_strings:dc_interp_value/2`, which the interpolation rewrite emits)
8832
+ %% must run natively. Interpreting its body here would resolve *its* unqualified
8833
+ %% helper calls against this module and fail with `deepclause_mi:helper/2`.
8834
+ mi_call_dispatch(Goal, StateIn, StateOut) :-
8835
+ get_session_id(SessionId),
8836
+ nonvar(Goal),
8837
+ Goal = Module:Inner,
8838
+ atom(Module),
8839
+ Module \== SessionId,
8840
+ % Only external modules: a session-qualified goal still needs the
8841
+ % interpreter so task/N, exec/2 and gas accounting keep working.
8842
+ Module \== user,
8843
+ !,
8844
+ get_depth(StateIn, Depth),
8845
+ trace_goal_call(SessionId, Goal, Depth),
8846
+ ( call(Module:Inner)
8847
+ *-> trace_goal_exit(SessionId, Goal, Depth), StateOut = StateIn
8848
+ ; trace_goal_fail(SessionId, Goal, Depth), fail
8849
+ ).
8850
+
8851
+ mi_call_dispatch(Goal, StateIn, StateOut) :-
7015
8852
  get_session_id(SessionId),
7016
8853
  callable(Goal),
7017
8854
  predicate_property(SessionId:Goal, defined),
7018
8855
  predicate_property(Goal, built_in),
7019
8856
  !,
7020
- call(SessionId:Goal).
8857
+ get_depth(StateIn, Depth),
8858
+ trace_goal_call(SessionId, Goal, Depth),
8859
+ ( call(SessionId:Goal)
8860
+ *-> trace_goal_exit(SessionId, Goal, Depth), StateOut = StateIn
8861
+ ; trace_goal_fail(SessionId, Goal, Depth), fail
8862
+ ).
7021
8863
 
7022
- mi_call_dispatch(Goal, StateIn, StateIn) :-
8864
+ mi_call_dispatch(Goal, StateIn, StateOut) :-
7023
8865
  predicate_property(Goal, built_in),
7024
8866
  !, % Commit: it's built-in, no backtracking needed
7025
- call(Goal).
8867
+ get_session_id(SessionId),
8868
+ get_depth(StateIn, Depth),
8869
+ trace_goal_call(SessionId, Goal, Depth),
8870
+ ( call(Goal)
8871
+ *-> trace_goal_exit(SessionId, Goal, Depth), StateOut = StateIn
8872
+ ; trace_goal_fail(SessionId, Goal, Depth), fail
8873
+ ).
8874
+
8875
+ %% `script_file/2` is a fact annotation, not a helper. Calling it before the
8876
+ %% fact exists used to fail as `existence_error(procedure, ...)` with no hint.
8877
+ mi_call_dispatch(script_file(_, _), _StateIn, _StateOut) :-
8878
+ get_session_id(SessionId),
8879
+ \+ current_predicate(SessionId:script_file/2),
8880
+ !,
8881
+ throw(error(existence_error(procedure, script_file/2), context(script_file/2,
8882
+ 'script_file/2 is an annotation, not a helper: declare script_file(Name, "path/to/script.py"), then run it with run_script(Name, Args, Value)'))).
7026
8883
 
7027
8884
  mi_call_dispatch(Goal, StateIn, StateOut) :-
7028
8885
  get_session_id(SessionId),
@@ -7030,41 +8887,347 @@ mi_call_dispatch(Goal, StateIn, StateOut) :-
7030
8887
  predicate_property(SessionId:Goal, defined),
7031
8888
  % If it's a library/imported predicate, call it directly
7032
8889
  ( (predicate_property(SessionId:Goal, imported_from(_)) ; predicate_property(SessionId:Goal, foreign))
7033
- -> StateOut = StateIn,
7034
- call(SessionId:Goal)
7035
- ; % User-defined predicate - use clause/2 for backtracking
7036
- % Add trace entry for call
8890
+ -> get_depth(StateIn, Depth),
8891
+ trace_goal_call(SessionId, Goal, Depth),
8892
+ ( call(SessionId:Goal)
8893
+ *-> trace_goal_exit(SessionId, Goal, Depth), StateOut = StateIn
8894
+ ; trace_goal_fail(SessionId, Goal, Depth), fail
8895
+ )
8896
+ ; % A pure predicate that uses a cut runs natively: interpreting its body
8897
+ % would turn `!` into `true` (docs/META_INTERPRETER_CUTS.md), because the
8898
+ % cut cannot reach the clause/2 choice point from mi_call/3.
8899
+ mi_call_predicate_class(SessionId, Goal, Class),
7037
8900
  get_depth(StateIn, Depth),
7038
- Goal =.. [Functor|Args],
7039
- add_trace_entry(SessionId, call, Functor, Args, Depth),
7040
- % Find a matching clause - allows backtracking to try multiple clauses
7041
- clause(SessionId:Goal, Body),
8901
+ trace_goal_call(SessionId, Goal, Depth),
8902
+ ( Class == native
8903
+ -> % Pure predicate with a cut: run the real clauses so `!` is a real
8904
+ % Prolog cut (bindings kept, clause committed, scopes honoured).
8905
+ ( call(SessionId:Goal)
8906
+ *-> trace_goal_exit(SessionId, Goal, Depth), StateOut = StateIn
8907
+ ; trace_goal_fail(SessionId, Goal, Depth), fail
8908
+ )
8909
+ ; ( Class == cut
8910
+ -> % Interpreted goal by goal with a lowered cut. Each call gets its
8911
+ % own commit marker so the cut can stop later clauses from being
8912
+ % tried; the marker must survive backtracking, so it cannot live
8913
+ % in the threaded state.
8914
+ ( get_dict(call_id, StateIn, OuterCall) -> true ; OuterCall = none ),
8915
+ mi_fresh_call_id(CallId),
8916
+ call_cleanup(
8917
+ mi_call_clause_loop(SessionId, Goal, Depth, StateIn.put(call_id, CallId),
8918
+ CallId, true, StateOut0),
8919
+ mi_clear_cut_mark(CallId)
8920
+ ),
8921
+ StateOut = StateOut0.put(call_id, OuterCall)
8922
+ ; % No cut: the plain interpreter path, unchanged.
8923
+ mi_call_clause_loop(SessionId, Goal, Depth, StateIn, none, false, StateOut)
8924
+ )
8925
+ )
8926
+ ).
8927
+
8928
+ %% mi_call_clause_loop(+SessionId, +Goal, +Depth, +StateIn, +CallId, +Lower, -StateOut)
8929
+ %% Enumerate clauses, interpreting each lowered body. Once the call's commit
8930
+ %% marker is set, later clauses are never tried - that is the cut's second
8931
+ %% effect, which must survive backtracking and therefore cannot live in the
8932
+ %% threaded state.
8933
+ mi_call_clause_loop(SessionId, Goal, Depth, StateIn, CallId, Lower, StateOut) :-
8934
+ clause(SessionId:Goal, Body),
8935
+ ( CallId \== none,
8936
+ mi_cut_done(CallId)
8937
+ -> fail
8938
+ ; ( Lower == true -> mi_lower_cut_body(Body, Lowered) ; Lowered = Body ),
7042
8939
  NewDepth is Depth + 1,
7043
8940
  set_depth(StateIn, NewDepth, State1),
7044
- % Soft cut: execute the body for every solution (so findall/backtracking
7045
- % works), but still record a fail trace when the body has none.
7046
- ( mi_call(Body, State1, State2)
7047
- *-> add_trace_entry(SessionId, exit, Functor, Args, Depth),
8941
+ ( mi_call(Lowered, State1, State2)
8942
+ *-> trace_goal_exit(SessionId, Goal, Depth),
7048
8943
  set_depth(State2, Depth, StateOut)
7049
- ; add_trace_entry(SessionId, fail, Functor, Args, Depth),
8944
+ ; trace_goal_fail(SessionId, Goal, Depth),
7050
8945
  fail
7051
8946
  )
7052
8947
  ).
7053
8948
 
7054
- mi_call_dispatch(Goal, StateIn, StateIn) :-
8949
+ %% mi_native_query(+SessionId, +Goal): a pure query containing a cut.
8950
+ mi_native_query(SessionId, Goal) :-
8951
+ term_has_cut(Goal),
8952
+ mi_body_is_pure(SessionId, Goal).
8953
+
8954
+ %% ============================================================
8955
+ %% Cut inside user predicates
8956
+ %%
8957
+ %% `!` cannot be interpreted faithfully: the interpreted body is executed by
8958
+ %% mi_call/3, so a cut cannot prune the clause/2 choice point created in
8959
+ %% mi_call_dispatch/3 (see docs/META_INTERPRETER_CUTS.md). A *pure* predicate
8960
+ %% that contains a cut is therefore executed natively with call/1, which gives
8961
+ %% exact Prolog cut semantics: bindings are kept, the clause commits, and
8962
+ %% \+/1, call/1, findall/3 and if-then-else scope it correctly.
8963
+ %%
8964
+ %% "Pure" means: neither the predicate nor anything it calls needs state
8965
+ %% threading (task/N, prompt/N, llm/2, exec/2, forms, processes, system/1, ...).
8966
+ %% Such a predicate stays interpreted and its cut is ignored; that restriction
8967
+ %% is documented. Both decisions are cached per predicate and invalidated
8968
+ %% whenever the harness changes.
8969
+ %% ============================================================
8970
+
8971
+ %% mi_call_predicate_class(+SessionId, +Goal, -Class)
8972
+ %% native - contains a cut and is pure: run the real clauses
8973
+ %% cut - contains a cut but needs the interpreter: lower the cut
8974
+ %% no_cut - no cut: interpret the body as written
8975
+ mi_call_predicate_class(SessionId, Goal, Class) :-
8976
+ callable(Goal),
8977
+ functor(Goal, Name, Arity),
8978
+ ( mi_cut_class(SessionId, Name/Arity, Cached)
8979
+ -> Class = Cached
8980
+ ; ( mi_classify_cut_predicate(SessionId, Name/Arity, Class0)
8981
+ -> Class = Class0
8982
+ ; Class = no_cut
8983
+ ),
8984
+ assertz(mi_cut_class(SessionId, Name/Arity, Class))
8985
+ ).
8986
+
8987
+ mi_classify_cut_predicate(SessionId, Name/Arity, Class) :-
8988
+ functor(Head, Name, Arity),
8989
+ findall(Body, clause(SessionId:Head, Body), Bodies),
8990
+ Bodies \== [],
8991
+ ( member(Body0, Bodies),
8992
+ term_has_cut(Body0)
8993
+ -> ( forall(member(Body, Bodies), mi_body_is_pure(SessionId, Body))
8994
+ -> Class = native
8995
+ ; Class = cut
8996
+ )
8997
+ ; fail
8998
+ ).
8999
+
9000
+ %% term_has_cut(+Term): a cut occurs anywhere in the term (conservative).
9001
+ term_has_cut(Term) :-
9002
+ ( Term == !
9003
+ -> true
9004
+ ; compound(Term),
9005
+ Term =.. [_|Args],
9006
+ member(Arg, Args),
9007
+ term_has_cut(Arg)
9008
+ ).
9009
+
9010
+ mi_body_is_pure(SessionId, Body) :-
9011
+ \+ ( sub_term(Goal, Body),
9012
+ compound(Goal),
9013
+ mi_impure_goal(SessionId, Goal)
9014
+ ).
9015
+
9016
+ %% A host/model predicate, or a user predicate that (transitively) needs one.
9017
+ mi_impure_goal(_SessionId, Goal) :-
9018
+ is_mi_special_predicate(Goal),
9019
+ \+ mi_control_construct(Goal).
9020
+ mi_impure_goal(SessionId, Goal) :-
9021
+ \+ is_mi_special_predicate(Goal),
9022
+ predicate_property(SessionId:Goal, defined),
9023
+ \+ predicate_property(SessionId:Goal, imported_from(_)),
9024
+ \+ predicate_property(SessionId:Goal, foreign),
9025
+ functor(Goal, Name, Arity),
9026
+ mi_predicate_purity(SessionId, Name/Arity, impure).
9027
+
9028
+ mi_predicate_purity(SessionId, Indicator, Purity) :-
9029
+ ( mi_purity(SessionId, Indicator, Cached)
9030
+ -> Purity = Cached
9031
+ ; assertz(mi_purity(SessionId, Indicator, in_progress)),
9032
+ Indicator = Name/Arity,
9033
+ functor(Head, Name, Arity),
9034
+ findall(Body, clause(SessionId:Head, Body), Bodies),
9035
+ ( Bodies \== [],
9036
+ forall(member(Body, Bodies), mi_body_is_pure(SessionId, Body))
9037
+ -> Purity = pure
9038
+ ; Purity = impure
9039
+ ),
9040
+ retractall(mi_purity(SessionId, Indicator, _)),
9041
+ ( Purity == pure -> true ; true ),
9042
+ assertz(mi_purity(SessionId, Indicator, Purity))
9043
+ ).
9044
+
9045
+ %% Control constructs and native-safe builtins are not "impure": they carry no
9046
+ %% state or are re-implemented natively.
9047
+ mi_control_construct((_, _)).
9048
+ mi_control_construct((_; _)).
9049
+ mi_control_construct((_ -> _)).
9050
+ mi_control_construct((_ *-> _)).
9051
+ mi_control_construct((_ *-> _ ; _)).
9052
+ mi_control_construct(\+(_)).
9053
+ mi_control_construct(!).
9054
+ mi_control_construct(true).
9055
+ mi_control_construct(fail).
9056
+ mi_control_construct(false).
9057
+ mi_control_construct(catch(_, _, _)).
9058
+ mi_control_construct(throw(_)).
9059
+ mi_control_construct(findall(_, _, _)).
9060
+ mi_control_construct(bagof(_, _, _)).
9061
+ mi_control_construct(setof(_, _, _)).
9062
+ mi_control_construct(aggregate_all(_, _, _)).
9063
+ mi_control_construct(forall(_, _)).
9064
+ mi_control_construct(call(_)).
9065
+ mi_control_construct(call(_, _)).
9066
+ mi_control_construct(call(_, _, _)).
9067
+ mi_control_construct(call(_, _, _, _)).
9068
+ mi_control_construct(once(_)).
9069
+ mi_control_construct(ignore(_)).
9070
+ mi_control_construct(not(_)).
9071
+ mi_control_construct(assertz(_)).
9072
+ mi_control_construct(asserta(_)).
9073
+ mi_control_construct(retract(_)).
9074
+ mi_control_construct(retractall(_)).
9075
+
9076
+ %% sub_term(?Sub, +Term): any subterm, including arguments and list elements.
9077
+ sub_term(Term, Term).
9078
+ sub_term(Sub, Term) :-
9079
+ compound(Term),
9080
+ Term =.. [_|Args],
9081
+ member(Arg, Args),
9082
+ sub_term(Sub, Arg).
9083
+
9084
+ %% ============================================================
9085
+ %% Cut lowering for interpreted predicates
9086
+ %%
9087
+ %% A predicate that needs the interpreter (it calls task/N, exec/2, output/1,
9088
+ %% forms, processes, ...) cannot run natively, so its cuts are compiled away
9089
+ %% instead:
9090
+ %%
9091
+ %% ! -> '$dc_cut_flag' (commit the clause)
9092
+ %% (L, !, R) -> '$dc_cut_commit'(L), R (once(L), then commit)
9093
+ %% (L ; R) -> ( L' ; '$dc_cut_guard'(R') ) when L may cut
9094
+ %% \+ G, call(G), findall(_,G,_), (C->T;E) -> the goal keeps its own scope
9095
+ %%
9096
+ %% '$dc_cut_commit'(L) is once(L) plus the commit flag, and once/1 is already
9097
+ %% interpreter-aware, so bindings and the threaded state behave exactly as a
9098
+ %% real cut. The flag is a non-backtrackable fact per call (mi_cut_done/1): it
9099
+ %% must survive backtracking, which the threaded state cannot do.
9100
+ %% ============================================================
9101
+
9102
+ %% mi_lower_cut_body(+Body, -Lowered)
9103
+ mi_lower_cut_body(Body, Lowered) :-
9104
+ ( term_has_cut(Body)
9105
+ -> mi_lower_goal(Body, Lowered, _)
9106
+ ; Lowered = Body
9107
+ ).
9108
+
9109
+ %% mi_lower_goal(+Goal, -Lowered, -HasClauseCut)
9110
+ mi_lower_goal(!, '$dc_cut_flag', true) :- !.
9111
+ mi_lower_goal((A, B), Lowered, HasCut) :- !,
9112
+ mi_lower_goal(A, A1, CutA),
9113
+ mi_lower_goal(B, B1, CutB),
9114
+ ( CutA == true
9115
+ -> % The cut is inside A: A1 already commits its own prefix and keeps
9116
+ % enumerating after the cut, so do not wrap it again.
9117
+ Lowered = (A1, B1)
9118
+ ; CutB == true
9119
+ -> % A cut follows: every goal to its left is committed.
9120
+ Lowered = ('$dc_cut_commit'(A1), B1)
9121
+ ; Lowered = (A1, B1)
9122
+ ),
9123
+ ( CutA == true -> HasCut = true ; HasCut = CutB ).
9124
+ mi_lower_goal((A ; B), Lowered, HasCut) :- !,
9125
+ mi_lower_goal(A, A1, CutA),
9126
+ mi_lower_goal(B, B1, CutB),
9127
+ ( CutA == true
9128
+ -> Lowered = (A1 ; '$dc_cut_guard'(B1))
9129
+ ; Lowered = (A1 ; B1)
9130
+ ),
9131
+ ( CutA == true -> HasCut = true ; HasCut = CutB ).
9132
+ mi_lower_goal((Cond -> Then ; Else), Lowered, HasCut) :- !,
9133
+ mi_lower_scope(Cond, C1),
9134
+ mi_lower_goal(Then, T1, CutT),
9135
+ mi_lower_goal(Else, E1, CutE),
9136
+ Lowered = (C1 -> T1 ; E1),
9137
+ ( CutT == true -> HasCut = true ; HasCut = CutE ).
9138
+ mi_lower_goal((Cond -> Then), Lowered, HasCut) :- !,
9139
+ mi_lower_scope(Cond, C1),
9140
+ mi_lower_goal(Then, T1, CutT),
9141
+ Lowered = (C1 -> T1),
9142
+ HasCut = CutT.
9143
+ mi_lower_goal(\+(Goal), \+(G1), false) :- !, mi_lower_scope(Goal, G1).
9144
+ mi_lower_goal(call(Goal), call(G1), false) :- !, mi_lower_scope(Goal, G1).
9145
+ mi_lower_goal(call(Goal, A), call(G1, A), false) :- !, mi_lower_scope(Goal, G1).
9146
+ mi_lower_goal(once(Goal), once(G1), false) :- !, mi_lower_scope(Goal, G1).
9147
+ mi_lower_goal(ignore(Goal), ignore(G1), false) :- !, mi_lower_scope(Goal, G1).
9148
+ mi_lower_goal(not(Goal), not(G1), false) :- !, mi_lower_scope(Goal, G1).
9149
+ mi_lower_goal(findall(T, Goal, L), findall(T, G1, L), false) :- !, mi_lower_scope(Goal, G1).
9150
+ mi_lower_goal(bagof(T, Goal, L), bagof(T, G1, L), false) :- !, mi_lower_scope(Goal, G1).
9151
+ mi_lower_goal(setof(T, Goal, L), setof(T, G1, L), false) :- !, mi_lower_scope(Goal, G1).
9152
+ mi_lower_goal(aggregate_all(T, Goal, R), aggregate_all(T, G1, R), false) :- !, mi_lower_scope(Goal, G1).
9153
+ mi_lower_goal(forall(Cond, Action), forall(C1, A1), false) :- !,
9154
+ mi_lower_scope(Cond, C1),
9155
+ mi_lower_scope(Action, A1).
9156
+ mi_lower_goal(Goal, Goal, false).
9157
+
9158
+ %% A goal that is a cut scope of its own: lower its cuts, then mark the scope.
9159
+ mi_lower_scope(Goal, Scoped) :-
9160
+ ( term_has_cut(Goal)
9161
+ -> mi_lower_goal(Goal, Lowered, _),
9162
+ Scoped = '$dc_cut_scope'(Lowered)
9163
+ ; Scoped = Goal
9164
+ ).
9165
+
9166
+ %% ============================================================
9167
+ %% Cut lowering - runtime support
9168
+ %% ============================================================
9169
+
9170
+ mi_fresh_call_id(Id) :-
9171
+ ( nb_current(mi_call_seq, N) -> true ; N = 0 ),
9172
+ N1 is N + 1,
9173
+ nb_setval(mi_call_seq, N1),
9174
+ Id = N1.
9175
+
9176
+ %% mi_cut_mark(+State): this call must not try later clauses.
9177
+ mi_cut_mark(State) :-
9178
+ ( get_dict(call_id, State, CallId), CallId \== none
9179
+ -> ( mi_cut_done(CallId) -> true ; assertz(mi_cut_done(CallId)) )
9180
+ ; true
9181
+ ).
9182
+
9183
+ mi_cut_committed(State) :-
9184
+ get_dict(call_id, State, CallId),
9185
+ CallId \== none,
9186
+ mi_cut_done(CallId).
9187
+
9188
+ mi_clear_cut_mark(CallId) :-
9189
+ retractall(mi_cut_done(CallId)).
9190
+
9191
+ %% mi_clear_cut_classes(+SessionId): the harness changed; reclassify lazily.
9192
+ mi_clear_cut_classes(SessionId) :-
9193
+ retractall(mi_cut_class(SessionId, _, _)),
9194
+ retractall(mi_purity(SessionId, _, _)).
9195
+
9196
+ mi_call_dispatch(Goal, StateIn, StateOut) :-
9197
+ get_session_id(SessionId),
9198
+ get_harness_context(StateIn, Current),
9199
+ Current == SessionId,
9200
+ callable(Goal),
9201
+ functor(Goal, Name, Arity),
9202
+ import_target(SessionId, Name, Arity, TargetModule, TargetName),
9203
+ !,
9204
+ retarget_goal(Goal, TargetName, TargetGoal),
9205
+ mi_call_harness_goal(TargetModule, TargetGoal, StateIn, StateOut).
9206
+
9207
+ mi_call_dispatch(Goal, StateIn, StateOut) :-
7055
9208
  % Fallback for external/library predicates
7056
9209
  get_session_id(SessionId),
7057
9210
  % Check if this predicate exists in the session module but not as user-defined
7058
9211
  \+ predicate_property(SessionId:Goal, defined),
7059
- catch(call(SessionId:Goal), _, fail),
9212
+ get_depth(StateIn, Depth),
9213
+ trace_goal_call(SessionId, Goal, Depth),
9214
+ ( catch(call(SessionId:Goal), _, fail)
9215
+ -> trace_goal_exit(SessionId, Goal, Depth), StateOut = StateIn
9216
+ ; trace_goal_fail(SessionId, Goal, Depth), fail
9217
+ ),
7060
9218
  !.
7061
9219
 
7062
- mi_call_dispatch(Goal, StateIn, StateIn) :-
9220
+ mi_call_dispatch(Goal, StateIn, StateOut) :-
7063
9221
  % Final fallback: call without module
7064
9222
  % Only for predicates not defined in session
7065
9223
  get_session_id(SessionId),
7066
9224
  \+ predicate_property(SessionId:Goal, defined),
7067
- call(Goal).
9225
+ get_depth(StateIn, Depth),
9226
+ trace_goal_call(SessionId, Goal, Depth),
9227
+ ( call(Goal)
9228
+ *-> trace_goal_exit(SessionId, Goal, Depth), StateOut = StateIn
9229
+ ; trace_goal_fail(SessionId, Goal, Depth), fail
9230
+ ).
7068
9231
 
7069
9232
  %% ============================================================
7070
9233
  %% Helper Predicates
@@ -7373,13 +9536,23 @@ build_format_call(Template, Bindings, TempVar, FullGoal) :-
7373
9536
  ),
7374
9537
  extract_interpolation_vars(T, VarNames, FormatString),
7375
9538
  lookup_vars_with_params(VarNames, Bindings, VarList, ParamGoals),
7376
- FormatGoal = format(string(TempVar), FormatString, VarList),
7377
- ( ParamGoals == []
9539
+ % Values are rendered by dc_interp_value/2 and spliced with `~s`, so a list
9540
+ % or a dict arrives as JSON rather than Prolog syntax.
9541
+ render_interp_vars(VarList, RenderedVars, RenderGoals),
9542
+ FormatGoal = format(string(TempVar), FormatString, RenderedVars),
9543
+ append(ParamGoals, RenderGoals, Goals),
9544
+ ( Goals == []
7378
9545
  -> FullGoal = FormatGoal
7379
- ; list_to_conjunction(ParamGoals, ParamConj),
7380
- FullGoal = (ParamConj, FormatGoal)
9546
+ ; list_to_conjunction(Goals, Conj),
9547
+ FullGoal = (Conj, FormatGoal)
7381
9548
  ).
7382
9549
 
9550
+ %% render_interp_vars(+Vars, -Rendered, -Goals)
9551
+ render_interp_vars([], [], []).
9552
+ render_interp_vars([Var|Vars], [Rendered|Rendereds], [Goal|Goals]) :-
9553
+ Goal = deepclause_strings:dc_interp_value(Var, Rendered),
9554
+ render_interp_vars(Vars, Rendereds, Goals).
9555
+
7383
9556
  %% list_to_conjunction(+List, -Conjunction)
7384
9557
  list_to_conjunction([G], G) :- !.
7385
9558
  list_to_conjunction([G|Gs], (G, Rest)) :-
@@ -7402,7 +9575,7 @@ extract_interpolation_vars(Template, VarNames, FormatString) :-
7402
9575
  extract_vars_from_codes([], [], []) :- !.
7403
9576
 
7404
9577
  % Found opening brace
7405
- extract_vars_from_codes([0'{|Rest], [VarName|VarNames], [0'~, 0'w|FormatRest]) :-
9578
+ extract_vars_from_codes([0'{|Rest], [VarName|VarNames], [0'~, 0's|FormatRest]) :-
7406
9579
  extract_var_until_close(Rest, VarNameCodes, AfterClose),
7407
9580
  valid_placeholder_codes(VarNameCodes),
7408
9581
  !,