scout-ai 2.0.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 (185) hide show
  1. checksums.yaml +4 -4
  2. data/.vimproject +135 -55
  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 +320 -34
  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 +402 -44
  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 +64 -0
  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 +79 -17
  39. data/lib/scout/llm/agent.rb +151 -27
  40. data/lib/scout/llm/ask.rb +37 -27
  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 +131 -32
  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 -52
  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 +352 -626
  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 +72 -26
  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 +845 -80
  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 +109 -22
  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 +200 -28
  127. data/test/scout/llm/chat/test_agent_meta_tokens.rb +112 -7
  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 +708 -13
  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 +71 -25
  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/synthesis-report.md +0 -487
  185. data/research/tools-system-analysis.md +0 -779
@@ -0,0 +1,230 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Editing implementation for the agent-level virtual Path interface
4
+ # (see lib/scout/llm/agent/path.rb for the engine overview).
5
+ #
6
+ # Extracted verbatim from path.rb (behavior-preserving move): this module is
7
+ # included into LLM::Agent and holds the selector-based editing path only -
8
+ # `path_edit`, the selector application `path_apply_selector`, and the
9
+ # selector-validation helpers. Shared engine machinery (kind registry,
10
+ # capability gates, `path_argument`, `path_authorize!`, resolution, content
11
+ # handlers, read/write text adapters) stays in path.rb and is called through
12
+ # the including instance.
13
+ module LLM
14
+ class Agent
15
+ module AgentPathEdit
16
+ # ------------------------------------------------------------------
17
+ # Argument and selector validation
18
+ # ------------------------------------------------------------------
19
+
20
+ # Selector keys are validated the same way as tool arguments.
21
+ def path_selector_key(selector, key)
22
+ selector.fetch(key) do
23
+ raise ParameterException, "Invalid selector: missing key #{key.inspect}"
24
+ end
25
+ end
26
+
27
+ # Selector indexes (lines/chars start/end, regexp pattern) must be
28
+ # validated, not just presence-checked: a nil or string-valued index
29
+ # would otherwise raise NoMethodError/ArgumentError deep inside the
30
+ # comparison, escaping path_install_tool's ScoutException-only rescue
31
+ # so the agent never sees it. Everything invalid surfaces as
32
+ # ParameterException at the point it occurs, BEFORE any mutation.
33
+ def path_selector_index(selector, key, length: nil, maximum: nil)
34
+ value = path_selector_key(selector, key)
35
+ unless value.is_a?(Integer)
36
+ raise ParameterException,
37
+ "Invalid selector: #{key.inspect} must be an integer, got #{value.inspect}"
38
+ end
39
+ raise ParameterException,
40
+ "Invalid selector: #{key.inspect} must be >= 0, got #{value}" if value.negative?
41
+
42
+ if length && key == "end" && value > length
43
+ # Exclusive-end clamping is deliberate and documented: an end
44
+ # beyond the document is the same as "to the end of the document".
45
+ value = length
46
+ elsif length && key == "start" && value > length
47
+ raise ParameterException,
48
+ "Invalid selector: #{key.inspect} #{value} is beyond the last index #{length}"
49
+ end
50
+
51
+ value
52
+ end
53
+
54
+ # ------------------------------------------------------------------
55
+ # Selectors
56
+ # ------------------------------------------------------------------
57
+
58
+ def path_apply_selector(content, selector, replacement)
59
+ unless selector.respond_to?(:fetch)
60
+ raise ParameterException,
61
+ "Invalid selector: expected a mapping with type lines, chars, or regexp"
62
+ end
63
+ type = path_selector_key(selector, "type").to_s
64
+
65
+ case type
66
+ when "regexp"
67
+ pattern_value = path_selector_key(selector, "pattern")
68
+ unless pattern_value.is_a?(String)
69
+ # A non-String pattern would raise TypeError inside Regexp.new,
70
+ # escaping path_install_tool's ScoutException-only rescue so the
71
+ # agent never sees it; invalid input surfaces as ParameterException.
72
+ raise ParameterException,
73
+ "Invalid selector: pattern must be a String, got #{pattern_value.inspect}"
74
+ end
75
+ pattern =
76
+ begin
77
+ Regexp.new(pattern_value)
78
+ rescue RegexpError => e
79
+ # NARROW rescue at the Regexp.new call site only: a malformed
80
+ # pattern is an invalid input, and must surface as
81
+ # ParameterException (ScoutException subclass) so the tool
82
+ # wrapper's rescue can serialize it to the agent.
83
+ raise ParameterException,
84
+ "Invalid selector: malformed regexp pattern " \
85
+ "#{path_selector_key(selector, "pattern").inspect}: #{e.message}"
86
+ end
87
+ content.sub(pattern, replacement.to_s)
88
+ when "chars"
89
+ start = path_selector_index(selector, "start")
90
+ finish = path_selector_index(selector, "end", length: content.length)
91
+ raise ParameterException, "Character range must satisfy start <= end" if start > finish
92
+
93
+ content.dup.tap do |text|
94
+ text[start...finish] = replacement.to_s
95
+ end
96
+ when "lines"
97
+ # Explicit line semantics (see "Selector semantics" in tmp/path_recon.md):
98
+ # - indexes are 0-based; "start".."end" is an EXCLUSIVE-end line range
99
+ # - a line includes its terminator; the final line may lack one
100
+ # - the replacement's content substitutes for the selected lines'
101
+ # content; untouched lines are byte-identical
102
+ # - the final newline of the file is preserved IFF it existed before
103
+ # - DECISION: start == lines.length (insertion-at-end) is ALLOWED and
104
+ # appends after the last line; start > lines.length raises
105
+ # ParameterException. An "end" beyond the document clamps to the
106
+ # document end (so the append form is start=length, end>length).
107
+ lines = content.lines
108
+ start = path_selector_index(selector, "start", length: lines.length)
109
+ finish = path_selector_index(selector, "end", length: lines.length)
110
+ raise ParameterException, "Line range must satisfy start <= end" if start > finish
111
+
112
+ # Rebuild keeping untouched lines byte-identical: lines before the
113
+ # span, the replacement text, and lines after the span.
114
+ head = lines[0...start]
115
+ tail = lines[finish..] || []
116
+ body = replacement.to_s
117
+
118
+ # Terminal-newline normalization is BIDIRECTIONAL at the EOF
119
+ # boundary: when the replaced span reaches EOF the result's
120
+ # final-newline state must match the ORIGINAL document's, whatever
121
+ # the replacement's trailing newline looks like (a replacement
122
+ # ending in "\n" must NOT introduce a final newline the original
123
+ # lacked). When a line follows the span (interior boundary) the
124
+ # replacement is terminated with exactly one newline. tail is
125
+ # empty exactly when the span reaches EOF.
126
+ eof_span = finish >= lines.length
127
+ final_newline = content.end_with?("\n")
128
+ new_span =
129
+ if body.empty?
130
+ # Deleting the span leaves nothing; no stray terminator is
131
+ # reintroduced by the EOF normalization below.
132
+ ""
133
+ elsif !eof_span || final_newline
134
+ # Interior boundary, or EOF where the original ended with a
135
+ # newline: exactly one terminal newline (appended when
136
+ # missing, collapsed when repeated).
137
+ body.sub(/\n*\z/, "\n")
138
+ else
139
+ # EOF boundary and the original lacked a final newline: strip
140
+ # every trailing newline the replacement may carry.
141
+ body.sub(/\n+\z/, "")
142
+ end
143
+
144
+ joined = (head + [new_span] + tail).join
145
+ # The EOF boundary inherits the original document's final-newline
146
+ # state, including the empty-replacement case where only head
147
+ # lines remain (deleting the last line of a file that had no
148
+ # final newline must not add one).
149
+ joined = joined.sub(/\n+\z/, "") if eof_span && !final_newline
150
+ joined
151
+ else
152
+ raise ParameterException,
153
+ "Unknown selector type #{type.inspect}; expected lines, chars, or regexp"
154
+ end
155
+ end
156
+
157
+ # ------------------------------------------------------------------
158
+ # Tool implementations
159
+ # ------------------------------------------------------------------
160
+
161
+ def path_edit(args)
162
+ kind = path_argument(args, "kind")
163
+ path = path_reject_root_selector!("path_edit", path_argument(args, "path"))
164
+ selector = path_argument(args, "selector")
165
+ replacement = path_argument(args, "replacement")
166
+ location = args["location"]
167
+
168
+ raise ParameterException, "Context compactation tag detected in replacement (#{Chat::COMPACTATION_MESSAGE}); old tool calls are stale and may need to be re-derived." if replacement && replacement.include?(Chat::COMPACTATION_MESSAGE)
169
+
170
+ unless path_kind_capable?(kind, "edit")
171
+ raise ParameterException, "Path kind #{kind} does not support edit"
172
+ end
173
+
174
+ target = resolve_path(kind, path, location)
175
+ path_authorize!(kind, target, location, mode: :write)
176
+ original = path_read_text(target)
177
+
178
+ override = path_operation_implementation(kind, "edit")
179
+ payload, engine_edited =
180
+ if override && path_operation_handler_type(kind, "edit") == :full
181
+ # DC-2: a :full edit override performs the edit itself. The
182
+ # engine hands it the resolved, AUTHORIZED target; the handler
183
+ # returns a Hash payload whose non-canonical keys are merged
184
+ # into the result (canonical keys stay engine-authoritative,
185
+ # same contract as path_write's :full branch).
186
+ handler_result = override.call(self, target, args)
187
+ unless Hash === handler_result
188
+ raise ParameterException,
189
+ "Path kind #{kind} :full edit override must return a " \
190
+ "Hash payload, got #{handler_result.class}"
191
+ end
192
+ [handler_result, nil]
193
+ elsif override
194
+ # DC-2, pinned behavior: under a :content edit override the
195
+ # selector/replacement arguments are validated above (they are
196
+ # required by the tool schema) but are NOT applied - the
197
+ # handler's returned content IS the edited file. A :content
198
+ # edit override replaces the edit transform wholesale; a kind
199
+ # that wants selector semantics must not override edit at all.
200
+ # (Documented in doc/developer/PathEngine.md §5.)
201
+ edited = path_apply_content_handler(
202
+ override, target, original, args, kind
203
+ )
204
+ path_write_text(target, edited)
205
+ [{}, edited]
206
+ else
207
+ edited = path_apply_selector(original, selector, replacement)
208
+ path_write_text(target, edited)
209
+ [{}, edited]
210
+ end
211
+
212
+ # Edit keeps its own canonical result shape (doc_id/kind/path/
213
+ # changed/content). Under a :full override the handler performed
214
+ # the write, so changed/content are read back from the authorized
215
+ # target: verified reality, never the handler's claim.
216
+ final_content = engine_edited || path_read_text(target)
217
+ canonical = {
218
+ "doc_id" => path_doc_id(kind, path, args["version"]),
219
+ "kind" => kind,
220
+ "path" => path,
221
+ "changed" => original != final_content,
222
+ "content" => final_content
223
+ }
224
+ payload.each_with_object(canonical) do |(key, value), result|
225
+ result[key] = value unless canonical.key?(key)
226
+ end
227
+ end
228
+ end
229
+ end
230
+ end
@@ -0,0 +1,252 @@
1
+ # frozen_string_literal: true
2
+
3
+ # In-memory single-file unified-diff applier for the Path engine.
4
+ #
5
+ # Contract (see tmp/path_recon.md "Round 3 — Step 6 design"):
6
+ # * EXACTLY ONE `--- `/`+++ ` header pair; header filenames are ignored
7
+ # as target selectors and can never redirect the write.
8
+ # * Hunks: `@@ -l[,s] +l[,s] @@`, body lines starting with ' '
9
+ # (context), '-' (removal), '+' (addition), or the
10
+ # `` marker (toggles the no-newline state
11
+ # of the preceding line).
12
+ # * STRICT application: no fuzz, no search window. Context must match
13
+ # exactly at the computed position. Any failure raises
14
+ # ParameterException and the caller writes NOTHING.
15
+ # * All hunks apply or none: the caller only writes the final result.
16
+ #
17
+ # This is an original implementation written from the unified-diff
18
+ # grammar; no code was copied from the Workspace patch task (whose
19
+ # shell-out execution model was deliberately rejected).
20
+ module LLM
21
+ class Agent
22
+ module PathPatch
23
+ module_function
24
+
25
+ # Parse the patch text. Returns hunks: array of
26
+ # { old_start:, old_size:, new_start:, new_size:, lines: }
27
+ # where lines is an array of [tag, text, no_newline] tuples with
28
+ # tags :context / :del / :add.
29
+ def parse(patch_text)
30
+ raise ParameterException, "Patch must be a String" unless String === patch_text
31
+
32
+ raw_lines = patch_text.split(/\r?\n/, -1)
33
+ # A trailing empty element from a final newline is not a body line
34
+ raw_lines.pop if raw_lines.last == ""
35
+
36
+ headers = raw_lines.each_index.select do |i|
37
+ raw_lines[i].start_with?("--- ", "+++ ")
38
+ end
39
+
40
+ if headers.empty?
41
+ raise ParameterException, "Patch is missing the ---/+++ header pair"
42
+ end
43
+
44
+ if headers.length > 2 || !headers.include?(headers.first + 1)
45
+ raise ParameterException,
46
+ "multi-file patch not supported: #{[headers.length, 2].min}+ file headers"
47
+ end
48
+ unless raw_lines[headers.first].start_with?("--- ") &&
49
+ raw_lines[headers.first + 1].start_with?("+++ ")
50
+ raise ParameterException, "Patch header pair is malformed"
51
+ end
52
+
53
+ hunks = []
54
+ i = headers.first + 2
55
+
56
+ while i < raw_lines.length
57
+ line = raw_lines[i]
58
+
59
+ if line.start_with?("@@")
60
+ hunk, i = parse_hunk(raw_lines, i)
61
+ hunks << hunk
62
+ elsif line.strip.empty?
63
+ i += 1
64
+ else
65
+ raise ParameterException, "Unexpected text between hunks: #{line.inspect}"
66
+ end
67
+ end
68
+
69
+ if hunks.empty?
70
+ raise ParameterException, "Patch contains no hunks"
71
+ end
72
+
73
+ hunks
74
+ end
75
+
76
+ def parse_hunk(raw_lines, start)
77
+ header = raw_lines[start]
78
+ match = header.match(/\A@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/)
79
+ unless match
80
+ raise ParameterException, "Malformed hunk header: #{header.inspect}"
81
+ end
82
+
83
+ old_start = match[1].to_i
84
+ old_size = match[2] ? match[2].to_i : 1
85
+ new_start = match[3].to_i
86
+ new_size = match[4] ? match[4].to_i : 1
87
+
88
+ lines = []
89
+ i = start + 1
90
+ old_count = 0
91
+ new_count = 0
92
+
93
+ while i < raw_lines.length
94
+ line = raw_lines[i]
95
+
96
+ if line.start_with?("\\ No newline")
97
+ if lines.empty?
98
+ raise ParameterException, "No-newline marker before any hunk line"
99
+ end
100
+ lines.last[2] = true
101
+ i += 1
102
+ next
103
+ end
104
+
105
+ break if line.start_with?("@@") ||
106
+ (line.start_with?("--- ", "+++ ") && looks_like_header?(raw_lines, i))
107
+
108
+ tag, text =
109
+ if line.start_with?(" ") || line.empty?
110
+ [:context, line.sub(/\A /, "")]
111
+ elsif line.start_with?("-")
112
+ [:del, line[1..]]
113
+ elsif line.start_with?("+")
114
+ [:add, line[1..]]
115
+ else
116
+ raise ParameterException, "Malformed patch body line: #{line.inspect}"
117
+ end
118
+
119
+ old_count += 1 if tag == :context || tag == :del
120
+ new_count += 1 if tag == :context || tag == :add
121
+ lines << [tag, text, false]
122
+ i += 1
123
+ end
124
+
125
+ if lines.empty?
126
+ raise ParameterException, "Hunk starting at #{header.inspect} has no body"
127
+ end
128
+
129
+ unless old_count == old_size && new_count == new_size
130
+ raise ParameterException,
131
+ "Hunk #{header.inspect} counts mismatch: declared " \
132
+ "#{old_start},#{old_size} #{new_start},#{new_size}; " \
133
+ "found old=#{old_count} new=#{new_count}"
134
+ end
135
+
136
+ [{old_start: old_start, old_size: old_size,
137
+ new_start: new_start, new_size: new_size, lines: lines}, i]
138
+ end
139
+
140
+ def looks_like_header?(raw_lines, i)
141
+ # `--- ` inside a hunk body (context line whose content starts
142
+ # with `-`) starts with " ", so a bare `--- ` line here is a
143
+ # header only when followed by `+++ ` (a second file header).
144
+ raw_lines[i + 1]&.start_with?("+++ ")
145
+ end
146
+
147
+ # Apply parsed hunks to content. Returns [new_content, changed].
148
+ # Raises ParameterException on any context mismatch; content is
149
+ # never modified by this method (pure function of its inputs).
150
+ def apply(content, hunks)
151
+ original = content.dup
152
+ original_terminated = original.end_with?("\n")
153
+ body = original.sub(/\n\z/, "")
154
+ buffer = body.split("\n", -1)
155
+ # split("\n", -1) on "a\nb" -> ["a","b"]; on "" -> [""]
156
+ buffer = [] if body.empty?
157
+
158
+ offset = 0
159
+ hunks.each_with_index do |hunk, hunk_index|
160
+ header = "@@ -#{hunk[:old_start]},#{hunk[:old_size]}"
161
+ position = hunk[:old_start] - 1 + offset
162
+
163
+ unless position >= 0 && position <= buffer.length
164
+ raise ParameterException,
165
+ "Patch hunk #{hunk_index + 1} (#{header}) starts out of range: " \
166
+ "line #{hunk[:old_start]} in a #{buffer.length}-line file"
167
+ end
168
+
169
+ # Verify and apply: walk context/del lines against the buffer,
170
+ # collect additions.
171
+ cursor = position
172
+ additions = []
173
+ hunk[:lines].each_with_index do |(tag, text, _no_newline), line_index|
174
+ case tag
175
+ when :context, :del
176
+ if cursor >= buffer.length || buffer[cursor] != text
177
+ raise ParameterException,
178
+ "Patch hunk #{hunk_index + 1} (#{header}) context mismatch " \
179
+ "at hunk line #{line_index + 1}: expected #{text.inspect}, " \
180
+ "found #{buffer[cursor]&.inspect}"
181
+ end
182
+ cursor += 1
183
+ additions << nil if tag == :context
184
+ when :add
185
+ additions << text
186
+ end
187
+ end
188
+
189
+ # Rebuild: buffer[0...position] + interleaved new sequence +
190
+ # remainder. The new sequence replaces old_size lines starting
191
+ # at position: context lines map 1:1, dels vanish, adds insert.
192
+ new_sequence = []
193
+ old_consumed = 0
194
+ hunk[:lines].each do |tag, text, _no_newline|
195
+ case tag
196
+ when :context
197
+ new_sequence << buffer[position + old_consumed]
198
+ old_consumed += 1
199
+ when :del
200
+ old_consumed += 1
201
+ when :add
202
+ new_sequence << text
203
+ end
204
+ end
205
+
206
+ unless old_consumed == hunk[:old_size]
207
+ raise ParameterException,
208
+ "Patch hunk #{hunk_index + 1} (#{header}) consumed " \
209
+ "#{old_consumed} old lines, expected #{hunk[:old_size]}"
210
+ end
211
+
212
+ buffer[position, old_consumed] = new_sequence
213
+ offset += new_sequence.length - old_consumed
214
+ end
215
+
216
+ result = buffer.join("\n")
217
+
218
+ # Newline policy: explicit no-newline markers override; otherwise
219
+ # preserve the ORIGINAL's termination. The old side's final line
220
+ # is the last :del/:context; the new side's the last
221
+ # :add/:context (both of the last hunk, the usual EOF position).
222
+ new_no_newline = final_line_marked?(hunks, :new)
223
+ old_no_newline = final_line_marked?(hunks, :old)
224
+ if new_no_newline
225
+ result = result.sub(/\n+\z/, "")
226
+ elsif old_no_newline
227
+ result = result.sub(/\n*\z/, "\n")
228
+ elsif original_terminated
229
+ result = result.sub(/\n*\z/, "\n")
230
+ else
231
+ result = result.sub(/\n+\z/, "")
232
+ end
233
+
234
+ [result, result != original]
235
+ end
236
+
237
+ # Whether the final line of the old or new side (as of the last
238
+ # hunk) carries the no-newline marker. side is :old or :new.
239
+ def final_line_marked?(hunks, side)
240
+ last_hunk = hunks.last
241
+ return false unless last_hunk
242
+
243
+ wanted = side == :old ? %i[del context] : %i[add context]
244
+ last = last_hunk[:lines].reverse.find { |tag, _, _| wanted.include?(tag) }
245
+ return false unless last
246
+
247
+ tag, _text, no_newline = last
248
+ no_newline
249
+ end
250
+ end
251
+ end
252
+ end
@@ -0,0 +1,175 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Whole-workflow PATH_KINDS incorporation for the agent-level virtual Path
4
+ # interface (see lib/scout/llm/agent/path.rb for the engine overview).
5
+ module LLM
6
+ class Agent
7
+ module AgentPathWorkflowKinds
8
+ # Whole-workflow PATH_KINDS incorporation. Invoked from Agent#ask when a
9
+ # `tool: <workflow>` line (whole workflow, no task token) incorporates an
10
+ # entire workflow; task-level `tool: <workflow> <task>` lines never reach
11
+ # this. `workflow` must be a loaded local workflow Module (not a
12
+ # RemoteWorkflow, not an agent-fallback) that defines a `PATH_KINDS`
13
+ # constant in its own namespace.
14
+ #
15
+ # A workflow without `PATH_KINDS` registers nothing and returns nil
16
+ # silently. With it, every entry is registered through the regular
17
+ # `register_path_kind` (which dups the definition and reinstalls the tools
18
+ # atomically); the shared `PATH_KINDS` constant is never mutated.
19
+ #
20
+ # Provenance bookkeeping (`path_kind_sources`, kind name => workflow
21
+ # name) is kept beside the authoritative `path_kind_registry`: it records
22
+ # WHICH whole-workflow incorporation supplied a kind name, so a second
23
+ # DIFFERENT workflow reusing an existing kind name fails deterministically
24
+ # instead of letting import order decide. It is not a second registry:
25
+ # kinds are always looked up in `path_kind_registry`; re-registering the
26
+ # same kind from the same workflow overwrites idempotently.
27
+ #
28
+ # Kind definitions supplied by other callers (plugins, direct Ruby) do not
29
+ # record a source; a later whole-workflow incorporation of the same kind
30
+ # name simply re-registers it (the new source then owns the name).
31
+ #
32
+ # `only:` optionally restricts the incorporation to a subset of the
33
+ # workflow's kinds: nil (or an empty list) means every kind, unchanged;
34
+ # a nonempty list of kind names registers exactly those. Selection
35
+ # happens AFTER normalization, so the names are the workflow's own kind
36
+ # names; an unknown name raises ParameterException naming the workflow
37
+ # and the kind. A workflow without PATH_KINDS stays a silent no-op
38
+ # without a list, and raises with one (every requested name is
39
+ # unknown). Normalization, deep-copying, conflict bookkeeping and
40
+ # registration are untouched by the selection.
41
+ def integrate_workflow_path_kinds(workflow, only: nil)
42
+ # Only a local workflow Module qualifies: RemoteWorkflow instances
43
+ # (remote `tool:` targets) and anything else without a resolvable
44
+ # constant name are skipped entirely.
45
+ return nil unless Module === workflow
46
+ return nil if (workflow < RemoteWorkflow rescue false)
47
+ return nil if workflow.name.nil?
48
+
49
+ selection = path_kind_selection(only)
50
+ if workflow.const_defined?(:PATH_KINDS, false)
51
+ kinds = workflow.const_get(:PATH_KINDS, false)
52
+ workflow_name = workflow.name
53
+ definitions = path_normalize_workflow_path_kinds(kinds, workflow_name)
54
+ else
55
+ # Without a selection a PATH_KINDS-less workflow is the historical
56
+ # silent no-op; WITH a selection every requested name is unknown,
57
+ # which the selection check below raises on (empty definitions).
58
+ return nil unless selection
59
+ definitions = {}
60
+ workflow_name = workflow.name
61
+ end
62
+
63
+ definitions = path_select_workflow_path_kinds(definitions, selection, workflow_name) if selection
64
+
65
+ definitions.each do |name, definition|
66
+ source = path_kind_sources[name]
67
+ if source && source != workflow_name
68
+ raise ParameterException,
69
+ "Path kind #{name.inspect} is already provided by workflow " \
70
+ "#{source.inspect}; workflow #{workflow_name.inspect} cannot " \
71
+ "redefine it. Two workflows must not supply the same path kind."
72
+ end
73
+
74
+ # Deep-dup at this boundary: register_path_kind dups only one level,
75
+ # and Hash#freeze is shallow, so a shared frozen PATH_KINDS constant
76
+ # could otherwise be mutated through the registry (for instance by a
77
+ # future definition mutation). Copies are kept as plain unfrozen
78
+ # Hashes; callables are shared by reference as everywhere else.
79
+ register_path_kind(name, path_deep_copy(definition))
80
+ path_kind_sources[name] = workflow_name
81
+ end
82
+
83
+ definitions
84
+ end
85
+
86
+ # Normalize the optional `only:` selection of integrate_workflow_path_kinds
87
+ # into a sorted Array of unique kind-name Strings. nil and [] select
88
+ # everything (nil result); the input may be a single name or any
89
+ # enumerable of names, stringified like every other kind name.
90
+ def path_kind_selection(only)
91
+ return nil if only.nil?
92
+ selection = Array === only || only.respond_to?(:to_a) ? Array(only) : [only]
93
+ selection = selection.map(&:to_s).reject(&:empty?)
94
+ return nil if selection.empty?
95
+ selection.uniq.sort
96
+ end
97
+
98
+ # Apply the selection to a normalized definitions Hash: keeps exactly
99
+ # the named kinds. An unknown name raises ParameterException naming
100
+ # the workflow, the kind and the valid names, so a typo cannot silently
101
+ # degrade into a no-op.
102
+ def path_select_workflow_path_kinds(definitions, selection, workflow_name)
103
+ missing = selection.reject { |name| definitions.key?(name) }
104
+ unless missing.empty?
105
+ raise ParameterException,
106
+ "Workflow #{workflow_name.inspect} does not declare the path " \
107
+ "kind#{missing.length > 1 ? 's' : ''} #{missing.inspect}. Valid " \
108
+ "path kinds: #{definitions.keys.sort.inspect}"
109
+ end
110
+
111
+ definitions.select { |name, _| selection.include?(name) }
112
+ end
113
+
114
+ # Accept either a Hash of kind name => definition or an Array of
115
+ # definition hashes (each carrying its own "name"), mirroring what
116
+ # `register_path_kind` accepts per entry. Always returns a normalized
117
+ # Hash of kind name => definition.
118
+ def path_normalize_workflow_path_kinds(kinds, workflow_name)
119
+ if kinds.respond_to?(:each_pair)
120
+ entries = kinds.collect{|name, definition| [name, definition] }
121
+ elsif kinds.respond_to?(:each_with_index) && kinds.respond_to?(:first) && Hash === kinds.first
122
+ entries = kinds.collect{|definition|
123
+ [definition["name"] || definition[:name], definition]
124
+ }
125
+ else
126
+ raise ParameterException,
127
+ "Workflow #{workflow_name.inspect} declares PATH_KINDS as a " \
128
+ "#{kinds.class}; expected a Hash of kind name => definition " \
129
+ "(or an Array of definition Hashes with a \"name\" key)"
130
+ end
131
+
132
+ normalized = {}
133
+ entries.each do |name, definition|
134
+ name = name.to_s
135
+ if name.empty?
136
+ raise ParameterException,
137
+ "Workflow #{workflow_name.inspect} declares a PATH_KINDS entry " \
138
+ "with an empty kind name"
139
+ end
140
+ unless Hash === definition
141
+ raise ParameterException,
142
+ "Workflow #{workflow_name.inspect} PATH_KINDS entry " \
143
+ "#{name.inspect} is a #{definition.class}, expected a Hash"
144
+ end
145
+ normalized[name] = definition
146
+ end
147
+ normalized
148
+ end
149
+
150
+ # Recursive copy for Hash/Array/Primitive structures used by path-kind
151
+ # definitions. Callables and other opaque values are shared by
152
+ # reference, matching the rest of the engine.
153
+ def path_deep_copy(value)
154
+ case value
155
+ when Hash
156
+ value.each_with_object({}){|(k, v), acc| acc[k] = path_deep_copy(v) }
157
+ when Array
158
+ value.collect{|v| path_deep_copy(v) }
159
+ when String, Symbol, Numeric, true, false, nil
160
+ value
161
+ else
162
+ value.respond_to?(:call) || !value.respond_to?(:dup) ? value : value.dup
163
+ end
164
+ end
165
+
166
+ # Per-agent provenance map recording which workflow supplied each
167
+ # whole-workflow-incorporated kind name. Bookkeeping only; the
168
+ # authoritative registry remains `path_kind_registry`.
169
+ def path_kind_sources
170
+ @path_kind_sources ||= {}
171
+ end
172
+
173
+ end
174
+ end
175
+ end