Skip to content

fix(cron): return a refused script call's status and gateway code - #13352

Merged
bolichen97 merged 1 commit into
kirodotdev:mainfrom
m-yousri:fix/cron-script-run-trigger-403
Oct 10, 2026
Merged

bolichen97 merged 1 commit into
kirodotdev:mainfrom
m-yousri:fix/cron-script-run-trigger-403

Conversation

@m-yousri

@m-yousri m-yousri commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: A script-mode cron job can trigger another cron job again, and when the gateway refuses one of its calls the script is told why.

A script cron that calls ctx._post("/api/crons/<id>/run", {}) gets back only
{"error": "HTTP 409: <raw gateway JSON>"} when the gateway refuses it. To
learn whether the refusal was an identity problem (member_identity_unavailable)
or a job that is already running, the script has to parse that text. Nothing
in the test suite checks that the token the launcher mints actually attests the
request ScriptContext builds, so a drift between the two would bring the
original 409 back with no failing test.

#16398 already sends the launcher's signed token as X-Session-Token on every
ScriptContext call, which is what lets the trigger through. This PR adds the
two pieces still missing on main. The requirement is the open suggestion in
#11862's closing comment:
surface the refusal body's code from ctx._post. The caller is a user's own
script cron that triggers another job, as in #11862; no in-tree caller needs it.

Why it matters

A refused trigger looked like an ordinary result dict, which is how a daily
digest stopped arriving for four days before anyone noticed. A script that can
read status_code and code can alert on a refused identity instead of
swallowing it. The end-to-end test is what keeps the token, the header and the
gateway's check in agreement.

Not a goal

What changed (motivation → approach → change)

A refused script call now says, in fields, what the gateway refused and why.

Where What
src/kiro_crew/cron_script.py — ScriptContext._exchange a refusal adds status_code and, when the body names one, the gateway's code beside the unchanged error
src/kiro_crew/cron_script.py — _refusal_code parses the body with json_line.parse_json_object_line and keeps code only when it is a short identifier ([a-z0-9_.-]{1,64})
docs/system-specs/modules/learn-cron-dashboard.md documents the two new keys under "Script-mode dashboard sessions"
test/test_cron_script_identity.py, test/test_cron_script_sessions.py the end-to-end attestation test and the refusal-shape tests

The gateway's refusal body is text this process did not write. So code is
echoed only when it looks like an identifier, and a body that does not parse,
including one nested past the JSON parser's limit, yields no code. A
transport failure has no status and keeps the plain {"error": str(exc)}.

The two _http_error_body helpers in mcp_shared.py and mcp_core.py do not
fit here. Each reads the HTTPError body itself, but _exchange needs that one
read for its unchanged error text too. mcp_shared's returns any string
code, with no identifier check. mcp_core's rewrites error into its own
shape, and error must stay exactly what main returns.

The end-to-end test runs the real launcher, which publishes the run's token,
and builds the request ScriptContext sends from the child's env. It then asks
the gateway's own member_memory_auth.session_key_is_attested about that
request: attested for the job's own key, not for a neighbour's, and unattested
when the token is left out. The identity test module also pins KIROCREW_HOME
to the test's tmp dir, so under --noconftest the launcher's writes stay out
of the real data home. In that mode it also stubs cron_script.sel, because
the root conftest.py fixture that gives the process-wide SEL writer a
session-scoped directory is not loaded, and the writer must not bind to a
per-test directory. The fixture patches through its own MonkeyPatch, so a
test that calls monkeypatch.undo() cannot lift these pins.

Backwards compatibility

Compatible: error is unchanged, so notify() and the session methods, which
check "error" in result and raise with result["error"], behave exactly as
before. status_code and code are additive keys on the refusal dict only.

Tests

  • test_cron_script_identity.py::TestLauncherPublishesAVerifiableToken — test_the_gateway_attests_the_request_scriptcontext_builds locks in that the launcher's token, the header ScriptContext sends and the gateway's check agree; test_the_same_request_without_the_token_is_unattested is the baseline the original 409 came from. TestBridgePinsIdentityOnTheServerSpawn::test_call_tool_passes_the_jobs_key_to_the_bridge also checks, under --noconftest, that the audited tool call leaves the SEL singleton unset.
  • test_cron_script_sessions.py::TestARefusalIsStructured — a JSON refusal yields status_code and code; a non-JSON body, an empty body and a too-deeply-nested body still yield the status; a non-identifier code (markup, spaces, over 64 chars, a number, null, a list) is dropped; a transport failure keeps the plain shape.

With the _exchange change reverted, every TestARefusalIsStructured test
except the transport-failure one fails. The two attestation tests pass on
main too: they pin behaviour #16398 shipped without a test.

Manual verification

N/A — unit coverage sufficient: the attestation test drives the real launcher,
signing primitives and gateway check rather than mocks of them, and the
refusal tests feed _exchange real HTTPError objects.

Screenshots / video

N/A — no UI change.

Related Issues

no linked issue: #11862 reported the original symptom and is closed; its
closing comment
left "surface the 403 body's code from ctx._post" as an open suggestion,
which status_code / code cover. #16398 landed the token header this PR
first carried.

Pattern harvest

Rule candidate: none
Pattern: a refusal dict that carries the gateway's status only inside its error text, so a caller has to parse prose to branch.

Checklist

  • At most two commits (one is the norm), with a Conventional Commits title (feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert: ...)
  • Existing tests pass and new tests added for new functionality
  • Self-review completed; code follows project style guidelines
  • Documentation updated (if applicable)
  • No secrets, credentials, or internal references in the diff

@m-yousri
m-yousri requested review from a team and smeyffret September 24, 2026 13:06
@github-actions github-actions Bot added fork Pull request from a fork (external contributor) readiness: action required A blocking check or review needs attention labels Sep 24, 2026
@m-yousri

Copy link
Copy Markdown
Contributor Author

Intent: Let a script-mode cron reach owner-surface gateway routes such as POST /api/crons/{id}/run as its own job, by having ScriptContext send the signed token its launcher already mints, and return a refused request to the script as a readable, structured refusal instead of a bare status line.
Not a goal: widening what a script cron may reach (job ownership and the owner-surface guard are unchanged), changing how the launcher mints or retracts the token or how the gateway attests it, or changing the pre-#11780 refusal chain that older insider builds hit.

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 24, 2026
@github-actions

github-actions Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Opus 5.5, fork) — 🟡 CONCERNS

Design-level review of 270d9e0416d5a4d3b4c8028b7cc624285c89a995 via the fork AI-review pipeline — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

Design-Verdict: CONCERNS

The new status_code/code contract exists only on private ctx._post, so scripts depend on an underscore method while public methods raising RuntimeError drop the code.

Watch

  • The supported contract sits on a private method. The spec now tells scripts to call "ctx._post itself, for example on POST /api/crons/{id}/run". That turns _post and its return shape into the documented way to trigger a job, but nothing marks it public. A later refactor of _post/_exchange would quietly break user crons that were following the spec.
    Clears when: the trigger path is a public method, e.g. ctx.run_job(job_id), returning or raising with status_code/code, and the spec documents that method instead of _post. Or a human accepts _post as public API and the spec says so.
  • The fix covers only one of two refusal paths. The goal says "when the gateway refuses one of its calls the script is told why". But open_session, send_to_session, set_session_mode and notify still raise RuntimeError(self._reason(result)) with text only. A script that hits session_control_disabled or not_creator still has to parse the message, which is the problem the PR names.
    Clears when: the raised error carries status_code/code as attributes (e.g. a RuntimeError subclass), or the description narrows the claim to direct _post callers.

[DESIGN-REVIEWED] 270d9e0

Description read

[DESCRIPTION-READ] 9af9c5578752505185108c3f64745ce2d2bb381216ef13ab90c2ca963dae3744

That sha256 names everything this verdict read: the PR description, plus the 1 evidence file(s) the workflow collected from it and handed this review. It covers that evidence because the media strip replaces every attachment URL with the same placeholder, so an edit swapping one attachment for another would leave the description's captured text identical while what this review judged changed. Recompute it with .github/scripts/pr-description-capture.sh over the same inputs; if it differs, the description or that evidence changed after this verdict was formed and any finding drawn from either is unproven.

@github-actions

github-actions Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

GPT 6.1 Review (fork) — ✅ no blocking findings

Reviewed 270d9e0416d5a4d3b4c8028b7cc624285c89a995 via the fork AI-review pipeline; updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] 270d9e0

@github-actions

github-actions Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Opus 5.5, fork) — 🟡 CONCERNS

Premise-level review of 270d9e0416d5a4d3b4c8028b7cc624285c89a995 via the fork AI-review pipeline — why this exists and whether the shipped surface is the smallest honest version. Updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

First-Principles-Verdict: CONCERNS

This is labelled a fix but adds new fields to a private method's return value, and no in-tree code reads them. Half of the Goal already shipped in #16398.

Not justified as shipped

  • Item 1 — inherited: the Goal says "A script-mode cron job can trigger another cron job again", but the description also says "The two attestation tests pass on main too". This diff restores nothing. It adds status_code/code to ScriptContext._post, a private method. User docs never mention it (ctx._post matched 0 .md files) and no in-tree code reads the new keys (0 consumers). The only support is a suggestion in a closing comment on Script-cron gateway callbacks are refused 403 member_session_unverified once any V2 member store exists: cron children never get an identity row #11862.
    Clears when: a maintainer confirms that ctx._post's refusal dict is meant to be script-facing.
  • Item 2 — oversized: _REFUSAL_CODE = re.compile(r"[a-z0-9_.-]{1,64}") filters code as "text this process did not write". The same body already comes back, redacted, in error, so the filter withholds nothing a caller can't already read.
    Subtraction: delete _REFUSAL_CODE and keep only isinstance(code, str), as mcp_shared._http_error_body already does.
    Clears when: the regex is removed, or a harm it prevents that error doesn't already expose is named.

What this change ships

Inventory (5 items) — 3 justified

Intent: a script cron that triggers another job can tell why the gateway refused it. This is an ADDITION framed as a FIX.

  1. A refused script call now also returns status_code — inherited
  2. A refused call also returns the gateway's code when it looks like an identifier — oversized
  3. A new end-to-end test checks that the launcher's token, the header ScriptContext sends and the gateway's attestation check agree — justified
  4. Under --noconftest, the identity tests pin KIROCREW_HOME and stub the SEL writer — justified
  5. The cron spec documents the two new keys — justified

[FIRST-PRINCIPLES-REVIEWED] 270d9e0

Description read

[DESCRIPTION-READ] 88da80fe1744f9af0c63a19941c4472b25a48686075cd9d3021aefd2fc4cbe6b

That sha256 names the PR description this verdict read. Recompute it with .github/scripts/pr-description-capture.sh; if it differs, the description changed after this verdict was formed and any finding drawn from the description is unproven.

@github-actions

github-actions Bot commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Opus 5.5 Review (fork) — ✅ no blocking findings

Reviewed 270d9e0416d5a4d3b4c8028b7cc624285c89a995 via the fork AI-review pipeline; updated in place on each push.

Review details

No findings.

[OPUS-REVIEWED] 270d9e0

@m-yousri

m-yousri commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author
  • Item 3 — session_token_sig and mcp_gateway.claim imported at module level

rebutted: the hoist is required by the fix, not behaviour-neutral churn. ScriptContext.__post_init__ and _post use STUB_SESSION_TOKEN_ENV and session_token_header, so lazy imports would mean five function-local imports of the same two modules across four functions.
No cycle: neither mcp_gateway.claim nor session_token_sig imports cron_script.
The PR body states this under What changed.

@m-yousri

m-yousri commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author
  • Item 2 — structured refusal from ScriptContext._post

rebutted: part of the stated Goal ("when the gateway refuses one of its calls the script is told why"), not a ride-along.
Named harm: a refused trigger came back as a bare HTTP Error 409: Conflict inside an ordinary result dict and hid a four-day silent failure.
The closing comment on #11862 left "surface the 403 body's code from ctx._post" open; this closes it.
Additive: the error key stays, so notify()'s "error" in result contract holds, and transport failures keep {"error": str(exc)}.

@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Oct 1, 2026
@m-yousri

m-yousri commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author
  • F1 span=31cfe0f000f2 — attested _post reaches api_cron_run with a foreign job id

rebutted, not a defect of this diff: the token grants the script child no authority it lacked on base.
The child already holds the internal secret (ScriptContext._secret, cron_script.py:1125/1131), and a POST carrying only X-Internal-Secret with no X-Session-Key resolves verified-global (dashboard/handlers/_shared.py:941) on /api/crons (server.py:905).
That keyless POST is what the shipped helper sends (cron_trigger.py:57-70, i.e. kirocrew cron trigger <id>), and api_cron_run (handlers/cron.py:1913) checks job ownership only for app callers, on base and here.
The triggered run executes under the target job's own identity, is cancellable and SEL-audited, so no identity moves.
This restores the pre-#12164 behaviour; changing which jobs a script cron may trigger is under Not a goal. Route-level ownership on api_cron_run binds every internal-secret caller and is its own change.
Override reason for a maintainer who verifies the above: the header adds no authority; the same foreign-job trigger is reachable on base through the keyless internal-secret POST cron_trigger.py already makes, and route-level ownership is a separate change.

@m-yousri

m-yousri commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author
  • Item 2 span=1d23aa530fed — _http_refusal is a third gateway-refusal decoder

needs-a-decision: the duplication is real and declared in the description; the one-decoder fix is a cross-module refactor larger than this PR, as the review itself notes.
The import-weight reason holds: cron_script runs in the script child and imports neither mcp_core nor mcp_shared; _http_refusal is used only by ScriptContext._post.
Subtraction path: hoist one decoder into a leaf module beside loopback_urlopen, have mcp_core, mcp_shared and cron_script import it, and delete all three copies.
Question for a maintainer: accept the third spelling as the recorded trade for this fix, or ask for a tracked follow-up issue for the hoist?

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Oct 1, 2026
@m-yousri
m-yousri force-pushed the fix/cron-script-run-trigger-403 branch from d279966 to 158187b Compare October 1, 2026 13:26
@m-yousri

m-yousri commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

Rebased: fecca3e -> 8ae5dff (picks up #15729, which touches sandbox.py on the script launcher path); the diff is byte-identical. Cron-script and sandbox tests (383) plus black/isort/flake8/mypy pass locally. CI re-running.

@github-actions github-actions Bot removed the readiness: action required A blocking check or review needs attention label Oct 1, 2026
@github-actions github-actions Bot added the readiness: checking Automated validation is still running label Oct 8, 2026
@github-actions

github-actions Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

UX Review (Opus 5.5, fork) — ⏭️ skipped

Revision 270d9e0416d5a4d3b4c8028b7cc624285c89a995 touches no user-facing surface (no changes under website/ or committed screenshots), so the UX review was skipped. Advisory — does not block merge.

@github-actions github-actions Bot removed the merge conflict Branch has merge conflicts with its base — author must resolve before merge label Oct 8, 2026
@KiroCrewCaptain KiroCrewCaptain changed the title fix(cron): attest a script child's HTTP identity with its launcher token fix(cron): return a refused script call's status and gateway code Oct 8, 2026
@KiroCrewCaptain
KiroCrewCaptain force-pushed the fix/cron-script-run-trigger-403 branch from 9cc1824 to 82f29c4 Compare October 8, 2026 07:38
@KiroCrewCaptain

Copy link
Copy Markdown
Collaborator

self-added: no

  • Item 3 span=59220587ff30 duplicate of _http_error_body in mcp_shared.py / mcp_core.py

rebutted: neither helper fits this caller, and the description now names why (What changed, last paragraph of the refusal part).
Both call exc.read() themselves, but _exchange needs that single read for its unchanged redacted error text as well; an HTTPError body cannot be read twice.
mcp_shared._http_error_body returns any string code with no identifier check, so markup or a 10 KB string would reach script output.
mcp_core._http_error_body replaces error with the body's own error field and rewrites internal_auth_mismatch, while Not a goal says error stays exactly what main returns.
What _refusal_code keeps is one call to the shared parse_json_object_line plus the identifier check.

[operator: KiroCrewCaptain for bolichen97]

@KiroCrewCaptain

Copy link
Copy Markdown
Collaborator

self-added: no

  • Item 5 span=f7bdef1fea6f title names an attestation change the diff does not make

fixed: the title is now fix(cron): return a refused script call's status and gateway code, the shipped structured refusal shape, matching the commit subject.
The attestation tests stay as regression pins only; the description already says they pass on main.

Also on 82f29c4: _no_ambient_identity patches through its own MonkeyPatch (SAST rule kirocrew.test-autouse-shared-monkeypatch), and the branch is rebased on current main. [operator: KiroCrewCaptain for bolichen97]

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running and removed readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention labels Oct 8, 2026
@KiroCrewCaptain
KiroCrewCaptain force-pushed the fix/cron-script-run-trigger-403 branch from 82f29c4 to d6b28b1 Compare October 8, 2026 08:11
@KiroCrewCaptain

Copy link
Copy Markdown
Collaborator

Rebased: main moved in test/test_agent_panel_crew_log.py (imports a file this PR touches) since this head went green (aee834c -> 8c7417e); CI re-running. The patch is unchanged (82f29c4 -> d6b28b1). The E2E red on the previous head was one frontend spec (session-tags-e2e 17b) that passed only on retry; this PR changes no frontend code.

@KiroCrewCaptain

Copy link
Copy Markdown
Collaborator

self-added: no

  • Item 1 span=6c887b1c52d0 zero consumers of status_code / code

rebutted, with the requirement now linked in Problem / Motivation: #11862's closing comment (issuecomment-5745246256) left "surface the 403 body's code from ctx._post" as the open follow-up, and this PR is that change.
The consumer is a user's own script cron calling ctx._post("/api/crons/<id>/run", {}), the #11862 case; such scripts live under the user's ~/.kiro/crew/crons/, not in this tree.
The six in-tree callers keep checking "error" in result on purpose: error is unchanged, so they need no edit.

[operator: KiroCrewCaptain for bolichen97]

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Oct 8, 2026
ScriptContext._exchange now adds status_code and, when the refusal body
names an identifier-shaped one, the gateway's code beside the unchanged
error text, so a script calling ctx._post itself (POST
/api/crons/{id}/run) can tell 409 member_identity_unavailable from a job
that is already running.

Adds the end-to-end regression test that runs the launcher's token
through the request ScriptContext builds and the gateway's real
session_key_is_attested: attested for the job's own key, not for a
neighbour's, and unattested without the token. The identity tests also
pin KIROCREW_HOME so the launcher's security-event write stays out of
the real data home under --noconftest.
@m-yousri
m-yousri force-pushed the fix/cron-script-run-trigger-403 branch from d6b28b1 to 270d9e0 Compare October 8, 2026 14:52
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: passed Eligible automated validation passed for the current revision and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Oct 8, 2026
@iamwhatever

Copy link
Copy Markdown
Contributor

This PR makes a refused ScriptContext call return status_code and the gateway's code next to the unchanged redacted error text. It also adds an end-to-end test that the launcher's token, the X-Session-Token header and the gateway's attestation check agree. The production diff (cron_script.py _exchange plus _refusal_code) is small and correct: re and parse_json_object_line are already imported, a non-JSON or non-object body yields no code, and transport failures keep {"error": ...}. Checks are green. I am holding because both whole-design lanes on the current head 270d9e04 say this needs a maintainer API decision, and I agree. The new contract lives only on the private ctx._post, and the spec now tells scripts to call _post. The public methods (open_session, send_to_session, set_session_mode, notify) still raise a text-only RuntimeError, so the stated goal ("the script is told why") is only half met. The goal's "can trigger another cron job again" was already delivered by #16398. A maintainer should decide whether _post's refusal dict is supported script-facing API, or ask for a public ctx.run_job and a RuntimeError subclass carrying status_code and code. First Principles' point that the _REFUSAL_CODE regex withholds nothing error doesn't already expose is minor. — crew-pr-reviewer

@bolichen97
bolichen97 merged commit d84eee5 into kirodotdev:main Oct 10, 2026
105 checks passed
@github-actions github-actions Bot removed the readiness: passed Eligible automated validation passed for the current revision label Oct 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fork Pull request from a fork (external contributor)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants