scout-rig 0.2.6 → 0.2.7

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 (51) hide show
  1. checksums.yaml +4 -4
  2. data/.vimproject +31 -13
  3. data/README.md +27 -4
  4. data/Rakefile +1 -0
  5. data/VERSION +1 -1
  6. data/doc/Improvements.md +396 -0
  7. data/doc/StartHere.md +95 -0
  8. data/doc/developer/Architecture.md +232 -0
  9. data/doc/developer/DataConversionInternals.md +407 -0
  10. data/doc/developer/DesignPrinciples.md +254 -0
  11. data/doc/developer/PythonTaskRunnerInternals.md +371 -0
  12. data/doc/developer/PythonWorkflowInternals.md +539 -0
  13. data/doc/developer/ScoutPythonInternals.md +504 -0
  14. data/doc/user/Cookbook.md +337 -0
  15. data/doc/user/DefiningPythonTasks.md +708 -0
  16. data/doc/user/DrivingWorkflowsFromPython.md +418 -0
  17. data/doc/user/IteratingPythonData.md +142 -0
  18. data/doc/user/PassingDataToPython.md +223 -0
  19. data/doc/user/PythonEnvironments.md +197 -0
  20. data/doc/user/RunningPythonFromRuby.md +267 -0
  21. data/doc/user/ScriptingPython.md +281 -0
  22. data/doc/user/TestingAndPackaging.md +487 -0
  23. data/lib/scout/python/script.rb +11 -2
  24. data/lib/scout/workflow/python/inputs.rb +33 -23
  25. data/lib/scout/workflow/python/task.rb +219 -22
  26. data/lib/scout/workflow/python.rb +236 -9
  27. data/lib/scout-rig/testing/availability.rb +608 -0
  28. data/python/README.md +51 -0
  29. data/python/scout/__init__.py +2 -0
  30. data/python/scout/runner.py +193 -29
  31. data/python/scout/task_errors.py +6 -0
  32. data/research/00_scope_and_themes.md +131 -0
  33. data/research/data-conversion-and-scripting-analysis.md +209 -0
  34. data/research/design-philosophy-analysis.md +246 -0
  35. data/research/python-helper-package-analysis.md +272 -0
  36. data/research/pythonworkflow-analysis.md +199 -0
  37. data/research/scoutpython-bridge-analysis.md +185 -0
  38. data/research/synthesis-report.md +109 -0
  39. data/research/testing-availability-baseline.md +1625 -0
  40. data/research/testing-availability-final-report.md +500 -0
  41. data/research/validation-report.md +149 -0
  42. data/scout-rig.gemspec +35 -5
  43. data/test/scout/python/test_util.rb +13 -0
  44. data/test/scout/test_python.rb +10 -0
  45. data/test/scout/workflow/python/test_task.rb +1119 -1
  46. data/test/scout-rig/testing/test_availability.rb +495 -0
  47. data/test/scout-rig/testing/test_test_support.rb +166 -0
  48. data/test/test_helper.rb +96 -19
  49. metadata +47 -4
  50. data/doc/Python.md +0 -482
  51. data/doc/PythonWorkflow.md +0 -163
@@ -0,0 +1,708 @@
1
+ # Defining Python Tasks
2
+
3
+ This document explains how to write Scout workflow tasks whose logic is
4
+ implemented in Python, using the `python_task` declaration and the
5
+ `scout.task` Python decorator.
6
+
7
+ ## Audience
8
+
9
+ This page is intended for:
10
+
11
+ - ✓ Workflow authors who want to write task logic in Python
12
+ - ✓ Agent developers building Python-backed workflows
13
+ - ✗ Framework contributors (see [PythonWorkflow Internals](../developer/PythonWorkflowInternals.md))
14
+
15
+ ## When to use this
16
+
17
+ Use Python tasks when:
18
+
19
+ - You have existing Python code that should become part of a Scout workflow.
20
+ - Your task logic depends on Python libraries (pandas, scikit-learn, etc.).
21
+ - You want to leverage Python's ecosystem while keeping Scout's dependency
22
+ management, persistence, and provenance.
23
+ - You're building a workflow that serves both Ruby and Python users.
24
+
25
+ ## Core concepts
26
+
27
+ A Python task is defined by two parts:
28
+
29
+ 1. **A Python file** that defines one or more functions and registers them
30
+ with `scout.task`.
31
+ 2. **A Ruby workflow** that calls `python_task` to import the function
32
+ definitions as Scout tasks.
33
+
34
+ The Python function's type hints and docstring fully determine the Scout
35
+ task's inputs and return type. You don't need to declare inputs manually
36
+ on the Ruby side.
37
+
38
+ ### The contract
39
+
40
+ ```
41
+ Python function signature (types, defaults) → Scout task inputs
42
+ Python return annotation → Scout task return type
43
+ Python docstring → Task description + input help
44
+ ```
45
+
46
+ ## Typical usage
47
+
48
+ ### Step 1: Write the Python task file
49
+
50
+ Create a Python file (e.g., `python/tasks/greet.py`):
51
+
52
+ ```python
53
+ import scout
54
+
55
+ def hello(name: str, excited: bool = False) -> str:
56
+ """
57
+ Greet a person.
58
+
59
+ Args:
60
+ name: The name of the person to greet.
61
+ excited: Whether to add an exclamation mark.
62
+
63
+ Returns:
64
+ A greeting message.
65
+ """
66
+ return f"Hello, {name}{'!' if excited else ''}"
67
+
68
+ scout.task(hello)
69
+ ```
70
+
71
+ ### Step 2: Define the Ruby workflow
72
+
73
+ ```ruby
74
+ require 'scout'
75
+
76
+ module GreetingWorkflow
77
+ extend Workflow
78
+ extend PythonWorkflow
79
+
80
+ self.name = 'Greeting'
81
+
82
+ python_task :hello
83
+ end
84
+ ```
85
+
86
+ That's it. The workflow now has a `hello` task with inputs `name` (string,
87
+ required) and `excited` (boolean, default false), returning a string.
88
+
89
+ ### Step 3: Run it
90
+
91
+ ```ruby
92
+ job = GreetingWorkflow.job(:hello, name: "World")
93
+ puts job.run # => "Hello, World"
94
+
95
+ job = GreetingWorkflow.job(:hello, name: "World", excited: true)
96
+ puts job.run # => "Hello, World!"
97
+ ```
98
+
99
+ Or from the command line:
100
+
101
+ ```bash
102
+ scout workflow task Greeting hello --name World
103
+ ```
104
+
105
+ ## Type mapping
106
+
107
+ The Python function's type annotations are mapped to Scout types
108
+ automatically:
109
+
110
+ ### Input types
111
+
112
+ | Python type hint | Scout input type |
113
+ |--------------------|------------------|
114
+ | `str` | `:string` |
115
+ | `int` | `:integer` |
116
+ | `float` | `:float` |
117
+ | `bool` | `:boolean` |
118
+ | `bytes` | `:binary` |
119
+ | `pathlib.Path` | `:file` |
120
+ | `list[str]` | `:array` |
121
+ | `list[int]` | `:array` |
122
+ | `list[float]` | `:array` |
123
+ | `list[pathlib.Path]` | `:file_array` |
124
+ | `Optional[str]` | `:string` (required unless it has a default) |
125
+ | unannotated parameter | `:string` (required) |
126
+
127
+ Unsupported annotations (dict, bare `list`, `int | str`, custom classes)
128
+ raise a clear error at task-registration time instead of silently mapping
129
+ to `:string`.
130
+
131
+ Notes, verified at HEAD:
132
+
133
+ - The mapping keys on the *Python type string* produced by
134
+ `describe_function`, so `list[...]` (typing or builtin generics) yields
135
+ `:array`/`:file_array`, while a bare `list` annotation raises at
136
+ registration time.
137
+ - A parameter is `required` iff it has no Python default (so
138
+ `Optional[str]` without a default is still required).
139
+ - Python defaults are propagated verbatim as Scout input defaults, whatever
140
+ their JSON type (e.g. `5`, `'hi'`, `True`).
141
+ - The Python parameter's `help` text (from the docstring) becomes the Scout
142
+ input description.
143
+ - **Postponed annotations** (`from __future__ import annotations`) are fully
144
+ supported and map identically to plain ones: `str→:string`,
145
+ `pathlib.Path→:file`, `list[Path]→:file_array`, `Path | None→:file`, and
146
+ `Annotated[Path, …]→:file`. `python_annotation` preserves the complete
147
+ annotation form: bare classes keep their short name (`str`, `Path`), while
148
+ anything parameterized renders in full — `Annotated[Path, 'extra']` is
149
+ recorded as `typing.Annotated[pathlib._local.Path, 'extra']`,
150
+ `Optional[Path]` as `typing.Optional[pathlib._local.Path]` and `Path | None`
151
+ as `pathlib._local.Path | None`. The value is diagnostic only; it never
152
+ affects the annotation→Scout-type mapping. Annotations are resolved eagerly
153
+ with
154
+ `inspect.signature(..., eval_str=True)`, so a postponed or quoted annotation
155
+ is evaluated against the module namespace at registration time. A name that
156
+ does not resolve fails **loudly** — never a silent `:string` mapping — and
157
+ the error explains that a quoted annotation stays a string unless the type
158
+ is importable or defined at registration time; a genuinely undefined name
159
+ raises `NameError` at import.
160
+
161
+ ### Return types
162
+
163
+ | Python return annotation | Scout return type |
164
+ |--------------------------|-------------------|
165
+ | `str` | `:string` |
166
+ | `int` | `:integer` |
167
+ | `float` | `:float` |
168
+ | `bool` | `:boolean` |
169
+ | `bytes` | `:binary` |
170
+ | `pathlib.Path` | `:string` |
171
+ | `list[str]` | `:array` |
172
+ | no return annotation | `:string` |
173
+
174
+ Unsupported return annotations raise the same registration-time error as
175
+ parameters. Note the asymmetry: a `pathlib.Path` **input** maps to
176
+ `:file`, but a `pathlib.Path` **return** maps to `:string` (there is no
177
+ `:file` return type in this mapping).
178
+
179
+ ## What a task returns
180
+
181
+ The Python function's return value is serialized by the runner and decoded
182
+ by Ruby. The *decoded* Ruby type depends on the actual runtime value, not on
183
+ the declared return annotation (the annotation only sets the Scout task
184
+ return type):
185
+
186
+ | Python return value | Ruby result (verified) |
187
+ |---------------------|------------------------|
188
+ | `str` | String (stripped) |
189
+ | `int` | Integer |
190
+ | `float` | Float |
191
+ | `bool` | `True`/`False` printed as text → String `"True"`/`"False"` |
192
+ | `None` | `""` (empty String) |
193
+ | `bytes` | String (raw bytes passed through) |
194
+ | `pathlib.Path` | String path |
195
+ | `list`/`tuple` of scalars | one item per line; with a `list[...]` return annotation the task is `:array` and Ruby splits the lines back into an Array of **Strings** (ints come back as `"1"`, `"2"`; a nested list comes back as the strings `"[1, 2]"`, `"[3]"`) |
196
+ | `dict` (or other object) | JSON object → Hash |
197
+
198
+ Note the JSON-first heuristic: anything whose stdout is valid JSON is
199
+ parsed as JSON regardless of the annotation.
200
+
201
+ ## Multi-function files
202
+
203
+ A single Python file can define multiple functions. All registered functions
204
+ become Scout tasks:
205
+
206
+ ```python
207
+ import scout
208
+
209
+ def add(a: int, b: int) -> int:
210
+ """Add two numbers."""
211
+ return a + b
212
+
213
+ def multiply(a: float, b: float) -> float:
214
+ """Multiply two numbers."""
215
+ return a * b
216
+
217
+ scout.task(add)
218
+ scout.task(multiply)
219
+ ```
220
+
221
+ ```ruby
222
+ module MathWF
223
+ extend Workflow
224
+ extend PythonWorkflow
225
+ self.name = 'Math'
226
+
227
+ python_task :math # Creates both :add and :multiply tasks
228
+ end
229
+ ```
230
+
231
+ The `python_task :math` call discovers all functions in `math.py` and creates
232
+ one Scout task per function.
233
+
234
+ The name you pass to `python_task` selects the *file*
235
+ (`python_task :math` → `math.py`), not the function. The registered
236
+ function names become the task names, so they may differ from the file
237
+ name — `python_task :math_ops` on the file above still yields `:add` and
238
+ `:multiply` tasks.
239
+
240
+ Consequently, calling `python_task` twice on the same file (or on a file
241
+ whose function name matches another file's) re-registers the task under the
242
+ same name; the last registration silently wins. The Python-side
243
+ `--scout-metadata` output keeps **both** entries (verified: two `@task`
244
+ functions with the same name both appear in the JSON array), so which one
245
+ wins is decided by whoever consumes the array last.
246
+
247
+ ### Result file extension
248
+
249
+ Pass `extension:` to `python_task` to set the suffix on the Scout result path:
250
+
251
+ ```ruby
252
+ python_task :network, extension: 'sif'
253
+ ```
254
+
255
+ This sets a filename suffix only; it does not convert or validate the
256
+ Python function's return value or make the result conform to a file format.
257
+ For example, `json`, `tsv`, and `sif` can be used as suffixes, but `sif`
258
+ does not imply special SIF-format support. If `extension:` is omitted (or
259
+ `nil`), Scout's normal extension behavior for the task's result type applies.
260
+
261
+ The option belongs to the Python task-file registration and is a fallback for
262
+ all functions registered from that file. A function may override it by adding
263
+ one standalone `Extension:` field to its docstring:
264
+
265
+ ```python
266
+ def network() -> str:
267
+ """Create a network result.
268
+
269
+ Extension: json
270
+ """
271
+ ...
272
+ ```
273
+
274
+ The field may be indented with the surrounding docstring, and its value is
275
+ trimmed but must be one non-empty suffix token (no whitespace). Duplicate
276
+ `Extension:` fields are rejected. It is removed before description and
277
+ parameter-help extraction. A function-level value takes precedence over the
278
+ file-level `extension:` option; without it, the file option and then Scout's
279
+ normal result-type behavior apply. In a multi-function file each function's
280
+ field affects only that function.
281
+
282
+ This changes only the result path suffix; it does not change serialization,
283
+ conversion, or format validation.
284
+
285
+ ## Docstring format
286
+
287
+ Use Google-style docstrings for the best metadata extraction and CLI help:
288
+
289
+ ```python
290
+ def search(query: str, max_results: int = 10) -> list[str]:
291
+ """
292
+ Search for items.
293
+
294
+ Args:
295
+ query: Natural language search query.
296
+ max_results: Maximum number of results to return.
297
+
298
+ Returns:
299
+ A list of matching items.
300
+ """
301
+ ...
302
+ ```
303
+
304
+ The metadata extractor reads:
305
+ - **Description:** Everything before `Args:`/`Returns:`.
306
+ - **Parameter help:** The text after each parameter name in the `Args:` section.
307
+
308
+ `Args:` and `Arguments:` are both accepted; `Params:` is **not**
309
+ recognized. A docstring is not required at all: with no docstring the
310
+ description is `""` and every parameter's help is `""`. Two spellings of a
311
+ parameter entry work in `Args:` — `name: text` (Google style) and
312
+ `name : type\ntext` (numpydoc style, one blank line between entries).
313
+ Documenting a name that is not in the signature is silently dropped, and
314
+ not documenting a parameter simply leaves its help empty. The full rules
315
+ live in [Python Task Runner Internals](../developer/PythonTaskRunnerInternals.md).
316
+
317
+ Two corrections to that picture (both verified against
318
+ `describe_function` at HEAD):
319
+
320
+ - **Return descriptions are not captured.** Only the *return type* is
321
+ derived from the annotation; `Returns:` text is dropped. It is useful to
322
+ humans, but it never reaches the task metadata.
323
+ - **`name (type): text` and bare `name: text` behave the same**: the
324
+ parenthesized type in a Google-style entry is parsed and discarded — the
325
+ signature decides the type.
326
+
327
+ ## Metadata execution at definition time
328
+
329
+ Every `python_task` call — and every `load_directory` — **re-runs the Python
330
+ file as a subprocess** to obtain the metadata (`python file.py
331
+ --scout-metadata`), even for an unchanged file. There is no cache and no
332
+ keying on content or mtime. Measured on this checkout, a single
333
+ `python_task` registration costs roughly 0.4–0.5 s and
334
+ `load_directory` over a three-file directory roughly 1.3 s, almost all of it
335
+ interpreter startup. Keep Python task files import-light (heavy imports run
336
+ once per registered task) and expect definition time to scale linearly with
337
+ the number of registered functions.
338
+
339
+ If the metadata subprocess fails, registration aborts:
340
+
341
+ | Failure | What you see (verified) |
342
+ |---------|-------------------------|
343
+ | Python syntax error in the file | `ProcessFailed` from `CMD.cmd` with the interpreter's `SyntaxError` and exit status 1 in the message |
344
+ | File runs fine but does not register any `scout.task` | `--scout-metadata` succeeds with exit status 0 and prints nothing, so Ruby raises `JSON::ParserError: unexpected token at ''` |
345
+ | File prints non-JSON to stdout at import time | `JSON::ParserError` whose message shows the offending output |
346
+ | File exits non-zero | `ProcessFailed` |
347
+
348
+ ## Running Python tasks standalone
349
+
350
+ Python task files are also valid CLI tools. You can run them directly:
351
+
352
+ ```bash
353
+ # Get metadata
354
+ python greet.py --scout-metadata
355
+
356
+ # Run a function
357
+ python greet.py --name World --excited
358
+
359
+ # For multi-function files, specify the function name
360
+ python math.py add --a 3 --b 4
361
+ ```
362
+
363
+ Caveats (verified):
364
+
365
+ - A single-function file ignores any positional function name:
366
+ `python greet.py hello --name X` still runs `hello`, and so does
367
+ `python greet.py bogus --name X`.
368
+ - A multi-function file **expects** the function name as the first
369
+ positional argument; without it the **last registered** function is
370
+ selected. That may still work (when it has defaults for everything) or
371
+ fail with exit status 2 (`error: the following arguments are required:
372
+ --a ...` for the missing arguments of *that* function).
373
+ - Asking a multi-function file for an unregistered function prints
374
+ `[scout.task] Unknown task 'x'` on stderr. Beware: the message is
375
+ emitted, then `SystemExit(2)` is raised inside the `atexit` callback, and
376
+ Python reports it as "Exception ignored in atexit callback", so **the
377
+ process still exits 0**; you must check stderr, not the exit code.
378
+ - The `--scout-output` flag exists on every generated CLI and is reserved.
379
+ Ruby never passes it. A parameter literally named `scout_output` gets a
380
+ flag of its own (`--scout_output`, single underscore — argparse derives
381
+ flags from the parameter name, while the reserved flag is
382
+ `--scout-output`), so the two do **not** collide at the flag level, but
383
+ they do share the argparse *destination* `scout_output`: passing
384
+ `--scout_output V` silently loses the value (the function receives
385
+ `None`) and instead creates a file `V` with the result. Parameters that
386
+ simply have a default but are not named `scout_output` are unaffected.
387
+
388
+ ## Auxiliary files from a running Scout task
389
+
390
+ When PythonWorkflow runs a task as a Scout job, the Python subprocess receives
391
+ `SCOUT_JOB_FILES_DIR`, set to that job's `.files` sidecar directory. Write
392
+ auxiliary outputs there so they are kept with the job and its provenance:
393
+
394
+ ```python
395
+ import os
396
+ from pathlib import Path
397
+
398
+ files_dir = Path(os.environ["SCOUT_JOB_FILES_DIR"])
399
+ report = files_dir / "report.txt"
400
+ report.write_text("Generated by this job\\n", encoding="utf-8")
401
+ ```
402
+
403
+ The variable is scoped to the task's Python child; Ruby's environment is not
404
+ modified. Metadata discovery (`--scout-metadata`) and direct
405
+ `ScoutPython.run_file` calls are not running in a Scout Step, so they do not
406
+ receive this variable. Those invocations explicitly remove an inherited
407
+ `SCOUT_JOB_FILES_DIR` rather than accidentally using a stale job's sidecar.
408
+ Standalone Python CLI execution also does not set it. Do not assume the
409
+ variable exists outside a PythonWorkflow task job.
410
+
411
+
412
+ ## Task file discovery
413
+
414
+
415
+ By default, `python_task` looks for `.py` files via the Scout Path subsystem:
416
+ `python_task_dir` defaults to `Scout.python.tasks.find`, which resolves the
417
+ first existing `python/tasks` directory in the usual Scout search order (the
418
+ workflow's own `python/tasks` first, then the user's `~/.scout/python/tasks`).
419
+ If none exists, the default falls back to the user path even when it does not
420
+ exist. You can override this:
421
+
422
+ ```ruby
423
+ module MyWF
424
+ extend Workflow
425
+ extend PythonWorkflow
426
+
427
+ # Use a custom directory
428
+ self.python_task_dir = Path.setup("python/task")
429
+
430
+ python_task :hello
431
+ end
432
+ ```
433
+
434
+ Or load all Python files from a directory at once:
435
+
436
+ ```ruby
437
+ PythonWorkflow.load_directory(Path.setup("python/task"), :MyWF)
438
+ ```
439
+
440
+ `load_directory` returns a new named workflow module registered as a constant (it does not extend
441
+ the receiver) and registers one task per `scout.task`-decorated function
442
+ across **every** `*.py` file in the directory. It takes a `Path` object, not
443
+ a plain `String`; a `String` raises
444
+ `NoMethodError: undefined method 'glob_names'`.
445
+
446
+ With one argument, `load_directory(dir)` uses the fixed constant name
447
+ `PythonWorkflow`; pass an explicit second argument
448
+ (`load_directory(dir, :MyPyWF)`) to name the module. Both forms **overwrite
449
+ an existing constant of that name** (with an "already initialized constant"
450
+ warning).
451
+
452
+ `python_task` also accepts an explicit `file:` option, which bypasses
453
+ `python_task_dir` entirely. If the file does not exist, registration fails
454
+ with `RuntimeError: Python task file not found: <file>`; the same message
455
+ appears when the name resolves through `python_task_dir` but no `.py` file
456
+ exists at the resolved path.
457
+
458
+ ### Loading a Python task directory
459
+
460
+ To configure a workflow with a directory of Python task files, extend the
461
+ Ruby workflow first and PythonWorkflow second, then assign the directory:
462
+
463
+ ```ruby
464
+ module TestWF
465
+ extend Workflow
466
+ end
467
+ TestWF.extend PythonWorkflow
468
+ TestWF.python_task_dir = Path.setup("python/tasks")
469
+ ```
470
+
471
+ The extension hook does not preload tasks. Assigning `python_task_dir` loads
472
+ the assigned directory using batch metadata discovery (one Python runner
473
+ invocation for the directory). The lower-level
474
+ `PythonWorkflow.load_directory(path, name, batch: false)` explicitly requests
475
+ per-file metadata discovery (one Python invocation per file); its default is
476
+ `batch: true`. `load_directory(path, name, literal_strings: true)` also
477
+ initializes `python_literal_strings` **before** any task is registered, so
478
+ string inputs get `noload` from the start — the plain
479
+ `python_literal_strings=` setter does not re-register already-loaded tasks. Use
480
+ per-file mode when process isolation is needed; batch and per-file loading are
481
+ not guaranteed to be semantically equivalent for Python files with
482
+ process-global state or shared imports.
483
+
484
+ Batch mode executes each task file as `__main__` to preserve registrations
485
+ inside `if __name__ == '__main__'` blocks. The runner reuses one interpreter
486
+ for the directory, so imported Python modules are cached across files. In
487
+ particular, registrations performed only as a side effect of a shared import
488
+ may not appear in later files' metadata. This behavior was reproduced by the
489
+ workflow tests; choose default per-file loading if such imports are significant.
490
+
491
+ ## Missing and optional inputs
492
+
493
+ A Python parameter without a default becomes a **required** Scout input.
494
+ What happens then depends on how it is missing:
495
+
496
+ | Situation | Behaviour (verified) |
497
+ |-----------|----------------------|
498
+ | Input omitted entirely, or passed as `nil` | Scout raises `ParameterException` (`Input 'x' is required but was not provided or is nil`; plural form lists all missing) before any Python process starts |
499
+ | Required input passed as `nil` through a path that bypasses the check (e.g. explicit `nil` accepted by `job`) | No `--x` flag is emitted; Python's argparse then fails with exit status 2 and its usage message, surfaced by Ruby as `ProcessFailed` |
500
+ | Optional input omitted | No flag is emitted; the Python default applies |
501
+
502
+ Omitted optional inputs are simply **not passed** to the CLI: the Python
503
+ side sees its own default (`None` if the default was `None`, the literal
504
+ default otherwise). The Scout input default records the Python default but
505
+ is not itself injected into the call.
506
+
507
+ ## Boolean inputs
508
+
509
+ How a boolean input is passed depends on its Python default:
510
+
511
+ | Python default | Ruby `true` | Ruby `false` / omitted |
512
+ |---------------|-------------|------------------------|
513
+ | none (required) | `--flag` | no flag → the Python-side argparse default (`False` for a required bool, which argparse registers with `action="store_true"`) |
514
+ | `False` | `--flag` | no flag → `False` |
515
+ | `True` | `--flag` | `--no-flag` → `False` |
516
+
517
+ Only the `default = True` case can express `false` explicitly (via
518
+ `--no-flag`). For a boolean without a default, passing `false` from Ruby
519
+ emits no flag at all, so `true` and `false` are indistinguishable on the
520
+ wire; the function always receives `False`.
521
+
522
+ ## List inputs
523
+
524
+ List inputs accept several value shapes on the Ruby side. The bridge
525
+ serializes an `Array` **literally** — one flag, elements as separate argv
526
+ words, no re-reading of files. Array elements are never reinterpreted:
527
+ the file name `'tmp/probes/listfile.txt'` in an `Array` is passed as path
528
+ text.
529
+
530
+ | Ruby value | Resulting argv |
531
+ |------------|----------------|
532
+ | `Array` | `--items a b c` (one flag, elements as separate argv words, taken literally) |
533
+ | `String` containing commas | `--items a b c` (split on commas, each part stripped) |
534
+ | Any other single value | `--items value` |
535
+
536
+ Caveats (verified):
537
+
538
+ - **Two layers.** The bridge itself never reads a file for a list value.
539
+ But the *Scout input layer* is a separate layer: a bare-filename
540
+ `String` may still be expanded into its lines by Scout's `:array` input
541
+ before the task block runs. That behaviour is Scout-native and out of
542
+ scope here — pass an `Array` when you need the literal path text.
543
+ - **Comma ambiguity.** A single-element array whose element contains a
544
+ comma, `['a,b']`, is passed faithfully as one argv word when it comes
545
+ from an `Array`; but the same text given as a `String`, `'a,b'`, is
546
+ **split into two elements** `a` and `b`. Pass arrays when elements may
547
+ contain commas.
548
+ - **Leading-dash elements.** An element beginning with `-` (e.g. `['a','-b']`)
549
+ is emitted as a bare argv word; argparse then interprets it as an option
550
+ and the run fails with exit status 2.
551
+ - Empty-string elements are preserved (`['a','','b']` → `--items a '' b`).
552
+ - **Empty-string scalars.** A scalar input whose value is the empty string
553
+ always emits `--word ''`, so `''` is distinguishable from a missing input
554
+ (only `nil` is skipped and produces no flag).
555
+
556
+ ## Literal strings
557
+
558
+ One workflow flag controls whether Scout expands filename-like values
559
+ before they reach Python.
560
+
561
+ ### `python_literal_strings`
562
+
563
+ Default `false`: for a `str`-annotated parameter, Scout loads a Ruby
564
+ `String` naming an existing file into that file's contents (the Scout
565
+ input-layer convention for `:string` inputs), so the Python function
566
+ receives the file contents.
567
+
568
+ With `workflow.python_literal_strings = true`, `str` parameters register
569
+ their Scout input with `noload`, so a Ruby `String` reaches Python
570
+ literally as the text (or path text) you passed — no file read happens.
571
+
572
+ The flag is read **at registration time**, when the input options are
573
+ built: set it *before* `load_directory` / any `python_task` registration.
574
+ Flipping it afterwards requires `refresh_python_tasks!` (or re-registering
575
+ the tasks) to rebuild the input options; `Workflow.job_cache` can also
576
+ memoize old steps, so clear it (`workflow.job_cache.clear`) when switching
577
+ modes inside one process. List inputs are not affected by this flag: an
578
+ `Array` list value is always serialized literally by the bridge (see
579
+ [List inputs](#list-inputs)).
580
+
581
+ ## Input contracts
582
+
583
+ `workflow.python_input_contracts` returns one string-keyed entry per
584
+ registered Python task — index it as `python_input_contracts['task']` — and
585
+ `python_input_contract('task', 'input')` inspects a single input (both
586
+ arguments are strings, not symbols). There is **one authoritative view per
587
+ task**, built from the stored registration metadata — not from a fresh
588
+ extraction of the live task's inputs.
589
+
590
+ Each input entry carries the Python annotation (`python_annotation`, the
591
+ complete annotation form as described above), the Scout type (`scout_type`),
592
+ the default, requiredness, and a `behavior` column describing what the Ruby
593
+ value becomes:
594
+
595
+ - `:file` / `:file_array` → `'filename'`
596
+ - `:string` → `'literal text'` when `python_literal_strings` was set at
597
+ registration time, otherwise `'text or loaded file contents'`
598
+ - `:array` → `'list of strings'`; `:file_array` → `'list of filenames'`
599
+
600
+ A `flags` field records active options such as `noload`.
601
+
602
+ **The contract comes from stored registration metadata, not live
603
+ extraction** — after editing a Python file, run `refresh_python_tasks!`
604
+ before the contract reflects the new source.
605
+
606
+ ## Refreshing registered Python tasks
607
+
608
+ `workflow.refresh_python_tasks!` re-reads the Python task directory and
609
+ reconciles the registered tasks with what the files currently export:
610
+
611
+ | Situation | Result |
612
+ |-----------|--------|
613
+ | New Python function | registered (`:added`) |
614
+ | Changed signature or metadata | re-registered (`:changed`) |
615
+ | Deleted Python function | its registration is removed (`:removed`) |
616
+ | Unchanged definition | left alone (`:unchanged`) — the task object and cached job results survive |
617
+ | Name collision, including with an existing native (Ruby-defined) task | raises a clear error, nothing changed |
618
+ | Body changed, metadata unchanged | still `:unchanged`: the registration is kept, execution uses the current source on a fresh run, cached results remain |
619
+
620
+ It returns a summary hash `{added:, changed:, removed:, unchanged:}` and is
621
+ idempotent (a second refresh with unchanged sources reports everything as
622
+ `unchanged`). A failed refresh mutates nothing: the complete desired
623
+ registry — shape, duplicates, names exported by two files, native
624
+ collisions — is validated **before** the first mutation, so a raise leaves
625
+ the registry and the tracking map exactly as they were. Only the tasks whose
626
+ metadata actually changed are re-registered; their unchanged siblings keep
627
+ the task objects and in-process cached results the previous registration
628
+ installed. Editing the `python_literal_strings` flag alone (without a source
629
+ change) also shows up as `:changed`, because the flag is fixed at
630
+ registration time. It is the right call after editing Python sources
631
+ in-process (e.g. from a ScoutCoder `reload_workflow`).
632
+
633
+ ## Common mistakes
634
+
635
+ ### Missing type hints
636
+
637
+ Type hints are required for proper type mapping. Without them, parameters
638
+ default to `:string`:
639
+
640
+ ```python
641
+ # Bad — no type hints, everything becomes :string
642
+ def add(a, b):
643
+ return a + b
644
+
645
+ # Good
646
+ def add(a: int, b: int) -> int:
647
+ return a + b
648
+ ```
649
+
650
+ ### Missing `scout.task` registration
651
+
652
+ The Python file must end with `scout.task(function)` calls. Without
653
+ registration, `--scout-metadata` won't produce output:
654
+
655
+ ```python
656
+ # Bad — function won't be discovered
657
+ def hello(name: str) -> str:
658
+ return f"Hello, {name}"
659
+
660
+ # Good
661
+ def hello(name: str) -> str:
662
+ return f"Hello, {name}"
663
+
664
+ scout.task(hello)
665
+ ```
666
+
667
+ ### Expecting the raw string back for JSON-looking returns
668
+
669
+ Return decoding tries `JSON.parse` on the whole stdout first. A function
670
+ that returns the plain string `"[1, 2]"` yields a Ruby `Array` `[1, 2]`,
671
+ not the string; `"1"` yields the Integer `1`. Use a `:string`-typed
672
+ wrapping or avoid JSON-shaped plain text if you need it verbatim.
673
+
674
+ ### Expecting JSON when the Python function prints to stdout
675
+
676
+ Any `print()` in the task body is concatenated with the serialized return
677
+ value, so the whole stdout is no longer valid JSON and decoding falls back
678
+ to the array/text heuristics (see the next section).
679
+
680
+ ### Forgetting `result` is returned via stdout
681
+
682
+ The Python function's return value is printed to stdout and decoded by Ruby
683
+ (see [PythonWorkflow Internals](../developer/PythonWorkflowInternals.md) for
684
+ the decoding order). Avoid printing debug output to stdout, as it will
685
+ interfere with result decoding — with a dict/list return the process output
686
+ stops being valid JSON and Ruby raises `JSON::ParserError`; with a string
687
+ return the stray text is silently glued onto the result:
688
+
689
+ ```python
690
+ # Bad — debug print corrupts the return value
691
+ def compute(x: int) -> int:
692
+ print("Processing...") # This goes to stdout!
693
+ return x * 2
694
+
695
+ # Good — use stderr for debug output
696
+ def compute(x: int) -> int:
697
+ import sys
698
+ print("Processing...", file=sys.stderr)
699
+ return x * 2
700
+ ```
701
+
702
+ ## See also
703
+
704
+ - [PythonWorkflow Internals](../developer/PythonWorkflowInternals.md) — How
705
+ metadata discovery and type mapping work internally.
706
+ - [Driving Workflows from Python](DrivingWorkflowsFromPython.md) — Using the
707
+ Python `scout` package.
708
+ - [Cookbook](Cookbook.md) — Recipes combining Python tasks with other features.