pikuri-core 0.0.7 → 0.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 (60) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +17 -30
  3. data/lib/pikuri/agent/chat_transport.rb +168 -107
  4. data/lib/pikuri/agent/configurator.rb +194 -173
  5. data/lib/pikuri/agent/control/cancellable.rb +100 -70
  6. data/lib/pikuri/agent/control/handoff.rb +75 -0
  7. data/lib/pikuri/agent/control/interloper.rb +107 -118
  8. data/lib/pikuri/agent/control.rb +13 -35
  9. data/lib/pikuri/agent/event.rb +144 -197
  10. data/lib/pikuri/agent/extension.rb +83 -95
  11. data/lib/pikuri/agent/history.rb +247 -0
  12. data/lib/pikuri/agent/listener/in_memory_event_list.rb +1 -1
  13. data/lib/pikuri/agent/listener/terminal.rb +169 -136
  14. data/lib/pikuri/agent/listener/token_log.rb +84 -157
  15. data/lib/pikuri/agent/listener.rb +24 -44
  16. data/lib/pikuri/agent/listener_list.rb +32 -47
  17. data/lib/pikuri/agent/request_instrumenter.rb +102 -0
  18. data/lib/pikuri/agent.rb +1095 -577
  19. data/lib/pikuri/attachment.rb +65 -0
  20. data/lib/pikuri/bundler_env.rb +68 -0
  21. data/lib/pikuri/extractor/passthrough.rb +24 -31
  22. data/lib/pikuri/extractor.rb +125 -155
  23. data/lib/pikuri/file_type.rb +64 -136
  24. data/lib/pikuri/finalizers.rb +32 -47
  25. data/lib/pikuri/paths.rb +104 -13
  26. data/lib/pikuri/sanitizer.rb +46 -67
  27. data/lib/pikuri/subprocess.rb +86 -118
  28. data/lib/pikuri/testing.rb +369 -0
  29. data/lib/pikuri/tool/calculator.rb +168 -74
  30. data/lib/pikuri/tool/execute_context.rb +42 -0
  31. data/lib/pikuri/tool/parameters.rb +31 -29
  32. data/lib/pikuri/tool/result.rb +164 -0
  33. data/lib/pikuri/tool/trifecta_legs.rb +248 -0
  34. data/lib/pikuri/tool.rb +416 -67
  35. data/lib/pikuri/trifecta/contribution.rb +43 -0
  36. data/lib/pikuri/trifecta/node.rb +47 -0
  37. data/lib/pikuri/trifecta/report.rb +228 -0
  38. data/lib/pikuri/trifecta.rb +126 -0
  39. data/lib/pikuri/version.rb +1 -1
  40. data/lib/pikuri-core.rb +70 -92
  41. data/prompts/agent-loop.txt +5 -0
  42. data/prompts/pikuri-chat.txt +3 -12
  43. metadata +26 -72
  44. data/lib/pikuri/agent/context_window_detector.rb +0 -222
  45. data/lib/pikuri/agent/control/step_limit.rb +0 -111
  46. data/lib/pikuri/agent/extension_context.rb +0 -147
  47. data/lib/pikuri/agent/listener/rate_limited.rb +0 -172
  48. data/lib/pikuri/agent/synthesizer.rb +0 -171
  49. data/lib/pikuri/extractor/html.rb +0 -303
  50. data/lib/pikuri/tool/fetch.rb +0 -172
  51. data/lib/pikuri/tool/scraper.rb +0 -186
  52. data/lib/pikuri/tool/search/brave.rb +0 -198
  53. data/lib/pikuri/tool/search/duckduckgo.rb +0 -207
  54. data/lib/pikuri/tool/search/engines.rb +0 -186
  55. data/lib/pikuri/tool/search/exa.rb +0 -229
  56. data/lib/pikuri/tool/search/rate_limiter.rb +0 -92
  57. data/lib/pikuri/tool/search/result.rb +0 -29
  58. data/lib/pikuri/tool/web_scrape.rb +0 -121
  59. data/lib/pikuri/tool/web_search.rb +0 -57
  60. data/lib/pikuri/url_cache.rb +0 -112
@@ -1,73 +1,54 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Pikuri
4
- # Renders attacker-controlled text safe to display, and reports *why*
5
- # it was unsafe.
4
+ # Renders attacker-controlled text safe to display, and reports *why* it was
5
+ # unsafe.
6
6
  #
7
- # Every string an LLM composes is untrusted: a bash command, a tool
8
- # observation echoed back to the user, a description it wrote for a
9
- # confirmation prompt. A model that is broken — or, far more likely,
10
- # being driven by a prompt injection — can embed bytes that a terminal
11
- # acts on rather than prints: a carriage return that overwrites the
12
- # line the user just read, an ESC that recolors or repositions, a
13
- # backspace that erases, a bidirectional override that reorders text so
14
- # it reads differently than it runs, a zero-width character that hides
15
- # in plain sight, or a Cyrillic +а+ masquerading as a Latin +a+. The
16
- # whole point of a confirmation prompt collapses if the bytes the user
17
- # approves are not the bytes that execute.
7
+ # Every string an LLM composes is untrusted (a bash command, a tool
8
+ # observation echoed to the user, a confirmation-prompt description). A model
9
+ # — usually one being prompt-injected — can embed bytes a terminal *acts on*
10
+ # rather than prints: a CR that overwrites the line just read, an ESC that
11
+ # recolors/repositions, a backspace that erases, a bidi override that reorders
12
+ # text so it reads differently than it runs, a zero-width char, or a Cyrillic
13
+ # +а+ posing as Latin +a+. A confirmation prompt is worthless if the bytes the
14
+ # user approves aren't the bytes that execute.
18
15
  #
19
- # {.sanitize} is the one chrome-independent primitive every renderer
20
- # (terminal, TUI, web) routes through. It does two things and returns
21
- # both as a {Result}:
16
+ # {.sanitize} is the one chrome-independent primitive every renderer routes
17
+ # through, returning a {Result}:
22
18
  #
23
- # 1. *Neutralize* — make the dangerous bytes visible without changing
24
- # structure. Control bytes become +\xNN+, bidi/zero-width codepoints
25
- # become +\u{NNNN}+, tab becomes +\t+. Newlines are preserved
26
- # (multi-line commands are normal). This is *faithful, not
27
- # beautifying*: it never collapses runs of whitespace or rewrites a
28
- # tab to a space, because the user must see exactly what they are
29
- # approving — a Makefile's leading tab stays visibly a tab. A web
30
- # chrome composes +html_escape(sanitize(s).text)+; the HTML layer is
31
- # the caller's, not ours.
32
- # 2. *Warn* — return a {Warning} per category detected, each a semantic
33
- # record (kind + offending tokens + a plain-English explanation).
34
- # Presentation is the chrome's: a terminal renders these bold yellow,
35
- # a web client a banner. The {Warning} carries no color or markup.
19
+ # 1. *Neutralize* — make dangerous bytes visible without changing structure:
20
+ # control bytes → +\xNN+, bidi/zero-width → +\u{NNNN}+, tab → +\t+;
21
+ # newlines preserved. *Faithful, not beautifying* — it never collapses
22
+ # whitespace, and a tab shows as +\t+, never as spaces, because the user
23
+ # must see exactly what they approve (a Makefile recipe whose leading tab
24
+ # is spaces breaks). A web chrome adds +html_escape+ on top; the HTML
25
+ # layer is the caller's.
26
+ # 2. *Warn* — one {Warning} per category detected (kind + offending tokens +
27
+ # plain-English explanation). Presentation is the chrome's.
36
28
  #
37
29
  # == Scope (deliberately closed)
38
30
  #
39
- # Detection covers the *invisibility / cursor-control / reordering*
40
- # attack classes completely, because each is a finite, enumerable set
41
- # of codepoints: C0 controls, C1 controls (a second ANSI introducer on
42
- # some emulators), DEL, the bidi overrides, and the zero-width
43
- # characters. On top of that, {.sanitize} flags *mixed-script tokens* —
44
- # a single word combining letters from Latin + Cyrillic + Greek, which
45
- # is the signature of a homoglyph spoof and has near-zero false
46
- # positives on real text (humans do not weld two alphabets inside one
47
- # word; +café+ is all-Latin, +Москва+ all-Cyrillic, only +Pаypal+ mixes).
31
+ # Detection is complete on the *invisibility / cursor-control / reordering*
32
+ # classes, each a finite codepoint set: C0/C1 controls, DEL, bidi overrides,
33
+ # zero-width chars. Plus *mixed-script tokens* — one word welding Latin +
34
+ # Cyrillic + Greek, the homoglyph-spoof signature, near-zero false positives
35
+ # (+café+ all-Latin, +Москва+ all-Cyrillic, only +Pаypal+ mixes).
48
36
  #
49
- # Two confusable classes are explicitly *out of scope*, because
50
- # detecting them needs Unicode confusables tables and produces heavy
51
- # false positives on legitimate multilingual text:
52
- #
53
- # * *Whole-script* homoglyphs — an entirely-Cyrillic string that merely
54
- # looks Latin (no mixing to detect).
55
- # * *Single-symbol* confusables — the Greek question mark +;+ (U+037E)
56
- # that looks like a semicolon, full-width forms, the division slash.
57
- #
58
- # "Solid" here means complete on the classes above, not exhaustive over
59
- # all of Unicode.
37
+ # Two confusable classes are *out of scope* — detecting them needs Unicode
38
+ # confusables tables and heavy false positives on legitimate multilingual
39
+ # text: *whole-script* homoglyphs (an all-Cyrillic string that looks Latin,
40
+ # no mixing to detect) and *single-symbol* confusables (the Greek +;+ U+037E,
41
+ # full-width forms). "Solid" means complete on the classes above, not
42
+ # exhaustive over Unicode.
60
43
  module Sanitizer
61
- # One reason a piece of text was flagged, ready for a chrome to
62
- # render however it surfaces warnings (bold yellow line, web banner).
44
+ # One reason a piece of text was flagged, for a chrome to render its own way.
63
45
  #
64
- # * +kind+ — a {Symbol} category: +:backspace+, +:control_bytes+,
65
- # +:bidi+, +:zero_width+, or +:mixed_script+.
66
- # * +offenders+ — the distinct offending tokens, in first-seen order:
67
- # the escaped forms (+"\\x1b"+, +"\\u{202e}"+) for byte categories,
68
- # the raw tokens (+"Pаypal"+) for +:mixed_script+.
69
- # * +explanation+ — a one-line, chrome-agnostic English summary of
70
- # what the bytes can do.
46
+ # * +kind+ — a {Symbol}: +:backspace+, +:control_bytes+, +:bidi+,
47
+ # +:zero_width+, or +:mixed_script+.
48
+ # * +offenders+ — the distinct offending tokens, first-seen order: escaped
49
+ # forms (+"\\x1b"+, +"\\u{202e}"+) for byte categories, raw tokens
50
+ # (+"Pаypal"+) for +:mixed_script+.
51
+ # * +explanation+ — a one-line chrome-agnostic summary.
71
52
  Warning = Data.define(:kind, :offenders, :explanation)
72
53
 
73
54
  # The output of {Sanitizer.sanitize}.
@@ -84,17 +65,15 @@ module Pikuri
84
65
  # zero-width no-break space.
85
66
  ZERO_WIDTH = [0x200b, 0x200c, 0x200d, 0xfeff].freeze
86
67
 
87
- # Codepoints {.sanitize} rewrites: C0 controls including tab (U+0009)
88
- # but *excluding* newline (U+000A, which passes through untouched),
89
- # C1 controls + DEL (U+007F–009F), the zero-width set, and the bidi
90
- # overrides. Newline is the one control character a faithful render
91
- # must keep, so the C0 range is split around it.
68
+ # Codepoints {.sanitize} rewrites: C0 controls including tab (U+0009) but
69
+ # *excluding* newline (U+000A, passes through), C1 + DEL (U+007F–009F), the
70
+ # zero-width set, and the bidi overrides. Newline is the one control a
71
+ # faithful render keeps, so the C0 range splits around it.
92
72
  SUSPECT = /[\u0000-\u0009\u000b-\u001f\u007f-\u009f\u200b-\u200d\u202a-\u202e\u2066-\u2069\ufeff]/
93
73
 
94
- # The three Latin-confusable scripts whose mixing inside one token
95
- # signals a homoglyph spoof. Punctuation, digits and spaces are the
96
- # +Common+ script and match none of these, so they never count toward
97
- # the "two distinct scripts" threshold.
74
+ # The three Latin-confusable scripts whose mixing inside one token signals a
75
+ # homoglyph spoof. Punctuation/digits/spaces are +Common+ and match none, so
76
+ # they never count toward the two-script threshold.
98
77
  CONFUSABLE_SCRIPTS = { 'Latin' => /\p{Latin}/, 'Cyrillic' => /\p{Cyrillic}/, 'Greek' => /\p{Greek}/ }.freeze
99
78
 
100
79
  # Neutralize +text+ for literal display and report what was flagged.
@@ -4,88 +4,75 @@ require 'open3'
4
4
  require 'set'
5
5
 
6
6
  module Pikuri
7
- # Chokepoint for *all* subprocess spawning in pikuri. Forces a new
8
- # process group for each invocation, tracks pgids so descendants of
9
- # the direct child (commands backgrounded with +&+) can be cleaned
10
- # up at process exit. Two front doors: {.spawn} (combined
11
- # stdout+stderr through a single pipe — the shell-command shape) and
12
- # {.run} (stdin fed from a String or streamed from an IO, stdout
13
- # redirected to a file, stderr captured — the filter shape).
7
+ # Chokepoint for *all* subprocess spawning in pikuri. Forces a new process
8
+ # group per invocation and tracks pgids so descendants (commands
9
+ # backgrounded with +&+) can be cleaned up at exit. Two front doors:
10
+ # {.spawn} (combined stdout+stderr through one pipe — the shell-command
11
+ # shape) and {.run} (stdin from a String/IO, stdout to a file, stderr
12
+ # captured — the filter shape).
14
13
  #
15
14
  # == Seam discipline
16
15
  #
17
- # All subprocess spawning in +lib/+ goes through {.spawn}. Direct
18
- # +Process.spawn+ / +Open3.*+ / +system+ / backticks anywhere in
19
- # +lib/+ are bugs. The convention is grep-enforceable:
20
- # +grep -rnE 'Process\.spawn|Open3\.|\bsystem\(' lib/+ should
21
- # only hit this file (plus the comment in
22
- # +pikuri-mcp/lib/pikuri/mcp/servers.rb+ explaining the MCP
23
- # exception).
16
+ # All subprocess spawning in +lib/+ goes through {.spawn}/{.run}; direct
17
+ # +Process.spawn+ / +Open3.*+ / +system+ / backticks are bugs.
18
+ # Grep-enforceable: +grep -rnE 'Process\.spawn|Open3\.|\bsystem\(' lib/+
19
+ # should hit only this file. The one exception lives downstream:
20
+ # pikuri-workshop's MCP client, which owns a long-lived stdio pipe.
24
21
  #
25
22
  # == Timeouts are the caller's job
26
23
  #
27
- # {.spawn} does not implement a timeout — Ruby's +Timeout.timeout+
28
- # cannot kill subprocesses cleanly. Callers that need a timeout
29
- # wrap their argv with coreutils' +timeout+ binary:
24
+ # {.spawn} implements no timeout — Ruby's +Timeout.timeout+ can't kill
25
+ # subprocesses cleanly. Callers wrap their argv with coreutils' +timeout+:
30
26
  #
31
27
  # Pikuri::Subprocess.spawn(
32
28
  # 'timeout', '--signal=TERM', '--kill-after=5s', '120s',
33
- # 'bash', '-c', command,
34
- # chdir: workspace.cwd.to_s
35
- # )
29
+ # 'bash', '-c', command, chdir: workspace.cwd.to_s)
36
30
  #
37
- # When +timeout+ and its FD-inheriting children die, the combined
38
- # output pipe closes and {#wait}'s +io.read+ returns. No Ruby-side
39
- # timeout machinery; the +timeout+ binary handles SIGTERM-then-
40
- # SIGKILL race-free.
31
+ # When +timeout+ and its FD-inheriting children die, the output pipe closes
32
+ # and {#wait}'s +io.read+ returns — +timeout+ handles the
33
+ # SIGTERM-then-SIGKILL race-free, no Ruby-side machinery.
41
34
  #
42
35
  # == Backgrounded subprocesses
43
36
  #
44
- # When a shell command backgrounds work with +&+, the resulting
45
- # process stays in our pgroup. {#wait} returns as soon as the
46
- # direct child exits, but {.active} keeps the pgid in the tracked
47
- # set as long as any process in the group is alive (probed with
48
- # +kill(0, -pgid)+). On pikuri exit, {.cleanup!} sends SIGTERM to
49
- # every tracked group. The model can opt out via +nohup cmd &+ or
50
- # +setsid cmd &+ — both detach from our group.
37
+ # A command that backgrounds work with +&+ leaves a process in our pgroup.
38
+ # {#wait} returns when the direct child exits, but {.active} keeps the pgid
39
+ # tracked while any group member is alive (+kill(0, -pgid)+); {.cleanup!}
40
+ # SIGTERMs every tracked group at exit. The model opts out with +nohup+ /
41
+ # +setsid+ (both detach from our group).
51
42
  #
52
- # == State is process-global
43
+ # == Daemon children
44
+ #
45
+ # A long-lived child — a relay, a sidecar — is a {.spawn} nobody {#wait}s on:
53
46
  #
54
- # One +@active+ Set for the whole process, swept once at exit via
55
- # {Pikuri::Finalizers} (see the registration at the bottom of this
56
- # file). A +Mutex+ guards register/prune/cleanup; v1 is
57
- # single-threaded, so this is more for the exit-sweep/register race
58
- # than for current callers.
47
+ # relay = Pikuri::Subprocess.spawn('socat', listen, connect, chdir: '/')
48
+ # Thread.new { relay.io.each_line { |l| LOGGER.warn(l) } } # drain, or it blocks on a full pipe
49
+ # relay.terminate # when its owner closes
59
50
  #
60
- # == Why +Pikuri::Subprocess+, not top-level
51
+ # The shape lives here rather than with its caller because the exit-sweep
52
+ # set is private to this class: a daemon spawned anywhere else escapes the
53
+ # sweep, and opening +register+ would be the wider seam.
61
54
  #
62
- # First class actually under the +Pikuri::+ namespace. Domain
63
- # classes (+Tool+, +Agent+, +URLCache+) are top-level as a legacy
64
- # convention — they predate the namespacing decision and an
65
- # eventual refactor moves them too. For now: library-level
66
- # infrastructure under +Pikuri::+; domain objects flat. See
67
- # +CLAUDE.md+ for the convention.
55
+ # == State is process-global
56
+ #
57
+ # One +@active+ Set for the process, swept once at exit via
58
+ # {Pikuri::Finalizers}. A +Mutex+ guards register/prune/cleanup.
68
59
  class Subprocess
69
60
  # Combined output + exit status, returned from {#wait}.
70
61
  Result = Data.define(:output, :status)
71
62
 
72
- # Spawn +argv+ in a new process group, redirecting stderr onto
73
- # stdout. Tracked for cleanup.
63
+ # Spawn +argv+ in a new process group with stderr on stdout. Tracked for
64
+ # cleanup.
74
65
  #
75
- # @param argv [Array<String>] command and arguments. Caller does
76
- # any shell wrapping (e.g. +'bash', '-c', cmd+) when shell
77
- # interpretation is wanted; +argv+ is passed to +exec+
78
- # directly, so no implicit shell expansion happens here.
66
+ # @param argv [Array<String>] command + arguments, passed to +exec+
67
+ # directly — no implicit shell (caller wraps in +'bash', '-c', cmd+ when
68
+ # shell interpretation is wanted).
79
69
  # @param chdir [String, Pathname] working directory
80
- # @param env [Hash{String=>String}] extra environment variables to
81
- # set in the child process. The child otherwise inherits the
82
- # parent's full environment; entries in +env+ override or add to
83
- # it. Default +{}+ (pure inheritance). Used by {Code::Bash} to
84
- # thread {Pikuri::Workspace::Filesystem#env} (host git identity,
85
- # etc.) into a bash subprocess whose sandbox would otherwise
86
- # strip the host's config files.
87
- # @return [Subprocess] handle — call {#wait} to block for the
88
- # direct child to exit and read the captured output
70
+ # @param env [Hash{String=>(String,nil)}] extra env vars for the child; it
71
+ # otherwise inherits the parent's full environment (default +{}+, pure
72
+ # inheritance). A +nil+ value *unsets* that variable, which is how
73
+ # {Pikuri::BundlerEnv} hands back the environment pikuri's own boot
74
+ # rewrote.
75
+ # @return [Subprocess] handle — call {#wait} to block and read output.
89
76
  def self.spawn(*argv, chdir:, env: {})
90
77
  stdin, io, wait_thr = Open3.popen2e(env, *argv, chdir: chdir.to_s, pgroup: true)
91
78
  stdin.close
@@ -93,43 +80,33 @@ module Pikuri
93
80
  new(io: io, wait_thr: wait_thr)
94
81
  end
95
82
 
96
- # Run +argv+ as a one-shot *filter*: feed it +stdin_data+, redirect
97
- # its stdout straight to +stdout+ (an open +File+), capture stderr
98
- # through a pipe, and block until it exits. Built for the
99
- # stdin→markdown document converters (pikuri-extractors), where
100
- # {.spawn}'s shape is wrong twice over: it closes the child's stdin
101
- # immediately, and it merges stderr onto stdout — fatal when stdout
102
- # *is* the payload and a converter's warnings would corrupt it.
103
- #
104
- # Redirecting stdout to a file (not a pipe) is also what makes the
105
- # I/O deadlock-free with one writer thread: the child never blocks
106
- # writing output, so it keeps draining stdin, while the parent
107
- # drains the (low-volume) stderr pipe. The returned
108
- # {Result#output} is the captured *stderr* — the diagnostics — not
109
- # the payload; the payload is in +stdout+, whose file offset is
110
- # shared with the child, so rewind before reading it back.
83
+ # Run +argv+ as a one-shot *filter*: feed it +stdin_data+, redirect stdout
84
+ # to +stdout+ (an open +File+), capture stderr through a pipe, block until
85
+ # it exits. Built for stdin→markdown converters (pikuri-workshop's
86
+ # pikuri-extractors runs them in a container),
87
+ # where {.spawn}'s shape is wrong twice: it closes stdin immediately and
88
+ # merges stderr onto stdout — fatal when stdout *is* the payload.
111
89
  #
112
- # Same discipline as {.spawn}: new process group, registered for
113
- # the exit sweep, no built-in timeout (wrap +argv+ with coreutils'
114
- # +timeout+ — see the class docs).
90
+ # Redirecting stdout to a file (not a pipe) is what makes the I/O
91
+ # deadlock-free with one writer thread: the child never blocks on output,
92
+ # so it keeps draining stdin while the parent drains the low-volume stderr
93
+ # pipe. {Result#output} is the captured *stderr*, not the payload — the
94
+ # payload is in +stdout+, whose file offset is shared with the child, so
95
+ # rewind before reading it back. Same discipline as {.spawn} (new group,
96
+ # exit-sweep tracked, no built-in timeout).
115
97
  #
116
- # @param argv [Array<String>] command and arguments, passed to
117
- # +exec+ directly — no implicit shell.
118
- # @param stdin_data [String, IO, StringIO] the child's stdin: a
119
- # String is written as-is, an IO is streamed through
120
- # +IO.copy_stream+ (so a large source file never materialises in
121
- # the Ruby heap) and read from its current position. Either way
122
- # stdin is closed (EOF) afterwards. May be empty.
123
- # @param stdout [File] open writable file the child's stdout is
124
- # redirected to.
98
+ # @param argv [Array<String>] command + arguments; no implicit shell.
99
+ # @param stdin_data [String, IO, StringIO] the child's stdin: a String is
100
+ # written as-is, an IO is streamed via +IO.copy_stream+ from its current
101
+ # position (so a large file never hits the Ruby heap). Closed (EOF)
102
+ # after. May be empty.
103
+ # @param stdout [File] open writable file stdout is redirected to.
125
104
  # @param chdir [String, Pathname] working directory.
126
- # @param env [Hash{String=>String}] extra environment variables,
127
- # as for {.spawn}.
128
- # @return [Result] +output+ is the captured stderr; +status+ the
129
- # child's exit status.
130
- # @raise [SystemCallError] whatever an IO +stdin_data+ raises
131
- # mid-stream (disk error, closed handle) — re-raised here after
132
- # the child has been reaped.
105
+ # @param env [Hash{String=>String}] extra env vars, as for {.spawn}.
106
+ # @return [Result] +output+ is the captured stderr; +status+ the exit
107
+ # status.
108
+ # @raise [SystemCallError] whatever an IO +stdin_data+ raises mid-stream,
109
+ # re-raised after the child is reaped.
133
110
  def self.run(*argv, stdin_data:, stdout:, chdir:, env: {})
134
111
  in_r, in_w = IO.pipe
135
112
  err_r, err_w = IO.pipe
@@ -169,9 +146,8 @@ module Pikuri
169
146
  # child was spawned with +pgroup: true+ (it's the group leader).
170
147
  attr_reader :pgid
171
148
 
172
- # @return [IO] read end of the combined stdout+stderr pipe.
173
- # Exposed for future live-streaming consumers; v1 callers go
174
- # straight to {#wait}, which drains it.
149
+ # @return [IO] read end of the combined stdout+stderr pipe. Callers
150
+ # normally go straight to {#wait}, which drains it.
175
151
  attr_reader :io
176
152
 
177
153
  # @api private — call {.spawn}, not the constructor.
@@ -182,10 +158,9 @@ module Pikuri
182
158
  @pgid = wait_thr.pid # pgroup:true → pgid == pid
183
159
  end
184
160
 
185
- # Block until the direct child exits, read whatever remains on
186
- # the combined-output pipe, return a {Result}. The pgid stays
187
- # tracked if the group still has live members (backgrounded
188
- # children); pruned if everything's gone.
161
+ # Block until the direct child exits, drain the combined-output pipe,
162
+ # return a {Result}. The pgid stays tracked if the group still has live
163
+ # members (backgrounded children); pruned if everything's gone.
189
164
  #
190
165
  # @return [Result]
191
166
  def wait
@@ -196,13 +171,10 @@ module Pikuri
196
171
  self.class.send(:prune, @pgid)
197
172
  end
198
173
 
199
- # SIGTERM the whole process group without blocking for output —
200
- # the stop button for a *daemon* child (one the caller never
201
- # {#wait}s on, e.g. {Pikuri::Memory::Mem0Server}'s socat relay).
202
- # Best-effort and idempotent: an already-dead group is a no-op.
203
- # The group stays in the exit-sweep set until it actually dies,
204
- # so a child that ignores SIGTERM is still re-signalled by
205
- # {.cleanup!} at process exit.
174
+ # SIGTERM the whole process group without blocking for output — the stop
175
+ # button for a daemon child (see the class doc). Best-effort and idempotent;
176
+ # the group stays in the exit-sweep set until it dies, so a child ignoring
177
+ # SIGTERM is re-signalled by {.cleanup!} at exit.
206
178
  #
207
179
  # @return [void]
208
180
  def terminate
@@ -214,9 +186,8 @@ module Pikuri
214
186
  end
215
187
 
216
188
  class << self
217
- # Currently-tracked process groups, with dead ones pruned as a
218
- # side effect. Useful for a future +/bg+ REPL command or a
219
- # between-turn status line.
189
+ # Currently-tracked process groups, with dead ones pruned as a side
190
+ # effect.
220
191
  #
221
192
  # @return [Array<Integer>]
222
193
  def active
@@ -227,8 +198,7 @@ module Pikuri
227
198
  end
228
199
 
229
200
  # SIGTERM every tracked process group. Run at process exit via
230
- # {Pikuri::Finalizers} (production) and from +after+ blocks
231
- # (specs). Best-effort — ignores errors from already-dead groups.
201
+ # {Pikuri::Finalizers}, and from specs' +after+ blocks. Best-effort.
232
202
  #
233
203
  # @return [void]
234
204
  def cleanup!
@@ -261,10 +231,8 @@ module Pikuri
261
231
  end
262
232
  end
263
233
 
264
- # Registered at load (boot) — before any agent or server registers at
265
- # construction time — so in {Pikuri::Finalizers}' LIFO sweep this runs
266
- # LAST: graceful +#close+ on agents and servers first, then SIGTERM
267
- # whatever child groups are still alive. The reaper, not a peer. (Was a
268
- # standalone +at_exit+; routed through Finalizers so the order relative
269
- # to every other teardown is controlled, not left to file load order.)
234
+ # Registered at load (boot) — before any agent/server registers at
235
+ # construction — so in {Pikuri::Finalizers}' LIFO sweep this runs LAST:
236
+ # graceful +#close+ on agents and servers first, then SIGTERM whatever child
237
+ # groups remain. The reaper, not a peer.
270
238
  Pikuri::Finalizers.register { Pikuri::Subprocess.cleanup! }