Skip to content

fix(cron): run the configured default agent for an agent-less cron - #5706

Merged
bolichen97 merged 2 commits into
kirodotdev:mainfrom
leozhad:fix/cron-default-agent-fallback
Sep 30, 2026
Merged

bolichen97 merged 2 commits into
kirodotdev:mainfrom
leozhad:fix/cron-default-agent-fallback

Conversation

@leozhad

@leozhad leozhad commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: An LLM cron job that names no agent runs the agent the operator configured as the default, instead of silently running without its toolset.

A cron LLM job with an empty agent_id runs the wrong agent. The empty selector reaches execution_for_store as template_id=... or "kirocrew", and "kirocrew" is AcpClient's own CLIENT_NAME floor — an agent config that carries none of the configured default agent's MCP servers. The job still runs, silently without the toolset the operator expects.

Why it matters

The failure is silent: no error, no conflict, no failing test. The job completes on an agent whose config carries none of the expected MCP servers, so the first signal an operator gets is a cron that produced the wrong work. Observed in production on 2026-08-19.

Every chat transport already honours the configured default — transport_dispatch resolves self.agent or cfg.agent.default_agent — so cron was the one dispatch path that ignored it. An operator who sets agent.default_agent and leaves a cron's agent blank has expressed the intent unambiguously in both places; only cron failed to act on it.

Not a goal

  • Removing the "kirocrew" floor. It is kept deliberately as the degradation path for an unset or non-str configured default, so a malformed config cannot abort a dispatch with missing execution template.
  • Changing how a declared agent_sequence picks agents. A dispatching sequence owns its own dispatch and is left untouched; only a dormant lone entry falls through to agent_id.
  • Persisting the resolved name. The default reaches the dispatched agent only; it is never written to the shared CronJob, the captured execution, or crons.json, so an agent-less cron keeps tracking agent.default_agent instead of being pinned to one agent.
  • Re-pointing a job that already names a real agent. The override is gated on the resolved agent still being the bare "kirocrew" floor. A schedule created from a template chat with no agent argument names its template ONLY in execution_context.template_id, agent_id staying empty, so an agent_id-only gate would read that job as agent-less and replace a deliberate selection on every fire — the same silent wrong-agent class this PR fixes, on the other arm.
  • Changing any job's captured execution identity. The default is resolved above the execution_context branch and applied below it, to the dispatched agent alone, so a job that carries an execution_context keeps the exact template_id it was created with. Both halves of that placement are load-bearing: above the branch because every record created since the execution-context migration carries execution_context, so resolving inside the else: arm would reach only pre-migration jobs and leave the reported symptom in place for everything created since; out of the capture because bind_session_execution publishes template_id under the stable cron:{job.id} key and refuses a candidate that differs from what a persistent_session job has already recorded.

What changed (motivation → approach → change)

Resolve config.agent.default_agent into a local above the execution_context branch in _cron_callback, then apply it below the branch to the dispatched cron_agent alone, and only where that resolved agent is still the bare "kirocrew" floor. Neither the shared CronJob nor the captured execution is written to.

This is the review's required change ("do not mutate the shared CronJob; resolve the agent into a local"), and it is also now the only placement that has any effect. _cron_callback snapshots its selectors before yielding — "captured selectors, never the scheduler's mutable job" — and after that capture job.agent_id has no remaining reader in the callback; every downstream consumer reads the resulting cron_agent. A write to job.agent_id placed below that capture reaches nothing: no error, no conflict, no failing test, just a cron quietly running on the floor agent.

Leaving the shared job untouched is also what keeps the resolved name out of the durable store. CronService hands the callback the live object from self._jobs (await self._on_job(job)) and _save() reserialises self._jobs wholesale, so mutating job.agent_id would pin an agent-less cron to a concrete agent name in crons.json on its first completed run, and the job would stop tracking agent.default_agent. Only the dispatched agent carries the default.

Two details worth flagging for review:

  • Gated on agent_sequence_dispatches(job.agent_sequence) rather than on a bare job.agent_sequence. A lone sequence entry is dormant and dispatch falls through to agent_id, which must still receive the default; that helper documents itself as the one spelling of the gate.

  • The configured value is accepted only when isinstance(..., str). ExecutionContext.__post_init__ requires a str template_id, so a malformed or unset default degrades to the existing "kirocrew" floor instead of aborting the dispatch with missing execution template.

  • Gated on the resolved cron_agent being the "kirocrew" floor rather than on job.agent_id alone. bind_cron_memory (cron_service/identity.py:143-152) captures the CREATOR session's execution and overwrites template_id only if job.agent_id, so a job created from a template chat names its template only in the captured execution_context.template_id; comparing the resolved agent is what lets such a job keep it while the reported floor case still picks the default up.

  • Also gated on the capture carrying no member_id. resolve_member_execution sets template_id to agent.kiro_agent or "kirocrew", so a cron created from a crew member's chat whose member agent names no kiro_agent captures the floor SPELLING with agent_id empty. A floor-only gate reads that as "selected nothing"; substituting there would have build_message inject the substituted template's system prompt and documents into that member's envelope while _resolve_cron_agent still dispatches the member's own kiro_agent, and would attribute the usage row to the substituted name. member_id alone does not narrow it far enough, which is the blocking GPT 5.6 finding on this gate: a member predating the identity migration persists no member_id at all, and with_template states the admitting rule -- such a record "is named by selection_kind == "member" and selection_name alone". The gate therefore also requires selection_kind != "member", the namespace ExecutionContext.__post_init__ constrains to exactly "member" or "template", so it answers "did this capture select a member?" for the persisted and unpersisted member alike. Both capture gates together are still not sufficient, which is the SECOND blocking GPT 5.6 finding on this gate (raised against d6ceb8c2b) and is fixed here: on the job.execution_context is None arm cron_execution is RECONSTRUCTED rather than loaded -- resolve_legacy_execution calls execution_for_store, which for a V1 store returns ExecutionContext(None, MemoryStoreRef(name), "template", template_id), hardcoding a null member_id and the "template" namespace whatever the schedule selected. A member cron predating the execution-context migration therefore passed BOTH capture gates while job.member_id still named the member, and resolve_cron_memory deliberately keeps that record dispatching instead of raising ("Older V1 schedules may still carry the historical member selector beside their explicit legacy store", cron_service/identity.py), with nothing backfilling execution_context on load -- so the arm stays live and the substitution ran the configured default template against that member's own silo. The gate now also requires not job.member_id: on that arm the job record is the only surviving evidence of the selection. A truthy non-str declines too, which is the safe direction -- declining leaves the pre-change floor behaviour.

  • Also gated on the SUBSTITUTED VALUE: a default whose agent spec declares toolsSettings.subagent.availableAgents is NOT substituted, and the job keeps the floor. This is the THIRD blocking GPT 5.6 finding on this gate (raised against 99fded90a) and is fixed here. The substitution reaches the dispatched agent= only, while bind_session_execution publishes the UNSUBSTITUTED capture, and both spawn entry points derive the parent's declaration from that record alone -- read_session_execution(parent) -> parent_spawn_allowlists(execution.template_id) in dashboard/handlers/messaging.py and the off-loop twin in subagent.py. The floor spelling resolves to (), which _vet_parent_available_agents admits as "no declaration to honour", so a restrictive declaration on the substituted template is never consulted and a child it forbids starts. I did not take the prescribed remedy, which was to publish the substituted template as a non-durable parent execution for spawn admission: that is a new cross-cutting mechanism in two files this PR does not touch, whose reviewers are scoped to spawn admission rather than cron, and PR Scope/First Principles are already flagging ride-alongs here. Narrowing the substitution removes the finding's precondition instead, and a declined job keeps exactly the floor it has on main today, so nothing regresses. Honouring the declaration is worth its own CR. Deny by default: a non-empty tuple declines and so does the reader's None, and only () permits the substitution. The first revision of this gate substituted on None, arguing the spawn gate would refuse anyway from the capture's floor spelling -- a FALSE premise Opus 5 disproved and this revision fixes: agent.py installs kirocrew.json into the agents directory and config/defaults.json declares "name": "kirocrew", so a readable spec DOES declare the floor name, and parent_spawn_allowlists answers None only when NO readable spec declares the name -- for the floor it returns (), which ADMITS. () is "no declaration", the unchanged case. None is the reader's UNKNOWN, on which the spawn gate ITSELF refuses -- and it computes that answer from the floor spelling the capture names, so the same unreadable state refuses the spawn whether or not the fire substituted; there is no bypass to close there, and declining would strip the configured default from every agent-less cron on such a host.

  • The substituted default keeps its template namespace. _resolve_cron_agent collapses any name that merely keys cfg.agents into a crew alias and returns it as crew_agent, which resolve_crew_identity honours verbatim -- binding that member's workspace, pinned model and capability MCP servers. agent.default_agent is a free-form str in the TEMPLATE namespace with no alias validation (config/sections.py); the alias-namespaced default is a separate field guarded by default_agent_not_alias, so an operator naming a crew member in the template field is ordinary input rather than an extreme one. That is the blocking GPT 5.6 finding on this hunk: the collapse would widen an agent-less cron's capabilities and identity with no signal above DEBUG. The substitution therefore calls _resolve_cron_agent(..., template_namespace=True), which returns crew_agent="" -- the spelling resolve_crew_identity documents as opting out ("an explicit crew_agent wins verbatim -- including """), not None, which is its fallback-ENABLED spelling and would let if agent and agent in config.agents reselect the colliding crew and make the bypass a no-op (config/loader.py:5859-5867). That None-vs-"" distinction is the second blocking GPT 5.6 finding on this hunk. kiro_agent/cwd stay None, so the name dispatches as the template it was configured as, in the default workspace. Consequence, and the intended one: a default that is really only a crew alias now fails closed and loudly with "Agent mode '' is not available" instead of quietly inheriting that crew's identity.

  • Read from live.snapshot() or self._cfg, not the boot snapshot. agent.default_agent carries no restart=True mark, so the config watcher adopts a dashboard/CLI change live while self._cfg is rebuilt only by unrelated MCP handlers — a boot-only read would keep dispatching the "kirocrew" floor after an operator sets a default, the exact symptom this change removes, until a gateway restart. Same one-liner the sibling resolver below already uses for the same reason.

A whitespace-only agent_id is treated as absent at that dispatch gate — the comparison is made after .strip(). The capture itself is left byte-for-byte alone, so a whitespace job's already-bound template_id is not rewritten.

Also in this PR: a gap-list node-id spelling correction

Declared here rather than left as undeclared scope. Two passages documented the windows-expected-failures.txt spelling rule backwards, and both are corrected: docs/system-specs/common/testing-conventions.md and _apply_tracked_gap_list's own docstring summary in conftest.py.

What was wrong. Both asserted entries are "plain node ids ... no [params]" and that the matcher "reduces both the list and each collected item to that base form". That holds only for a line without [. A line carrying [ is compared with its params intact (_ungrouped_nodeid), so it covers that one parametrization rather than every one -- which is the only way to track a test whose params do not all fail on the platform. test_seed_audit_uses_rail_tag_not_raw_path is the existing entry in that form, so the documented rule contradicted the file it documents. The docstring summary also contradicted the parametrization paragraph thirty lines below it in the same docstring.

The @group stripping those passages describe IS unconditional, and that half is preserved. No matcher behaviour changes -- conftest.py is a docstring edit only.

An earlier revision of this PR also registered two apps-registry symlink tests as Windows expected failures. That registration is dropped. Upstream has since removed the platform divergence those tests encoded, so both now pass on Windows; a strict entry for either would XPASS and red the job. Only the documentation correction remains.

Also in this PR: a fail-closed retained-session guard

Declared here rather than left as undeclared scope. GPT 5.6 Review raised it as a blocking finding on head 8699e0f4a and Opus 5 Review upheld it. This PR opens the window, so it closes it.

The window. Before this change an agent-less cron dispatched the constant "kirocrew" floor on every fire, so two consecutive fires could not differ. With the fallback in place they can -- an operator narrows config.agent.default_agent between fires. Three facts then compose: the cron session key is the stable cron:{job.id} with no agent term; the post-run reset is DEFERRED while _subagent_work_pending(...) or _cron_injecting > 0; and the claim path returns the live session.provider without ever comparing the agent kwarg (session_allocation.py:1913-1961). So the next fire builds agent B's context and reuses agent A's runtime, leaving A-only capability MCP servers, workspace and pinned model reachable.

It defers; it does not reset. A retained session implies pending subagent work -- the no-pending case already reset in the prior fire's finally -- so resetting to obtain a correct runtime would destroy work in flight. The guard routes through the existing _defer_cron_before_dispatch, which marks the run retained (run_never_started, so a delete_after_run job is not consumed) and records the reason on last_error WITHOUT calling record_failure(), so a transient state cannot auto-pause a job that never ran a line. The deferral is temporary by construction: _subagent_done clears the pend and the reaper still targets the key, so it cannot become permanent.

Scoped to the AGENT-LESS PREDICATE (not job.agent_id.strip() and not agent_sequence_dispatches(job.agent_sequence)), which is exactly the window this PR opens. It is deliberately NOT keyed on whether this fire substituted: that spelling failed open in the case the guard exists for, which Opus 5 raised as blocking against d2df4f420 and this revision fixes -- fire N substitutes and defers its reset, the operator clears agent.default_agent, fire N+1 resolves an empty default so the flag is false, the guard is skipped, and the fire runs the FLOOR's context on the process still holding the previous default's runtime. Every other reason for declining the substitution reaches the same hole. A job pinning agent_id dispatches one name on every fire, so its own stale-session case predates this change and fixing it here would newly defer fires for jobs this PR does not touch. The sequence path is immune for a different reason -- it keys per agent (f"cron:{job.id}:{agent}"), so a changed agent already lands on a different session.

Positive evidence only, and that is load-bearing. The guard fires only on a non-empty str from _get_session_agent that differs from the dispatched name. No reader, an unreadable reader, a non-str and "" all behave exactly as before. Deferring on a silent reader would stall every agent-less cron on such a host forever, which is a worse failure than the widening being closed. Fail-closed here means refusing the unsafe REUSE, not treating an unanswerable question as a mismatch.

docs/system-specs/modules/learn-cron-dashboard.md is updated in the SAME commit as the code, which AGENTS.md:203-204 makes a MUST.

Backwards compatibility

Compatible. The fallback fills agent_id only when it is empty or whitespace-only and no agent_sequence dispatches; nothing that main accepts today is rejected, renamed or removed. A job with an explicit agent_id dispatches exactly as before, an unset or non-str config.agent.default_agent still degrades to the existing "kirocrew" floor, and neither the shared CronJob nor crons.json is written to.

Tests

New TestCronDefaultAgent in test/test_cron_gateway_integration.py — 24 cases. Most assert on the agent kwarg get_or_create actually receives, which is the only place the dispatch difference is observable; one also asserts on the execution the binder publishes, which is where the durable half is observable; and the retained-session mismatch case asserts get_or_create is never reached at all, plus the retention markers _defer_cron_before_dispatch sets:

case expected
agent-less job, default configured dispatches the default
shared CronJob after that run agent_id unchanged
explicit agent_id not overridden
whitespace-only agent_id treated as absent
no default configured "kirocrew" floor
non-str default "kirocrew" floor, dispatch completes
dispatching sequence (2 entries) keeps its own agents
dormant lone sequence (1 entry) still gets the default
agent-less job, default configured bound execution keeps template_id="kirocrew"
agent-less job, captured template_id="researcher" keeps researcher
agent-less job, captured template_id="kirocrew" dispatches the default
agent-less job, MEMBER capture spelling "kirocrew" keeps the member's own agent
agent-less job, LEGACY member capture with no member_id keeps the member's own agent
agent-less UNMIGRATED member schedule (no execution_context, job.member_id set) keeps the member's own agent
agent-less job, default DECLARES availableAgents keeps the "kirocrew" floor
agent-less job, allowlist reader answers UNKNOWN (None) keeps the floor (deny by default)
retained session under another agent, default CLEARED this fire deferred
pinned agent_id job past a stale session still fires, dispatches the pinned agent
agent-less job, default name also a crew alias dispatches the template name, binds no crew
live default differs from the boot snapshot dispatches the live value
retained session under a DIFFERENT agent deferred; get_or_create never called
retained session under the SAME agent still fires, dispatches the default
live session agent unreadable or non-str still fires, dispatches the default
explicit agent_id past a stale session still fires, dispatches the pinned agent

The suite discriminates in both directions, verified by mutation rather than asserted. Against a write placed below the capture the dispatch cases fail identically, which is the silent no-op demonstrated; against a mutating placement the stored-record assertion fails as well. The bind case fails on its own against a version that folds the resolved default into the captured execution. The researcher case fails against an ungated cron_agent = _default_agent or cron_agent (assert 'configured-default' == 'researcher'), and the floor-captured case fails against a resolution confined to the else: arm — so the two halves of the placement each have a test that dies without them. The member case fails against a floor-only gate (assert 'configured-default' != 'configured-default') and the live-config case fails against a boot-snapshot read (assert 'stale-boot-default' == 'live-default'). test_a_legacy_member_with_no_member_id_keeps_its_own_agent fails against the removal of the selection_kind term alone (assert 'configured-default' != 'configured-default') and no other case does, so that term carries its own guard. test_a_default_naming_a_crew_alias_does_not_inherit_that_crew fails against the removal of the template_namespace gate alone (assert 'kirocrew' == 'shared-name'), proving the collapse really did hijack the template name into the crew's kiro_agent. It asserts crew_agent == "" exactly rather than merely falsy, and fails against the None spelling (assert None == '') -- the assertion the reviewer correctly identified as too weak when it read not kwargs["crew_agent"]. The retained-session guard's three clauses were verified the same way, each arm caught and the control restored byte-identical: dropping the _default_substituted gate fails 1 case (the explicit-agent one), dropping isinstance(_live_agent, str) fails 9, and inverting != to == fails 2 (the mismatch and same-agent cases). The isinstance arm failing 9 is itself the evidence for that clause: _make_gw_for_llm leaves sessions a MagicMock, so the reader answers a non-str in every pre-existing case, and without the type check the guard would defer them all.

test/test_cron_gateway_integration.py alone: 130 passed. Whole cron suite (114 files matching test/*cron*.py): 3225 collected, 3221 passed, 4 skipped, 0 failed. flake8 and black clean on both files. Rebased onto 5332beab7, which contains the cron.py -> cron_service split (#14615); the figures above and the cron_service/identity.py citations are both measured against that base.

The two xdist failures reported against an earlier head (test_cron_reaper, test_cron_resilience) are INHERITED, not introduced by this change. Running those two files on clean main with both of this PR's files reverted to main's version failed them 1, then 5, then 0 times across three consecutive runs. The cause is xdist worker-count variance under host memory pressure: the worker budget is chosen from free memory at collection time (3 of 16 workers on the full run above, 4 of 16 on the run that showed failures), and those two modules are order-sensitive across that split. One run of either arm therefore proves nothing in either direction, and the full-suite figures above are from a single 3-worker run.

Pattern harvest

Rule candidate: grep
Pattern: a dispatch path that resolves an agent selector without applying the agent.default_agent fallback its sibling transports already apply.

The defect was not the floor itself but its reach: transport_dispatch resolves self.agent or cfg.agent.default_agent for every chat transport, and cron was the one dispatch path that read the selector and stopped at the "kirocrew" CLIENT_NAME floor. A grep for selector reads that pass straight into template_id=... or "kirocrew" without consulting the configured default enumerates the whole family, and the same shape would catch any future transport added alongside cron.

@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 Aug 24, 2026
@bolichen97

Copy link
Copy Markdown
Contributor

👋 Hi! This PR is currently in draft status. Workflow runs won't be auto-approved until it's marked as ready for review.

When you're ready, click "Ready for review" and the workflows will be approved on the next cycle automatically.

3 similar comments
@NicholasRBowers

Copy link
Copy Markdown
Contributor

👋 Hi! This PR is currently in draft status. Workflow runs won't be auto-approved until it's marked as ready for review.

When you're ready, click "Ready for review" and the workflows will be approved on the next cycle automatically.

@dwu96

dwu96 commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

👋 Hi! This PR is currently in draft status. Workflow runs won't be auto-approved until it's marked as ready for review.

When you're ready, click "Ready for review" and the workflows will be approved on the next cycle automatically.

@iamwhatever

Copy link
Copy Markdown
Contributor

👋 Hi! This PR is currently in draft status. Workflow runs won't be auto-approved until it's marked as ready for review.

When you're ready, click "Ready for review" and the workflows will be approved on the next cycle automatically.

@bolichen97 bolichen97 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Description / code mismatch

The Description states that the default-agent fallback is in-memory only and cannot reach the durable job store, but the object it mutates is the same object _save() reserialises, so the resolved agent name is written into crons.json on the first completed run.

1. The default-agent resolution is not in-memory only — it persists into crons.json on the first merged run

The Description says —

Resolve the fallback at job execution, mirroring the chat transports (agent or cfg.agent.default_agent): if a job has no agent_id and no agent_sequence, set job.agent_id to config.agent.default_agent in memory. _merge_job_result never persists agent_id, so stored job definitions are unchanged.

The code does — the first clause is literally true and the conclusion is not. _merge_job_result's field-by-field merge does not copy agent_id onto by_id[job.id], but by_id[job.id] is job: the scheduler passes the live CronJob out of self._jobs to the callback (await self._on_job(job), src/kiro_crew/cron.py:3591), so the assignment added at src/kiro_crew/slack/gateway.py:4047 mutates the stored object in place. _merge_job_result (src/kiro_crew/cron.py:3641) then calls self._save(), and _save (src/kiro_crew/cron.py:4269) reserialises every field of every object in self._jobs, agent_id included. The mutated value is also what the run itself already reads back — job.agent_id or None at src/kiro_crew/slack/gateway.py:4279 and :4299, and the usage row at :4357 (line numbers as of head bc61ccc7f). The aliasing the Description denies is already documented three lines below the callback: src/kiro_crew/cron.py:3592-3594 notes that "the command/script paths return NORMALLY and signal failure by mutating the shared job". The diff adds no test, so nothing catches the write.

Risk — an LLM cron created with no agent, meaning "follow the configured default", is silently rewritten on disk to pin the concrete agent name after its first completed run. The job then stops tracking agent.default_agent: an operator who later changes the default keeps running the old agent forever, and anyone inspecting crons.json, the Schedule UI, cron_list, or GET /api/crons sees an explicit agent they never set. This is a second, undisclosed user-visible change on top of the runtime fix the PR intends, and because the Description asserts the durable store cannot be touched, a reviewer who trusts that sentence will not look for it.

Required change — do not mutate the shared CronJob. Resolve the agent into a local and pass it through the call sites that consume it: _acquire_with_model_fallback(session_key, ...) at src/kiro_crew/slack/gateway.py:4279, ctx_builder.build_message(..., agent=...) at :4299, and the usage row agent= at :4357. Alternatively restore the previous agent_id in a finally, or add agent_id to a documented runtime-only exclusion that _save() skips. Either way, correct the Description sentence and add a test asserting that a cron run leaves crons.json's agent_id untouched.

@dwu96

dwu96 commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

👋 Hi! This PR is currently in draft status. Workflow runs won't be auto-approved until it's marked as ready for review.

When you're ready, click "Ready for review" and the workflows will be approved on the next cycle automatically.

@github-actions github-actions Bot added the merge conflict Branch has merge conflicts with its base — author must resolve before merge label Sep 7, 2026
@dwu96

dwu96 commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

👋 Hi! This PR is currently in draft status. Workflow runs won't be auto-approved until it's marked as ready for review.

When you're ready, click "Ready for review" and the workflows will be approved on the next cycle automatically.

1 similar comment
@dwu96

dwu96 commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

👋 Hi! This PR is currently in draft status. Workflow runs won't be auto-approved until it's marked as ready for review.

When you're ready, click "Ready for review" and the workflows will be approved on the next cycle automatically.

@bolichen97

Copy link
Copy Markdown
Contributor

@leozhad Thanks for this. The default_agent fallback is genuinely missing on main, so this is not superseded, but two open PRs rewrite the exact lines you touch in src/kiro_crew/slack/gateway.py, and both are further along than this branch.

#9201 (@mbajaj92, project-scoped cron agents). It replaces the same two consumer sites, the _acquire_with_model_fallback(session_key, job.agent_id or None) call and ctx_builder.build_message(agent=job.agent_id or None), with a local _resolved_agent_id resolved through resolve_agent_bindings against job.project_path. That local-variable shape is exactly what the CHANGES_REQUESTED review here asked for, instead of assigning to job.agent_id. It does not cover your case, though: with no project_path, _resolved_agent_id stays job.agent_id or None, so a global job with a blank agent still gets no default. Suggestion: let #9201 land first, then narrow this PR to a small addition on top of it, the default_agent fallback for jobs without a project_path, written against the same local variable.

#9038 (@rubencu, pruned-install retryable skips). It rewrites the same _acquire_with_model_fallback statement for an unrelated goal, so that conflict is textual only and needs ordering rather than a design change.

Two other items before this can move. The branch is 1984 commits behind with a dirty merge state, so it needs a rebase. The code comment claiming the change is in-memory only and cannot rewrite crons.json is inaccurate: the callback holds the live CronJob, so _save() reserialises the assigned name. Please add a test asserting agent_id in crons.json stays untouched.

Posted from the 2026-09-08 open-PR relationship audit (read-only, one auditor per PR); reply here if any of this is wrong.

@iamwhatever iamwhatever added the drive-to-green PR claimed by drive-to-green pipeline label Sep 17, 2026
@leozhad
leozhad force-pushed the fix/cron-default-agent-fallback branch from bc61ccc to 7a31c62 Compare September 21, 2026 23:40
@dwu96

dwu96 commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

👋 Hi! This PR is currently in draft status. Workflow runs won't be auto-approved until it's marked as ready for review.

When you're ready, click "Ready for review" and the workflows will be approved on the next cycle automatically.

@leozhad
leozhad force-pushed the fix/cron-default-agent-fallback branch from 7a31c62 to ec6256a Compare September 21, 2026 23:45
@leozhad leozhad changed the title fix(cron): fall back to config default_agent for LLM jobs with no agent_id fix(cron): run the configured default agent for an agent-less cron Sep 21, 2026
@leozhad

leozhad commented Sep 21, 2026

Copy link
Copy Markdown
Contributor Author

Thanks — the finding was correct on both counts, and the fix has been rewritten around it.

Required change implemented. The default is now resolved into a local and folded into the execution capture; the shared CronJob is never assigned to, so there is no longer an object for _save() to reserialise the resolved name out of. The Description sentence that claimed in-memory-only on the strength of _merge_job_result not copying agent_id was wrong for exactly the reason given — by_id[job.id] is job — and has been removed rather than reworded. The body now rests on non-mutation alone and states the aliasing explicitly.

Test added, as required. TestCronDefaultAgent::test_the_shared_job_record_is_never_mutated asserts the stored record's agent_id is unchanged after a completed run, alongside 7 further cases. It fails against the previous mutating placement.

One thing that changed underneath this PR while it sat. _cron_callback now snapshots its selectors before resolving the agent, and after that capture job.agent_id has no remaining reader — every consumer reads cron_agent. So the old placement was not merely persisting the value, it had also stopped having any runtime effect: rebased as-is it would have been a silent no-op, falling back to "kirocrew" with no error and no failing test. The new tests demonstrate that directly — against an unfixed tree 3 fail, and against a write placed below the capture the result is identical.

Two small additions beyond the required change, both flagged in the Description: the sequence gate now uses agent_sequence_dispatches (a lone entry is dormant, so agent_id still needs the default), and the configured value is accepted only when it is a str, since ExecutionContext.__post_init__ requires a str template_id and would otherwise abort the dispatch instead of degrading to the floor.

Cron suite: 3338 → 3346 passed, 0 regressions.

@dwu96

dwu96 commented Sep 21, 2026

Copy link
Copy Markdown
Contributor

👋 Hi! This PR is currently in draft status. Workflow runs won't be auto-approved until it's marked as ready for review.

When you're ready, click "Ready for review" and the workflows will be approved on the next cycle automatically.

@github-actions github-actions Bot removed the merge conflict Branch has merge conflicts with its base — author must resolve before merge label Sep 22, 2026
@dwu96

dwu96 commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

👋 Hi! This PR is currently in draft status. Workflow runs won't be auto-approved until it's marked as ready for review.

When you're ready, click "Ready for review" and the workflows will be approved on the next cycle automatically.

3 similar comments
@dwu96

dwu96 commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

👋 Hi! This PR is currently in draft status. Workflow runs won't be auto-approved until it's marked as ready for review.

When you're ready, click "Ready for review" and the workflows will be approved on the next cycle automatically.

@dwu96

dwu96 commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

👋 Hi! This PR is currently in draft status. Workflow runs won't be auto-approved until it's marked as ready for review.

When you're ready, click "Ready for review" and the workflows will be approved on the next cycle automatically.

@dwu96

dwu96 commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

👋 Hi! This PR is currently in draft status. Workflow runs won't be auto-approved until it's marked as ready for review.

When you're ready, click "Ready for review" and the workflows will be approved on the next cycle automatically.

@leozhad
leozhad force-pushed the fix/cron-default-agent-fallback branch from ec6256a to 091ffdd Compare September 28, 2026 21:45
@leozhad

leozhad commented Sep 28, 2026

Copy link
Copy Markdown
Contributor Author

The required change is in at 091ffdd7, and your aliasing analysis was correct — the original description's claim that _merge_job_result shields the durable store was false. by_id[job.id] is job, and _save() reserialises self._jobs wholesale, so the old placement would have pinned an agent-less cron to a concrete agent name in crons.json on its first completed run and the job would have stopped tracking agent.default_agent.

The default is now resolved into a local and folded into the legacy_selection capture in _cron_callback. The shared CronJob is never written to.

Why "resolve into a local" was the only one of the three options that works

A write to job.agent_id anywhere below the capture is a silent no-op. _cron_callback snapshots its selectors before yielding — "captured selectors, never the scheduler's mutable job" — and after that point job.agent_id has no remaining reader: scanning the whole remainder of the file finds it only inside the capture itself (gateway.py:4558) and once in a docstring (:4582). So a finally-restore, or adding agent_id to a _save() exclusion, would have left the original bug in place while looking fixed — no error, no conflict, no failing test.

The tests discriminate in both directions

8 new cases in TestCronDefaultAgent, asserting on the agent kwarg get_or_create actually receives, which is the only place the difference is observable.

  • Against an unfixed tree: 3 fail.
  • Against a write placed below the capture: identical result — same 3 fail, same 4 pass. The no-op is demonstrated rather than asserted.
  • Against a mutating placement: 4 fail — those three plus test_the_shared_job_record_is_never_mutated, which is the assertion this path had no cover for.

Rebased onto 15184342e (current main) and re-verified there: the block is still inside _cron_callback above the capture, agent_sequence_dispatches is still the imported gate, and 8/8 pass. Still 2 commits.

One housekeeping note: the red Fork PR Description check is the pre-edit payload from 23:45:27Z — two later runs of the same check pass on the current body.

Marking ready for review.

@leozhad
leozhad marked this pull request as ready for review September 28, 2026 21:46
@leozhad
leozhad requested a review from a team as a code owner September 28, 2026 21:46
@leozhad
leozhad requested a review from kyleseaman September 28, 2026 21:46
@dwu96

dwu96 commented Sep 28, 2026

Copy link
Copy Markdown
Contributor

👋 Hi! This PR's description is missing some required sections from our PR template. Workflow runs won't be auto-approved until the description is updated.

Missing sections:

  • ## Problem / Motivation
  • ## Why it matters
  • ## What changed
  • ## Tests

Please update your PR description to include these sections, then push or re-save the description. The workflows will be approved on the next cycle.

@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 Sep 29, 2026
@leozhad
leozhad force-pushed the fix/cron-default-agent-fallback branch from 68972db to 20f12a7 Compare September 29, 2026 07:33
@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 Sep 29, 2026
@leozhad
leozhad force-pushed the fix/cron-default-agent-fallback branch from 20f12a7 to deaca8d Compare September 29, 2026 08:10
@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 Sep 29, 2026
@leozhad
leozhad force-pushed the fix/cron-default-agent-fallback branch from deaca8d to 8ed7d28 Compare September 29, 2026 08:11
@leozhad

leozhad commented Sep 29, 2026

Copy link
Copy Markdown
Contributor Author

@bolichen97 @iamwhatever @CrysisDeu — two things on this PR need commit access, and neither is a code change. MAINTAINERS.md says tagging the list to get a decision unstuck is fine, so I am doing that rather than pinging anyone directly.

1. A re-review to clear the stale CHANGES_REQUESTED. That review was submitted against head bc61ccc7f on 2026-09-02. The branch has since been rebased twice and is now 8ed7d28a7 on 5332beab7. All three of its required changes are in, and each is checkable in one command:

Required change Where it is now
Do not mutate the shared CronJob; resolve into a local git diff origin/main...HEAD -- '*.py' | grep -E "^\+.*job\.agent_id\s*=" returns only a test assertion, no assignment. The default lands in a local cron_agent.
Add a test asserting crons.json's agent_id is untouched TestCronDefaultAgent::test_the_shared_job_record_is_never_mutated, test/test_cron_gateway_integration.py:2952 — assert job.agent_id == "", "the stored CronJob must not carry the resolved default"
Correct the Description sentence The flagged wording ("in-memory only", "_merge_job_result never persists agent_id", "stored job definitions are unchanged") is gone. The Design section now states the aliasing the review named — await self._on_job(job) hands out the live object and _save() reserialises self._jobs wholesale — and explains that this is why the shared job is left untouched.

The review's diagnosis was correct and the risk it described was real: an agent-less cron would have been pinned to a concrete agent name in crons.json after its first completed run and stopped tracking agent.default_agent. Please re-review, or dismiss if you would rather not re-read the whole thing.

2. Run approval for 8ed7d28a7. 19 of 24 workflow runs on this head are action_required, so no content lane has executed. PR Readiness is red purely as the fan-in of that — its status description reads "4 workflow(s) awaiting maintainer approval; none has run yet". Approval is per-SHA and I am pull-only here, so I cannot clear it and pushing again would only create another gated batch.

On 20f12a7b6 — the last head whose reviewer lanes actually executed — both previously-blocking lanes cleared (GPT 5.6 Review and Opus 5 Review, no blocking findings), along with Design Review (PASS), Security Scope Review and UX Review. I am not counting that as a clean sweep: First Principles Review returned neutral — "review incomplete (advisory)" — which is an infra outcome, not a pass, and it has not re-rolled since.

Local verification on the current base 5332beab7: 120 tests pass in TestCronDefaultAgent's file, 3211 passed / 4 skipped / 0 failed across the 114 test/*cron*.py files, flake8 and black clean.

@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 Sep 29, 2026
@leozhad
leozhad force-pushed the fix/cron-default-agent-fallback branch 2 times, most recently from 8ed7d28 to 473df7a Compare September 29, 2026 08:45
@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 Sep 29, 2026
@leozhad

leozhad commented Sep 29, 2026

Copy link
Copy Markdown
Contributor Author

Backend Tests (Windows) (1) — inherited from main, not from this PR

The two failures on that shard arrived from main about ten minutes before our shard ran, and they are not reachable from anything this PR changes.

FAILED test/test_apps_registry_coverage.py::TestSubdirGates::test_contained_join_degrades_to_none_on_a_symlink_loop
  AssertionError: assert WindowsPath('C:/.../root/pkg/app.json') is None
FAILED test/test_apps_registry_coverage.py::TestRunAppBuild::test_a_self_pointing_directory_link_under_a_deep_declared_path_is_judged_in_bounded_time[60]
  assert True is (60 == 30)
2 failed, 16066 passed, 893 skipped, 11 xfailed

Provenance. Both tests are absent from this branch and present on main. They were added by 244afb1d7 — fix(apps): let a backend app's requirements.txt pass the desktop gate (#13568) — merged to main at 07:32:29Z. Our Windows shard 1 ran 07:42:59Z → 07:56:36Z, so the PR merge commit picked them up.

Why they fail only on Windows. Both encode POSIX symlink semantics and are gated only by @requires_symlinks, which skips on missing SeCreateSymbolicLinkPrivilege — a privilege the GitHub Windows runners grant, so the tests run there:

  • the first test's own comment states "non-strict Path.resolve reports ELOOP as RuntimeError"; on Windows it does not raise, so _contained_join returns a path instead of None;
  • the second asserts runtime_accepts is (depth == 30) because "60 exceed the kernel's symlink budget"; Windows' budget differs, so a 60-deep path is accepted and the assertion inverts.

Both pass on Linux against the exact merge commit CI built (our head + origin/main):

$ pytest test/test_apps_registry_coverage.py::TestSubdirGates::test_contained_join_degrades_to_none_on_a_symlink_loop \
         test/test_apps_registry_coverage.py::TestRunAppBuild::test_a_self_pointing_directory_link_under_a_deep_declared_path_is_judged_in_bounded_time
3 passed in 3.81s

No coupling to this diff. test_apps_registry_coverage.py imports only kiro_crew.apps.registry and kiro_crew.platform. The only source file this PR touches is src/kiro_crew/slack/gateway.py. It is deterministic rather than flaky — the same two tests failed identically on two consecutive heads here.

It needs a platform gate on main (skip on os.name == "nt", or assert the Windows behaviour), which a fork PR cannot land. Flagging for the author of #13568.

This PR's own state

  • test/test_cron_gateway_integration.py — 120 passed against merged main; flake8 clean on both changed files.
  • GPT 5.6 Review — no blocking findings (the earlier security-fenced selection_kind finding is fixed and covered by test_a_legacy_member_with_no_member_id_keeps_its_own_agent).
  • First Principles Review — PASS, justified and minimal.
  • Design Review CONCERNS is addressed in this push: docs/system-specs/modules/learn-cron-dashboard.md:241 said the gateway passes agent=job.agent_id bare, which this change makes false. It now states the live-config default fallback and all four gates, in the fix commit per the same-commit rule.

@leozhad

leozhad commented Sep 29, 2026

Copy link
Copy Markdown
Contributor Author

GPT 5.6 F1 — fixed (src/kiro_crew/slack/gateway.py:4651, default template can inherit same-named crew capabilities)

Accepted as stated, and the adjudicator's rarity reasoning is right: agent.default_agent is a free-form str in the template namespace with no alias validation (config/sections.py:865-868), while the alias-namespaced default is a separate field guarded by default_agent_not_alias (handlers/agents.py:1384-1391) — so an operator naming a crew member in the template field is ordinary input, and _resolve_cron_agent collapses on nothing more than membership in cfg.agents (gateway.py:4622), returning the alias as crew_agent, which resolve_crew_identity honours verbatim (config/loader.py:5858-5861). Silent apart from DEBUG.

The fix is the one the finding prescribes. The substitution now records that the dispatched name came from the template namespace, and the resolver is called with template_namespace=True, which returns its documented miss tuple and bypasses the collapse:

                cron_agent = _default_agent
                _default_substituted = True
...
                if template_namespace:
                    return None, None, None
...
                _single_kagent, _single_cwd, _single_crew = _resolve_cron_agent(
                    cron_agent or None, template_namespace=_default_substituted
                )

So the substituted default dispatches as the template it was configured as, with crew_agent unset and no crew cwd. A default that is really only a crew alias now fails closed and loudly with Agent mode '<name>' is not available rather than inheriting that member's workspace, pinned model and capability MCP servers. The sequence call site (gateway.py:5809) is deliberately untouched — the substitution is gated on no dispatching agent_sequence, so a sequence agent is never the substituted default.

Covered and verified by mutation. New case test_a_default_naming_a_crew_alias_does_not_inherit_that_crew builds the collision the finding describes — a real cfg.agents dict keyed by the configured default, with resolve_agent_bindings and workspace_dir_from_entry stubbed so the collapse would otherwise succeed — and asserts the dispatch receives agent="shared-name", a falsy crew_agent, and cwd is None. Removing only the template_namespace gate fails it, and only it:

E       AssertionError: assert 'kirocrew' == 'shared-name'
FAILED test/test_cron_gateway_integration.py::TestCronDefaultAgent::test_a_default_naming_a_crew_alias_does_not_inherit_that_crew

test/test_cron_gateway_integration.py: 121 passed. flake8 clean on both changed files. The spec paragraph and the PR description both record the namespace rule, in the same commit as the code.

Also in this push, answering Design Review's earlier CONCERNS: docs/system-specs/modules/learn-cron-dashboard.md now states the namespace preservation alongside the three substitution gates.

@leozhad

leozhad commented Sep 29, 2026

Copy link
Copy Markdown
Contributor Author

GPT 5.6 F1 (second round) — fixed: None was the fallback-enabled spelling

Correct, and my previous fix was a no-op for exactly the reason given. resolve_crew_identity says so in its own docstring:

    """...An explicit ``crew_agent`` wins verbatim — including "" ("no crew"), which is how the
    dashboard, the one kiro-name-passing surface, opts out of the fallback..."""
    if crew_agent is not None:
        return crew_agent
    if agent and agent in config.agents:
        logger.debug("crew_agent %r resolved by crew-namespace fallback", agent)
        return agent
    return ""

None means "apply the crew-namespace fallback", so returning the miss tuple (None, None, None) bypassed the collapse inside _resolve_cron_agent and then let resolve_crew_identity reselect the same colliding crew one layer down — reaching the crew's capability MCP servers and workspace cwd (session_capabilities.py:53,70-73) and its model/watchdog pin anyway. The template_namespace branch now returns the explicit opt-out:

                if template_namespace:
                    return None, None, ""

kiro_agent/cwd stay None, so the substituted default dispatches as the template it was configured as, in the default workspace, with the crew fallback off. The other early returns keep None deliberately — those are genuine misses that must preserve today's fallback behaviour.

The weak assertion is fixed too, and it is what would have caught this. The reviewer is right that assert not kwargs["crew_agent"] passed on None. The case now asserts the spelling exactly:

        assert kwargs["crew_agent"] == ""

Reverting only the return value to None fails it, and only it:

E       AssertionError: assert None == ''
FAILED test/test_cron_gateway_integration.py::TestCronDefaultAgent::test_a_default_naming_a_crew_alias_does_not_inherit_that_crew

test/test_cron_gateway_integration.py: 121 passed. flake8 clean. The spec paragraph and the PR description both now name the None-vs-"" distinction rather than saying "unset", in the same commit as the code.

@leozhad

leozhad commented Sep 29, 2026

Copy link
Copy Markdown
Contributor Author

The spawn-allowlist finding is real and I reproduced it before changing anything. I closed it by a different mechanism than the one prescribed, and that is deliberate — head is now d2df4f420.

The finding, verified leg by leg. The substitution reaches the dispatched agent= only, while bind_session_execution publishes the unsubstituted capture under cron:{job.id}. Both spawn entry points derive the parent's declaration from that record alone — read_session_execution(parent) → parent_spawn_allowlists(parent_execution.template_id) in dashboard/handlers/messaging.py, and the off-loop twin in subagent.py. For the floor spelling that returns (), which _vet_parent_available_agents admits as "no declaration to honour". So a toolsSettings.subagent.availableAgents list on the substituted template is never consulted and a child it forbids starts.

Why not the prescribed remedy. "Use the substituted template as the non-durable parent execution for spawn admission" needs a non-durable parent-execution channel that the spawn gate reads. There is no such channel today: bind_session_execution is durable, and publishing the substituted name into it is the one thing this change must not do — the binder is called positionally, so replace_existing=False, and it refuses a candidate differing from what a prior fire recorded, which turns every later fire into a recorded failure until the job auto-pauses. Building that channel means editing the spawn admission gate in two files this PR does not touch, whose reviewers are scoped to spawn admission rather than cron — which is the same ride-along objection Design Review and First Principles Review are already raising against this PR.

What I did instead — a narrowing, not an addition. A default whose spec declares an allowlist is not substituted; the job keeps the "kirocrew" floor. That removes the finding's precondition rather than compensating for it, and a declined job keeps exactly the behaviour it has on main today, so no operator loses a control they currently hold. Honouring the declaration is a real capability and worth its own CR; it is not landable inside a fix(cron) diff.

Positive evidence only, the same rule the retained-session guard follows. Only a NON-EMPTY tuple declines. () is "no declaration", the unchanged case. None is the reader's UNKNOWN — and the spawn gate itself refuses on that answer, computing it from the floor spelling the capture names, so the same unreadable state refuses the spawn whether or not the fire substituted. There is no bypass to close there, and declining on it would strip the configured default from every agent-less cron on such a host.

Mutation-proved in both directions: disabling the gate fails exactly the bypass test (1 failed / 21 passed), and also declining on None fails exactly the UNKNOWN test (1 failed / 21 passed). Control restores byte-identical, 22/22. TestCronDefaultAgent is now 22 cases; whole cron suite 3223 collected / 3219 passed / 0 failed. The spec went in the same commit as the code, per AGENTS.md.

A cron with no explicit agent_id was dispatched as the AcpClient fallback
CLIENT_NAME ("kirocrew"), whose agent config carries none of the default
agent's MCP servers -- so agent-less cron sessions silently ran without the
expected toolset (observed in production). Now mirrors the chat transports'
fallback (transport_dispatch: `self.agent or cfg.agent.default_agent`).

Resolved into a local above the execution branch, applied to the dispatched
agent below it, and only where that resolved agent is still the bare "kirocrew"
floor. All three placements are load-bearing.

Above the branch, because every record created since the execution-context
migration carries execution_context and takes the other arm, so resolving inside
the legacy arm alone leaves the symptom in place for all of them.

Out of the capture, because the captured execution is what bind_session_execution
publishes under the session key, and a persistent_session job (the default)
reuses the stable key cron:{job.id} on every fire; that binder refuses a
candidate differing from the record, so folding the default into the captured
identity makes every later fire of an already-run job raise "session already
belongs to another execution" until it auto-pauses. Only the dispatched agent
carries the default; the captured identity is left byte-for-byte alone, which is
also what keeps the resolved name out of the durable store.

Floor-gated, because a captured template_id that names a real template is a
deliberate selection. A schedule created from a template chat with no `agent`
argument names its template ONLY there, agent_id staying empty (cron.py:381-385),
so an agent_id-only gate reads that job as agent-less. Overriding it would
re-point the job onto the default on every fire while its captured execution and
memory store stayed the original template's, and dispatched_agents_from_disk --
the delete guard's one walk of the dispatch-mirroring rule -- would still report
the old agent, so guard and dispatch would drift. That is the same silent
wrong-agent class this commit fixes, reintroduced on the other arm.

Leaving the shared CronJob untouched is what keeps the resolved name out of
crons.json. CronService hands the callback the live object from self._jobs
(`await self._on_job(job)`) and _save() reserialises self._jobs wholesale, so
mutating job.agent_id would pin an agent-less cron to a concrete agent name on
its first completed run -- the job would stop tracking agent.default_agent.
_cron_callback snapshots its selectors before yielding ("captured selectors,
never the scheduler's mutable job") and job.agent_id has no reader after that
capture, so a write below it reaches nothing.

Gated on agent_sequence_dispatches rather than on a bare agent_sequence: a lone
sequence entry is dormant and dispatch falls through to agent_id, which must
still receive the default. That helper is the one spelling of the gate.

The configured value is accepted only when it is a str, so a malformed default
degrades to the existing "kirocrew" floor rather than reaching the dispatched
agent kwarg. A whitespace-only agent_id is treated as absent at the dispatch
gate, where the comparison is made after .strip(); the capture is not rewritten,
so an already-bound whitespace template_id keeps its recorded value.
@leozhad

leozhad commented Sep 29, 2026

Copy link
Copy Markdown
Contributor Author

Both blocking findings were real and both are fixed in 6bfacad83. The second one disproved a premise I had written into the code as a rebuttal, so I want to be explicit that it was my error, not a reviewer misread.

1. The retained-session guard failed open in the case it was written for. Keying it on "did this fire substitute" meant fire N could substitute and defer its reset, the operator could then clear agent.default_agent, and fire N+1 would resolve an empty default — flag false, guard skipped, floor context running on the process still holding the previous default's runtime. Any other reason for declining the substitution reached the same hole. Fixed by keying on the agent-less predicate itself (not job.agent_id.strip() and not agent_sequence_dispatches(job.agent_sequence)), which is the window this change opens. It costs nothing elsewhere: a pinned agent_id dispatches one name forever and a dispatching sequence already runs on per-agent keys, so both are excluded by that predicate — there is a test asserting a pinned job is not deferred by a stale session.

2. None now declines, and my in-code rebuttal was wrong. I had argued the spawn gate would refuse anyway because it asks about the capture's floor spelling. Verified against source and it does not hold: agent.py generates and installs kirocrew.json into the agents directory and config/defaults.json declares "name": "kirocrew", so a readable spec does declare the floor name — and parent_spawn_allowlists answers None only when no readable spec declares the name while some file could not be read. For the floor it therefore returns (), "no declaration to honour", and the gate admits. None is exactly the state where a restrictive declaration may sit in the spec file the hardened reader refused, in a shared user-writable directory, so the check is now if _declared or _declared is None. The log line no longer claims a declaration exists when the answer was UNKNOWN.

3. The expected-failures justification is corrected too. It claimed depth 30 is "refused on both platforms"; the test asserts runtime_accepts is (depth == 30), so 30 is accepted — which is why [30] passes on Windows and is deliberately unlisted. And the first entry is a single self-referential link (os.symlink("pkg", root / "pkg")) expecting non-strict Path.resolve to report ELOOP, not a 40-link budget. Both now say so.

Each fix was reproduced before it was written: the two new/inverted tests fail on the previous head and pass here. Mutation-proved — reverting the guard to the flag fails exactly the cleared-default test (1 of 24), and restoring if _declared: fails exactly the UNKNOWN test (1 of 24); control restores byte-identical at 24/24. test_cron_gateway_integration.py 130 passed, whole cron suite 3225 collected / 3221 passed / 0 failed, flake8 + black + docs-lint clean. The spec went in the same commit as the code and both now-false paragraphs in it were rewritten rather than left standing.

@leozhad

leozhad commented Sep 29, 2026

Copy link
Copy Markdown
Contributor Author

This one I am not folding, and the reason is in the adjudication attached to it: fenced=1 flagged=1, with the FLAG recording that in the named window "the spawn gate consults exactly the kirocrew capture it consults on main … so no child is admitted that main would have refused."

The window is real and it is pre-existing, not opened by this change. The finding needs an operator to tighten their own default template's spec strictly between this fire's pre-dispatch read and a spawn inside that same turn. In that window the gate resolves the parent from the persisted capture, which this change deliberately leaves unmutated — it assigns only the local cron_agent — so the identity the spawn gate consults is byte-identical to what an agent-less cron presents on main today. A TOCTOU window that admits exactly what main admits is not a regression this PR introduces; closing it changes main's behaviour, not this PR's.

Three things bound it, each verified against source rather than argued:

  • _PARENT_ALLOWLIST_MEMO is pinned to agents_dir_revision — entry names, mtime and ctime, size, inode, mode, the in-process spec generation, "nothing younger than the racy window" — and it refuses to pin whenever freshness cannot be proven, running the walk uncached instead. Its own comment states the threat it exists for: a mtime-preserving rewrite must not "serve a PERMISSIVE allowlist for ever after the operator tightened it". So the tightened spec is not served stale.
  • _vet_spawn_governance (subagent.py:460) is an independent half of the intersection: it checks the parent surface's ceiling ∩ profile and never reads the agent spec, so it still applies throughout the window.
  • The next fire re-resolves the allowlist and declines the substitution, and the retained-session guard defers a fire whose dispatch name differs from the live session's.

The prescribed fix is the same change I declined two revisions ago — "make live spawn-policy resolution use the dispatched default template" is the non-durable parent-execution mechanism that requires editing the spawn admission gate in subagent.py and dashboard/handlers/messaging.py, neither of which this PR touches, under reviewers scoped to spawn admission rather than cron. That rebuttal was accepted: this seat returned ✅ on d2df4f420 after it. I still think the capability is worth having and still think it belongs in its own CR, where a reviewer who owns that gate can judge a change to a security control on its merits.

I have folded every other finding this review raised, including two on my own guards in the previous revision where the reviewer was right and my in-code reasoning was wrong. This one I am declining on the mechanism, with its own adjudicator's flag as the supporting evidence.

@pepmach

pepmach commented Sep 29, 2026

Copy link
Copy Markdown
Contributor

Heads-up: the test/windows-expected-failures.txt strict-xfail entries this PR adds for test/test_apps_registry_coverage.py::TestRunAppBuild::test_a_self_pointing_directory_link_under_a_deep_declared_path_is_judged_in_bounded_time[60] and ::TestSubdirGates::test_contained_join_degrades_to_none_on_a_symlink_loop would XPASS under the strict list: the loop test passes on the Windows shard on main since #15081 (merged 20:48Z, run 36628949636), and the deep-link test was reshaped by #15065 (merged 22:33Z) and passed on that PR's own Windows shard; main's first run carrying #15065 is pending.

…ling docs

Two test-layer changes in one commit because this repository caps a pull
request at two commits (code-review.yml, MAX_COMMITS: 2) and the first is
the behaviour change plus the module spec AGENTS.md requires to move with
it. Everything here is test-layer: no runtime file is touched.

-- Cron default-agent dispatch cover --

Eleven cases, asserting on the agent kwarg get_or_create actually receives --
the only place a default resolved below the capture is distinguishable from one
that reaches dispatch.

Includes the two assertions this path had no cover for: that the stored CronJob
is unchanged after a run (the scheduler hands the callback its live object, so a
mutation would reach crons.json via _save), and that a non-str configured
default degrades to the floor rather than aborting the dispatch on
ExecutionContext's str template_id requirement. Plus the dormant lone-sequence
case, a dispatching sequence keeping its own agents, and the explicit-agent and
no-default-configured negatives.

Two cases cover records that carry an execution_context, which every record
created since the execution-context migration does. A captured
template_id="researcher" must survive -- a schedule created from a template chat
names its template only there, agent_id staying empty -- while a captured
template_id="kirocrew" must still pick the configured default up at dispatch.
Each dies without one half of the placement: the researcher case fails against an
ungated cross-arm override, the floor case against a resolution confined to the
legacy arm.

-- Gap-list node-id spelling, documented correctly --

Two passages described `windows-expected-failures.txt` entries as "plain node
ids ... no `[params]`", and said the matcher "reduces both the list and each
collected item to that base form". That is true only for a line without `[`.
`_apply_tracked_gap_list` compares a line carrying `[` with its params intact
(`_ungrouped_nodeid`), so such a line covers that one parametrization rather
than every one -- which is the only way to track a test whose params do not all
fail on the platform. `test_seed_audit_uses_rail_tag_not_raw_path` is the
existing entry in that form, so the documented rule contradicted the file it
documents. Both passages now state the two-spelling rule, in
testing-conventions.md and in the matcher's own docstring summary, which had
contradicted the parametrization paragraph thirty lines below it. The `@group`
stripping those passages describe IS unconditional, and that half is preserved.

An earlier revision of this commit also registered two apps-registry symlink
tests as Windows expected failures. Upstream has since removed the platform
divergence they encoded, so both now pass on Windows and a strict entry for
either would XPASS and red the job; the registration is dropped and only the
documentation correction remains.
@leozhad

leozhad commented Sep 29, 2026

Copy link
Copy Markdown
Contributor Author

Confirmed, and fixed in c14bdd1 — thank you, this was exactly right on both entries.

Verified against main rather than taking it on the summary:

So both would XPASS under the strict list, and [30] is no longer a special case either — the per-depth assertion the [60]-only spelling was built around no longer exists.

What changed: the whole registration is dropped — the two node ids and their comment block come out of test/windows-expected-failures.txt, which is now byte-identical to base (154 entries). The diff goes 6 files → 5.

What I kept: the testing-conventions.md and conftest.py docstring corrections. Those passages were wrong independently of this registration — they said entries carry "no [params]" and that the matcher always base-reduces, which holds only for a line without [, while test_seed_audit_uses_rail_tag_not_raw_path has been in the selective form all along. Docstring text only; no matcher behaviour changes.

Commit title and message updated to match, and the PR description section rewritten so it no longer describes a registration that isn't there.

Verified locally: test/test_windows_gap_list.py 5 passed (including test_every_entry_names_a_test_that_still_exists), test/test_cron_gateway_integration.py 130 passed, flake8 and black --check clean, docs lint passes with no new entry.

@bolichen97 bolichen97 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-reviewed on head c14bdd1: the changes I requested earlier are present and verified (sweep 2026-09-30). Superseding my stale CHANGES_REQUESTED; approving.

@bolichen97 bolichen97 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed on behalf of the maintainers (sweep 2026-09-30): readiness passed, required checks green on c14bdd1, no blocking review threads, security posture unchanged. Approving and merging.

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) readiness: passed Eligible automated validation passed for the current revision

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants