scout-ai 2.1.0 → 2.2.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 (186) hide show
  1. checksums.yaml +4 -4
  2. data/.vimproject +133 -58
  3. data/README.md +2 -1
  4. data/VERSION +1 -1
  5. data/doc/Improvements.md +490 -148
  6. data/doc/Model.md +53 -10
  7. data/doc/StartHere.md +44 -19
  8. data/doc/developer/Architecture.md +25 -6
  9. data/doc/developer/Backends.md +207 -48
  10. data/doc/developer/ChatLifecycle.md +121 -20
  11. data/doc/developer/DelegationInternals.md +319 -33
  12. data/doc/developer/DesignPrinciples.md +205 -16
  13. data/doc/developer/PathEngine.md +628 -0
  14. data/doc/developer/PromptProcessing.md +332 -82
  15. data/doc/developer/Provenance.md +388 -40
  16. data/doc/developer/Sandbox.md +213 -0
  17. data/doc/user/BuildingAgents.md +130 -18
  18. data/doc/user/Cookbook.md +29 -8
  19. data/doc/user/CoreConcepts.md +7 -6
  20. data/doc/user/Delegation.md +166 -15
  21. data/doc/user/GettingStarted.md +20 -16
  22. data/doc/user/ManagingContext.md +155 -17
  23. data/doc/user/MultiAgentWorkflows.md +105 -15
  24. data/doc/user/Python.md +11 -1
  25. data/doc/user/RunningInference.md +90 -47
  26. data/doc/user/ToolCalling.md +134 -29
  27. data/doc/user/WritingChats.md +56 -27
  28. data/lib/scout/llm/agent/attach.rb +13 -17
  29. data/lib/scout/llm/agent/chat.rb +32 -0
  30. data/lib/scout/llm/agent/construction.rb +64 -0
  31. data/lib/scout/llm/agent/conversation.rb +304 -0
  32. data/lib/scout/llm/agent/delegate.rb +56 -238
  33. data/lib/scout/llm/agent/path/edit.rb +230 -0
  34. data/lib/scout/llm/agent/path/patch.rb +252 -0
  35. data/lib/scout/llm/agent/path/workflow_kinds.rb +175 -0
  36. data/lib/scout/llm/agent/path.rb +1777 -0
  37. data/lib/scout/llm/agent/save.rb +11 -9
  38. data/lib/scout/llm/agent/workflow.rb +77 -16
  39. data/lib/scout/llm/agent.rb +147 -31
  40. data/lib/scout/llm/ask.rb +28 -17
  41. data/lib/scout/llm/backends/anthropic.rb +1 -1
  42. data/lib/scout/llm/backends/bedrock.rb +3 -2
  43. data/lib/scout/llm/backends/default.rb +127 -34
  44. data/lib/scout/llm/backends/glm.rb +28 -1
  45. data/lib/scout/llm/backends/huggingface.rb +1 -1
  46. data/lib/scout/llm/backends/ollama.rb +1 -1
  47. data/lib/scout/llm/backends/openai.rb +7 -6
  48. data/lib/scout/llm/backends/openwebui.rb +14 -7
  49. data/lib/scout/llm/backends/relay.rb +8 -2
  50. data/lib/scout/llm/chat/agent_meta.rb +24 -60
  51. data/lib/scout/llm/chat/parse.rb +1 -1
  52. data/lib/scout/llm/chat/process/files.rb +10 -0
  53. data/lib/scout/llm/chat/process/meta.rb +5 -7
  54. data/lib/scout/llm/chat/process/tools.rb +104 -49
  55. data/lib/scout/llm/chat/prompt/epoch_tool_compactation.rb +355 -0
  56. data/lib/scout/llm/chat/prompt/inbox.rb +188 -0
  57. data/lib/scout/llm/chat/prompt/shorten_tools.rb +797 -13
  58. data/lib/scout/llm/chat/prompt/shorten_tools_epoch.rb +1 -365
  59. data/lib/scout/llm/chat/prompt/shorten_tools_epoch_increment.rb +1 -0
  60. data/lib/scout/llm/chat/prompt.rb +24 -10
  61. data/lib/scout/llm/chat/provenance/live.rb +1080 -0
  62. data/lib/scout/llm/chat/provenance/tokens.rb +386 -0
  63. data/lib/scout/llm/chat/provenance.rb +343 -676
  64. data/lib/scout/llm/chat.rb +8 -2
  65. data/lib/scout/llm/embed.rb +15 -3
  66. data/lib/scout/llm/image.rb +4 -1
  67. data/lib/scout/llm/mcp.rb +4 -2
  68. data/lib/scout/llm/request_context.rb +234 -0
  69. data/lib/scout/llm/sandbox.rb +263 -0
  70. data/lib/scout/llm/tools/call.rb +163 -42
  71. data/lib/scout/llm/tools/definition.rb +48 -0
  72. data/lib/scout/llm/tools/knowledge_base.rb +1 -0
  73. data/lib/scout/llm/tools/mcp.rb +50 -43
  74. data/lib/scout/llm/tools/workflow.rb +90 -20
  75. data/lib/scout/llm/tools.rb +14 -41
  76. data/lib/scout/model/decision/base.rb +43 -0
  77. data/lib/scout/model/decision/jev.rb +161 -0
  78. data/lib/scout/model/python/torch.rb +1 -1
  79. data/research/clear-tools-inherit.md +171 -0
  80. data/research/path-engine-dc1-dc2-dc3-fixes.md +279 -0
  81. data/research/path-kind-chat-role.md +96 -0
  82. data/research/path-kind-contract-fixes-engine.md +307 -0
  83. data/research/scout-ai-runtime-availability.md +65 -0
  84. data/research/subsys/README.md +127 -0
  85. data/research/subsys/agent-delegation.md +201 -0
  86. data/research/subsys/agent-society.md +275 -0
  87. data/research/subsys/agentworkflow.md +233 -0
  88. data/research/subsys/backends.md +221 -0
  89. data/research/subsys/chat.md +314 -0
  90. data/research/subsys/embed-image.md +244 -0
  91. data/research/subsys/entry-cli.md +253 -0
  92. data/research/subsys/model-ml.md +326 -0
  93. data/research/subsys/provenance.md +290 -0
  94. data/research/subsys/tools.md +334 -0
  95. data/scout-ai.gemspec +71 -27
  96. data/scout_commands/agent/ask +8 -7
  97. data/scout_commands/llm/abridged +40 -0
  98. data/scout_commands/llm/ask +9 -9
  99. data/scout_commands/llm/md +2 -0
  100. data/scout_commands/llm/prov +724 -59
  101. data/scout_commands/llm/word +4 -0
  102. data/share/word/reference.docx +0 -0
  103. data/test/integration/scout/model/decision/test_jev.rb +144 -0
  104. data/test/scout/llm/agent/test_attach.rb +117 -0
  105. data/test/scout/llm/agent/test_conversation.rb +407 -0
  106. data/test/scout/llm/agent/test_delegate.rb +209 -0
  107. data/test/scout/llm/agent/test_path.rb +1812 -0
  108. data/test/scout/llm/agent/test_path_edit.rb +908 -0
  109. data/test/scout/llm/agent/test_path_errors.rb +390 -0
  110. data/test/scout/llm/agent/test_path_filesystem.rb +532 -0
  111. data/test/scout/llm/agent/test_path_patch.rb +233 -0
  112. data/test/scout/llm/agent/test_path_promotion.rb +386 -0
  113. data/test/scout/llm/agent/test_path_workflow_integration.rb +665 -0
  114. data/test/scout/llm/agent/test_save.rb +70 -15
  115. data/test/scout/llm/agent/test_workflow.rb +130 -4
  116. data/test/scout/llm/backends/test_anthropic.rb +4 -4
  117. data/test/scout/llm/backends/test_bedrock.rb +4 -4
  118. data/test/scout/llm/backends/test_format_other.rb +43 -0
  119. data/test/scout/llm/backends/test_ollama.rb +2 -2
  120. data/test/scout/llm/backends/test_openwebui.rb +12 -8
  121. data/test/scout/llm/backends/test_reasoning.rb +114 -0
  122. data/test/scout/llm/chat/agent_meta_fixtures.rb +28 -27
  123. data/test/scout/llm/chat/prompt/test_epoch_tool_compactation.rb +612 -0
  124. data/test/scout/llm/chat/prov_plot_fixtures.rb +131 -0
  125. data/test/scout/llm/chat/test_agent_meta.rb +40 -80
  126. data/test/scout/llm/chat/test_agent_meta_provenance.rb +67 -28
  127. data/test/scout/llm/chat/test_agent_meta_tokens.rb +59 -8
  128. data/test/scout/llm/chat/test_agent_view.rb +178 -0
  129. data/test/scout/llm/chat/test_live_report.rb +282 -0
  130. data/test/scout/llm/chat/test_live_workload.rb +193 -0
  131. data/test/scout/llm/chat/test_parse.rb +32 -2
  132. data/test/scout/llm/chat/test_prompt.rb +411 -0
  133. data/test/scout/llm/chat/test_prov_cli.rb +310 -15
  134. data/test/scout/llm/chat/test_prov_cli_live.rb +152 -0
  135. data/test/scout/llm/chat/test_prov_plot.rb +213 -0
  136. data/test/scout/llm/chat/test_prov_timeline.rb +355 -0
  137. data/test/scout/llm/chat/test_provenance.rb +67 -22
  138. data/test/scout/llm/chat/test_provenance_index.rb +479 -0
  139. data/test/scout/llm/chat/test_society_view.rb +159 -0
  140. data/test/scout/llm/test_agent.rb +1 -1
  141. data/test/scout/llm/test_embed.rb +103 -1
  142. data/test/scout/llm/test_request_context.rb +299 -0
  143. data/test/scout/llm/test_sandbox.rb +249 -0
  144. data/test/scout/llm/tools/test_agent_pairing.rb +150 -0
  145. data/test/scout/llm/tools/test_call_delegation_conflict.rb +316 -0
  146. data/test/scout/llm/tools/test_definition.rb +332 -0
  147. data/test/scout/llm/tools/test_jobs_file.rb +211 -0
  148. data/test/scout/llm/tools/test_mcp.rb +37 -8
  149. data/test/scout/llm/tools/test_workflow.rb +45 -1
  150. data/test/scout/model/decision/test_jev.rb +453 -0
  151. data/test/scout/model/python/huggingface/causal/test_next_token.rb +7 -10
  152. data/test/scout/model/python/huggingface/test_causal.rb +11 -2
  153. data/test/scout/model/python/huggingface/test_classification.rb +5 -3
  154. data/test/scout/model/python/test_availability.rb +116 -0
  155. data/test/scout/model/python/test_torch.rb +54 -2
  156. data/test/support/availability.rb +72 -174
  157. data/test/support/fake_clients.rb +18 -9
  158. data/test/support/fixtures.rb +75 -6
  159. data/test/support/mock_backend.rb +9 -1
  160. data/test/support/test_fixtures.rb +156 -0
  161. data/test/test_helper.rb +14 -4
  162. metadata +70 -26
  163. data/research/ChatAnalyst-required-changes.md +0 -167
  164. data/research/agent-delegation-analysis.md +0 -810
  165. data/research/agent-meta-provenance-integration-plan.md +0 -622
  166. data/research/agent-workflow-analysis.md +0 -1120
  167. data/research/backends-analysis.md +0 -836
  168. data/research/chat-core-analysis.md +0 -946
  169. data/research/chatanalyst-provenance/00-baseline.md +0 -30
  170. data/research/chatanalyst-provenance/01-repo-map.md +0 -60
  171. data/research/chatanalyst-provenance/02-event-reconstruction.md +0 -55
  172. data/research/chatanalyst-provenance/03-duplication-evidence.md +0 -45
  173. data/research/chatanalyst-provenance/04-tooling-root-cause.md +0 -57
  174. data/research/chatanalyst-provenance/05-fix-plan.md +0 -46
  175. data/research/chatanalyst-provenance/07-critic-review.md +0 -25
  176. data/research/chatanalyst-provenance/final-report.md +0 -45
  177. data/research/chatanalyst-provenance/resumption.md +0 -37
  178. data/research/coding-philosophy-analysis.md +0 -928
  179. data/research/commands-analysis.md +0 -947
  180. data/research/multi-agent-patterns-analysis.md +0 -853
  181. data/research/prompt-strategies-analysis.md +0 -630
  182. data/research/prov-verbosity-fix-notes.md +0 -77
  183. data/research/provenance-analysis.md +0 -469
  184. data/research/provenance-continuation-accounting.md +0 -255
  185. data/research/synthesis-report.md +0 -487
  186. data/research/tools-system-analysis.md +0 -779
@@ -0,0 +1,1777 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Agent-level virtual Path interface.
4
+ #
5
+ # A path is addressed by a kind and a path, e.g.:
6
+ #
7
+ # view::studies/show.slim
8
+ # task::sync.rb
9
+ # cortex::briefs/current.md
10
+ #
11
+ # Kinds are deliberately represented as hashes. A kind describes the
12
+ # namespace, where objects live, which generic operations are available, and
13
+ # optionally supplies kind-specific operations such as validation, smoke,
14
+ # or promotion.
15
+ #
16
+ # Path plugins are loaded in the context of an Agent instance, so a plugin
17
+ # file can simply call `register_path_kind`; registration is agent-local
18
+ # (there is no class-wide registry).
19
+
20
+ require "fileutils"
21
+ require_relative "../sandbox"
22
+ require_relative "path/patch"
23
+ require_relative "path/edit"
24
+ require_relative "path/workflow_kinds"
25
+
26
+ module LLM
27
+ class Agent
28
+ include AgentPathEdit
29
+ include AgentPathWorkflowKinds
30
+ DEFAULT_CAPABILITIES = {
31
+ "read" => true,
32
+ "write" => true,
33
+ "edit" => true,
34
+ "list" => true,
35
+ "move" => true,
36
+ "rename" => true,
37
+ "delete" => true,
38
+ "validate" => false,
39
+ "promote" => false,
40
+ "smoke" => false,
41
+ "patch" => false
42
+ }.freeze
43
+
44
+ GENERIC_OPERATIONS = %w[
45
+ read write edit list move rename delete
46
+ ].freeze
47
+
48
+ SPECIAL_OPERATIONS = %w[
49
+ validate promote smoke patch
50
+ ].freeze
51
+
52
+ # All engine-owned built-in operations, in stable order. Public tool
53
+ # schemas for these stay engine-side (path_tool_definition); a kind can
54
+ # replace an implementation via an override, never the schema.
55
+ BUILT_IN_OPERATIONS = (GENERIC_OPERATIONS + SPECIAL_OPERATIONS).freeze
56
+
57
+ # Handler types a custom operation implementation may declare:
58
+ # :content - content-transform handler: receives resolved content and
59
+ # args, returns transformed content; the ENGINE reads and
60
+ # writes the authorized target around it.
61
+ # :full - full handler: receives the resolved authorized target and
62
+ # args, returns a result. Trusted plugin code: the engine
63
+ # cannot constrain which files it touches.
64
+ PATH_HANDLER_TYPES = %i[content full].freeze
65
+
66
+ # Authorization modes a custom operation may request; the engine's
67
+ # existing sandbox mode vocabulary. Fail-closed default is :write.
68
+ PATH_AUTHORIZATION_MODES = %i[read write].freeze
69
+
70
+ # Authorization mode the ENGINE applies to its own built-in operations
71
+ # (read/list are read-only; every other built-in mutates). Recorded
72
+ # into each kind's canonical operation table at registration.
73
+ BUILTIN_OPERATION_AUTHORIZATION = {
74
+ "read" => :read,
75
+ "list" => :read
76
+ }.freeze
77
+
78
+ # Built-ins whose overrides the engine actually DISPATCHES to, with the
79
+ # handler types each accepts. Registering an override for any other
80
+ # built-in is rejected at registration time: the callable could never
81
+ # run, because only write/edit/patch consult the operation table at
82
+ # dispatch (DC-1). The non-dispatching built-ins that are customizable
83
+ # at all use their own hook mechanisms instead of overrides.
84
+ OVERRIDE_DISPATCH_OPERATIONS = %w[write edit patch].freeze
85
+ OVERRIDE_HANDLER_TYPES = {
86
+ "write" => %i[content full].freeze,
87
+ "edit" => %i[content full].freeze,
88
+ "patch" => %i[content].freeze
89
+ }.freeze
90
+
91
+ # Handler type recorded in a kind's operation table for a built-in the
92
+ # kind does NOT override. Only write/edit/patch can be overridden
93
+ # (OVERRIDE_DISPATCH_OPERATIONS), so the engine-default entry for every
94
+ # other built-in stays :full; for the overridable three the default
95
+ # records the type the ENGINE method itself dispatches with (write
96
+ # dispatches content handlers, edit and patch dispatch content
97
+ # handlers too - see path_write / path_edit / path_patch).
98
+ BUILTIN_DEFAULT_HANDLER_TYPES = {
99
+ "write" => :content,
100
+ "edit" => :content,
101
+ "patch" => :content
102
+ }.freeze
103
+
104
+ # ------------------------------------------------------------------
105
+ # Registry
106
+ # ------------------------------------------------------------------
107
+
108
+ # Agent-local registry. This deliberately remains a plain Hash so
109
+ # workflows/agent definitions can inspect or modify it without another
110
+ # abstraction layer. It is the single authoritative registry: kinds are
111
+ # registered per agent instance and never shared between agents.
112
+ def path_kind_registry
113
+ @path_kinds ||= {}
114
+ end
115
+
116
+ # CANONICAL REPRESENTATION. `register_path_kind` normalizes a kind
117
+ # definition ONCE, at registration, into the form every later consumer
118
+ # reads directly. The normalized definition carries:
119
+ #
120
+ # "name", "description", "sandbox" (boolean, default true),
121
+ # "locations" (Array, default ["project"]), "default_location",
122
+ # "capabilities" (full DEFAULT_CAPABILITIES-shaped Hash),
123
+ # "operations" -> { op name -> normalized custom spec } (a custom op
124
+ # registers support implicitly; no capability flag),
125
+ # "overrides" -> { built-in name -> {"implementation" => Callable} }
126
+ # (implementation replacement only; capability
127
+ # gating is never bypassed),
128
+ # "operation_table" -> { op name -> {"implementation" => Callable or
129
+ # nil (engine default), "authorization" => :read/:write,
130
+ # "type" => :content/:full } } for every SUPPORTED
131
+ # operation of the kind: enabled built-ins, every
132
+ # override target, and every custom operation. An
133
+ # override of a capability-disabled built-in IS in the
134
+ # table (support), but the ENGINE method still gates on
135
+ # capabilities, so the pair can never be executed.
136
+ #
137
+ # Callers keep authoring the declarative form (Hash of keys); the
138
+ # engine is the only place that interpretation happens.
139
+ def register_path_kind(name, definition = nil, &block)
140
+ definition = block.call if definition.nil? && block
141
+ definition ||= {}
142
+
143
+ name = name.to_s
144
+ raise ParameterException, "Path kind cannot be empty" if name.empty?
145
+ unless Hash === definition
146
+ raise ParameterException, "Path kind definition must be a mapping"
147
+ end
148
+
149
+ definition = definition.dup
150
+ definition["name"] = name
151
+ definition["sandbox"] = true unless definition.key?("sandbox")
152
+ unless [true, false].include?(definition["sandbox"])
153
+ raise ParameterException, "Path kind sandbox setting must be boolean"
154
+ end
155
+ definition["description"] ||= "#{name} path"
156
+
157
+ definition["locations"] ||= ["project"]
158
+ path_validate_locations!(definition)
159
+
160
+ # Scout path maps: normalize an optional per-kind "path_map" key, then
161
+ # pin NON-absolute roots against the effective map (the kind's map,
162
+ # else the agent-level path_map option, else :current) BEFORE the
163
+ # absolute-root validation. Absolute roots pass through untouched.
164
+ definition.delete("path_map") if definition["path_map"].nil?
165
+ unless definition["path_map"].nil?
166
+ definition["path_map"] =
167
+ path_map_validate!(definition["path_map"], "Path kind #{name.inspect} path_map")
168
+ end
169
+ effective_path_map = path_kind_effective_map(definition)
170
+ path_pin_roots!(definition, effective_path_map)
171
+
172
+ path_validate_roots!(definition)
173
+
174
+ capabilities = definition.fetch("capabilities", {})
175
+ if Array === capabilities
176
+ unless capabilities.all? { |operation| String === operation || Symbol === operation }
177
+ raise ParameterException, "Path kind capabilities must name built-in operations"
178
+ end
179
+ capabilities = capabilities.each_with_object({}) do |operation, hash|
180
+ hash[operation.to_s] = true
181
+ end
182
+ elsif Hash === capabilities
183
+ capabilities = capabilities.each_with_object({}) do |(operation, enabled), hash|
184
+ unless String === operation || Symbol === operation
185
+ raise ParameterException, "Path kind capability names must be strings or symbols"
186
+ end
187
+ operation = operation.to_s
188
+ unless BUILT_IN_OPERATIONS.include?(operation)
189
+ raise ParameterException, "Unknown Path kind capability #{operation.inspect}"
190
+ end
191
+ unless [true, false].include?(enabled)
192
+ raise ParameterException, "Path kind capability #{operation.inspect} must be boolean"
193
+ end
194
+ hash[operation] = enabled
195
+ end
196
+ else
197
+ raise ParameterException, "Path kind capabilities must be an Array or mapping"
198
+ end
199
+ capabilities.each_key do |operation|
200
+ unless BUILT_IN_OPERATIONS.include?(operation)
201
+ raise ParameterException, "Unknown Path kind capability #{operation.inspect}"
202
+ end
203
+ end
204
+ definition["capabilities"] = DEFAULT_CAPABILITIES.merge(capabilities)
205
+
206
+ default_location = definition["default_location"]
207
+ default_location = definition["locations"].first if default_location.nil?
208
+ unless String === default_location && definition["locations"].include?(default_location)
209
+ raise ParameterException,
210
+ "Default location #{default_location.inspect} is not included in locations for #{name}"
211
+ end
212
+ definition["default_location"] = default_location
213
+
214
+ path_validate_kind_hooks!(definition)
215
+ path_validate_promotion_destination!(definition)
216
+ definition["operations"] = path_normalize_custom_operations(definition)
217
+ definition["overrides"] = path_normalize_operation_overrides(definition)
218
+
219
+ definition["operation_table"] =
220
+ path_operation_table(definition["capabilities"],
221
+ definition["operations"],
222
+ definition["overrides"])
223
+
224
+ had_registry = instance_variable_defined?(:@path_kinds)
225
+ registry = path_kind_registry
226
+ had_previous_kind = registry.key?(name)
227
+ previous_kind = registry[name]
228
+ had_options = instance_variable_defined?(:@other_options)
229
+ previous_options = @other_options if had_options
230
+ previous_tools_present = previous_options.is_a?(Hash) && previous_options.key?(:tools)
231
+ previous_tools = previous_options[:tools] if previous_tools_present
232
+ previous_tool_entries = previous_tools.dup if previous_tools.is_a?(Hash)
233
+
234
+ registry[name] = definition
235
+ begin
236
+ install_path_tools
237
+ rescue Exception
238
+ # Restore the exact prior registration and installed tool entries. The
239
+ # installation routine updates the tool Hash incrementally, so merely
240
+ # deleting the candidate kind would leave stale/partial tool schemas.
241
+ if had_previous_kind
242
+ registry[name] = previous_kind
243
+ else
244
+ registry.delete(name)
245
+ end
246
+ remove_instance_variable(:@path_kinds) unless had_registry
247
+
248
+ if had_options
249
+ @other_options = previous_options
250
+ if previous_options.is_a?(Hash)
251
+ if previous_tools_present
252
+ if previous_tools.is_a?(Hash) && previous_tool_entries
253
+ previous_tools.replace(previous_tool_entries)
254
+ end
255
+ previous_options[:tools] = previous_tools
256
+ else
257
+ previous_options.delete(:tools)
258
+ end
259
+ end
260
+ elsif instance_variable_defined?(:@other_options)
261
+ remove_instance_variable(:@other_options)
262
+ end
263
+ raise
264
+ end
265
+ definition
266
+ end
267
+
268
+ # Validate declared location names before any registry or tool mutation.
269
+ def path_validate_locations!(definition)
270
+ locations = definition["locations"]
271
+ unless Array === locations && !locations.empty? &&
272
+ locations.all? { |location| String === location && !location.empty? } &&
273
+ locations.uniq.length == locations.length
274
+ raise ParameterException,
275
+ "Path kind locations must be a nonempty Array of unique, nonempty Strings"
276
+ end
277
+ end
278
+
279
+ # ------------------------------------------------------------------
280
+ # Scout path maps for kind roots
281
+ # ------------------------------------------------------------------
282
+ # A NON-absolute (relative/unlocated) root would otherwise be carried
283
+ # as a logical Scout path and re-resolved later (Path#find on a missing
284
+ # target falls back through Scout's map_order to :user, i.e. ~/.scout).
285
+ # The map declared here (per kind, else the agent-level :path_map
286
+ # option, else :current) is applied ONCE at registration and the result
287
+ # is pinned to an absolute String, so the filesystem boundary
288
+ # (plain File.* on target.to_s) can never re-resolve.
289
+ DEFAULT_PATH_MAP = :current
290
+
291
+ # The agent-level default map, an option on this Agent instance:
292
+ # LLM.agent(path_map: :lib) { ... }
293
+ def path_map_option
294
+ raw = @other_options.key?(:path_map) ? @other_options[:path_map] : nil
295
+ raw = nil if raw.to_s.empty?
296
+ raw.nil? ? DEFAULT_PATH_MAP : path_map_validate!(raw, "Agent path_map option")
297
+ end
298
+
299
+ # Effective map for one kind: the kind's own "path_map" key wins, then
300
+ # the agent-level default. Returns a Symbol.
301
+ def path_kind_effective_map(definition)
302
+ map = definition["path_map"]
303
+ map = path_map_option if map.nil?
304
+ Symbol === map ? map : map.to_s.to_sym
305
+ end
306
+
307
+ # A map must be a String or Symbol naming a resolvable Scout path map.
308
+ # Instance maps (Path.add_path / per-PATH maps) and the global
309
+ # Path.path_maps table are both accepted; anything else raises the
310
+ # framework's parameter error.
311
+ def path_map_validate!(map, label)
312
+ unless String === map || Symbol === map
313
+ raise ParameterException,
314
+ "#{label} must be a String or Symbol naming a Scout path map"
315
+ end
316
+ name = map.to_s.to_sym
317
+ begin
318
+ Scout.root.follow(name)
319
+ rescue StandardError => error
320
+ raise ParameterException,
321
+ "#{label} is not a resolvable Scout path map: #{map.inspect} " \
322
+ "(#{error.class}: #{error.message.split("\n").first.strip[0, 120]})"
323
+ end
324
+ name
325
+ end
326
+
327
+ # Pin every NON-absolute root of the definition against the effective
328
+ # map and store it back as an absolute String. Absolute roots (Strings
329
+ # or Path-likes) pass through untouched, so kinds that already resolve
330
+ # to absolute roots keep their current placement (compatibility rule).
331
+ def path_pin_roots!(definition, effective_map)
332
+ roots = definition["roots"]
333
+ return unless Hash === roots
334
+
335
+ roots.each_pair do |location, root|
336
+ next if root.to_s.start_with?(File::SEPARATOR)
337
+
338
+ root = Path.setup(root.to_s)
339
+ begin
340
+ pinned = root.follow(effective_map)
341
+ rescue StandardError => error
342
+ raise ParameterException,
343
+ "Path kind #{definition['name'].inspect} root for location #{location.inspect} " \
344
+ "could not be resolved against path map #{effective_map.inspect}: " \
345
+ "#{error.class}: #{error.message.split("\n").first.strip[0, 120]}"
346
+ end
347
+ pinned = pinned.to_s
348
+ unless pinned.start_with?(File::SEPARATOR)
349
+ raise ParameterException,
350
+ "Path kind #{definition['name'].inspect} root for location #{location.inspect} " \
351
+ "did not resolve to an absolute path through map #{effective_map.inspect}"
352
+ end
353
+ roots[location] = pinned
354
+ end
355
+ end
356
+
357
+ # Roots are authorization grants. Every declared location needs a root,
358
+ # except the long-standing implicit project root used by resolve_path and
359
+ # path_authorize! when no explicit project root is supplied.
360
+ def path_validate_roots!(definition)
361
+ roots = definition.fetch("roots", {})
362
+ unless Hash === roots
363
+ raise ParameterException, "Path kind roots must be a mapping"
364
+ end
365
+ roots.each_pair do |location, root|
366
+ unless String === location && !location.empty?
367
+ raise ParameterException,
368
+ "Path kind root location names must be nonempty Strings"
369
+ end
370
+ path_validate_root!(location, root)
371
+ end
372
+
373
+ definition["locations"].each do |location|
374
+ next if roots.key?(location)
375
+ next if location == "project"
376
+
377
+ raise ParameterException,
378
+ "Path kind #{definition['name']} has no root configured for location #{location}"
379
+ end
380
+
381
+ if definition["locations"].include?("project") && !roots.key?("project")
382
+ begin
383
+ path_validate_root!("project", Scout.root.find(path_kind_effective_map(definition)))
384
+ rescue ParameterException
385
+ raise
386
+ rescue StandardError => error
387
+ raise ParameterException,
388
+ "Path kind implicit project root is unavailable: #{error.message}"
389
+ end
390
+ end
391
+ end
392
+
393
+ def path_validate_root!(location, root)
394
+ root_string = root.to_s
395
+ scout_path = root.respond_to?(:to_path) ||
396
+ (defined?(Path) && Path === root)
397
+ unless !root_string.empty? && root_string.start_with?(File::SEPARATOR) &&
398
+ (String === root || scout_path)
399
+ raise ParameterException,
400
+ "Path kind root for location #{location.inspect} must be a nonempty absolute path " \
401
+ "or an absolute Scout Path-like object"
402
+ end
403
+ end
404
+
405
+ def path_validate_kind_hooks!(definition)
406
+ %w[resolve list validate smoke promotion_post_move].each do |hook|
407
+ next unless definition.key?(hook)
408
+ unless definition[hook].respond_to?(:call)
409
+ raise ParameterException, "Path kind #{hook} hook must be Callable"
410
+ end
411
+ end
412
+ end
413
+
414
+ # Promotion destinations are resolved and authorized by the engine, so
415
+ # only the documented declarative forms may be stored in a kind.
416
+ def path_validate_promotion_destination!(definition)
417
+ destination = definition["promotion_destination"]
418
+ if destination.nil?
419
+ # The implicit project destination matters only when promotion is
420
+ # enabled; non-promotable kinds need not declare an unused location.
421
+ return unless definition["capabilities"].fetch("promote", false)
422
+ location = "project"
423
+ unless definition["locations"].include?(location)
424
+ raise ParameterException,
425
+ "Invalid promotion destination for path kind #{definition['name']}: default project location is not declared"
426
+ end
427
+ return
428
+ end
429
+
430
+ if String === destination
431
+ unless definition["locations"].include?(destination)
432
+ raise ParameterException,
433
+ "Invalid promotion destination for path kind #{definition['name']}: location #{destination.inspect} is not declared"
434
+ end
435
+ return
436
+ end
437
+
438
+ unless Hash === destination && destination.key?("location") &&
439
+ (destination.keys - %w[location path]).empty?
440
+ raise ParameterException,
441
+ "Invalid promotion destination for path kind #{definition['name']}: expected a location String or a Hash with location and optional path"
442
+ end
443
+ location = destination["location"]
444
+ unless String === location && definition["locations"].include?(location)
445
+ raise ParameterException,
446
+ "Invalid promotion destination for path kind #{definition['name']}: location #{location.inspect} is not declared"
447
+ end
448
+ if destination.key?("path") && !(String === destination["path"])
449
+ raise ParameterException,
450
+ "Invalid promotion destination for path kind #{definition['name']}: path must be a String"
451
+ end
452
+ end
453
+
454
+ # Build the per-kind operation table at registration time: one entry per
455
+ # SUPPORTED operation, ready for direct reads. Entry shape:
456
+ # {"implementation" => Callable or nil, "authorization" => :read/:write,
457
+ # "type" => :content/:full}
458
+ # Precedence mirrors the engine contract: an override beats the engine
459
+ # default; a custom operation carries its own registered callable; the
460
+ # engine default for a built-in has implementation nil (dispatched to the
461
+ # engine method). Disabled built-ins are absent - support is exactly
462
+ # `operation_table.key?(op)` after this point.
463
+ def path_operation_table(capabilities, operations, overrides)
464
+ table = {}
465
+
466
+ capabilities.each_pair do |operation, enabled|
467
+ next unless enabled
468
+ operation = operation.to_s
469
+ table[operation] = {
470
+ "implementation" => overrides.dig(operation, "implementation"),
471
+ "authorization" => BUILTIN_OPERATION_AUTHORIZATION.fetch(operation, :write),
472
+ "type" => overrides.dig(operation, "type") || BUILTIN_DEFAULT_HANDLER_TYPES.fetch(operation, :full)
473
+ }
474
+ end
475
+
476
+ overrides.each_pair do |operation, spec|
477
+ operation = operation.to_s
478
+ next if table.key?(operation)
479
+ table[operation] = {
480
+ "implementation" => spec["implementation"],
481
+ "authorization" => BUILTIN_OPERATION_AUTHORIZATION.fetch(operation, :write),
482
+ "type" => spec["type"]
483
+ }
484
+ end
485
+
486
+ operations.each_pair do |operation, spec|
487
+ table[operation.to_s] = {
488
+ "implementation" => spec["implementation"],
489
+ "authorization" => spec["authorization"],
490
+ "type" => spec["type"]
491
+ }
492
+ end
493
+
494
+ table
495
+ end
496
+
497
+ # Load a plugin file in the context of this Agent instance.
498
+ #
499
+ # Example plugin:
500
+ #
501
+ # register_path_kind :view,
502
+ # "description" => "A Slim web view",
503
+ # "locations" => ["tmp", "project"],
504
+ # # Roots MUST be absolute paths (build them with File.expand_path);
505
+ # # relative roots are rejected by the sandbox. Plugin-author docs:
506
+ # # doc/developer/PathEngine.md.
507
+ # "roots" => {
508
+ # "tmp" => File.expand_path(".scout/var/path/views"),
509
+ # "project" => File.expand_path("share/views")
510
+ # },
511
+ # "capabilities" => {"promote" => true},
512
+ # "validate" => ->(path, content) { ... },
513
+ # # Promotion destination is DECLARATIVE: a location String, or a Hash
514
+ # # with "location" (plus optional "path"; default is the source path).
515
+ # # The ENGINE authorizes both endpoints and performs the move itself;
516
+ # # no mover callback exists. A Callable destination is rejected.
517
+ # "promotion_destination" => "project",
518
+ # # Optional post-move hook: runs AFTER the engine-controlled move,
519
+ # # receives the authorized endpoints in args; never the writer.
520
+ # "promotion_post_move" => ->(agent, path, location, args) { ... }
521
+ #
522
+ # The file can therefore be a very small declarative definition rather
523
+ # than a class hierarchy.
524
+ def load_path_plugins(*files)
525
+ files.flatten.each do |file|
526
+ instance_eval(File.read(file), file.to_s, 1)
527
+ end
528
+ install_path_tools
529
+ self
530
+ end
531
+
532
+ def path_kind_definition(kind)
533
+ path_kind_registry.fetch(kind.to_s) do
534
+ raise ParameterException, "Unknown path kind: #{kind}"
535
+ end
536
+ end
537
+
538
+ # Direct read of the canonical representation: capability gating.
539
+ def path_kind_capable?(kind, operation)
540
+ !!path_kind_definition(kind).fetch("capabilities", {}).fetch(operation.to_s, false)
541
+ end
542
+
543
+ # ------------------------------------------------------------------
544
+ # Operation registration contract
545
+ # ------------------------------------------------------------------
546
+
547
+ # Normalize the optional "operations" key of a kind definition into
548
+ # validated custom-operation specs. Registering a custom operation
549
+ # ESTABLISHES support for it on that kind: no capability flag, no
550
+ # second boolean.
551
+ def path_normalize_custom_operations(definition)
552
+ operations = definition["operations"]
553
+ operations = {} if operations.nil?
554
+ unless operations.respond_to?(:each_pair)
555
+ raise ParameterException,
556
+ "Path kind operations must be a mapping of operation name to spec"
557
+ end
558
+
559
+ normalized = {}
560
+ operations.each_pair do |name, spec|
561
+ name = name.to_s
562
+ raise ParameterException, "Custom operation name cannot be empty" if name.empty?
563
+
564
+ if BUILT_IN_OPERATIONS.include?(name)
565
+ raise ParameterException,
566
+ "Custom operation #{name.inspect} collides with a built-in " \
567
+ "operation; register an override instead"
568
+ end
569
+
570
+ spec = {"implementation" => spec} if spec.respond_to?(:call)
571
+ unless Hash === spec
572
+ raise ParameterException,
573
+ "Custom operation #{name.inspect} must be a Callable or a spec Hash"
574
+ end
575
+
576
+ implementation = spec["implementation"]
577
+ unless implementation.respond_to?(:call)
578
+ raise ParameterException,
579
+ "Custom operation #{name.inspect} requires an implementation Callable"
580
+ end
581
+
582
+ authorization = spec["authorization"]
583
+ authorization = :write if authorization.nil?
584
+ unless String === authorization || Symbol === authorization
585
+ raise ParameterException,
586
+ "Custom operation #{name.inspect} authorization must be a String or Symbol"
587
+ end
588
+ authorization = authorization.to_sym
589
+ unless PATH_AUTHORIZATION_MODES.include?(authorization)
590
+ raise ParameterException,
591
+ "Custom operation #{name.inspect} authorization must be one of " \
592
+ "#{PATH_AUTHORIZATION_MODES.map(&:inspect).join(', ')}; got " \
593
+ "#{authorization.inspect}"
594
+ end
595
+
596
+ handler = spec["type"]
597
+ handler = :full if handler.nil?
598
+ unless String === handler || Symbol === handler
599
+ raise ParameterException,
600
+ "Custom operation #{name.inspect} type must be a String or Symbol"
601
+ end
602
+ handler = handler.to_sym
603
+ unless PATH_HANDLER_TYPES.include?(handler)
604
+ raise ParameterException,
605
+ "Custom operation #{name.inspect} type must be one of " \
606
+ "#{PATH_HANDLER_TYPES.map(&:inspect).join(', ')}; got #{handler.inspect}"
607
+ end
608
+
609
+ parameters = spec["parameters"]
610
+ parameters = {} if parameters.nil?
611
+ unless Hash === parameters
612
+ raise ParameterException,
613
+ "Custom operation #{name.inspect} parameters must be a Hash"
614
+ end
615
+
616
+ normalized[name] = {
617
+ "name" => name,
618
+ "description" => spec["description"] || "Custom Path operation #{name}.",
619
+ "parameters" => parameters,
620
+ "implementation" => implementation,
621
+ "authorization" => authorization,
622
+ "type" => handler
623
+ }
624
+ end
625
+ normalized
626
+ end
627
+
628
+ # ------------------------------------------------------------------
629
+ # Operation registry queries
630
+ # ------------------------------------------------------------------
631
+
632
+ # One canonical table per kind ("operation_table") is built at
633
+ # registration (path_operation_table); the queries below are direct
634
+ # reads of it. Support, authorization and implementation no longer
635
+ # re-derive anything at lookup time.
636
+
637
+ # Does this kind support the operation? Support is established at
638
+ # registration: enabled built-ins, their overrides, and custom
639
+ # operations are all in the table; nothing else is.
640
+ def path_operation_support?(kind, operation)
641
+ path_kind_definition(kind).fetch("operation_table", {}).key?(operation.to_s)
642
+ end
643
+
644
+ # Implementation selection: a direct read of the table entry - an
645
+ # override's callable, a custom operation's callable, or nil for the
646
+ # engine default. Nil when the operation is unsupported.
647
+ def path_operation_implementation(kind, operation)
648
+ entry = path_kind_definition(kind).fetch("operation_table", {})[operation.to_s]
649
+ entry && entry["implementation"]
650
+ end
651
+
652
+ # Handler type of the recorded entry (:content/:full); the engine
653
+ # default carries BUILTIN_DEFAULT_HANDLER_TYPES, an override carries
654
+ # its declared (validated) type.
655
+ def path_operation_handler_type(kind, operation)
656
+ entry = path_kind_definition(kind).fetch("operation_table", {})[operation.to_s]
657
+ entry && entry["type"]
658
+ end
659
+
660
+ # Apply a :content handler and REQUIRE a String return. Used where the
661
+ # engine has no final-newline preservation to perform (write), so the
662
+ # shared path_apply_content_handler guarantees would be a no-op; the
663
+ # String check itself is the shared non-String guard.
664
+ def path_content_handler_string(handler, target, original, args, kind)
665
+ result = handler.call(original, args)
666
+ unless String === result
667
+ raise ParameterException,
668
+ "Path kind #{kind} content handler must return a String, " \
669
+ "got #{result.class}"
670
+ end
671
+ result
672
+ end
673
+
674
+ # Normalize the optional "overrides" key: built-in name -> implementation
675
+ # Callable (or spec Hash with an "implementation" entry). An override
676
+ # replaces the implementation ONLY; the public tool schema stays
677
+ # engine-owned, and capability gating is not bypassed.
678
+ #
679
+ # The spec's declared "type" is preserved (default :content) and
680
+ # validated against the handler types the target built-in actually
681
+ # supports (OVERRIDE_HANDLER_TYPES). Only write/edit/patch dispatch to
682
+ # overrides today; overriding any other built-in is rejected here,
683
+ # because the callable would silently never run.
684
+ def path_normalize_operation_overrides(definition)
685
+ overrides = definition["overrides"]
686
+ overrides = {} if overrides.nil?
687
+ unless overrides.respond_to?(:each_pair)
688
+ raise ParameterException,
689
+ "Path kind overrides must be a mapping of built-in name to implementation"
690
+ end
691
+
692
+ normalized = {}
693
+ overrides.each_pair do |name, spec|
694
+ name = name.to_s
695
+ unless BUILT_IN_OPERATIONS.include?(name)
696
+ raise ParameterException,
697
+ "Override #{name.inspect} must name a built-in operation " \
698
+ "(#{BUILT_IN_OPERATIONS.join(', ')})"
699
+ end
700
+
701
+ unless OVERRIDE_DISPATCH_OPERATIONS.include?(name)
702
+ raise ParameterException,
703
+ "Override #{name.inspect} cannot be dispatched: the engine " \
704
+ "only consults overrides for #{OVERRIDE_DISPATCH_OPERATIONS.join(', ')}. " \
705
+ "Kind hooks, not overrides, customize the remaining built-ins: " \
706
+ "\"list\" (definition[\"list\"]), \"validate\" and \"smoke\" " \
707
+ "(definition[\"validate\"] / definition[\"smoke\"] via " \
708
+ "path_kind_operation); read/move/rename/delete have no " \
709
+ "customization surface"
710
+ end
711
+
712
+ spec = {"implementation" => spec} if spec.respond_to?(:call)
713
+ implementation = spec["implementation"] if Hash === spec
714
+ unless implementation.respond_to?(:call)
715
+ raise ParameterException,
716
+ "Override #{name.inspect} requires an implementation Callable"
717
+ end
718
+
719
+ handler = spec["type"] if Hash === spec
720
+ handler = :content if handler.nil?
721
+ unless String === handler || Symbol === handler
722
+ raise ParameterException,
723
+ "Override #{name.inspect} type must be a String or Symbol"
724
+ end
725
+ handler = handler.to_sym
726
+ supported = OVERRIDE_HANDLER_TYPES.fetch(name)
727
+ unless supported.include?(handler)
728
+ raise ParameterException,
729
+ "Override #{name.inspect} type must be one of " \
730
+ "#{supported.map(&:inspect).join(', ')}; got #{handler.inspect}. " \
731
+ "#{name} dispatches its override as a content transform"
732
+ end
733
+
734
+ normalized[name] = {"implementation" => implementation, "type" => handler}
735
+ end
736
+ normalized
737
+ end
738
+
739
+ # ------------------------------------------------------------------
740
+ # Tool installation
741
+ # ------------------------------------------------------------------
742
+
743
+ # One tool per operation name, derived from the canonical registry:
744
+ #
745
+ # 1. the `path_kinds` listing tool (kind enum live from the registry);
746
+ # 2. one engine-owned tool per BUILT-IN operation supported by at
747
+ # least one registered kind (`path_tool_definition`);
748
+ # 3. one aggregated tool per CUSTOM operation name across all kinds
749
+ # (`path_custom_tool_definition` contract-checks exact matches).
750
+ #
751
+ # `path_install_tool` is the single choke point every definition goes
752
+ # through, so re-running this routine replaces the whole surface.
753
+ def install_path_tools
754
+ return if path_kind_registry.empty?
755
+
756
+ path_install_tool("path_kinds",
757
+ "description" => <<~DESC.strip,
758
+ List the virtual Path kinds currently available to this agent.
759
+ Each kind identifies a namespace of textual objects and declares
760
+ its supported locations and operations. Supply kind to return
761
+ only that kind's entry.
762
+ DESC
763
+ "parameters" => {
764
+ "type" => "object",
765
+ "properties" => {
766
+ "kind" => {
767
+ "type" => "string",
768
+ "description" => "Registered Path kind to identify.",
769
+ "enum" => path_kind_registry.keys
770
+ }
771
+ },
772
+ "additionalProperties" => false
773
+ })
774
+
775
+ BUILT_IN_OPERATIONS.each do |operation|
776
+ next unless path_kind_registry.values.any? do |definition|
777
+ definition.fetch("capabilities", {}).fetch(operation, false)
778
+ end
779
+
780
+ path_install_tool("path_#{operation}", path_tool_definition(operation))
781
+ end
782
+
783
+ path_kind_registry.values
784
+ .flat_map { |definition| definition.fetch("operations", {}).keys }
785
+ .uniq.sort.each do |operation|
786
+ path_install_tool(operation, path_custom_tool_definition(operation))
787
+ end
788
+ end
789
+
790
+ # ------------------------------------------------------------------
791
+ # Custom-operation tool aggregation
792
+ # ------------------------------------------------------------------
793
+
794
+ # ONE public tool per custom operation name. Kinds registering the same
795
+ # operation must declare EXACTLY matching parameter contracts (after
796
+ # normalization, see path_normalized_contract); invocation routes by the
797
+ # "kind" argument. Built-ins keep engine-owned schemas and are never
798
+ # affected by custom registration.
799
+ def path_custom_tool_definition(operation)
800
+ kinds = []
801
+ spec = nil
802
+ description = nil
803
+
804
+ path_kind_registry.each_pair do |kind, definition|
805
+ candidate = definition.fetch("operations", {}).fetch(operation, nil)
806
+ next unless candidate
807
+
808
+ # Description resolution: the most recent registration wins. The
809
+ # registry is a plain Hash in insertion order, so iterating in order
810
+ # and overwriting on every candidate keeps the last-registered
811
+ # description, deterministically.
812
+ description = candidate.fetch("description")
813
+
814
+ if spec.nil?
815
+ spec = candidate
816
+ else
817
+ differences = path_contract_differences(
818
+ spec.fetch("parameters", {}),
819
+ candidate.fetch("parameters", {})
820
+ )
821
+ unless differences.empty?
822
+ raise ParameterException,
823
+ "Custom operation #{operation.inspect} registered by kinds " \
824
+ "#{kinds.first.inspect} and #{kind.inspect} with conflicting " \
825
+ "parameter contracts: #{differences.join('; ')}"
826
+ end
827
+ end
828
+ kinds << kind
829
+ end
830
+
831
+ properties = path_base_properties("Supported kinds: #{kinds.join(', ')}.")
832
+ properties["kind"]["enum"] = kinds
833
+
834
+ parameters = spec.fetch("parameters", {})
835
+ own_properties = parameters["properties"] || parameters.fetch(:properties, {})
836
+ required = parameters["required"] || parameters.fetch(:required, []) || []
837
+
838
+ own_properties = own_properties.each_with_object({}) do |(key, value), acc|
839
+ acc[key.to_s] = value
840
+ end
841
+ own_properties.each_pair do |key, value|
842
+ raise ParameterException,
843
+ "Custom operation #{operation.inspect} declares parameter " \
844
+ "#{key.inspect}, which collides with a path argument" if properties.key?(key)
845
+
846
+ properties[key] = value
847
+ end
848
+
849
+ required = (["kind", "path"] + required.map(&:to_s)).uniq
850
+
851
+ {
852
+ "description" => description,
853
+ "parameters" => {
854
+ "type" => "object",
855
+ "properties" => properties,
856
+ "required" => required,
857
+ "additionalProperties" => false
858
+ },
859
+ # The installed callable routes by the "kind" argument into the
860
+ # single engine dispatch entry point.
861
+ "implementation" => lambda do |arguments|
862
+ args = arguments.dup || {}
863
+ kind = args.delete("kind")
864
+ dispatch = method(:path_dispatch)
865
+ dispatch.call(kind: kind, operation: operation, **args)
866
+ end
867
+ }
868
+ end
869
+
870
+ # Normalized parameter-contract comparison. Two contracts match iff,
871
+ # recursively:
872
+ # - keys are compared STRINGIFIED (Symbol vs String are the same key);
873
+ # - "type" values are compared by ==;
874
+ # - "required" is compared as an UNORDERED SET;
875
+ # - "enum" lists are compared as UNORDERED SETS;
876
+ # - "default" values are compared by ==;
877
+ # - "description" is NOT compared (per-property descriptions are free
878
+ # text; the first kind's wording is kept);
879
+ # - Arrays and Hashes are compared element-wise recursively;
880
+ # - anything else is compared by ==.
881
+ # Returns a list of human-readable difference strings (empty == match).
882
+ def path_contract_differences(left, right, where = "parameters")
883
+ differences = []
884
+
885
+ # Contract parameters may use String or Symbol keys interchangeably;
886
+ # normalization lives here so callers can pass hashes either way.
887
+ left_keys = (left.respond_to?(:keys) ? left.keys : []).map(&:to_s)
888
+ right_keys = (right.respond_to?(:keys) ? right.keys : []).map(&:to_s)
889
+
890
+ (left_keys - right_keys).each do |key|
891
+ differences << "#{where}.#{key} present only in the first contract"
892
+ end
893
+ (right_keys - left_keys).each do |key|
894
+ differences << "#{where}.#{key} present only in the second contract"
895
+ end
896
+
897
+ (left_keys & right_keys).each do |key|
898
+ # String/Symbol-agnostic fetch; the key always exists on both sides
899
+ # because it comes from the key intersection above.
900
+ l = left.each_pair { |k, v| break v if k.to_s == key }
901
+ r = right.each_pair { |k, v| break v if k.to_s == key }
902
+
903
+ case key.to_s
904
+ when "description"
905
+ next # not compared
906
+ when "required"
907
+ l_set = Array(l).map(&:to_s).sort
908
+ r_set = Array(r).map(&:to_s).sort
909
+ differences << "#{where}.#{key} differs: #{l_set.inspect} vs #{r_set.inspect}" if l_set != r_set
910
+ when "enum"
911
+ l_set = Array(l).map(&:to_s).sort
912
+ r_set = Array(r).map(&:to_s).sort
913
+ differences << "#{where}.#{key} differs: #{l_set.inspect} vs #{r_set.inspect}" if l_set != r_set
914
+ else
915
+ if l.is_a?(Hash) && r.is_a?(Hash)
916
+ differences.concat(path_contract_differences(l, r, "#{where}.#{key}"))
917
+ elsif l.is_a?(Array) && r.is_a?(Array)
918
+ if l.length != r.length
919
+ differences << "#{where}.#{key} length differs: #{l.length} vs #{r.length}"
920
+ else
921
+ l.each_with_index do |lv, i|
922
+ rv = r[i]
923
+ if lv.is_a?(Hash) && rv.is_a?(Hash)
924
+ differences.concat(path_contract_differences(lv, rv, "#{where}.#{key}[#{i}]"))
925
+ elsif lv != rv
926
+ differences << "#{where}.#{key}[#{i}] differs: #{lv.inspect} vs #{rv.inspect}"
927
+ end
928
+ end
929
+ end
930
+ elsif l != r
931
+ differences << "#{where}.#{key} differs: #{l.inspect} vs #{r.inspect}"
932
+ end
933
+ end
934
+ end
935
+
936
+ differences
937
+ end
938
+
939
+ # Store tools in the same [callable, definition] format consumed by Agent#ask.
940
+ # When +definition+ carries an "implementation" key, that callable is used
941
+ # instead of public_send(name); custom-operation tools use this to route
942
+ # through the engine dispatch entry point.
943
+ def path_install_tool(name, definition, implementation=nil)
944
+ properties = definition.fetch("parameters").fetch("properties")
945
+ required = definition.fetch("parameters").fetch("required", [])
946
+ tool_definition = LLM.tool_definition(name, definition.fetch("description"), properties, required: required)
947
+ implementation = definition["implementation"] if implementation.nil? && definition.key?("implementation")
948
+ implementation = name.to_sym if implementation.nil?
949
+ callable = Proc.new { |_tool_name, arguments|
950
+ begin
951
+ if implementation.respond_to?(:call)
952
+ implementation.call(arguments)
953
+ else
954
+ public_send(implementation, arguments)
955
+ end
956
+ rescue ScoutException => e
957
+ error = :scout
958
+ stack = e.backtrace
959
+ content = {exception: e.message, exception_line: e.backtrace&.first}.to_json
960
+ end
961
+ }
962
+
963
+ @other_options ||= {}
964
+ @other_options[:tools] ||= {}
965
+ @other_options[:tools][name] = [callable, tool_definition]
966
+ end
967
+
968
+ # ------------------------------------------------------------------
969
+ # Centralized dispatch entry point
970
+ # ------------------------------------------------------------------
971
+
972
+ # Single engine entry point for CUSTOM operations. Every custom operation
973
+ # flows through here; built-in tools keep calling their engine methods
974
+ # directly, and those methods share the same funnel (resolve -> capability
975
+ # -> authorize -> implement) inside themselves.
976
+ #
977
+ # Custom-operation flow:
978
+ # 1. kind known? -> ParameterException otherwise
979
+ # 2. operation supported? -> ParameterException otherwise (support is
980
+ # looked up on THIS kind only; no cross-kind fallback)
981
+ # 3. resolve target from args (kind, path, location)
982
+ # 4. authorize target with the registered mode BEFORE any callback
983
+ # runs (unauthorized call: no callback, no mutation)
984
+ # 5. execute by handler type:
985
+ # - :content -> engine read -> implementation.call(content, args)
986
+ # -> engine writes the SAME authorized target
987
+ # - :full -> implementation.call(self, target, args); trusted
988
+ # plugin code, the engine cannot constrain what a
989
+ # full handler touches (documented trust boundary)
990
+ #
991
+ # Built-ins with an OVERRIDE stay entered through their engine method
992
+ # (public behavior and result shape unchanged); the override runs at
993
+ # the read/transform/write boundary inside that method, after
994
+ # authorization - see path_edit and path_apply_content_handler.
995
+ def path_dispatch(kind:, operation:, **args)
996
+ kind = kind.to_s
997
+ operation = operation.to_s
998
+
999
+ unless path_kind_registry.key?(kind)
1000
+ raise ParameterException,
1001
+ "Unknown Path kind: #{kind.inspect}"
1002
+ end
1003
+
1004
+ definition = path_kind_definition(kind)
1005
+ entry = definition.fetch("operation_table", {})[operation]
1006
+ custom = definition.fetch("operations", {})[operation]
1007
+
1008
+ unless entry
1009
+ raise ParameterException,
1010
+ "Path kind #{kind.inspect} does not support operation #{operation.inspect}"
1011
+ end
1012
+
1013
+ if custom
1014
+ authorization = custom.fetch("authorization", :write)
1015
+ path = path_argument(args, "path")
1016
+ location = args["location"]
1017
+ path_map = args["path_map"] || DEFAULT_PATH_MAP
1018
+ target = resolve_path(kind, path, location, path_map)
1019
+ path_authorize!(kind, target, location, mode: authorization)
1020
+
1021
+ implementation = custom.fetch("implementation")
1022
+
1023
+ if custom.fetch("type", :full) == :content
1024
+ original = path_read_text(target)
1025
+ transformed = implementation.call(original, args)
1026
+ path_write_text(target, transformed)
1027
+
1028
+ {
1029
+ "doc_id" => path_doc_id(kind, path, args["version"]),
1030
+ "kind" => kind,
1031
+ "path" => path,
1032
+ "changed" => original != transformed,
1033
+ "content" => transformed
1034
+ }
1035
+ else
1036
+ implementation.call(self, target, args)
1037
+ end
1038
+ else
1039
+ # Built-in reached through dispatch: delegate to the engine
1040
+ # method, which applies the same funnel and result shape. The
1041
+ # kind arrives as a dispatch keyword; engine methods take it as a
1042
+ # hash argument, so re-inject it here.
1043
+ public_send("path_#{operation}", args.merge("kind" => kind))
1044
+ end
1045
+ end
1046
+
1047
+ # Shared kind/path(/location) property trio every Path tool starts
1048
+ # from. Insertion order is part of the serialized schema.
1049
+ def path_base_properties(kind_description, with_location: true)
1050
+ properties = {
1051
+ "kind" => {
1052
+ "type" => "string",
1053
+ "description" => "Kind of path. #{kind_description}"
1054
+ },
1055
+ "path" => {
1056
+ "type" => "string",
1057
+ "description" => "Path within the selected kind."
1058
+ }
1059
+ }
1060
+
1061
+ if with_location
1062
+ properties["location"] = {
1063
+ "type" => "string",
1064
+ "description" => "Storage location; defaults to the kind's default location."
1065
+ }
1066
+ end
1067
+
1068
+ properties
1069
+ end
1070
+
1071
+ def path_tool_definition(operation)
1072
+ kinds = path_kind_registry.keys
1073
+ kind_description = if kinds.empty?
1074
+ "No Path kinds are currently registered."
1075
+ else
1076
+ "Supported kinds: #{kinds.join(', ')}."
1077
+ end
1078
+
1079
+ properties = path_base_properties(kind_description,
1080
+ with_location: operation != "list")
1081
+
1082
+ case operation
1083
+ when "list"
1084
+ # `path` is optional for list: an omitted path lists the kind root,
1085
+ # a relative subdirectory lists that subtree. The parameter keeps
1086
+ # the base spelling; only its description is specialized here.
1087
+ properties["path"]["description"] =
1088
+ "Optional subdirectory within the selected kind; omit to list the kind root."
1089
+ when "write"
1090
+ properties["content"] = {
1091
+ "type" => "string",
1092
+ "description" => "Complete textual content to write."
1093
+ }
1094
+ when "edit"
1095
+ properties["selector"] = {
1096
+ "type" => "object",
1097
+ "description" => "Text selector. Supports line, character, or regexp selectors.",
1098
+ "properties" => {
1099
+ "type" => {"type" => "string", "enum" => %w[lines chars regexp]},
1100
+ "start" => {"type" => "integer"},
1101
+ "end" => {"type" => "integer"},
1102
+ "pattern" => {"type" => "string"}
1103
+ },
1104
+ "additionalProperties" => false
1105
+ }
1106
+ properties["replacement"] = {
1107
+ "type" => "string",
1108
+ "description" => "Replacement text."
1109
+ }
1110
+ when "patch"
1111
+ properties["patch"] = {
1112
+ "type" => "string",
1113
+ "description" => "Unified diff for THIS file only (one ---/+++ pair, " \
1114
+ "one or more @@ hunks). Header filenames are ignored; " \
1115
+ "the target is the resolved kind/path/location."
1116
+ }
1117
+ when "move"
1118
+ properties["destination"] = {
1119
+ "type" => "string",
1120
+ "description" => "Destination path within the same kind/location."
1121
+ }
1122
+ when "rename"
1123
+ properties["name"] = {
1124
+ "type" => "string",
1125
+ "description" => "New path/name."
1126
+ }
1127
+ when "promote"
1128
+ properties["overwrite"] = {
1129
+ "type" => "boolean",
1130
+ "description" => "Allow replacing an existing promotion destination. " \
1131
+ "Default false: an existing destination aborts the promotion."
1132
+ }
1133
+ properties["defer_reload"] = {
1134
+ "type" => "boolean",
1135
+ "description" => "ScoutCoder-only caller argument: when true, skip " \
1136
+ "the automatic post-promotion workflow reload and " \
1137
+ "report promotion_status \"deferred\" in the tool " \
1138
+ "result (default false = immediate reload)."
1139
+ }
1140
+ when "validate"
1141
+ # Kind-specific operations may extend this schema through the
1142
+ # optional `parameters` hash in the kind definition.
1143
+ end
1144
+
1145
+ operation_descriptions = {
1146
+ "read" => "Read the textual content of a virtual Path.",
1147
+ "write" => "Write complete textual content to a virtual Path.",
1148
+ "edit" => "Edit a textual Path using a line range, character range, or regular expression selector.",
1149
+ "list" => "List paths in a virtual Path kind, optionally below a prefix.",
1150
+ "move" => "Move a virtual Path to another path in the same kind and location.",
1151
+ "rename" => "Rename a virtual Path.",
1152
+ "delete" => "Delete a virtual Path.",
1153
+ "validate" => "Run the kind-specific syntax or validity check for a virtual Path.",
1154
+ "smoke" => "Run the kind-specific lightweight smoke check for a virtual Path.",
1155
+ "promote" => "Promote a virtual Path from its temporary location to its project location.",
1156
+ "patch" => "Apply a single-file unified diff to a virtual Path in memory and " \
1157
+ "write it back atomically (no fuzz, no side files)."
1158
+ }
1159
+
1160
+ definition = {
1161
+ "description" => operation_descriptions.fetch(operation, "Operate on a virtual Path."),
1162
+ "parameters" => {
1163
+ "type" => "object",
1164
+ "properties" => properties,
1165
+ "required" => operation == "list" ? ["kind"] : %w[kind path],
1166
+ "additionalProperties" => false
1167
+ }
1168
+ }
1169
+
1170
+ # Dynamic enum is useful to models when kinds are known. Do not add
1171
+ # an empty enum, since that makes some JSON-schema consumers reject the
1172
+ # tool.
1173
+ unless kinds.empty?
1174
+ definition["parameters"]["properties"]["kind"]["enum"] = kinds
1175
+ end
1176
+
1177
+ definition
1178
+ end
1179
+
1180
+ # ------------------------------------------------------------------
1181
+ # Path resolution
1182
+ # ------------------------------------------------------------------
1183
+
1184
+ # Resolves a virtual path to the underlying Scout/File path.
1185
+ #
1186
+ # A kind can provide `resolve`, which receives `(agent, path, location)`
1187
+ # and returns the target object; the FS-boundary adapters use its String
1188
+ # representation (see the FS-boundary comment above path_read_text).
1189
+ # Otherwise `roots` are treated as filesystem roots.
1190
+ def resolve_path(kind, path, location = nil, path_map = DEFAULT_PATH_MAP)
1191
+ definition = path_kind_definition(kind)
1192
+ location ||= definition["default_location"]
1193
+
1194
+ locations = definition.fetch("locations", [])
1195
+ unless locations.include?(location.to_s)
1196
+ raise ParameterException,
1197
+ "Location #{location.inspect} is not supported by path kind #{kind}"
1198
+ end
1199
+
1200
+ if definition["resolve"]
1201
+ return definition["resolve"].call(self, path.to_s, location.to_s)
1202
+ end
1203
+
1204
+ roots = definition.fetch("roots", {})
1205
+ case location
1206
+ when nil, 'project', :project
1207
+ root = roots.fetch(location.to_s) { Scout.root.find(path_kind_effective_map(definition)) }
1208
+ else
1209
+ root = roots.fetch(location.to_s) do
1210
+ raise ParameterException,
1211
+ "No root configured for #{kind} at location #{location}"
1212
+ end
1213
+ end
1214
+
1215
+ root = root.sub('BASEDIR', File.basename(Dir.pwd))
1216
+
1217
+ # A Scout Path-like root may implement [] for child paths. Otherwise
1218
+ # use ordinary filesystem paths.
1219
+ # Absolute filesystem paths address their exact target. Authorization
1220
+ # below still limits them to the configured location root.
1221
+ return path.to_s if root.is_a?(String) && path.to_s.start_with?(File::SEPARATOR)
1222
+
1223
+ final_path = if Path === root
1224
+ root[path.to_s]
1225
+ else
1226
+ Path.setup(File.join(root.to_s, path.to_s))
1227
+ end
1228
+
1229
+ if definition["extension"]
1230
+ final_path = final_path.set_extension(definition["extension"])
1231
+ end
1232
+
1233
+ final_path.find(path_map)
1234
+ end
1235
+
1236
+ # Authorize the resolved primary target. Custom resolvers are sandboxed
1237
+ # only when their kind declares a root that can serve as the policy grant.
1238
+ def path_authorize!(kind, target, location, mode: :read)
1239
+ definition = path_kind_definition(kind)
1240
+ return true unless definition.fetch("sandbox", true)
1241
+
1242
+ sandbox = LLM.const_get(:Sandbox)
1243
+ unless sandbox.respond_to?(:authorize_path)
1244
+ raise ParameterException, "Path sandbox authorization is unavailable"
1245
+ end
1246
+
1247
+ location = (location || definition["default_location"]).to_s
1248
+ root = if location == "project" && !definition.fetch("roots", {}).key?(location)
1249
+ Scout.root.find(path_kind_effective_map(definition))
1250
+ else
1251
+ definition.fetch("roots", {}).fetch(location) do
1252
+ raise ParameterException, "No sandbox root configured for #{kind} at #{location}"
1253
+ end
1254
+ end
1255
+ path_string = target.to_s
1256
+ root_string = root.to_s
1257
+ unless path_string.start_with?(File::SEPARATOR) && root_string.start_with?(File::SEPARATOR)
1258
+ raise ParameterException, "Path sandbox requires absolute filesystem paths"
1259
+ end
1260
+
1261
+ decision = sandbox.authorize_path(path_string, root: root_string, mode: mode)
1262
+ raise ParameterException, "Path access denied by sandbox (#{decision.reason || 'unknown'})" unless decision.allowed
1263
+ true
1264
+ rescue NameError, NoMethodError => error
1265
+ raise ParameterException, "Path sandbox authorization is unavailable: #{error.message}"
1266
+ end
1267
+
1268
+ def path_doc_id(kind, path, version = nil)
1269
+ id = "#{kind}::#{path}"
1270
+ version ? "#{id}@#{version}" : id
1271
+ end
1272
+
1273
+ # ------------------------------------------------------------------
1274
+ # Argument and selector validation
1275
+ # ------------------------------------------------------------------
1276
+
1277
+ # Root selectors are an ENUMERATION surface only: an empty string, "."
1278
+ # and "./" all address the kind ROOT as a whole, not one file within it.
1279
+ # Every file-shaped built-in calls this guard with its own tool name so
1280
+ # the rejection names the operation that received the bad value and
1281
+ # points at the enumeration surface (path_list). path_list itself is
1282
+ # NOT guarded: it normalizes a root selector to the empty prefix
1283
+ # instead. path_dispatch is not guarded either: custom operations own
1284
+ # their path grammar and may legitimately receive ".".
1285
+ ROOT_SELECTOR_PATHS = ["", ".", "./"].freeze
1286
+
1287
+ def path_reject_root_selector!(operation, path)
1288
+ value = path.to_s
1289
+ return value unless ROOT_SELECTOR_PATHS.include?(value)
1290
+
1291
+ raise ParameterException,
1292
+ "Invalid path for #{operation}: #{value.inspect} addresses the " \
1293
+ "kind root; use a path relative to the root, or path_list to " \
1294
+ "enumerate the root"
1295
+ end
1296
+
1297
+ # path_list's counterpart to the guard above: instead of rejecting a
1298
+ # root selector it maps it onto the empty prefix, which lists the whole
1299
+ # kind root.
1300
+ def path_root_selector_normalize(path)
1301
+ value = path.to_s
1302
+ ROOT_SELECTOR_PATHS.include?(value) ? "" : value
1303
+ end
1304
+
1305
+ # Fetch a required argument of a tool invocation. Invalid input must
1306
+ # surface as the framework's parameter error, never an incidental
1307
+ # KeyError from Hash#fetch.
1308
+ def path_argument(args, argument)
1309
+ args.fetch(argument.to_s) do
1310
+ raise ParameterException,
1311
+ "Missing required argument #{argument.inspect} for path operation"
1312
+ end
1313
+ end
1314
+
1315
+ # ------------------------------------------------------------------
1316
+ # Text adapter
1317
+ # ------------------------------------------------------------------
1318
+
1319
+ # Apply a :content-typed override callable with the engine's
1320
+ # single-file content-transform guarantees:
1321
+ # - the callable receives (original_content, args) and returns the
1322
+ # transformed content; it gets NO path argument, so it cannot
1323
+ # redirect the write - the engine writes the SAME authorized
1324
+ # target it read;
1325
+ # - final-newline preservation identical to the engine's own edits:
1326
+ # the written file's final-newline state must match the ORIGINAL
1327
+ # document's, regardless of trailing newlines in the callable's
1328
+ # return value.
1329
+ def path_apply_content_handler(handler, target, original, args, kind)
1330
+ result = handler.call(original, args)
1331
+
1332
+ unless String === result
1333
+ # The content-handler contract is "return transformed content". A
1334
+ # non-String return would raise NoMethodError on #end_with? below
1335
+ # and escape path_install_tool's ScoutException-only rescue, so it
1336
+ # is normalized here into the framework's parameter error.
1337
+ raise ParameterException,
1338
+ "Path kind #{kind} content handler must return a String, " \
1339
+ "got #{result.class}"
1340
+ end
1341
+
1342
+ original_terminated = original.end_with?("\n")
1343
+ result_terminated = result.end_with?("\n")
1344
+
1345
+ if original_terminated == result_terminated
1346
+ result
1347
+ elsif original_terminated
1348
+ result.sub(/\n*\z/, "\n")
1349
+ else
1350
+ result.sub(/\n+\z/, "")
1351
+ end
1352
+ end
1353
+
1354
+ # FS boundary (shared by path_read_text / path_write_text /
1355
+ # path_exists? / path_delete_target / path_move_target): resolve_path
1356
+ # and path_authorize! have already produced and AUTHORIZED the exact
1357
+ # target, so these adapters use plain File/FileUtils on target.to_s.
1358
+ # Scout Path#find/Open resolution is deliberately not applied here: its
1359
+ # fallback semantics (compressed .gz/.bgz/.zip alternatives, ~/.scout
1360
+ # default for unlocated paths) could move the target AFTER
1361
+ # authorization, and Open.read decompresses and fixes UTF-8 while
1362
+ # Open.write writes raw bytes (read/write asymmetry), breaking the
1363
+ # byte-exact contract. A custom kind "resolve" may return any object;
1364
+ # only its String representation is used here.
1365
+
1366
+ def path_read_text(target)
1367
+ target = target.to_s
1368
+ if File.file?(target)
1369
+ File.read(target)
1370
+ else
1371
+ raise ParameterException, "Path does not exist or is not readable: #{target}"
1372
+ end
1373
+ end
1374
+
1375
+ def path_write_text(target, content)
1376
+ target = target.to_s
1377
+ FileUtils.mkdir_p(File.dirname(target))
1378
+ File.write(target, content.to_s)
1379
+ content.to_s
1380
+ end
1381
+
1382
+ def path_exists?(target)
1383
+ File.exist?(target.to_s)
1384
+ end
1385
+
1386
+ def path_delete_target(target)
1387
+ # A resolved filesystem path is commonly a String, whose #delete
1388
+ # removes matching characters rather than the file. Only delegate to
1389
+ # a non-String path object that exposes the Path deletion protocol.
1390
+ begin
1391
+ if !target.is_a?(String) && target.respond_to?(:delete)
1392
+ target.delete
1393
+ else
1394
+ File.delete(target.to_s)
1395
+ end
1396
+ rescue Errno::ENOENT
1397
+ # Deleting a missing target is invalid input, not a system failure.
1398
+ # The rescue sits on the actual delete call (not a pre-existence
1399
+ # check, which would race) and reuses the engine's uniform
1400
+ # "does not exist" contract so the tool wrapper's
1401
+ # ScoutException-only rescue can serialize it to the agent.
1402
+ raise ParameterException,
1403
+ "Path does not exist or is not readable: #{target}"
1404
+ end
1405
+ end
1406
+
1407
+ # ------------------------------------------------------------------
1408
+ # Tool implementations
1409
+ # ------------------------------------------------------------------
1410
+
1411
+ def path_kinds(args = {})
1412
+ kind = args["kind"]
1413
+ registry = path_kind_registry
1414
+ unless kind.nil? || kind.to_s.empty?
1415
+ kind = kind.to_s
1416
+ unless registry.key?(kind)
1417
+ raise ParameterException,
1418
+ "Unknown path kind: #{kind} (available: #{registry.keys.sort.join(', ')})"
1419
+ end
1420
+
1421
+ return {kind => path_kind_registry_entry(registry.fetch(kind))}
1422
+ end
1423
+
1424
+ path_kind_registry.transform_values { |definition| path_kind_registry_entry(definition) }
1425
+ end
1426
+
1427
+ def path_kind_registry_entry(definition)
1428
+ {
1429
+ "description" => definition["description"],
1430
+ "locations" => definition["locations"],
1431
+ "default_location" => definition["default_location"],
1432
+ "sandbox" => definition["sandbox"],
1433
+ "capabilities" => definition["capabilities"]
1434
+ }
1435
+ end
1436
+
1437
+ def path_read(args)
1438
+ kind = path_argument(args, "kind")
1439
+ path = path_reject_root_selector!("path_read", path_argument(args, "path"))
1440
+ location = args["location"]
1441
+ target = resolve_path(kind, path, location)
1442
+ path_authorize!(kind, target, location, mode: :read)
1443
+
1444
+ {
1445
+ "doc_id" => path_doc_id(kind, path, args["version"]),
1446
+
1447
+ "kind" => kind,
1448
+ "path" => path,
1449
+ "location" => location || path_kind_definition(kind)["default_location"],
1450
+ "content" => path_read_text(target)
1451
+ }
1452
+ end
1453
+
1454
+ def path_write(args)
1455
+ kind = path_argument(args, "kind")
1456
+ path = path_reject_root_selector!("path_write", path_argument(args, "path"))
1457
+ content = path_argument(args, "content")
1458
+ raise ParameterException, "Context compactation tag detected in content (#{Chat::COMPACTATION_MESSAGE}); old tool calls are stale and may need to be re-derived." if content.include?(Chat::COMPACTATION_MESSAGE)
1459
+ location = args["location"]
1460
+
1461
+ unless path_kind_capable?(kind, "write")
1462
+ raise ParameterException, "Path kind #{kind} does not support write"
1463
+ end
1464
+
1465
+ target = resolve_path(kind, path, location)
1466
+ path_authorize!(kind, target, location, mode: :write)
1467
+
1468
+ override = path_operation_implementation(kind, "write")
1469
+ override_type = override && path_operation_handler_type(kind, "write")
1470
+ payload =
1471
+ if override && override_type == :full
1472
+ # DC-1: a :full write override performs the write itself. The
1473
+ # engine hands it the resolved, AUTHORIZED target; the engine
1474
+ # still composes the canonical result keys and verifies the
1475
+ # write landed on that target.
1476
+ handler_result = override.call(self, target, args)
1477
+ unless Hash === handler_result
1478
+ raise ParameterException,
1479
+ "Path kind #{kind} :full write override must return a " \
1480
+ "Hash payload, got #{handler_result.class}"
1481
+ end
1482
+ handler_result
1483
+ elsif override
1484
+ # DC-1: a :content write override is a pure content transform.
1485
+ # The engine reads nothing (there is no original to preserve for
1486
+ # a write) and writes the transformed String itself, exactly like
1487
+ # the default write.
1488
+ transformed = path_content_handler_string(
1489
+ override, target, content, args, kind
1490
+ )
1491
+ path_write_text(target, transformed)
1492
+ {}
1493
+ else
1494
+ path_write_text(target, content)
1495
+ {}
1496
+ end
1497
+
1498
+ canonical = {
1499
+ "doc_id" => path_doc_id(kind, path, args["version"]),
1500
+ "kind" => kind,
1501
+ "path" => path,
1502
+ "location" => location || path_kind_definition(kind)["default_location"],
1503
+ "target_file" => target,
1504
+ "written" => path_exists?(target)
1505
+ }
1506
+ # Engine-authoritative canonical keys are never overridable; any
1507
+ # other payload key the :full handler returned is merged additively.
1508
+ payload.each_with_object(canonical) do |(key, value), result|
1509
+ result[key] = value unless canonical.key?(key)
1510
+ end
1511
+ end
1512
+
1513
+ # path_edit lives in lib/scout/llm/agent/path/edit.rb
1514
+ # (module AgentPathEdit, included above).
1515
+
1516
+ # Generic single-file patch. Applies a unified diff in
1517
+ # memory with strict context verification and writes ONCE through
1518
+ # the authorized target: no subprocess, no .orig/.rej, no partial
1519
+ # writes, no fuzz. Default-off capability; overrides of :content
1520
+ # type receive (content, args) with the patch text in args["patch"].
1521
+ def path_patch(args)
1522
+ kind = path_argument(args, "kind")
1523
+ path = path_reject_root_selector!("path_patch", path_argument(args, "path"))
1524
+ patch_text = path_argument(args, "patch")
1525
+ location = args["location"]
1526
+
1527
+ raise ParameterException, "Context compactation tag detected in content (#{Chat::COMPACTATION_MESSAGE}); old tool calls are stale and may need to be re-derived." if patch_text.include?(Chat::COMPACTATION_MESSAGE)
1528
+
1529
+ unless path_kind_capable?(kind, "patch")
1530
+ raise ParameterException, "Path kind #{kind} does not support patch"
1531
+ end
1532
+
1533
+ target = resolve_path(kind, path, location)
1534
+ path_authorize!(kind, target, location, mode: :write)
1535
+ original = path_read_text(target)
1536
+
1537
+ hunks = PathPatch.parse(patch_text)
1538
+
1539
+ override = path_operation_implementation(kind, "patch")
1540
+ patched =
1541
+ if override
1542
+ path_apply_content_handler(override, target, original, args, kind)
1543
+ else
1544
+ PathPatch.apply(original, hunks).first
1545
+ end
1546
+ path_write_text(target, patched)
1547
+
1548
+ {
1549
+ "doc_id" => path_doc_id(kind, path, args["version"]),
1550
+ "kind" => kind,
1551
+ "path" => path,
1552
+ "changed" => original != patched,
1553
+ "content" => patched
1554
+ }
1555
+ end
1556
+
1557
+ def path_list(args)
1558
+ kind = path_argument(args, "kind")
1559
+ definition = path_kind_definition(kind)
1560
+ location = args["location"] || definition["default_location"]
1561
+ # A root selector (".", "./", or an empty prefix) addresses the kind
1562
+ # ROOT itself; normalize it to the empty prefix so listing falls into
1563
+ # the root branch below instead of resolving a bogus file target.
1564
+ prefix = path_root_selector_normalize(args["path"])
1565
+ target = resolve_path(kind, prefix, location)
1566
+
1567
+ path_authorize!(kind, target, location, mode: :read)
1568
+
1569
+ if definition["list"]
1570
+ return definition["list"].call(self, prefix, location)
1571
+ end
1572
+
1573
+ if roots = definition.fetch('roots', nil)
1574
+ root = roots.fetch(location.to_s) do
1575
+ raise ParameterException, "No root configured for #{kind} at location #{location}"
1576
+ end.to_s
1577
+ else
1578
+ root = Scout.root.find(path_kind_effective_map(definition))
1579
+ end
1580
+ # H4 hardening: the target is always a plain absolute String here
1581
+ # (resolve_path returns root[path] and every registered root is pinned
1582
+ # absolute at registration), so go straight to Dir.glob on the pinned
1583
+ # String. Path#glob on an unlocated logical path would resolve through
1584
+ # Scout's map_order and could reach :user; Dir.glob never re-resolves.
1585
+ base = prefix.empty? ? root : target.to_s
1586
+ entries = Dir.glob(File.join(base, "**", "*"), File::FNM_DOTMATCH)
1587
+ .reject { |entry| File.directory?(entry) }
1588
+ # Listing has always returned paths relative to the configured kind root,
1589
+ # even when the prefix supplied by the caller is absolute.
1590
+ entries.map { |entry| entry.to_s.sub(%r{\A#{Regexp.escape(root)}/?}, "") }.sort
1591
+ end
1592
+
1593
+ def path_move(args)
1594
+ kind = path_argument(args, "kind")
1595
+ source_path = path_reject_root_selector!("path_move", path_argument(args, "path"))
1596
+ destination = path_argument(args, "destination")
1597
+ location = args["location"]
1598
+
1599
+ unless path_kind_capable?(kind, "move")
1600
+ raise ParameterException, "Path kind #{kind} does not support move"
1601
+ end
1602
+
1603
+ path_relocate(kind, source_path, destination, location)
1604
+
1605
+ {"kind" => kind, "path" => source_path, "destination" => destination, "moved" => true}
1606
+ end
1607
+
1608
+ def path_rename(args)
1609
+ kind = path_argument(args, "kind")
1610
+ source_path = path_reject_root_selector!("path_rename", path_argument(args, "path"))
1611
+ name = path_argument(args, "name")
1612
+ location = args["location"]
1613
+
1614
+ unless path_kind_capable?(kind, "rename")
1615
+ raise ParameterException, "Path kind #{kind} does not support rename"
1616
+ end
1617
+
1618
+ path_relocate(kind, source_path, name, location)
1619
+
1620
+ {"kind" => kind, "path" => source_path, "name" => name, "renamed" => true}
1621
+ end
1622
+
1623
+ # Shared same-kind relocation mechanics for path_move and path_rename:
1624
+ # resolve BOTH endpoints, authorize both for writing, perform the move.
1625
+ # The public wrappers keep their own argument validation, capability
1626
+ # errors and result keys.
1627
+ private def path_relocate(kind, source_path, target_path, location)
1628
+ source = resolve_path(kind, source_path, location)
1629
+ target = resolve_path(kind, target_path, location)
1630
+ path_authorize!(kind, source, location, mode: :write)
1631
+ path_authorize!(kind, target, location, mode: :write)
1632
+ path_move_target(source, target)
1633
+ end
1634
+
1635
+ def path_delete(args)
1636
+ kind = path_argument(args, "kind")
1637
+ path = path_reject_root_selector!("path_delete", path_argument(args, "path"))
1638
+ location = args["location"]
1639
+
1640
+ unless path_kind_capable?(kind, "delete")
1641
+ raise ParameterException, "Path kind #{kind} does not support delete"
1642
+ end
1643
+
1644
+ target = resolve_path(kind, path, location)
1645
+ path_authorize!(kind, target, location, mode: :write)
1646
+ path_delete_target(target)
1647
+
1648
+ {"kind" => kind, "path" => path, "deleted" => true}
1649
+ end
1650
+
1651
+ # The kind-specific wrapper operations share one body: they only
1652
+ # differ in the operation name handed to path_kind_operation. The
1653
+ # generated methods keep the exact names the tools and tests use.
1654
+ %w[validate smoke].each do |operation|
1655
+ define_method("path_#{operation}") do |args|
1656
+ path_kind_operation(args, operation)
1657
+ end
1658
+ end
1659
+
1660
+ # ENGINE-CONTROLLED PROMOTION. The engine resolves the destination from
1661
+ # a purely declarative spec, authorizes BOTH endpoints, checks
1662
+ # no-clobber, and performs the move itself. A kind callback is never
1663
+ # the writer: the legacy "promote" mover callback is no longer invoked
1664
+ # at all, and post-move behavior (if any) hooks through the narrow
1665
+ # "promotion_post_move" key, which receives the authorized endpoints in
1666
+ # args and runs only after the engine's move completed.
1667
+ def path_promote(args)
1668
+ kind = path_argument(args, "kind")
1669
+ unless path_kind_capable?(kind, "promote")
1670
+ raise ParameterException, "Path kind #{kind} does not support promote"
1671
+ end
1672
+
1673
+ definition = path_kind_definition(kind)
1674
+
1675
+ location = args["location"] || definition["default_location"]
1676
+ path = path_reject_root_selector!("path_promote", path_argument(args, "path"))
1677
+ target = resolve_path(kind, path, location)
1678
+ path_authorize!(kind, target, location, mode: :write)
1679
+ unless path_exists?(target)
1680
+ raise ParameterException, "Path does not exist or is not readable: #{target}"
1681
+ end
1682
+
1683
+ # The destination is resolved from a DECLARATIVE spec only: a location
1684
+ # String, or a Hash with "location" (optional "path", defaulting to
1685
+ # the source path). A Callable form is deliberately NOT accepted: it
1686
+ # would have to run before the destination is authorized, so a
1687
+ # side-effecting callable could mutate anywhere.
1688
+ destination_spec = definition["promotion_destination"]
1689
+ destination_spec = {"location" => destination_spec} if destination_spec.is_a?(String)
1690
+ destination_spec = {"location" => "project"} if destination_spec.nil?
1691
+ unless destination_spec.is_a?(Hash) && destination_spec.key?("location")
1692
+ raise ParameterException,
1693
+ "Invalid promotion destination for path kind #{kind}: expected a " \
1694
+ "location String or a Hash with location"
1695
+ end
1696
+
1697
+ destination_location = destination_spec.fetch("location").to_s
1698
+ destination_path = (destination_spec["path"] || path).to_s
1699
+ destination_target = resolve_path(kind, destination_path, destination_location)
1700
+ path_authorize!(kind, destination_target, destination_location, mode: :write)
1701
+
1702
+ overwrite = [true, "true"].include?(args["overwrite"])
1703
+
1704
+ # ADVISORY existence check (TOCTOU): destination_target.exist? here and
1705
+ # the actual move below are not one atomic operation. Concurrent
1706
+ # promotion is OUT OF SCOPE BY DECISION: no cross-process locking or
1707
+ # exclusive-create/link guard is attempted (none is available without
1708
+ # new machinery). Within a single process the engine's serialized
1709
+ # authorize -> check -> move flow is the only writer.
1710
+ destination_exists = path_exists?(destination_target)
1711
+ if destination_exists && !overwrite
1712
+ raise ParameterException,
1713
+ "Promotion destination already exists: #{destination_target} " \
1714
+ "(pass overwrite to replace it)"
1715
+ end
1716
+
1717
+ # The ENGINE performs the move to the authorized destination itself.
1718
+ path_move_target(target, destination_target)
1719
+
1720
+ result = {
1721
+ "kind" => kind,
1722
+ "path" => path,
1723
+ "location" => location.to_s,
1724
+ "promoted" => true,
1725
+ "destination" => {"location" => destination_location, "path" => destination_path},
1726
+ "promotion_target" => destination_target.to_s,
1727
+ "promotion_source_target" => target.to_s
1728
+ }
1729
+
1730
+ post_move = definition["promotion_post_move"]
1731
+ if post_move
1732
+ hook_args = args.merge(
1733
+ "promotion_destination" => result["destination"],
1734
+ "promotion_target" => destination_target.to_s,
1735
+ "promotion_source_target" => target.to_s,
1736
+ "overwrite" => overwrite
1737
+ )
1738
+ hook_result = post_move.call(self, path, location.to_s, hook_args)
1739
+ result = hook_result.merge(result) if hook_result.is_a?(Hash)
1740
+ end
1741
+
1742
+ result
1743
+ end
1744
+
1745
+ # ------------------------------------------------------------------
1746
+ # Kind-specific operations
1747
+ # ------------------------------------------------------------------
1748
+
1749
+ def path_kind_operation(args, operation)
1750
+ kind = path_argument(args, "kind")
1751
+ unless path_kind_capable?(kind, operation)
1752
+ raise ParameterException, "Path kind #{kind} does not support #{operation}"
1753
+ end
1754
+
1755
+ definition = path_kind_definition(kind)
1756
+ implementation = definition[operation]
1757
+ raise ParameterException, "Path kind #{kind} has no #{operation} implementation" unless implementation
1758
+
1759
+ location = args["location"] || definition["default_location"]
1760
+ path = path_reject_root_selector!("path_#{operation}", path_argument(args, "path"))
1761
+ target = resolve_path(kind, path, location)
1762
+ path_authorize!(kind, target, location, mode: :read)
1763
+
1764
+ implementation.call(
1765
+ self,
1766
+ path,
1767
+ location.to_s,
1768
+ args
1769
+ )
1770
+ end
1771
+
1772
+ def path_move_target(source, destination)
1773
+ raise ParameterException, "Source file not found un path move #{source}" unless Open.exists?(source)
1774
+ Open.mv(source, destination)
1775
+ end
1776
+ end
1777
+ end