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.
- checksums.yaml +4 -4
- data/.vimproject +133 -58
- data/README.md +2 -1
- data/VERSION +1 -1
- data/doc/Improvements.md +490 -148
- data/doc/Model.md +53 -10
- data/doc/StartHere.md +44 -19
- data/doc/developer/Architecture.md +25 -6
- data/doc/developer/Backends.md +207 -48
- data/doc/developer/ChatLifecycle.md +121 -20
- data/doc/developer/DelegationInternals.md +319 -33
- data/doc/developer/DesignPrinciples.md +205 -16
- data/doc/developer/PathEngine.md +628 -0
- data/doc/developer/PromptProcessing.md +332 -82
- data/doc/developer/Provenance.md +388 -40
- data/doc/developer/Sandbox.md +213 -0
- data/doc/user/BuildingAgents.md +130 -18
- data/doc/user/Cookbook.md +29 -8
- data/doc/user/CoreConcepts.md +7 -6
- data/doc/user/Delegation.md +166 -15
- data/doc/user/GettingStarted.md +20 -16
- data/doc/user/ManagingContext.md +155 -17
- data/doc/user/MultiAgentWorkflows.md +105 -15
- data/doc/user/Python.md +11 -1
- data/doc/user/RunningInference.md +90 -47
- data/doc/user/ToolCalling.md +134 -29
- data/doc/user/WritingChats.md +56 -27
- data/lib/scout/llm/agent/attach.rb +13 -17
- data/lib/scout/llm/agent/chat.rb +32 -0
- data/lib/scout/llm/agent/construction.rb +64 -0
- data/lib/scout/llm/agent/conversation.rb +304 -0
- data/lib/scout/llm/agent/delegate.rb +56 -238
- data/lib/scout/llm/agent/path/edit.rb +230 -0
- data/lib/scout/llm/agent/path/patch.rb +252 -0
- data/lib/scout/llm/agent/path/workflow_kinds.rb +175 -0
- data/lib/scout/llm/agent/path.rb +1777 -0
- data/lib/scout/llm/agent/save.rb +11 -9
- data/lib/scout/llm/agent/workflow.rb +77 -16
- data/lib/scout/llm/agent.rb +147 -31
- data/lib/scout/llm/ask.rb +28 -17
- data/lib/scout/llm/backends/anthropic.rb +1 -1
- data/lib/scout/llm/backends/bedrock.rb +3 -2
- data/lib/scout/llm/backends/default.rb +127 -34
- data/lib/scout/llm/backends/glm.rb +28 -1
- data/lib/scout/llm/backends/huggingface.rb +1 -1
- data/lib/scout/llm/backends/ollama.rb +1 -1
- data/lib/scout/llm/backends/openai.rb +7 -6
- data/lib/scout/llm/backends/openwebui.rb +14 -7
- data/lib/scout/llm/backends/relay.rb +8 -2
- data/lib/scout/llm/chat/agent_meta.rb +24 -60
- data/lib/scout/llm/chat/parse.rb +1 -1
- data/lib/scout/llm/chat/process/files.rb +10 -0
- data/lib/scout/llm/chat/process/meta.rb +5 -7
- data/lib/scout/llm/chat/process/tools.rb +104 -49
- data/lib/scout/llm/chat/prompt/epoch_tool_compactation.rb +355 -0
- data/lib/scout/llm/chat/prompt/inbox.rb +188 -0
- data/lib/scout/llm/chat/prompt/shorten_tools.rb +797 -13
- data/lib/scout/llm/chat/prompt/shorten_tools_epoch.rb +1 -365
- data/lib/scout/llm/chat/prompt/shorten_tools_epoch_increment.rb +1 -0
- data/lib/scout/llm/chat/prompt.rb +24 -10
- data/lib/scout/llm/chat/provenance/live.rb +1080 -0
- data/lib/scout/llm/chat/provenance/tokens.rb +386 -0
- data/lib/scout/llm/chat/provenance.rb +343 -676
- data/lib/scout/llm/chat.rb +8 -2
- data/lib/scout/llm/embed.rb +15 -3
- data/lib/scout/llm/image.rb +4 -1
- data/lib/scout/llm/mcp.rb +4 -2
- data/lib/scout/llm/request_context.rb +234 -0
- data/lib/scout/llm/sandbox.rb +263 -0
- data/lib/scout/llm/tools/call.rb +163 -42
- data/lib/scout/llm/tools/definition.rb +48 -0
- data/lib/scout/llm/tools/knowledge_base.rb +1 -0
- data/lib/scout/llm/tools/mcp.rb +50 -43
- data/lib/scout/llm/tools/workflow.rb +90 -20
- data/lib/scout/llm/tools.rb +14 -41
- data/lib/scout/model/decision/base.rb +43 -0
- data/lib/scout/model/decision/jev.rb +161 -0
- data/lib/scout/model/python/torch.rb +1 -1
- data/research/clear-tools-inherit.md +171 -0
- data/research/path-engine-dc1-dc2-dc3-fixes.md +279 -0
- data/research/path-kind-chat-role.md +96 -0
- data/research/path-kind-contract-fixes-engine.md +307 -0
- data/research/scout-ai-runtime-availability.md +65 -0
- data/research/subsys/README.md +127 -0
- data/research/subsys/agent-delegation.md +201 -0
- data/research/subsys/agent-society.md +275 -0
- data/research/subsys/agentworkflow.md +233 -0
- data/research/subsys/backends.md +221 -0
- data/research/subsys/chat.md +314 -0
- data/research/subsys/embed-image.md +244 -0
- data/research/subsys/entry-cli.md +253 -0
- data/research/subsys/model-ml.md +326 -0
- data/research/subsys/provenance.md +290 -0
- data/research/subsys/tools.md +334 -0
- data/scout-ai.gemspec +71 -27
- data/scout_commands/agent/ask +8 -7
- data/scout_commands/llm/abridged +40 -0
- data/scout_commands/llm/ask +9 -9
- data/scout_commands/llm/md +2 -0
- data/scout_commands/llm/prov +724 -59
- data/scout_commands/llm/word +4 -0
- data/share/word/reference.docx +0 -0
- data/test/integration/scout/model/decision/test_jev.rb +144 -0
- data/test/scout/llm/agent/test_attach.rb +117 -0
- data/test/scout/llm/agent/test_conversation.rb +407 -0
- data/test/scout/llm/agent/test_delegate.rb +209 -0
- data/test/scout/llm/agent/test_path.rb +1812 -0
- data/test/scout/llm/agent/test_path_edit.rb +908 -0
- data/test/scout/llm/agent/test_path_errors.rb +390 -0
- data/test/scout/llm/agent/test_path_filesystem.rb +532 -0
- data/test/scout/llm/agent/test_path_patch.rb +233 -0
- data/test/scout/llm/agent/test_path_promotion.rb +386 -0
- data/test/scout/llm/agent/test_path_workflow_integration.rb +665 -0
- data/test/scout/llm/agent/test_save.rb +70 -15
- data/test/scout/llm/agent/test_workflow.rb +130 -4
- data/test/scout/llm/backends/test_anthropic.rb +4 -4
- data/test/scout/llm/backends/test_bedrock.rb +4 -4
- data/test/scout/llm/backends/test_format_other.rb +43 -0
- data/test/scout/llm/backends/test_ollama.rb +2 -2
- data/test/scout/llm/backends/test_openwebui.rb +12 -8
- data/test/scout/llm/backends/test_reasoning.rb +114 -0
- data/test/scout/llm/chat/agent_meta_fixtures.rb +28 -27
- data/test/scout/llm/chat/prompt/test_epoch_tool_compactation.rb +612 -0
- data/test/scout/llm/chat/prov_plot_fixtures.rb +131 -0
- data/test/scout/llm/chat/test_agent_meta.rb +40 -80
- data/test/scout/llm/chat/test_agent_meta_provenance.rb +67 -28
- data/test/scout/llm/chat/test_agent_meta_tokens.rb +59 -8
- data/test/scout/llm/chat/test_agent_view.rb +178 -0
- data/test/scout/llm/chat/test_live_report.rb +282 -0
- data/test/scout/llm/chat/test_live_workload.rb +193 -0
- data/test/scout/llm/chat/test_parse.rb +32 -2
- data/test/scout/llm/chat/test_prompt.rb +411 -0
- data/test/scout/llm/chat/test_prov_cli.rb +310 -15
- data/test/scout/llm/chat/test_prov_cli_live.rb +152 -0
- data/test/scout/llm/chat/test_prov_plot.rb +213 -0
- data/test/scout/llm/chat/test_prov_timeline.rb +355 -0
- data/test/scout/llm/chat/test_provenance.rb +67 -22
- data/test/scout/llm/chat/test_provenance_index.rb +479 -0
- data/test/scout/llm/chat/test_society_view.rb +159 -0
- data/test/scout/llm/test_agent.rb +1 -1
- data/test/scout/llm/test_embed.rb +103 -1
- data/test/scout/llm/test_request_context.rb +299 -0
- data/test/scout/llm/test_sandbox.rb +249 -0
- data/test/scout/llm/tools/test_agent_pairing.rb +150 -0
- data/test/scout/llm/tools/test_call_delegation_conflict.rb +316 -0
- data/test/scout/llm/tools/test_definition.rb +332 -0
- data/test/scout/llm/tools/test_jobs_file.rb +211 -0
- data/test/scout/llm/tools/test_mcp.rb +37 -8
- data/test/scout/llm/tools/test_workflow.rb +45 -1
- data/test/scout/model/decision/test_jev.rb +453 -0
- data/test/scout/model/python/huggingface/causal/test_next_token.rb +7 -10
- data/test/scout/model/python/huggingface/test_causal.rb +11 -2
- data/test/scout/model/python/huggingface/test_classification.rb +5 -3
- data/test/scout/model/python/test_availability.rb +116 -0
- data/test/scout/model/python/test_torch.rb +54 -2
- data/test/support/availability.rb +72 -174
- data/test/support/fake_clients.rb +18 -9
- data/test/support/fixtures.rb +75 -6
- data/test/support/mock_backend.rb +9 -1
- data/test/support/test_fixtures.rb +156 -0
- data/test/test_helper.rb +14 -4
- metadata +70 -26
- data/research/ChatAnalyst-required-changes.md +0 -167
- data/research/agent-delegation-analysis.md +0 -810
- data/research/agent-meta-provenance-integration-plan.md +0 -622
- data/research/agent-workflow-analysis.md +0 -1120
- data/research/backends-analysis.md +0 -836
- data/research/chat-core-analysis.md +0 -946
- data/research/chatanalyst-provenance/00-baseline.md +0 -30
- data/research/chatanalyst-provenance/01-repo-map.md +0 -60
- data/research/chatanalyst-provenance/02-event-reconstruction.md +0 -55
- data/research/chatanalyst-provenance/03-duplication-evidence.md +0 -45
- data/research/chatanalyst-provenance/04-tooling-root-cause.md +0 -57
- data/research/chatanalyst-provenance/05-fix-plan.md +0 -46
- data/research/chatanalyst-provenance/07-critic-review.md +0 -25
- data/research/chatanalyst-provenance/final-report.md +0 -45
- data/research/chatanalyst-provenance/resumption.md +0 -37
- data/research/coding-philosophy-analysis.md +0 -928
- data/research/commands-analysis.md +0 -947
- data/research/multi-agent-patterns-analysis.md +0 -853
- data/research/prompt-strategies-analysis.md +0 -630
- data/research/prov-verbosity-fix-notes.md +0 -77
- data/research/provenance-analysis.md +0 -469
- data/research/provenance-continuation-accounting.md +0 -255
- data/research/synthesis-report.md +0 -487
- data/research/tools-system-analysis.md +0 -779
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
# 09 - Entry points, CLI and config surface
|
|
2
|
+
|
|
3
|
+
> Investigation, not normative documentation. Verified behavior of the
|
|
4
|
+
> require entry, `LLM.ask`/`LLM.chat`/`LLM.messages`/`LLM.load_agent`, the
|
|
5
|
+
> command surface and the config/env handling at this layer. Normative
|
|
6
|
+
> reference: `doc/StartHere.md`, `doc/developer/Architecture.md`,
|
|
7
|
+
> `doc/user/RunningInference.md`, `doc/user/GettingStarted.md`.
|
|
8
|
+
|
|
9
|
+
## Scope
|
|
10
|
+
|
|
11
|
+
`lib/scout-ai.rb`, the top-level single-inference entry points in
|
|
12
|
+
`lib/scout/llm/{ask,chat}.rb`, `bin/scout-ai`, `scout_commands/{llm,agent,
|
|
13
|
+
workflow}` and the config/env handling consumed there.
|
|
14
|
+
|
|
15
|
+
## Verified behavior
|
|
16
|
+
|
|
17
|
+
### Require entry
|
|
18
|
+
|
|
19
|
+
`lib/scout-ai.rb` (11 lines): requires `scout`, `scout/path`,
|
|
20
|
+
`scout/resource`; registers the `:scout_ai_lib` pathmap
|
|
21
|
+
(`Path.add_path :scout_ai_lib, File.join(Path.caller_lib_dir(__FILE__),
|
|
22
|
+
"{TOPLEVEL}/{SUBPATH}")`) **before** requiring `scout/llm/{ask,chat,embed,
|
|
23
|
+
image,agent}`.
|
|
24
|
+
|
|
25
|
+
After `require 'scout-ai'`:
|
|
26
|
+
|
|
27
|
+
- `LLM.constants == [:Agent, :BACKENDS]` (backends load lazily per request).
|
|
28
|
+
- `LLM.methods(false)` (34): `agent, ask, associations,
|
|
29
|
+
call_id_name_and_arguments, call_knowledge_base, call_tools,
|
|
30
|
+
call_workflow, chat, database_details_tool_definition,
|
|
31
|
+
database_tool_definition, embed, get_url_config, get_url_server_tokens,
|
|
32
|
+
image, knowledge_base_ask, knowledge_base_tool_definition, load_agent,
|
|
33
|
+
max_content_length, max_content_length=, mcp_tools, messages,
|
|
34
|
+
meta_receipt_from_messages, options, print, process_calls, purge,
|
|
35
|
+
register_backend, run_tools, scout_to_tool_input_type,
|
|
36
|
+
task_tool_definition, tool_response, tools, workflow_ask,
|
|
37
|
+
workflow_tools`.
|
|
38
|
+
- `LLM::Agent.methods(false)` = `[:legacy_society_dir_for, :load_agent,
|
|
39
|
+
:load_from_path, :nested_save?, :society_dir_for]`.
|
|
40
|
+
|
|
41
|
+
### `LLM.ask`
|
|
42
|
+
|
|
43
|
+
`lib/scout/llm/ask.rb:12-116`, responsibilities in order:
|
|
44
|
+
|
|
45
|
+
1. `messages = LLM.chat(question)`; `options = IndiferentHash.add_defaults
|
|
46
|
+
options, LLM.options(messages)` (chat-embedded options first).
|
|
47
|
+
2. **Agent branch**: when `options[:agent]` is set, `agent =
|
|
48
|
+
LLM::Agent.load_agent(name)`, `agent.save_file = agent_save_file if
|
|
49
|
+
agent_save_file`, `agent.follow messages`, `res = agent.chat options`.
|
|
50
|
+
The agent path is taken entirely inside `LLM.ask` - `agent:` is a
|
|
51
|
+
legitimate `LLM.ask` option, not a separate entry point.
|
|
52
|
+
3. Endpoint/persist resolution: `persist` defaults to **true** (env
|
|
53
|
+
`ASK_PERSIST,LLM_PERSIST,PERSIST`); endpoint falls back to config (env
|
|
54
|
+
`ASK_ENDPOINT,LLM_ENDPOINT,ENDPOINT,LLM,ASK`). When
|
|
55
|
+
`Scout.etc.AI[endpoint].find_with_extension(:yaml)` exists, the yaml keys
|
|
56
|
+
are merged as option defaults - `provider` included; a non-empty unknown
|
|
57
|
+
endpoint raises `"Endpoint not found #{endpoint}"`.
|
|
58
|
+
4. Provenance context: `job_paths = messages.job_paths`;
|
|
59
|
+
`meta = Chat.meta(messages)`; `options[:current_meta] = meta` when
|
|
60
|
+
non-empty.
|
|
61
|
+
5. The relay backend is handed the request early (file-based round-trip).
|
|
62
|
+
6. The dispatch is wrapped in `Persist.persist(endpoint, :json, prefix:
|
|
63
|
+
"LLM ask", other: options.merge(messages:), persist:, dir:
|
|
64
|
+
Scout.var.cache.ask)`; `SCOUT_NO_ASK_CACHE` gates the cache.
|
|
65
|
+
7. Backend: `Scout::Config.get :backend, :ask, :llm, env:
|
|
66
|
+
'ASK_BACKEND,LLM_BACKEND', default: :responses` (ask.rb:71), then the
|
|
67
|
+
`when` ladder requiring each backend lazily.
|
|
68
|
+
8. Knowledge-base sugar: `LLM.knowledge_base_ask(kb, question, options)`
|
|
69
|
+
wraps `self.ask(question, options.merge(tools: knowledge_base_tools))`
|
|
70
|
+
with a block-dispatched `children` lookup.
|
|
71
|
+
|
|
72
|
+
Return shape: the assistant **String** by default; the full messages Array
|
|
73
|
+
with `return_messages: true` (the agent/`chat` paths and both CLIs rely on
|
|
74
|
+
this).
|
|
75
|
+
|
|
76
|
+
### `LLM.chat` / `LLM.messages`
|
|
77
|
+
|
|
78
|
+
`LLM.messages(question, role = nil)` accepts an Array of Strings (-> `user`
|
|
79
|
+
messages) or Hashes (kept) or a String (-> `Chat.parse`).
|
|
80
|
+
`LLM.chat(file = [], original = nil)` is the file-aware loader: String/Path
|
|
81
|
+
-> `Chat.parse`; Array -> used directly; then `Chat.files(messages,
|
|
82
|
+
original, caller_lib_dir)` resolves `file:` roles relative to the chat file,
|
|
83
|
+
and `Chat.setup` annotates. The compilation pipeline itself is owned by
|
|
84
|
+
`research/subsys/chat.md`.
|
|
85
|
+
|
|
86
|
+
`Chat#ask` / `Chat#chat` simply re-enter `LLM.ask(LLM.chat(self), options)`.
|
|
87
|
+
|
|
88
|
+
### Agent loading
|
|
89
|
+
|
|
90
|
+
`LLM.load_agent(...)` and `LLM::Agent.load_agent(...)` are equivalent; both
|
|
91
|
+
`LLM.ask` and the CLIs use them. Resolution for a non-filename name (see
|
|
92
|
+
`research/subsys/agent-society.md` for the full algorithm):
|
|
93
|
+
|
|
94
|
+
1. `Scout.workflows[name]`
|
|
95
|
+
2. `Scout.Agent[name]`
|
|
96
|
+
3. `Scout.var.Agent[name]`
|
|
97
|
+
4. `Scout.chats.Agent[name]`
|
|
98
|
+
5. `Scout.chats[name]`
|
|
99
|
+
|
|
100
|
+
None -> `raise ScoutException, "No agent found with name #{agent_name}"`.
|
|
101
|
+
The **filename branch runs first**: an existing path whose directory has an
|
|
102
|
+
`agent.rb` loads that file (Kernel `load`; last expression must be an
|
|
103
|
+
Agent). This branch is documented only in `doc/developer/Architecture.md` -
|
|
104
|
+
`doc/user/BuildingAgents.md` never mentions `agent.rb`.
|
|
105
|
+
|
|
106
|
+
### `bin/scout-ai` and command discovery
|
|
107
|
+
|
|
108
|
+
- Repo `bin/scout-ai` (53 lines) is a thin launcher: it prepends
|
|
109
|
+
`<repo>/lib` to `$LOAD_PATH`, pre-parses `--log`/`--dev` (`SCOUT_DEV` env
|
|
110
|
+
also accepted; `--dev DIR` adds `DIR/scout-*/lib` and `DIR/rbbt-*/lib`),
|
|
111
|
+
requires `'scout-ai'`, then `load Scout.bin.scout.find` - **the real
|
|
112
|
+
dispatcher is scout-gear's `bin/scout`**, which is why `scout-ai` and
|
|
113
|
+
`scout` share the generic help.
|
|
114
|
+
- The installed `scout-ai` wrapper is RubyGems-generated.
|
|
115
|
+
- Subcommands are found by globbing `Scout.scout_commands.find_all` for the
|
|
116
|
+
current command path, merging and sorting. From the repo root that
|
|
117
|
+
resolves to the repo's `scout_commands/` plus both gems'; from elsewhere
|
|
118
|
+
(e.g. `/tmp`) the local entry disappears and the commands come from the
|
|
119
|
+
gems only. This is why `scout agent` works from the repo root while
|
|
120
|
+
`scout llm` from `/tmp` errors - and `scout-ai llm` works everywhere,
|
|
121
|
+
because its gem ships the commands.
|
|
122
|
+
- `cmd_alias` (from `Scout.etc.cmd_alias.yaml`) rewrites ARGV before
|
|
123
|
+
dispatch. Unknown command -> `## ERROR Command '<x>' not understood`,
|
|
124
|
+
exit 255.
|
|
125
|
+
|
|
126
|
+
### Subcommand inventory
|
|
127
|
+
|
|
128
|
+
Top level (`scout-ai`, and `scout` where its command dir resolves):
|
|
129
|
+
`agent alias batch cat doc entity find glob kb llm log purge rbbt resource
|
|
130
|
+
system template update workflow`. `agent`, `llm` (+ `workflow/mcp`) come
|
|
131
|
+
from scout-ai; the rest from scout-gear.
|
|
132
|
+
|
|
133
|
+
`scout_commands/llm/*`:
|
|
134
|
+
|
|
135
|
+
| command | purpose | key options |
|
|
136
|
+
|---|---|---|
|
|
137
|
+
| `llm ask` | one-shot inference; STDIN as context via a `...` placeholder, template questions, chat continuation, inline rewriting | `-f/--file`, `-c/--chat`, `-i/--inline`, `-t/--template*`, `-w/--workflow*`, `-m/--model`, `-e/--endpoint`, `-b/--backend`, `-d/--dry_run` |
|
|
138
|
+
| `llm json` | convert a chat file to/from JSON | `--chat`, `--json`, `--output`, `-l/--last` |
|
|
139
|
+
| `llm md` | convert a chat file to Markdown | `--output`, `-l/--last` |
|
|
140
|
+
| `llm word` | convert a chat file to docx (uses the `reference.docx` option) | `--reference`, `-l/--last` |
|
|
141
|
+
| `llm process` | daemon: loop over `Scout.var.ask` files, run `LLM.ask(messages, options.merge(process: id))`, delete the file, `sleep 1` when idle | `-p/--process` |
|
|
142
|
+
| `llm process_queries` | the same pattern for query files | - |
|
|
143
|
+
| `llm prov` | provenance rendering (tree, flow, DOT, timeline) from `Chat.traverse_provenance` | `--evidence`, `--live`, `--flow=svg|png|pdf`, `--timeline=svg|png|pdf|dot` |
|
|
144
|
+
| `llm server` | sinatra server backing the offline notebook UI | - |
|
|
145
|
+
| `llm template` | list question templates under `Scout.questions` | - |
|
|
146
|
+
|
|
147
|
+
`llm ask` flow: `--template` loads `Scout.questions[template].read` and
|
|
148
|
+
appends `user: <question>`; `...` in the question is replaced by STDIN (or
|
|
149
|
+
`--file` contents); `--file` without `...` wraps the content in a
|
|
150
|
+
`<file basename=...>` block; `--chat <path>` loads/appends the conversation,
|
|
151
|
+
computes `agent_save_file = Agent.canonical_chat_file(chat + '.files')`,
|
|
152
|
+
calls `LLM.ask(..., return_messages: true, agent_save_file: ...)` and
|
|
153
|
+
appends the new messages back; `--inline <file>` repeatedly finds `# ask:`
|
|
154
|
+
comment blocks and rewrites the file with the responses; otherwise
|
|
155
|
+
`conversation = LLM.chat question` (+ a `tool: workflow` message when
|
|
156
|
+
`--workflow`) and `puts LLM.ask(conversation, options)`. `-d/--dry_run`
|
|
157
|
+
skips the model call and prints the prompt.
|
|
158
|
+
|
|
159
|
+
`scout_commands/agent/*`:
|
|
160
|
+
|
|
161
|
+
| command | purpose |
|
|
162
|
+
|---|---|
|
|
163
|
+
| `agent ask` | ask a named agent; same STDIN/file/chat/inline/template handling as `llm ask` but through `LLM::Agent` (load -> `current_chat.concat` -> `agent.chat`); extra `-wt/--workflow_tasks`, `-i/--imports` |
|
|
164
|
+
| `agent find` | load an agent by name/path and print (`LLM.load_agent`) |
|
|
165
|
+
| `agent kb` | run `scout kb` with `--knowledge_base <agent_dir.knowledge_base>` and `--agent` |
|
|
166
|
+
|
|
167
|
+
`agent ask` sets `agent_save_file` **before** the first chat call so the
|
|
168
|
+
ensure-hook and the restart snapshot see it.
|
|
169
|
+
|
|
170
|
+
`scout_commands/workflow/mcp` (43 lines) ships the MCP export for workflows
|
|
171
|
+
(`scout-ai workflow mcp [--tasks]`); the rest of the `workflow` namespace
|
|
172
|
+
comes from scout-gear. `scout_commands/llm/prov` is by far the largest
|
|
173
|
+
script (~1200 lines; the flow/DOT rendering lives inline).
|
|
174
|
+
|
|
175
|
+
All commands are listed in `scout-ai.gemspec` (lines 161-172) and shipped in
|
|
176
|
+
the gem.
|
|
177
|
+
|
|
178
|
+
### Config and environment
|
|
179
|
+
|
|
180
|
+
| what | tokens | env | default |
|
|
181
|
+
|---|---|---|---|
|
|
182
|
+
| persist (cache) | `persist` (`ask`, `llm`) | `ASK_PERSIST, LLM_PERSIST, PERSIST` | `true` |
|
|
183
|
+
| endpoint | `endpoint` (`ask`, `llm`) | `ASK_ENDPOINT, LLM_ENDPOINT, ENDPOINT, LLM, ASK` | none |
|
|
184
|
+
| backend | `backend` (`ask`, `llm`) | `ASK_BACKEND, LLM_BACKEND` | `:responses` |
|
|
185
|
+
|
|
186
|
+
- Endpoint YAML files at `~/.scout/etc/AI/<endpoint>.yaml`; keys merged as
|
|
187
|
+
option defaults.
|
|
188
|
+
- `--log N` sets `Log.severity` in every command script.
|
|
189
|
+
- `-ck/--config_keys k=v,...` applies `Scout::Config.process_config` per
|
|
190
|
+
comma-separated item; values may be a yaml file, a named profile
|
|
191
|
+
(`Scout.etc.config_profile[<name>]`) or `key=value` pairs.
|
|
192
|
+
- Config files read at boot: `Path.setup("etc").config.find_all` reversed -
|
|
193
|
+
`etc/config` files across path maps.
|
|
194
|
+
- `SCOUT_DEV` / `--dev DIR`; `SCOUT_CHAT_DIR` (consumed by the chat
|
|
195
|
+
machinery); `SCOUT_NO_ASK_CACHE`.
|
|
196
|
+
|
|
197
|
+
## Sharp edges and known issues
|
|
198
|
+
|
|
199
|
+
- **`scout-ai config set ...` does not exist** (F3, open): both
|
|
200
|
+
`doc/user/RunningInference.md:28` and `doc/user/GettingStarted.md:67-70`
|
|
201
|
+
instruct it; it fails with `Command 'config' not understood` (exit 255),
|
|
202
|
+
no `config` command exists in either command dir, and no code path writes
|
|
203
|
+
endpoint YAML. Workaround: hand-write `~/.scout/etc/AI/<endpoint>.yaml`
|
|
204
|
+
(what `LLM.ask` actually reads) or use `-ck key=value` per invocation.
|
|
205
|
+
- **The `agent.rb` convention is undocumented in user docs** (open):
|
|
206
|
+
BuildingAgents.md documents only `start_chat` + optional `workflow.rb`,
|
|
207
|
+
`knowledge_base/`, `python/`.
|
|
208
|
+
- **`scout` vs `scout-ai` prefix availability is location-dependent**
|
|
209
|
+
(open): the `llm`/`agent` subcommands resolve only where the scout-ai
|
|
210
|
+
`scout_commands/` is on the path maps; the docs show both forms without
|
|
211
|
+
flagging the distinction.
|
|
212
|
+
- **Repo vs installed gem**: repo `VERSION` 2.1.0, installed gem 2.0.0 at
|
|
213
|
+
study time; findings probed against the gem whenever `scout-ai` was
|
|
214
|
+
invoked outside the repo. The command surface observed is the same.
|
|
215
|
+
- The legacy `llm info` alias mentioned in `research/commands-analysis.md`
|
|
216
|
+
is background only; `llm prov` is current and consistent with
|
|
217
|
+
`doc/developer/Provenance.md`.
|
|
218
|
+
|
|
219
|
+
## Open questions
|
|
220
|
+
|
|
221
|
+
- `llm server` requires sinatra; its routes/endpoints are unprobed (help
|
|
222
|
+
printing fails in a sandbox on a missing dir).
|
|
223
|
+
- `llm prov`'s full option surface is documented in Provenance.md but owned
|
|
224
|
+
by `research/subsys/provenance.md`.
|
|
225
|
+
- Whether any env var beyond `SCOUT_DEV`/`SCOUT_CHAT_DIR`/
|
|
226
|
+
`SCOUT_NO_ASK_CACHE` is consumed in `bin/scout-ai` itself (only those
|
|
227
|
+
three appear in the file).
|
|
228
|
+
- Python agents (`PythonWorkflow.load_directory(agent_path.python,
|
|
229
|
+
'ScoutAgent')`) are reachable from `load_agent` but were not executed in
|
|
230
|
+
the study environment.
|
|
231
|
+
|
|
232
|
+
## Evidence
|
|
233
|
+
|
|
234
|
+
Provenance: derived from the 2026-09-10/11 Cortex subsystem studies, probed
|
|
235
|
+
against this checkout at HEAD `a992a33` plus the uncommitted 2026-09-11 fix
|
|
236
|
+
sweep (attach/MCP/embed/torch); no fix in this sweep touches this subsystem.
|
|
237
|
+
|
|
238
|
+
- Code: `lib/scout-ai.rb` (11 lines); `lib/scout/llm/ask.rb:12-116`
|
|
239
|
+
(`:71` default backend), `:127-141` (knowledge_base_ask);
|
|
240
|
+
`lib/scout/llm/chat.rb:13-62`; `lib/scout/llm/agent.rb:174-228`
|
|
241
|
+
(load_agent); `bin/scout-ai`; `scout_commands/llm/{ask,json,md,word,
|
|
242
|
+
process,process_queries,prov,server,template}`; `scout_commands/agent/
|
|
243
|
+
{ask,find,kb}`; `scout_commands/workflow/mcp`; scout-gear `bin/scout`
|
|
244
|
+
(command discovery, `cmd_alias`); scout-essentials config.rb:29, 166-179.
|
|
245
|
+
- Docs: `doc/StartHere.md`, `doc/developer/Architecture.md`,
|
|
246
|
+
`doc/user/{RunningInference,GettingStarted,BuildingAgents,ManagingContext,
|
|
247
|
+
CoreConcepts}.md`.
|
|
248
|
+
- Probes (`tmp/entry_probe/`, offline): agent discovery kinds and the exact
|
|
249
|
+
exception; `LLM.chat`/`LLM.messages` shapes; command-surface capture;
|
|
250
|
+
env/config token grep; `LLM.ask` offline/stubbed behaviour and return
|
|
251
|
+
shapes; the `agent.rb` shortcut and `agent_save_file`; `Scout.*` map
|
|
252
|
+
roots; endpoint-YAML merge (a yaml with `provider: ollama / model: qwen /
|
|
253
|
+
other: 1` merges all three keys as defaults); module surface summary.
|
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
# 08 - ScoutModel / Torch / HuggingFace ML layer
|
|
2
|
+
|
|
3
|
+
> Investigation, not normative documentation. Verified behavior of the ML
|
|
4
|
+
> model subsystem and the Python SDK's ML half. Normative reference:
|
|
5
|
+
> `doc/Model.md` (classified there as "ML model subsystem, separate from
|
|
6
|
+
> harness").
|
|
7
|
+
|
|
8
|
+
## Scope
|
|
9
|
+
|
|
10
|
+
`lib/scout/model/**` (ScoutModel, PythonModel, TorchModel, HuggingfaceModel
|
|
11
|
+
and specializations) and the ML half of `python/scout_ai/**` (`util`, `data`,
|
|
12
|
+
`huggingface/*`). The agent/chat half of the Python SDK is covered only at
|
|
13
|
+
the boundary.
|
|
14
|
+
|
|
15
|
+
## Verified behavior
|
|
16
|
+
|
|
17
|
+
### Placement and load graph
|
|
18
|
+
|
|
19
|
+
- The subsystem is **not required by `lib/scout-ai.rb`**. The only in-repo
|
|
20
|
+
require site is the LLM huggingface backend
|
|
21
|
+
(`lib/scout/llm/backends/huggingface.rb:35-36`), which is the single seam
|
|
22
|
+
to the agent layer.
|
|
23
|
+
- Class hierarchy: `CausalModel -> HuggingfaceModel -> TorchModel ->
|
|
24
|
+
PythonModel -> ScoutModel`; `NextTokenModel -> CausalModel`;
|
|
25
|
+
`SequenceClassificationModel -> HuggingfaceModel`.
|
|
26
|
+
|
|
27
|
+
### ScoutModel core
|
|
28
|
+
|
|
29
|
+
Dual-purpose registration API (`util/run.rb`): each of `init`, `eval`,
|
|
30
|
+
`eval_list`, `extract_features`, `extract_features_list`, `post_process`,
|
|
31
|
+
`post_process_list`, `train`, `save_state`, `load_state` takes an optional
|
|
32
|
+
block - **with** a block it registers the Proc, **without** it it executes
|
|
33
|
+
the stored one. `execute(method, *args)` runs a Proc via `instance_exec` or
|
|
34
|
+
returns `args.first` when the method is nil, so an unregistered
|
|
35
|
+
`post_process`/`extract_features` is an identity pass.
|
|
36
|
+
|
|
37
|
+
- `eval(sample)`: `features = extract_features sample`; `init unless @state`;
|
|
38
|
+
an arity-2 eval block receives `(features, nil)`, an arity-1 block
|
|
39
|
+
`(features)`; then `post_process result`.
|
|
40
|
+
- `eval_list(list)`: `extract_features_list list`; prefers `@eval_list`; else
|
|
41
|
+
an arity-2 eval block receives `(nil, list)`; else maps `eval` per element.
|
|
42
|
+
An arity-2 block therefore serves both single and list evaluation.
|
|
43
|
+
- `train`: registers or `execute @train, @features, @labels`, then
|
|
44
|
+
**`save_state`** - every train auto-persists state when a state hook
|
|
45
|
+
exists.
|
|
46
|
+
- `add(sample, label = nil)` / `add_list(list, labels = nil|Hash)` fill
|
|
47
|
+
`@features`/`@labels` after feature extraction; Hash labels keyed by sample
|
|
48
|
+
work.
|
|
49
|
+
- Constructor: `directory` is Path-ified and `restore` is called immediately
|
|
50
|
+
when present; `@features`/`@labels` reset to `[]` after restore.
|
|
51
|
+
|
|
52
|
+
### Persistence model
|
|
53
|
+
|
|
54
|
+
`save` (util/save.rb:50-67) writes:
|
|
55
|
+
|
|
56
|
+
1. `options.json` (JSON dump of `@options`).
|
|
57
|
+
2. One `.rb` file per registered block (`eval.rb`, `eval_list.rb`,
|
|
58
|
+
`extract_features.rb`, `extract_features_list.rb`, `post_process.rb`,
|
|
59
|
+
`post_process_list.rb`, `train.rb`, `init.rb`, `load_state.rb`,
|
|
60
|
+
`save_state.rb`) via `method_source`'s `Proc#source` - i.e. the
|
|
61
|
+
**original call-site source** (`m.eval { |v| v * 2 }` persists the literal
|
|
62
|
+
line including the receiver and call).
|
|
63
|
+
3. `save_state if @state`.
|
|
64
|
+
|
|
65
|
+
`restore` loads all ten blocks plus options. `load_method` returns the plain
|
|
66
|
+
file content when `directory[name]` exists without the `.rb` extension, else
|
|
67
|
+
`load_ruby_code` on `directory[name.rb]`.
|
|
68
|
+
|
|
69
|
+
`load_ruby_code` applies `code.sub!(/.*(\sdo\b|{)/, 'Proc.new\1')` - a single
|
|
70
|
+
greedy `.*` prefix strip up to the **last** ` do` or `{` on the line - then
|
|
71
|
+
`instance_eval`s it. Because the saved line is the call site, the rewrite
|
|
72
|
+
turns ` m.eval { |v| v * 2 }` into `Proc.new{ |v| v * 2 }`. Round-trips
|
|
73
|
+
verified for: single-line braces, do/end multiline, do/end with nested braces
|
|
74
|
+
and hash literals, ternary with braces, arity-2 do/end.
|
|
75
|
+
|
|
76
|
+
`state_file` = `directory.state`; nil without a directory (and `save` then
|
|
77
|
+
fails on `save_options`).
|
|
78
|
+
|
|
79
|
+
Options merge on restore (`load_options`): file options merge **over**
|
|
80
|
+
constructor options - saved values win. Verified concretely: a model saved
|
|
81
|
+
with `checkpoint: "saved/ckpt"` and reloaded as
|
|
82
|
+
`HuggingfaceModel.new("CausalLM", "NEW/ckpt", dir)` still reports
|
|
83
|
+
`"saved/ckpt"`.
|
|
84
|
+
|
|
85
|
+
### PythonModel
|
|
86
|
+
|
|
87
|
+
Constructor `initialize(dir, python_class = nil, python_module = nil,
|
|
88
|
+
options = nil)`; when `options` is nil and `python_module` is a Hash, the
|
|
89
|
+
third argument is treated as options and the module defaults to `:model`.
|
|
90
|
+
The class/module are stored into options, and only when
|
|
91
|
+
`options[:python_class]` is set an `init` block is registered that adds
|
|
92
|
+
`Scout.python.find(:lib)` and `directory` to the Python path,
|
|
93
|
+
`ScoutPython.init_scout`, then `ScoutPython.class_new_obj(module, class,
|
|
94
|
+
**options.except(:python_class, :python_module))` - the leftover options are
|
|
95
|
+
the Python kwargs. TorchModel/HuggingfaceModel pass `nil, nil` and therefore
|
|
96
|
+
inherit no PythonModel init block; they define their own.
|
|
97
|
+
|
|
98
|
+
### TorchModel
|
|
99
|
+
|
|
100
|
+
- Accessors `criterion`, `optimizer`, `device`, `dtype`; `fix_options`
|
|
101
|
+
normalizes `training_args`/`training_kwargs`/`training_x` into
|
|
102
|
+
`options[:training_args]`.
|
|
103
|
+
- Default `train` block (torch.rb:24-58): `TorchModel.init_python`, device/
|
|
104
|
+
dtype resolution, `state.to(device)`,
|
|
105
|
+
`@optimizer ||= TorchModel.optimizer(...)`,
|
|
106
|
+
`@criterion ||= TorchModel.criterion(state, options[:training_args] || {})`
|
|
107
|
+
(fixed 2026-09-11, uncommitted - it previously assigned
|
|
108
|
+
`TorchModel.optimizer(...)` to `@criterion`, an SGD optimizer, so the
|
|
109
|
+
default train path died with `PyCall::PyError TypeError: Non-callable
|
|
110
|
+
Python object was given` unless the user set `model.criterion` by hand;
|
|
111
|
+
see F7), full-batch tensors, then an epoch loop
|
|
112
|
+
`optimizer.zero_grad -> state.call(inputs) -> loss -> backward -> step`
|
|
113
|
+
under `Log::ProgressBar.with_bar`. `epochs` default 3; `batch_size` from
|
|
114
|
+
`options[:batch_size]` or `training_args[:batch_size]`, else 1.
|
|
115
|
+
- Default `eval` block: arity-2 (`features, list`), `state.eval`, chunks the
|
|
116
|
+
list by batch_size, `state.call(tensor)`, `Tensor#to_ruby!` per chunk
|
|
117
|
+
(frees the tensor), returns `res[0]` for a single input.
|
|
118
|
+
- Helpers (`torch/helpers.rb`): `TorchModel.init_python` (guarded by
|
|
119
|
+
`@@init_python`; imports `torch`, `scout`, `scout_ai`, `scout_ai.util`,
|
|
120
|
+
`torch.nn`), `optimizer` -> SGD with `lr = training_args[:learning_rate]
|
|
121
|
+
|| 0.01`, `criterion` -> `MSELoss`, device/dtype resolution (String/Symbol
|
|
122
|
+
-> torch object; nil device -> `scout_ai.util.device()`), `tensor(obj,
|
|
123
|
+
device, dtype)`.
|
|
124
|
+
- `Tensor` module: `to_ruby` (numpy2ruby), `to_ruby!` (to_ruby + `del`),
|
|
125
|
+
`del` (to cpu, detach, `grad = nil`, `untyped_storage.resize_ 0`, rescue ->
|
|
126
|
+
`Log.exception`), `length` (`PyCall.len`).
|
|
127
|
+
- `torch/load_and_save.rb`: `save_state` = `torch.save(state.state_dict(),
|
|
128
|
+
state_file)`; `save_architecture` = `torch.save(state, state_file +
|
|
129
|
+
'.architecture')`; `load_state` = `state.load_state_dict(torch.load(...))`;
|
|
130
|
+
`load_architecture` = `torch.load(..., weights_only: false)`;
|
|
131
|
+
`TorchModel.save(state_file, state)` saves both; `TorchModel.load` loads
|
|
132
|
+
architecture then weights; instance `reset_state` clears `@trainer`/`@state`
|
|
133
|
+
and removes both files.
|
|
134
|
+
- `torch/introspection.rb`: `get_layer`, `get_weights`,
|
|
135
|
+
`freeze_layer(state, layer, requires_grad = false)` plus instance
|
|
136
|
+
delegators.
|
|
137
|
+
- `torch/dataloader.rb`: `TorchModel.feature_tsv(elements, labels = nil,
|
|
138
|
+
class_labels = nil)` builds a TSV (`key_field ID`, field `features`, `:flat`
|
|
139
|
+
or `:list`, plus a `label` field when labels are given; labels mapped
|
|
140
|
+
through the `class_labels` index when provided) and
|
|
141
|
+
`TorchModel.text_dataset(file, elements, labels, class_labels)` writes it -
|
|
142
|
+
pure Ruby+TSV, no torch needed.
|
|
143
|
+
|
|
144
|
+
### HuggingfaceModel and specializations
|
|
145
|
+
|
|
146
|
+
- `fix_options`: folds `training_args|training_kwargs` ->
|
|
147
|
+
`training_options`, pulls `training_*` keys, same for tokenizer, then
|
|
148
|
+
re-exposes `options[:training_args]`/`options[:tokenizer_args]`.
|
|
149
|
+
Normalization matrix: `{training: {num_train_epochs: 3}}` ->
|
|
150
|
+
`training_args = {training: {num_train_epochs: 3}}` (the nested hash is
|
|
151
|
+
**not** flattened); `{training_num_train_epochs: 3}` ->
|
|
152
|
+
`training_args = {num_train_epochs: 3}`; the same pair of shapes for
|
|
153
|
+
tokenizer args; everything else (`trust_remote_code`, `torch_dtype`)
|
|
154
|
+
stays top-level.
|
|
155
|
+
- Constructor `(task = nil, checkpoint = nil, dir = nil, options = {})` ->
|
|
156
|
+
`super(dir, nil, nil, options)`, `fix_options`, then
|
|
157
|
+
`options[:checkpoint] = checkpoint; options[:task] = task`. Ordering: the
|
|
158
|
+
super already ran `restore`, so the file wins when a directory is present.
|
|
159
|
+
- `init` block: `TorchModel.init_python`; the checkpoint is `state_file`
|
|
160
|
+
**when it is an existing directory**, else `options[:checkpoint]` (so
|
|
161
|
+
re-init from a saved dir silently ignores the checkpoint); the model is
|
|
162
|
+
loaded via `ScoutPython.call_method("scout_ai.huggingface.model",
|
|
163
|
+
:load_model, task, checkpoint, **options.except(:training_args,
|
|
164
|
+
:tokenizer_args, :task, :checkpoint, :class_labels, :model_options,
|
|
165
|
+
:return_logits, :chat_template, :chat_template_kwargs,
|
|
166
|
+
:generation_kwargs))`; the tokenizer checkpoint is
|
|
167
|
+
`tokenizer_args[:checkpoint] || checkpoint` and the tokenizer is loaded
|
|
168
|
+
with all `tokenizer_args` as kwargs. `@state` is a **pair**
|
|
169
|
+
`[model, tokenizer]`.
|
|
170
|
+
- `load_state` / `save_state`: `model.from_pretrained(state_file)` /
|
|
171
|
+
`model.save_pretrained(state_file)` (+ tokenizer) - `directory.state` is a
|
|
172
|
+
**directory** for HF models, unlike TorchModel's two files.
|
|
173
|
+
- Python `scout_ai/huggingface/model.py`: `load_model(task, checkpoint,
|
|
174
|
+
**kwargs)` -> `AutoModel` when task is nil or `embedding`, `module:Class`
|
|
175
|
+
when the task contains `:`, else `transformers.AutoModelFor{task}`;
|
|
176
|
+
`load_tokenizer` -> `AutoTokenizer`; `load_model_and_tokenizer`.
|
|
177
|
+
|
|
178
|
+
`SequenceClassificationModel`: `eval` calls `eval_model(model, tokenizer,
|
|
179
|
+
texts, options[:locate_tokens])`; a single input returns `res[0]`;
|
|
180
|
+
`post_process` is an argmax over logits mapped through
|
|
181
|
+
`options[:class_labels]`. `train` writes `dataset.tsv` (+ `checkpoints/`)
|
|
182
|
+
under `directory` (or a `TmpFile.tmp_file` dir removed afterwards), builds
|
|
183
|
+
`training_args(checkpoint_dir, options[:training_args])`, materializes the
|
|
184
|
+
dataset with `HuggingfaceModel.text_dataset`, then `train_model(model,
|
|
185
|
+
tokenizer, training_args_obj, dataset_file, options[:class_weights])`.
|
|
186
|
+
Python-side `training_args` wraps `transformers.TrainingArguments`;
|
|
187
|
+
`train_model` tokenizes (json/tsv/in-memory) and, with `class_weights`,
|
|
188
|
+
subclasses `Trainer` with a weighted `CrossEntropyLoss` in `compute_loss`.
|
|
189
|
+
|
|
190
|
+
`CausalModel`: `eval(messages, list)` calls `eval_causal_lm_chat(model,
|
|
191
|
+
tokenizer, messages, chat_template, chat_template_kwargs,
|
|
192
|
+
generation_kwargs, tool_argument)`; **`chat(messages, tools = nil,
|
|
193
|
+
runtime_options = {})`** merges runtime options (generation_kwargs /
|
|
194
|
+
tool_argument / response_parser) and calls the tool-aware
|
|
195
|
+
`eval_causal_lm_response`. `train(pairs, labels)` -> `train_rlhf(state_file,
|
|
196
|
+
tokenizer, pairs, labels, options[:rlhf_config])` then `load_state`. Python
|
|
197
|
+
`eval.py`: `eval_causal_lm_chat` renders `tokenizer.apply_chat_template` (or
|
|
198
|
+
joins message contents as a fallback), `model.generate`, decodes only the
|
|
199
|
+
newly generated ids (`skip_special_tokens=True`);
|
|
200
|
+
`eval_causal_lm_response` additionally runs `parse_causal_lm_response` ->
|
|
201
|
+
the `tokenizer.parse_response` hook, else `<tool_call>...</tool_call>` regex
|
|
202
|
+
blocks, else a plain content message.
|
|
203
|
+
|
|
204
|
+
`NextTokenModel`: its `train` block calls
|
|
205
|
+
`train_next_token(model:, tokenizer:, dataset:, output_dir:,
|
|
206
|
+
**options[:training_args])` with `output_dir` = `directory['output'].find`
|
|
207
|
+
when a directory exists. Python `train/next_token.py`: a self-contained
|
|
208
|
+
next-token loop - tokenize with `max_length` padding + labels = input_ids,
|
|
209
|
+
`DataCollatorForLanguageModeling(mlm=False)`, AdamW + linear scheduler,
|
|
210
|
+
fp16/bf16 autocast, eval loss/ppl, best/step/epoch checkpoints with
|
|
211
|
+
`save_total_limit`, optional `resume_from_checkpoint` loading
|
|
212
|
+
`pytorch_model.bin` via `load_state_dict`. LoRA is a placeholder (logs "not
|
|
213
|
+
yet implemented").
|
|
214
|
+
|
|
215
|
+
### Python SDK
|
|
216
|
+
|
|
217
|
+
Two independent stories in one package:
|
|
218
|
+
|
|
219
|
+
1. **Agent/chat SDK** - the pip-installable `scout-ai` wheel, no hard
|
|
220
|
+
dependencies (`ml`/`huggingface` extras bring numpy/pandas/torch and
|
|
221
|
+
datasets/transformers/trl): `Agent`, `Chat`, `Message`,
|
|
222
|
+
`ScoutRunner`/`CommandError`, `load_agent`. The runner shells out to the
|
|
223
|
+
`scout-ai` CLI (`SCOUT_AI_COMMAND` env override) - Ruby stays the source
|
|
224
|
+
of truth.
|
|
225
|
+
2. **ML helpers**, imported lazily and only when the extras are present:
|
|
226
|
+
`util` (`set_seed`, `deterministic`, `device`, `model_device` - torch
|
|
227
|
+
required) and `data` (`TSVDataset`, a torch Dataset over a pandas TSV
|
|
228
|
+
read through the scout-rig `scout.tsv`/`tsv_pandas` helper;
|
|
229
|
+
`tsv_dataset`, `tsv`, `tsv_loader`, `data_dir`), plus
|
|
230
|
+
`scout_ai/huggingface/data.py` (datasets-based `load_tsv`/`load_json`,
|
|
231
|
+
`tokenize_dataset` with `max_length=32` default, list datasets).
|
|
232
|
+
|
|
233
|
+
How Ruby finds the package: `TorchModel.init_python` / the PythonModel init
|
|
234
|
+
add `Scout.python.find(:lib)` to `ScoutPython.paths` - the repo's `python/`
|
|
235
|
+
directory plus scout-rig's, both appended to `sys.path`. The
|
|
236
|
+
`:scout_ai_lib` pathmap registered by `lib/scout-ai.rb` is how
|
|
237
|
+
`Scout.python.find(:lib)` locates `python/` next to `lib/`. This is why the
|
|
238
|
+
SDK works from a checkout without `pip install`.
|
|
239
|
+
|
|
240
|
+
Tests: the seven Python tests that need no ML dependencies pass
|
|
241
|
+
(`test_chat_agent.py`, `test_runner.py`, `test_huggingface_eval.py`).
|
|
242
|
+
|
|
243
|
+
## Sharp edges and known issues
|
|
244
|
+
|
|
245
|
+
- **Restore precedence inversion** (F6, open): `load_options` merges saved
|
|
246
|
+
`options.json` **over** constructor options, and
|
|
247
|
+
`HuggingfaceModel#initialize` assigns `checkpoint` after `super` already
|
|
248
|
+
restored - a reloaded model silently ignores a fresh `checkpoint`
|
|
249
|
+
argument. The `doc/Model.md` example only works because that option was
|
|
250
|
+
never persisted.
|
|
251
|
+
- **`save_method`'s String branch is dead/broken** (open):
|
|
252
|
+
`when String === train_method` references an undefined local (`value` is
|
|
253
|
+
the parameter); it would raise `NameError` if ever hit. Only the Proc
|
|
254
|
+
branch is reachable today.
|
|
255
|
+
- **Proc-source persistence is fragile** (open): a block body containing a
|
|
256
|
+
string with an unbalanced `}` produces an unloadable `eval.rb`
|
|
257
|
+
(SyntaxError on reload) - the greedy `.*` match eats to the last `{`
|
|
258
|
+
inside the string. A body whose first line ends with a hash literal
|
|
259
|
+
`{ a: 1 }` is rewritten to `Proc.new{ a: 1 }`, which parses as a block,
|
|
260
|
+
not a hash; do/end call sites round-trip because the regex finds the ` do`
|
|
261
|
+
first. Worth a sanitizer or a documented constraint.
|
|
262
|
+
- **`eval_model`'s `return_logits` parameter receives
|
|
263
|
+
`options[:locate_tokens]`** (open): the option named `return_logits`
|
|
264
|
+
(used by `doc/Model.md`'s example) lands in the loader's `except` list and
|
|
265
|
+
is never forwarded, so logits always come back; the actually-read name is
|
|
266
|
+
`locate_tokens`, which appears nowhere in the docs.
|
|
267
|
+
- **`rlhf.py` hardcodes `device = 'cuda'`** (open): CPU-only hosts cannot run
|
|
268
|
+
PPO; and it ends with `model.save`, which is not a standard
|
|
269
|
+
transformers/trl method (`save_pretrained` is).
|
|
270
|
+
- **`fix_options` nested-hash shape** (open): `{training: {...}}` yields
|
|
271
|
+
`training_args = {training: {...}}` rather than the inner hash - if
|
|
272
|
+
`training:` was meant to be equivalent to `training_args:`, HF
|
|
273
|
+
`TrainingArguments` receives a wrong kwarg.
|
|
274
|
+
- **`reset_state` doc drift**: `doc/Model.md` omits that it also clears
|
|
275
|
+
`@trainer`, which is never set anywhere in the subsystem (harmless, stale).
|
|
276
|
+
- **Fixed 2026-09-11, uncommitted:** F7 - the default TorchModel train block
|
|
277
|
+
assigned an SGD optimizer to `@criterion` (copy-paste), so default training
|
|
278
|
+
was broken without a manual `model.criterion`. One-line fix in
|
|
279
|
+
`lib/scout/model/python/torch.rb` with a gated regression test in
|
|
280
|
+
`test/scout/model/python/test_torch.rb` (2/0; needs both `PYTHON` and
|
|
281
|
+
`SCOUT_TEST_PYTHON` pointing at the torch env, or neither - with only the
|
|
282
|
+
latter, PyCall imports a python without torch).
|
|
283
|
+
|
|
284
|
+
## Open questions
|
|
285
|
+
|
|
286
|
+
- Is the ExTRI2 `return_logits: true` option functional at all (see above)?
|
|
287
|
+
Needs the ExTRI2 workflow to decide; no code in this repo reads
|
|
288
|
+
`locate_tokens` other than the classification eval call.
|
|
289
|
+
- Does anything outside the LLM huggingface backend use this subsystem
|
|
290
|
+
in-repo? `grep` says no; the ExTRI2 usage lives in a separate workflow
|
|
291
|
+
repository. Worth a cross-repo check before any refactor.
|
|
292
|
+
- HuggingFace weights behaviour was never probed (no
|
|
293
|
+
torch/transformers/datasets installed in the study environment; the repo's
|
|
294
|
+
own `test/support/availability.rb` refuses network downloads) - HF weights
|
|
295
|
+
claims are code-read only.
|
|
296
|
+
|
|
297
|
+
## Evidence
|
|
298
|
+
|
|
299
|
+
Provenance: derived from the 2026-09-10/11 Cortex subsystem studies, probed
|
|
300
|
+
against this checkout at HEAD `a992a33` plus the uncommitted 2026-09-11 fix
|
|
301
|
+
sweep. The TorchModel criterion fix (F7) in that sweep is in scope here and
|
|
302
|
+
is described as current behavior above.
|
|
303
|
+
|
|
304
|
+
- Code: `lib/scout/model/base.rb` (19 lines); `util/run.rb`;
|
|
305
|
+
`util/save.rb:2-26,29-36,46-67` (state_file, load_ruby_code, load_method,
|
|
306
|
+
save_method, save/restore); `python/base.rb` (25 lines);
|
|
307
|
+
`python/torch.rb:4-10,24-93` (current fixed form);
|
|
308
|
+
`python/torch/{helpers,dataloader,load_and_save,introspection}.rb`;
|
|
309
|
+
`python/huggingface.rb`; `python/huggingface/{causal,classification}.rb`;
|
|
310
|
+
`python/huggingface/causal/next_token.rb`;
|
|
311
|
+
`lib/scout/llm/backends/huggingface.rb:34-44`;
|
|
312
|
+
`python/scout_ai/{__init__,util,data}.py`;
|
|
313
|
+
`python/scout_ai/huggingface/{model,eval,data,rlhf}.py`;
|
|
314
|
+
`python/scout_ai/huggingface/train/{__init__,next_token}.py`;
|
|
315
|
+
`test/support/availability.rb`.
|
|
316
|
+
- Ruby test runs: `test/scout/model/test_base.rb` 2/0;
|
|
317
|
+
`test/scout/model/util/test_save.rb` 1/0;
|
|
318
|
+
`test/scout/model/python/test_base.rb` 1/0;
|
|
319
|
+
`test/scout/model/python/test_torch.rb` 2/0 after the fix (omitted without
|
|
320
|
+
the torch env); `test_huggingface.rb` 6/0; the HF model tests are omitted
|
|
321
|
+
by the availability gate (model not cached). Python: 7/7 OK.
|
|
322
|
+
- Probe receipts: Cortex probe artifact `probe/model_ml.rb` (Observation
|
|
323
|
+
`model_ml`, property job `Observation/probe/model_ml_017c...json`) covering
|
|
324
|
+
the hierarchy, the save file list, Proc-source round-trips, arity-2
|
|
325
|
+
dispatch, the `fix_options` matrix, checkpoint-restore semantics and
|
|
326
|
+
code-fact greps; plus throwaway probes under `tmp/probe_model_ml/`.
|