diff --git a/docs/system-specs/modules/learn-cron-dashboard.md b/docs/system-specs/modules/learn-cron-dashboard.md index 356564c5be76..e91d2445378f 100644 --- a/docs/system-specs/modules/learn-cron-dashboard.md +++ b/docs/system-specs/modules/learn-cron-dashboard.md @@ -1730,7 +1730,7 @@ command or script runners may access member memory. - **Per-run temp dir (script and command crons)**: `run_script_sandboxed` and `run_command_sandboxed` give every run its own `agent_scratch` directory (`/scratch/`) and set all three of `TMPDIR`/`TMP`/`TEMP` to it in the child env, so a cron does not inherit the gateway's temp dir -- `/tmp` under the shipped systemd unit, a tmpfs on many distributions, where a clone or venv is charged to RAM. The scratch root is masked for sandboxed children, so the run's own directory is passed to `wrap_argv` as `extra_private_dirs`. After the spawn, `record_owner` hands the marker to the child pid and the existing hourly sweep reclaims the directory once that process group is dead and the tree is idle; a `refused` (link) or `stale` (still names the gateway) outcome kills the child and fails the run, as it fails an agent spawn. A directory no child ever got is removed in the runner's `finally`, because its marker names the live gateway and the sweep would keep it. Allocation failure is fail-open: the run proceeds with the inherited temp dir. `KIROCREW_SCRATCH` and the kiro-cli log pin are NOT set -- they are agent-facing and a cron child is not an agent. This is per-run temp only; state a LATER run must find still has no sanctioned home. - **Script-mode run status**: the script body and the launcher share the child's stdout, so the launcher writes the run's status (`ok`/`skip`/`done`/`report`/`error`) as one line carrying a per-run random tag (`_new_envelope_tag`), on a fresh line, through the stdout it bound before the body ran. `run_script_sandboxed` reads the status only from that tagged line (`_envelope_line`). A line the body prints itself, a JSON summary shaped like `{"status": "done"}` included, is never read as the status, so a body that prints one and then ends the process (`sys.exit`, `os._exit`) is a failed run (`Bad output:`) and the job is kept, rather than a `Done` that removes a recurring job. A body that rebinds `sys.stdout` or leaves a partial line still reports its status. - **Script-mode MCP reads**: `McpToolClient` decodes the server's stdout as UTF-8 with replacement and reads it through `json_line.parse_json_object_line`, so a banner or log line on stdout, a scalar, or a line nested past the decoder's ceiling is skipped instead of failing the handshake or the call. Every line read, a skipped one included, counts toward `_rpc`'s 1000-line cap, so a server that writes only noise fails the call rather than holding it until the job timeout. -- **Script-mode MCP server lifetime**: `ctx.call_tool()` starts a server on the first call to it and keeps it for the run's later calls to the same server name, so a server that signs in to a service when it starts signs in once per run rather than once per call (a Slack server signing in once per call drew HTTP 429 on most calls of a once-a-minute cron). At most one server per name is kept. A call the server answers with a tool error (a JSON-RPC `error` reply or an `isError` result, raised as `McpToolError`) keeps the server; a call that fails any other way stops its server and the next call starts a fresh one; a kept server whose process has exited is replaced; a call made while another call to the same server is still running starts a server of its own, so a call the script has given up on never holds up a later one. A local server must answer each call, its `initialize` handshake included, by the `time.monotonic()` reading the launcher hands `ScriptContext` as `_mcp_answer_by`: the child's start plus the script's `timeout` less a reserve of a quarter of the timeout, at most 10 s (`cron_script._local_call_window`), so the server's stop and the script's own `except` fit before the run is killed. A call made after that reading is not sent, and a call still unanswered at it raises `TimeoutError`, which the script can catch; like any other failed call it stops its server, here with no SIGTERM grace (`McpToolClient._given_up`), and is audited as an `error` tool invocation naming the tool. The request's write and the answer's read run on a daemon thread, because neither a full pipe nor a blocking `readline` has a bound on every platform (`McpToolClient._local_answer_by`). A remote server keeps its own `_REMOTE_ANSWER_SECS` bound, and `kirocrew cron preview`, which has no timeout, sets no answer time (`test/test_cron_script_mcp_answer_time.py`). A server whose start-up sign-in failed and that reports the failure as a tool error is therefore kept as well, and this is accepted. Its own retry rules decide when it signs in again, and one that never retries keeps failing only until the run ends, since the next run starts fresh servers. Restarting it after each such error would sign in again at once, which is the repeated sign-in that keeping servers avoids. The launcher calls `ScriptContext.close()` in a `finally` once the script function returns, which stops every kept server; it never raises, and calls after it keep nothing. `McpToolClient.close` stops the whole server tree on every platform. On POSIX it calls `platform_compat.terminate_popen_tree_pinned`, which reads the server's descendants with their start ids before any signal, SIGTERMs the server and them, waits up to 5 s, and SIGKILLs the survivors whose start id still matches, so a server started by a launcher script without `exec` does not outlive the launcher; it signals only pids read from the server's own tree, never a process group (the server stays in the run's group, which the run's cancel and timeout stops signal), and a failed descendant read keeps the `terminate()`-then-`kill()` stop of the direct child alone (`test/test_platform_compat_terminate_popen_tree.py`). On Windows it stops the whole tree with `platform_compat.kill_popen_tree` (`taskkill /T /F` through `kill_process_tree`, then `kill()` on the child), so a server behind a `.cmd` wrapper does not outlive the wrapper's `cmd.exe`. A capture file it cannot delete is logged at WARNING, and a failed stop after a failed call never replaces that call's own error (`test/test_cron_script_mcp_close.py`). The stderr capture is read for an error message and deleted under one lock (`McpToolClient._capture_lock`): a call given up on reads it on its own thread once the stop closes the server's stdout, and Windows refuses to delete a file that is still open, so `close()` deletes it only after that read ends. A kept server therefore lives until the run ends rather than for one call. A run killed at its timeout never reaches that `finally`, but its kept servers still stop: each runs inside the script child's process group, which the timeout `SIGKILL`s on POSIX, and inside the child's process tree, which `taskkill /T` reaps on Windows (`_kill_proc_group`). Only a server that starts a session of its own (`setsid`) outlives the kill, and it lives until it reads end-of-file on its stdin. `kirocrew cron preview` runs its script on the same `KeptMcpServers` lifecycle, so a previewed call signs in as often as the production run does. Pinned by `test/test_cron_script.py` (`TestScriptContextKeepsServers`, including `test_a_tool_error_keeps_its_server_for_the_next_call`, and `test_the_launcher_closes_the_context_however_the_script_ends`). +- **Script-mode MCP server lifetime**: `ctx.call_tool()` starts a server on the first call to it and keeps it for the run's later calls to the same server name, so a server that signs in to a service when it starts signs in once per run rather than once per call (a Slack server signing in once per call drew HTTP 429 on most calls of a once-a-minute cron). At most one server per name is kept. A call the server answers with a tool error (a JSON-RPC `error` reply or an `isError` result, raised as `McpToolError`) keeps the server; a call that fails any other way stops its server and the next call starts a fresh one; a kept server whose process has exited is replaced; a call made while another call to the same server is still running starts a server of its own, so a call the script has given up on never holds up a later one. A local server must answer each call, its `initialize` handshake included, by the `time.monotonic()` reading the launcher hands `ScriptContext` as `_mcp_answer_by`: the child's start plus the script's `timeout` less a reserve of a quarter of the timeout, at most 10 s (`cron_script._local_call_window`), so the server's stop and the script's own `except` fit before the run is killed. A call made after that reading is not sent, and a call still unanswered at it raises `TimeoutError`, which the script can catch; like any other failed call it stops its server, here with no SIGTERM grace (`McpToolClient._given_up`), and is audited as an `error` tool invocation naming the tool. The request's write and the answer's read run on a daemon thread, because neither a full pipe nor a blocking `readline` has a bound on every platform (`McpToolClient._local_answer_by`). A remote server keeps its own `_REMOTE_ANSWER_SECS` bound, and `kirocrew cron preview`, which has no timeout, sets no answer time (`test/test_cron_script_mcp_answer_time.py`). A server whose start-up sign-in failed and that reports the failure as a tool error is therefore kept as well, and this is accepted. Its own retry rules decide when it signs in again, and one that never retries keeps failing only until the run ends, since the next run starts fresh servers. Restarting it after each such error would sign in again at once, which is the repeated sign-in that keeping servers avoids. The launcher calls `ScriptContext.close()` in a `finally` once the script function returns, which stops every kept server; it never raises, and calls after it keep nothing. `McpToolClient.close` stops the whole server tree on every platform. On POSIX it calls `platform_compat.terminate_popen_tree_pinned`, which reads the server's descendants with their start ids before any signal, SIGTERMs the server and them, waits up to 5 s, and SIGKILLs the survivors whose start id still matches, so a server started by a launcher script without `exec` does not outlive the launcher; it signals only pids read from the server's own tree, never a process group (the server stays in the run's group, which the run's cancel and timeout stops signal), and a failed descendant read keeps the `terminate()`-then-`kill()` stop of the direct child alone (`test/test_platform_compat_terminate_popen_tree.py`). On Windows it stops the whole tree with `platform_compat.kill_popen_tree` (`taskkill /T /F` through `kill_process_tree`, then `kill()` on the child), so a server behind a `.cmd` wrapper does not outlive the wrapper's `cmd.exe`. A capture file it cannot delete is logged at WARNING, and a failed stop after a failed call never replaces that call's own error (`test/test_cron_script_mcp_close.py`). The stderr capture is read for an error message and deleted under one lock (`McpToolClient._capture_lock`): a call given up on reads it on its own thread once the stop closes the server's stdout, and Windows refuses to delete a file that is still open, so `close()` deletes it only after that read ends. On Windows it also deletes it only once the server's process object is signalled: the tree kill's closing `kill()`, refused on a server `taskkill` is already stopping, records the exit code, and a `wait()` on that code would return before the server closes the handles it inherited, so `close()` drops the code before it waits (`test_windows_close_deletes_the_capture_only_once_the_stopped_server_lets_go_of_it`); a teardown that outlasts the grace wait still leaves the capture, since the fallback `kill()` records the code again. A kept server therefore lives until the run ends rather than for one call. A run killed at its timeout never reaches that `finally`, but its kept servers still stop: each runs inside the script child's process group, which the timeout `SIGKILL`s on POSIX, and inside the child's process tree, which `taskkill /T` reaps on Windows (`_kill_proc_group`). Only a server that starts a session of its own (`setsid`) outlives the kill, and it lives until it reads end-of-file on its stdin. `kirocrew cron preview` runs its script on the same `KeptMcpServers` lifecycle, so a previewed call signs in as often as the production run does. Pinned by `test/test_cron_script.py` (`TestScriptContextKeepsServers`, including `test_a_tool_error_keeps_its_server_for_the_next_call`, and `test_the_launcher_closes_the_context_however_the_script_ends`). - **Script-mode spawn memory mode**: a script's `spawn_run` and `spawn_sub_agents` calls post `/api/spawn`, and `spawn_continue` posts `/api/spawn//continue`, each with `parent_session = cron:`. Both routes resolve that key through `resolve_session_memory_mode` (`_spawn_request_memory_mode`) and answer 409 `memory_unavailable` for a key with no admitted memory mode. So the script arm of the cron callback admits `cron:` in `ctx_builder._session_memory_modes` with the capture's `memory_mode` for the run alone: set before `_cron_run_script` and removed in a `finally` once it returns. A persistent message job's arm admits the same key with no end and also writes it durably (`_acquire_with_model_fallback`); the script arm writes nothing to disk, and it leaves an entry the message arm already made alone (a job edited from a message into a script keeps that entry). It publishes the mode only, never an execution record: a script caller's store and member already come from the scheduler's record of the job (`member_request_scope` -> `_cron_execution_from_registry`), so the script's other calls route as before. Outside a run the routes resolve the key exactly as before: from a durable record if a message run wrote one, else refused. Pinned by `test/test_cron_script_spawn_memory_mode.py`. - **Script-mode MCP server resolution**: `ctx.call_tool()` and `kirocrew cron preview` start a server from its entry in Crew's own agent spec, `kirocrew.json` in the Kiro agents directory (or the first `*kirocrew*.json` there), which holds every server installed through the MCP page ([mcp](../../architecture/mcp.md)); the job's own agent is not consulted. `_resolve_mcp_server` (`cron_script_mcp.py`) applies the launch rules the session and gateway paths apply, and raises `RuntimeError` naming the server and the reason, instead of starting it, when the entry is muted in the spec or in any MCP config scope (`mcp_cleanup.mcp_server_muted_in_any_store`, so a `disabled` that is not a boolean counts as muted), is a `"type": "registry"` entry (`mcp_entry_is_registry_governed`), or declares no `command`. An entry that is not a non-empty object is not found. An entry with a non-empty string `url` is a remote server and is called, not started; its `command` is never read or run (the agent schema requires a placeholder command beside a url). This differs from the session path for a url + real command + no `type` entry, which a session runs as a local process (`mcp_cleanup.mcp_entry_is_remote`) while the cron path calls its url, as it refused the url before. `_refuse_uncallable_remote` refuses, by name and before any request, a url that is not `http://` or `https://` (the bridge cannot dial it; `kas_env_shim.resolve_bridge` refuses it too), a url entry whose `type` is `sse` (the older two-endpoint transport the bridge does not speak), one with a header whose value holds a `secret://` reference (`secret_uri.header_secret_refs`; the error names the header key only and the server is not contacted, the dashboard probe's precedent), and, only while `acp.kas_env_launch.refuses_plain_http_headers()` (the operator's `agent.kas_refuse_plain_http_mcp_headers` opt-in, off by default and on while the config cannot be read), a plain `http://` url to a host `kas_accepts_url` does not accept that carries headers (read through `agent_sdk.agent_specs.plain_http_headers_refused`, since application code does not import the ACP layer); with the opt-in off such a url is called, as KAS's bridge calls it. Nothing else is refused: there is no address vet (the session and KAS paths have none, and the script can open any connection itself), no `mcp_registry_mode` read, and no OAuth token. A url entry resolves to `_RemoteMcpServer(remote_bridge_url(url), headers)`: `agent_sdk.agent_specs.remote_bridge_url` is `acp.kas_env_launch.bridge_url`, the canonical loopback spelling with userinfo dropped, as KAS dials it, and `_remote_headers` fills `${VAR}` and `${env:VAR}` in each header value through the same `_expanded` helper and `_placeholder_source` view `env` uses (below), drops a non-object block, a non-string value, a name that is not a token and a value holding a line break or NUL, each with a log line naming the header and never its value. `McpToolClient` holds a `kas_http_bridge.Bridge` with in-memory streams for such an entry instead of a process, in the script's own process (no subprocess, no sandbox wrapper: there is no local server to confine; a scheduled run's request leaves from inside the script child's sandbox, a preview's from outside it). It sends `initialize` and `notifications/initialized` like the process branch, each request on a daemon thread of its own as `Bridge.serve` sends it, a notification inline. A call returns as soon as its own id is answered, never waiting for the event stream to end (the wait is bounded by `_REMOTE_ANSWER_SECS`, past the bridge's own read timeout). A failure the bridge reports as its own (the reason on its `err` stream, the id answered with code -32000), and a failed or error answer to `initialize`, raises `RuntimeError` naming the server and the bridge's reason (`answered HTTP 401 (check its headers)`), which carries no header value, so `KeptMcpServers` stops that client and the next call starts fresh; a JSON-RPC error the server sends itself stays `McpToolError` and keeps the client. A request that ends without answering its id (a server that answers a request 202, say) raises `RuntimeError` as soon as its thread has ended with nothing queued, rather than waiting out `_REMOTE_ANSWER_SECS`. `is_running()` is true until `close()`, which calls `Bridge.close()` (a best-effort session DELETE) and never raises. A server that needs OAuth answers 401 and the call raises that error. `${VAR}` and `${env:VAR}` in a local entry's `env` are resolved by `mcp_gateway.rewriter_env._expand_env_placeholders`, the expander the broker sidecar and the KAS launcher use (through `_expanded`), from `_placeholder_source()`: `_placeholder_source_env()` less `_CRON_ENV_DENY` and `_GRANTED_ENV_KEYS`. A granted run's launcher puts the job's vault values in the child's `os.environ`, and `_clean_cron_env` keeps them from the server because the grant covers the approved script body and never the server binaries it calls; dropping the granted names from the source view keeps an entry (kirocrew.json is agent-writable) from copying one into the server under a name of its choosing, such as `"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"`. The shared view itself drops only a narrow prefix list (`AWS_SECRET`, `AWS_SESSION`, `AWS_ACCESS`, `OAUTH`, `SSH_AUTH_SOCK`, `GNUPGHOME`, `GIT_ASKPASS`) and the agent-denied names, so any other gateway variable, a `GITHUB_TOKEN` in the gateway's own environment included, is dereferenced. A miss stays literal, as in kiro-cli; `args` are not expanded. `KeptMcpServers.call_tool` refuses a tool the user switched off with `McpToolError` before it takes or starts a server. The switched-off set is `disabledTools` on the server's spec entry unioned with the one in `~/.kiro/settings/mcp.json`, where the dashboard's tool-off action writes, read through `agent_sdk.agent_specs.switched_off_tools` (`acp.session_mcp.session_mcp_disabled_tools`) as a chat session reads it, once per server name for the run, with keys compared through `mcp_server_alias` (the tool-off action writes either the raw key the Kiro global holds or the alias discovery shows). `_tool_is_switched_off` matches an entry exactly and, when it holds `*` or `?`, as a glob (`fnmatch.fnmatchcase`, as kiro-cli's globset reads it); a glob holding `{`, `}` or `\` covers every tool of that server, so the call is refused rather than let through. Pinned by `test/test_cron_script_mcp_launch_rules.py`; the url branch by its `TestRemoteEntry` (against a fake streamable-HTTP server on 127.0.0.1: the call with filled-in headers and no process for url-only and url-with-command, the answer on a held-open stream, the 401 and the fresh client after it, the three refusals, and a granted or cron-denied variable reaching the server as written). - **Script-mode `notify()` credential**: `ctx.notify()` authenticates `/api/send-message` with an `X-Internal-Secret` the child reads from a 0600 temp file the parent writes at spawn (`_KIROCREW_SECRET_FILE`; the value is scrubbed from the child env by `_CRON_ENV_DENY`). The in-process cron scheduler runs inside the gateway, so `run_script_sandboxed` takes an `internal_secret_provider` callable that returns the gateway's LIVE in-memory secret — the same `app["local_secret"]` the auth middleware compares against — and writes THAT into the file. Deriving the value from `KIROCREW_INTERNAL_SECRET` or the per-port `run/gateway-.secret` file (`_resolve_internal_secret`, env-first then file) is the FALLBACK, correct only for a runner built outside a gateway process (`kirocrew cron preview`, tests) or a gateway started with no dashboard (`--no-dashboard` / API-only). A gateway that re-derived instead of using its own value would mint its child a credential from any stale env var (operator shell, distribution wrapper) or stale file, which the middleware rejects `403 Forbidden` — the failure mode this provider closes. The provided secret is written only to the temp file; it is never logged, placed in the child env or argv, or put in an error string. diff --git a/src/kiro_crew/cron_script_mcp.py b/src/kiro_crew/cron_script_mcp.py index 89a33b7cbfe4..363991e49633 100644 --- a/src/kiro_crew/cron_script_mcp.py +++ b/src/kiro_crew/cron_script_mcp.py @@ -539,6 +539,16 @@ def close(self) -> None: if platform_compat.IS_WINDOWS: # A server behind a ``.cmd`` wrapper is a grandchild terminate() misses. platform_compat.kill_popen_tree(self._proc) + # Its closing ``kill()`` is refused on a server taskkill is already + # stopping, and the refusal stores the exit code, so ``wait()`` would + # return while the server still holds the stderr capture it inherited, + # which Windows will not delete. Cleared, ``wait()`` waits on the process + # handle ``Popen`` keeps open, so a server that has exited returns at once. + # shortcut: a teardown longer than the grace wait still leaves the + # capture, as the fallback's ``kill()`` stores the code again, so its + # ``wait()`` returns at once; clearing the code there too needs a bound + # on that wait, worth adding if Windows runs show a leftover. + self._proc.returncode = None self._proc.wait(timeout=_STOP_GRACE_SECS) else: # A launcher script without ``exec`` runs the server as a grandchild; diff --git a/test/test_cron_script_mcp_close.py b/test/test_cron_script_mcp_close.py index 74e21e1b3b45..0f3232f0ef39 100644 --- a/test/test_cron_script_mcp_close.py +++ b/test/test_cron_script_mcp_close.py @@ -216,6 +216,115 @@ def given_up_call(): assert not capture.exists(), "close() tried to delete the capture during the tail read" +class _ServerTeardown: + """A server process as Windows reports it while ``taskkill /F`` stops it. + + ``TerminateProcess`` starts the stop and returns. From then on the kernel refuses + another ``TerminateProcess`` (ACCESS_DENIED, a process already in teardown) and + the exit code reads back, but the process object is signalled, and the handles the + server inherited (its stderr capture among them) are closed, only when the + teardown ends, which the test releases. + """ + + def __init__(self): + self.stopping = False + self.waited = threading.Event() + self.ended = threading.Event() + + def terminate_process(self): + if self.stopping: + raise PermissionError(13, "Access is denied") + self.stopping = True + + def exit_code(self): + return 1 if self.stopping else 259 # 259 is STILL_ACTIVE + + def wait(self, timeout): + self.waited.set() + return self.ended.wait(timeout) + + +class _WindowsPopen: + """``subprocess.Popen``'s Windows ``kill``, ``poll`` and ``wait`` (CPython 3.12, + ``Lib/subprocess.py``), with :class:`_ServerTeardown` standing in for ``_winapi``.""" + + args = ["server"] + pid = UNALLOCATABLE_PID + + def __init__(self, server): + self._server = server + self.returncode = None + + def kill(self): + if self.returncode is not None: + return + try: + self._server.terminate_process() + except PermissionError: + rc = self._server.exit_code() + if rc == 259: + raise + self.returncode = rc + + def poll(self): + if self.returncode is None and self._server.ended.is_set(): + self.returncode = self._server.exit_code() + return self.returncode + + def wait(self, timeout=None): + if self.returncode is None: + if not self._server.wait(timeout): + raise subprocess.TimeoutExpired(self.args, timeout) + self.returncode = self._server.exit_code() + return self.returncode + + +def test_windows_close_deletes_the_capture_only_once_the_stopped_server_lets_go_of_it( + tmp_path, monkeypatch, caplog +): + """``taskkill`` starts the server's teardown; the tree kill's ``Popen.kill()`` that + follows is refused and reads the exit code, so ``Popen`` counts the server as + finished while it still holds the stderr capture it inherited, and Windows refuses + to delete a file that is open.""" + server = _ServerTeardown() + monkeypatch.setattr( + cron_script, + "platform_compat", + SimpleNamespace(IS_WINDOWS=True, kill_popen_tree=platform_compat.kill_popen_tree), + ) + monkeypatch.setattr(platform_compat, "IS_POSIX", False) + monkeypatch.setattr( + platform_compat, "kill_process_tree", lambda pid: server.terminate_process() + ) + + class WindowsPath: + def __init__(self, name): + self._path = Path(name) + + def unlink(self, missing_ok=False): + if not server.ended.is_set(): + raise PermissionError(13, "the server still holds the file open", str(self._path)) + self._path.unlink(missing_ok=missing_ok) + + monkeypatch.setattr(cron_script, "Path", WindowsPath) + capture = tmp_path / "mcp-stderr-held.log" + capture.write_text("", encoding="utf-8") + client = _client(stderr_name=capture) + client._proc = _WindowsPopen(server) + + with caplog.at_level(logging.WARNING, logger=cron_script_mcp.logger.name): + closer = threading.Thread(target=client.close, daemon=True) + closer.start() + try: + wait_until(lambda: server.waited.is_set() or not closer.is_alive()) + finally: + server.ended.set() + closer.join(default_timeout()) + assert not closer.is_alive() + assert not capture.exists(), "close() deleted the capture before the server let go of it" + assert not [r for r in caplog.records if "stderr capture" in r.getMessage()] + + def test_a_failed_stop_never_replaces_the_calls_own_error(monkeypatch): class StuckClient: def __init__(self, server, session_key="", answer_by=None):