The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): find unified-runtime cron runs by their scheduler admission
unsupportedpastelse2042c84bad5
diff --git a/apps/desktop/src/app/chat/sidebar/cron-jobs-section.tsx b/apps/desktop/src/app/chat/sidebar/cron-jobs-section.tsxindex 816629d742c..ccf18379706 100644--- a/apps/desktop/src/app/chat/sidebar/cron-jobs-section.tsx+++ b/apps/desktop/src/app/chat/sidebar/cron-jobs-section.tsx@@ -21,7 +21,7 @@ import { $selectedStoredSessionId } from '@/store/session'import type { CronJob } from '@/types/hermes'import { jobState, jobTitle, nextRunOverdueMs, STATE_DOT } from '../../cron/job-state'-import { openCronRun, reconcileCronRunVerdicts } from '../../cron/open-cron-run'+import { isCronRunRow, openCronRun, reconcileCronRunVerdicts } from '../../cron/open-cron-run'import { SidebarPanelLabel } from '../../shell/sidebar-label'import { SidebarRowBody, SidebarRowLabel, SidebarRowLead, SidebarRowShell } from './chrome'@@ -67,13 +67,6 @@ function formatRunTime(seconds?: null | number): string {return Number.isNaN(date.valueOf()) ? '—' : fmtDayTime.format(date)}-// Script-only (no_agent) jobs have no agent sessions; the runs endpoint-// surfaces their per-fire output docs as rows with source='cron_output'-// (see _list_cron_output_runs in hermes_cli/web_routers/cron.py).-function isSyntheticCronOutputRun(run: SessionInfo): boolean {- return run.source === 'cron_output'-}-interface SidebarCronJobsSectionProps {jobs: CronJob[]label: string@@ -471,7 +464,7 @@ function CronJobSidebarRuns({) : (<>{runs.map(run =>- isSyntheticCronOutputRun(run) ? (+ !isCronRunRow(run) ? (// Output-doc rows have no backing session to open.<divclassName="truncate rounded-md px-1.5 py-0.5 text-[0.6875rem] text-(--ui-text-secondary) tabular-nums"diff --git a/apps/desktop/src/app/cron/index.tsx b/apps/desktop/src/app/cron/index.tsxindex c89001ef8e6..e79f611944c 100644--- a/apps/desktop/src/app/cron/index.tsx+++ b/apps/desktop/src/app/cron/index.tsx@@ -87,7 +87,7 @@ import {validateCronEditor} from './cron-job-model'import { jobState, jobTitle, nextRunOverdueMs, STATE_DOT, truncateText } from './job-state'-import { openCronRun, reconcileCronRunVerdicts } from './open-cron-run'+import { isCronRunRow, openCronRun, reconcileCronRunVerdicts } from './open-cron-run'const DEFAULT_DELIVER = 'local'@@ -958,13 +958,6 @@ function formatRunTime(seconds?: null | number): string {return Number.isNaN(date.valueOf()) ? '—' : date.toLocaleString()}-// Script-only (no_agent) jobs have no agent sessions; the runs endpoint-// surfaces their per-fire output docs as rows with source='cron_output'-// (see _list_cron_output_runs in hermes_cli/web_routers/cron.py).-function isSyntheticCronOutputRun(run: SessionInfo): boolean {- return run.source === 'cron_output'-}-// Runs are produced by the background scheduler tick. cron.changed /// sessions.changed broadcasts re-load immediately on event-capable backends// (the tick dep below), so the poll drops to a slow backstop there; older@@ -1116,7 +1109,7 @@ function CronJobRuns({</div>)}{(runs ?? []).map(run =>- isSyntheticCronOutputRun(run) ? (+ !isCronRunRow(run) ? (// Output-doc rows have no backing session to open; show the// recorded output preview without a chat-navigation affordance.<div className="flex items-center justify-between gap-3 rounded-md px-2 py-1 text-xs" key={run.id}>diff --git a/apps/desktop/src/app/cron/open-cron-run.test.ts b/apps/desktop/src/app/cron/open-cron-run.test.tsindex 5482f6ab90d..5342b9c75b0 100644--- a/apps/desktop/src/app/cron/open-cron-run.test.ts+++ b/apps/desktop/src/app/cron/open-cron-run.test.ts@@ -1,6 +1,8 @@-import { beforeEach, describe, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { $cronRunReadOnlyVerdicts, isStoredTranscriptReadOnly } from '@/store/read-only-transcript'+import { $cronSessions, $sessions } from '@/store/session'+import type { SessionInfo } from '@/types/hermes'import { isResumableCronRun, openCronRun, reconcileCronRunVerdicts, refreshCronRunWriteGate } from './open-cron-run'@@ -155,3 +157,34 @@ describe('refreshCronRunWriteGate — restored tab after a restart (no verdict yexpect(fetchRow).not.toHaveBeenCalled()})})++describe('refreshCronRunWriteGate — a unified-runtime run is known by its row, not its id (#138812)', () => {+ // The unified gateway runtime keeps the run's runtime-minted `local-*` id;+ // only the row the backend served (`source: 'cron'`) says it is a cron run.+ const id = 'local-7e105fd6cca5c3d1'++ const cachedRow = (source: string) =>+ ({ ended_at: null, id, is_active: false, last_active: NOW_S, source }) as SessionInfo++ afterEach(() => {+ $cronSessions.set([])+ $sessions.set([])+ })++ it('gates a restored zombie run whose cached row is a cron run', async () => {+ $cronSessions.set([cachedRow('cron')])+ const fetchRow = vi.fn(async () => ({ ended_at: null, last_active: 0, scheduler_owned: false, source: 'cron' }))++ expect(await refreshCronRunWriteGate(id, fetchRow)).toBe(true)+ expect(fetchRow).toHaveBeenCalledWith(id)+ expect(isStoredTranscriptReadOnly(id)).toBe(true)+ })++ it('never fetches for an ordinary session that also has a local id', async () => {+ $sessions.set([cachedRow('desktop')])+ const fetchRow = vi.fn()++ expect(await refreshCronRunWriteGate(id, fetchRow)).toBe(false)+ expect(fetchRow).not.toHaveBeenCalled()+ })+})diff --git a/apps/desktop/src/app/cron/open-cron-run.ts b/apps/desktop/src/app/cron/open-cron-run.tsindex 9ba2acfdf22..67d970fda37 100644--- a/apps/desktop/src/app/cron/open-cron-run.ts+++ b/apps/desktop/src/app/cron/open-cron-run.ts@@ -1,4 +1,5 @@import { hasCronRunVerdict, isCronRunReadOnly, recordCronRunVerdict } from '@/store/read-only-transcript'+import { ownerLookupSessionRows, sessionMatchesStoredId } from '@/store/session'import type { SessionInfo } from '@/types/hermes'type CronRunLiveness = Pick<SessionInfo, 'ended_at' | 'last_active' | 'scheduler_owned'> &@@ -11,8 +12,10 @@ type CronRunRow = CronRunLiveness & Pick<SessionInfo, 'id'>// predates `scheduler_owned`.const ACTIVITY_WINDOW_MS = 300_000-// `cron/scheduler.py::run_job` names every agent run `cron_{job_id}_{YYYYmmdd_HHMMSS}`.-const CRON_RUN_SESSION_ID = /^cron_.+_\d{8}_\d{6}$/+// Agent runs from before the unified gateway runtime are named+// `cron_{job_id}_{YYYYmmdd_HHMMSS}`. A unified-runtime run keeps its+// runtime-minted `local-*` id (#138812), so only its row says what it is.+const LEGACY_CRON_RUN_SESSION_ID = /^cron_.+_\d{8}_\d{6}$//*** Cron run sessions are autonomous scheduled executions, never interactive@@ -48,8 +51,31 @@ export function isResumableCronRun(run: CronRunLiveness, nowMs = Date.now()): boreturn typeof run.last_active === 'number' && nowMs - run.last_active * 1000 < ACTIVITY_WINDOW_MS}-export function isCronRunSessionId(storedSessionId: null | string | undefined): boolean {- return Boolean(storedSessionId && CRON_RUN_SESSION_ID.test(storedSessionId.trim()))+/**+ * A row is a cron run session when the backend serves it as one: only the+ * scheduler writes `source === 'cron'` sessions. A run-history row with no+ * session behind it (`cron_output`, a script-only fire's output doc) is not.+ */+export function isCronRunRow(row: null | Pick<SessionInfo, 'source'> | undefined): boolean {+ return row?.source === 'cron'+}++/**+ * Whether a stored session id is a cron run: its cached row says so, whatever+ * id the run was minted with (an opened run's row is cached into the cron+ * slice when it resolves), or it carries the legacy run id (a tab restored+ * before any list loaded its row).+ */+export function isCronRunSession(storedSessionId: null | string | undefined): boolean {+ const id = storedSessionId?.trim()++ if (!id) {+ return false+ }++ const cached = ownerLookupSessionRows().find(row => sessionMatchesStoredId(row, id))++ return isCronRunRow(cached) || LEGACY_CRON_RUN_SESSION_ID.test(id)}function recordRunVerdict(run: CronRunRow): void {@@ -91,7 +117,7 @@ export function reconcileCronRunVerdicts(runs: readonly CronRunRow[]): void {* Covers what the Cron surfaces cannot: a verdict that went stale while no* surface was polling, and a restored route/tab after an app restart, where no* surface ever evaluated the run (the in-memory verdicts start empty). Such a- * session is recognised by its cron run id. Any other session returns+ * session is recognised by `isCronRunSession`. Any other session returns* immediately without a request.** An unreadable row keeps a known verdict; an unknown run fails CLOSED — a@@ -103,7 +129,7 @@ export async function refreshCronRunWriteGate(): Promise<boolean> {const id = storedSessionId?.trim()- if (!id || !(isCronRunSessionId(id) || hasCronRunVerdict(id))) {+ if (!id || !(isCronRunSession(id) || hasCronRunVerdict(id))) {return false}diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.tsindex a8121f9a742..773b5caf08f 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts@@ -41,7 +41,7 @@ import { profileScopeForSessionOwner } from '@/store/session-request-router'import { $sessionStates, $sessionTiles } from '@/store/session-states'import type { SessionInfo } from '@/types/hermes'-import { isCronRunSessionId, refreshCronRunWriteGate } from '../../../cron/open-cron-run'+import { isCronRunSession, refreshCronRunWriteGate } from '../../../cron/open-cron-run'import type { ClientSessionState } from '../../../types'import { routeTargetFromToken, sessionContextDrift } from '../session-context-drift'import type { CreateBackendSessionForSend } from '../use-session-actions/create-overrides'@@ -328,7 +328,7 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {// after a restart (no verdict yet) is gated too. No-op for non-cron// sessions. If the user moved to another chat meanwhile, drop the send// rather than route it on a stale target — the draft stays.- if (isCronRunSessionId(targetStoredSessionId) || isCronRunReadOnly(targetStoredSessionId)) {+ if (isCronRunSession(targetStoredSessionId) || isCronRunReadOnly(targetStoredSessionId)) {const viewBeforeGate = selectedStoredSessionIdRef.currentawait refreshCronRunWriteGate(targetStoredSessionId, id =>diff --git a/gateway/session_cron.py b/gateway/session_cron.pyindex 3c6440d51e1..b680bd7662f 100644--- a/gateway/session_cron.py+++ b/gateway/session_cron.py@@ -12,6 +12,7 @@ from pathlib import Pathimport threadingfrom gateway.session_contract import Principal, SessionRef+from hermes_state_keys import CRON_PRINCIPAL_ID, cron_request_idfrom hermes_state_runtime import RuntimeStoreError, admit_session_input, get_session_admission_execution: ContextVar[tuple | None] = ContextVar('cron_owner_execution', default=None)@@ -43,7 +44,7 @@ def current_execution():def _actor(authority, actor):if actor is None:- return Principal('cron-owner', authority.profile_id,+ return Principal(CRON_PRINCIPAL_ID, authority.profile_id,frozenset({'session:create', 'session:submit', 'session:read', 'session:control'}), 'cron-ticker')if actor.profile_id != authority.profile_id:raise RuntimeStoreError('profile_mismatch')@@ -51,7 +52,7 @@ def _actor(authority, actor):raise RuntimeStoreError('permission_denied')# Cron fires belong to the profile scheduler, not the transport that observes# them. The same execution ID from ticker and CLI must dedupe together.- return Principal('cron-owner', authority.profile_id, actor.capabilities, actor.transport_id)+ return Principal(CRON_PRINCIPAL_ID, authority.profile_id, actor.capabilities, actor.transport_id)def _create(authority, actor, params):@@ -70,10 +71,15 @@ def _create(authority, actor, params):if (not isinstance(jid, str) or not jid or not isinstance(request_id, str)or not request_id or len(request_id) > 256 or (extra is not None and not isinstance(extra, str))):raise RuntimeStoreError('invalid_params')- request_id = 'cron:' + jid + ':' + request_id+ execution_id, request_id = request_id, cron_request_id(jid, request_id)sid = local_identity(authority.profile_id, actor.subject, request_id)if authority.db.get_session(sid) is not None:return restore_local_session(authority, sid), request_id+ if ':' in execution_id:+ # Fresh admissions only: ``cron:<job>:<execution>`` then splits at its one ``:`` after the+ # job. Ledger ids are hex, so only a hand-made id has one; an identity admitted before this+ # guard keeps its exact retry above, and run history files it by its stored policy.+ raise RuntimeStoreError('invalid_params')job = get_job(jid)if job is None or job.get('no_agent'):raise RuntimeStoreError('not_found')@@ -115,7 +121,7 @@ async def operation(authority, name, params, actor=None):or any(not isinstance(params[k], str) or not params[k] for k in ('job_id', 'request_id'))or (params['extra_prompt'] is not None and not isinstance(params['extra_prompt'], str))):raise RuntimeStoreError('invalid_params')- request_id = 'cron:' + params['job_id'] + ':' + params['request_id']+ request_id = cron_request_id(params['job_id'], params['request_id'])sid = local_identity(authority.profile_id, actor.subject, request_id)from hermes_state_runtime import list_session_admissionsrows = list_session_admissions(authority.db, session_id=sid, pending_only=False)@@ -197,8 +203,7 @@ async def rpc(connection, name, params):def scheduler_execution_id(job_id, request_id):"""The scheduler's execution id this admission carries: ``_create`` admits under``cron:<job>:<request_id>`` and the ticker's ``request_id`` IS its ``cron/executions`` row id."""- prefix = 'cron:' + job_id + ':'- return request_id.removeprefix(prefix)+ return request_id.removeprefix(cron_request_id(job_id, ''))def _run_identified(run_job, job, execution_id, **kwargs):diff --git a/hermes_cli/web_routers/cron.py b/hermes_cli/web_routers/cron.pyindex ddc7fadcd26..3992b9309ea 100644--- a/hermes_cli/web_routers/cron.py+++ b/hermes_cli/web_routers/cron.py@@ -7,6 +7,7 @@ late-binding seam so ``monkeypatch.setattr(web_server_cron, ...)`` keeps workingimport asyncioimport functools+import mathimport reimport timefrom contextlib import contextmanager@@ -25,6 +26,7 @@ from hermes_cli.web_server_cron import (from hermes_cli.web_models import AutomationBlueprintInstantiate, CronJobCreate, CronJobUpdatefrom hermes_cli.web_routers._common import log as _logfrom hermes_time import get_timezone as _get_timezone+from hermes_state_keys import legacy_cron_run_jobfrom hermes_constants import (get_hermes_home as _get_hermes_home,reset_hermes_home_override as _reset_hermes_home_override,@@ -82,7 +84,7 @@ def _job_owner_profile(job_id: str, profile: Optional[str]) -> Optional[str]:``profile`` is a caller *hint*, not proof of ownership: the Desktop listsjobs cross-profile (``?profile=all``) while its per-item calls carry theambient active profile. Trusting that hint opened a profile that does not- hold the job, so the ``cron_{job_id}_*`` id-range scan matched nothing and+ hold the job, so the job's run-session lookup matched nothing andanswered ``200 {"runs": []}`` — the UI rendered "No runs yet" for a jobthat had run many times (#115345). A hint that does hold the job stillwins, so deliberately scoped lookups (the same job id in two profiles,@@ -306,6 +308,7 @@ def _owner_profile_executions(canonical_job_id: str) -> list[dict[str, Any]]:if str(row.get("status") or "") not in ("completed", "failed", "unknown"):continueterminal.append({+ "id": str(row.get("id") or ""),"claimed_at": _iso_to_epoch(row.get("claimed_at")) or 0.0,"finished_at": _iso_to_epoch(row.get("finished_at")),"status": str(row.get("status") or ""),@@ -326,9 +329,11 @@ def _execution_contains(lands within ``[claimed_at, finished_at + grace]`` of THAT attempt (a still-open attempt has no ``finished_at``). Older attempts closed before this docwas written, which is what keeps a fast-firing job's status from bleeding- onto an earlier run's row.+ onto an earlier run's row. The doc's filename keeps whole seconds only, so+ the claim is floored to its second: an attempt claimed at ``:00.500`` that+ writes at ``:00.750`` files its doc as ``:00``."""- if started_at + 0.001 < attempt["claimed_at"]:+ if started_at + 0.001 < math.floor(attempt["claimed_at"]):return Falsefinish = attempt["finished_at"]return finish is None or started_at <= finish + grace_seconds@@ -356,7 +361,7 @@ def _list_cron_output_runs(output docs — one .md per fire under cron/output/<job_id>/ — are the onlyper-run record. Rows mirror /api/sessions shape with source='cron_output'so the frontend reuses SessionInfo; ids use a cron_output: prefix that can- never collide with SessionDB cron_{job_id}_* session ids.+ never collide with a SessionDB session id.Status comes from the execution ledger (one row per fire), matched to a docby claim window — never from ``last_run_at`` proximity, which mislabels an@@ -386,16 +391,21 @@ def _list_cron_output_runs(started_at = 0.0preview = _cron_output_run_preview(path)title = preview or "Script-only run"- for index, attempt in enumerate(executions):- if attempt["status"] not in ("completed", "failed"):- continue- if _execution_contains(attempt, started_at):- represented.add(index)- title = _execution_status_title(attempt["status"], attempt["error"], title)- break+ candidates = [+ (index, attempt) for index, attempt in enumerate(executions)+ if attempt["status"] in ("completed", "failed") and _execution_contains(attempt, started_at)+ ]+ if candidates:+ # Newest first: the latest attempt claimed by the doc's second is the likeliest writer.+ index, attempt = candidates[0]+ represented.add(index)+ title = _execution_status_title(attempt["status"], attempt["error"], title)runs.append({"id": f"cron_output:{canonical_job_id}:{path.stem}",**_cron_output_run_row(started_at, title, preview),+ # Internal: a doc never records its execution, so this is a window guess — every+ # attempt it could be, for the caller to pair with a session by time, never by id.+ "_execution_candidates": tuple(attempt["id"] for _, attempt in candidates),})# Terminal attempts whose output doc is gone (pruned, or the run never@@ -416,9 +426,9 @@ def _list_cron_output_runs(_execution_status_title(attempt["status"], error, "Script-only run"),error or None,),- # Internal: the attempt's claim window, so the caller can drop this- # row when a session already represents the same execution.- "_claim_window": (attempt["claimed_at"], attempt["finished_at"]),+ # Internal: the attempt itself (durable), so the caller drops this row+ # exactly when a session already represents the same execution.+ "_execution_id": attempt["id"],})runs.sort(key=lambda r: float(r.get("started_at") or 0), reverse=True)@@ -444,8 +454,7 @@ def _list_cron_output_runs(}]-_CRON_RUN_SESSION_ID = re.compile(r"^cron_(.+)_\d{8}_\d{6}$")-# The run's session row is written just AFTER its execution claim; the grace only+# A legacy run's session row is written just AFTER its execution claim; the grace only# absorbs float/ISO rounding between the two clocks on one host._OWNERSHIP_CLAIM_GRACE_SECONDS = 5.0@@ -469,11 +478,14 @@ def _run_owned_by(session: dict[str, Any], inflight: Optional[dict[str, Any]]) -``is_active`` is a 300s activity window, so a live run inside a long tool call(no heartbeat, no message) reads inactive exactly like a zombie whose processdied. Ownership is the durable answer: the job's in-flight attempt is held by a- live process and this session started under that claim. An older never-closed- run of the same job predates the claim, so it stays a zombie.+ live process and this session is that attempt's run. A unified-runtime run names+ its execution, so that is exact; a legacy run must have started under the claim,+ so an older never-closed run of the same job predates it and stays a zombie."""if not inflight or session.get("ended_at") is not None:return False+ if session.get("cron_execution_id"):+ return session["cron_execution_id"] == inflight.get("id")claimed_at = _iso_to_epoch(inflight.get("claimed_at"))try:started_at = float(session.get("started_at") or 0)@@ -487,36 +499,41 @@ def cron_run_scheduler_owned(session: dict[str, Any], profile: Optional[str] = NThe session-detail endpoint stamps this so a client re-checking a run italready has open (a restored tab, a send) gets the same answer as the runs list.+ A unified-runtime run's ``local-*`` id says nothing, so the caller stamps the+ row's ``cron_job_id`` / ``cron_execution_id`` (``SessionDB.cron_run_identity``)+ first; a legacy ``cron_{job_id}_{timestamp}`` id still names its job."""if session.get("source") != "cron":return None- match = _CRON_RUN_SESSION_ID.match(str(session.get("id") or ""))- if not match:+ job_id = session.get("cron_job_id") or legacy_cron_run_job(session.get("id"))+ if not job_id:return Noneif session.get("ended_at") is not None:return Falsewith _owner_home_scope(profile):- return _run_owned_by(session, _live_inflight_execution(match.group(1)))+ return _run_owned_by(session, _live_inflight_execution(job_id))def _list_cron_job_runs_sync(job_id: str, profile: Optional[str] = None, limit: int = 20):"""Run history for a cron job, newest first: agent sessions PLUS script-only fires.- Agent runs are ordinary sessions with id ``cron_{job_id}_{timestamp}`` (see- cron/scheduler.run_job); ``source='cron'`` plus the id prefix binds them to- this job. Backed by ``SessionDB.list_cron_job_runs`` — a bounded id-range- scan, so cost scales with the requested window, not total cron history.- Script-only (no_agent) jobs never write sessions; their per-fire output docs- (``_list_cron_output_runs``) fill the gaps. The two representations are- reconciled PER EXECUTION, not by branch: a job can switch modes without- changing its id (update_job supports no_agent on an existing record), so a- surviving historical agent session must not hide newer script-only fires- and a recent session must not hide older script output. Rows carrying the- same wall-clock execution (an agent fire writes BOTH a session and an- output doc) are de-duplicated by timestamp window; script-only rows that- match no session are added in. All owner-scoped reads (SessionDB, output- docs, execution ledger, filename timezone) run inside the owner's profile- scope so the dashboard's own zone/store is never borrowed cross-profile.+ Agent runs are ordinary ``source='cron'`` sessions: a legacy+ ``cron_{job_id}_{timestamp}`` id, or a unified-runtime ``local-*`` id bound to+ this job by its scheduler admission. Backed by ``SessionDB.list_cron_job_runs``+ — bounded index range scans, so cost scales with this job's runs, not total+ cron history. Script-only (no_agent) jobs never write sessions; their+ per-fire output docs (``_list_cron_output_runs``) fill the gaps. The two+ representations are reconciled PER EXECUTION, not by branch: a job can+ switch modes without changing its id (update_job supports no_agent on an+ existing record), so a surviving historical agent session must not hide+ newer script-only fires and a recent session must not hide older script+ output. Rows carrying the same execution (an agent fire writes BOTH a+ session and an output doc) are de-duplicated by execution id, or by+ timestamp window for a legacy session that names none; script-only rows+ that match no session are added in. All owner-scoped reads (SessionDB,+ output docs, execution ledger, filename timezone) run inside the owner's+ profile scope so the dashboard's own zone/store is never borrowed+ cross-profile."""selected = _job_owner_profile(job_id, profile)# job_id may be a human name; resolve to the canonical id used in run-session ids.@@ -562,19 +579,38 @@ def _reconcile_cron_runs(An agent fire writes BOTH a session and an output doc for the sameexecution; keeping both would double-render the run. Sessions carry the- richer record (tokens, message counts, chat navigation), so a doc row- within ``_SESSION_DOC_MATCH_SECONDS`` of a session row is the same- execution and the session wins. Doc rows matching no session are distinct- executions — script-only fires — and are kept. A session row must never be- dropped in favor of a doc: the doc is the fallback representation.+ richer record (tokens, message counts, chat navigation), so the session+ wins. Only a durable association pairs by id: a unified-runtime session+ names its execution and a ledger row IS its attempt, so a neighbouring fire+ inside the time window (one that failed before it created a session) keeps+ its own row. An output doc never records its execution, only a window guess+ (``_execution_candidates``), so it pairs by time: a doc within+ ``_SESSION_DOC_MATCH_SECONDS`` of a legacy session, or of a session whose+ execution is one of its candidates, is that session's execution (a doc no+ attempt claims is matched against every session). Doc rows matching no+ session are distinct executions — script-only fires — and are kept. A session+ row must never be dropped in favor of a doc: the doc is the fallback+ representation."""_SESSION_DOC_MATCH_SECONDS = 300.0+ executions = {s["cron_execution_id"] for s in session_runs if s.get("cron_execution_id")}+ legacy = [s for s in session_runs if not s.get("cron_execution_id")]merged = list(session_runs)for doc in doc_runs:+ candidates = doc.get("_execution_candidates")+ execution_id = doc.get("_execution_id")+ if candidates:+ window = legacy + [s for s in session_runs if s.get("cron_execution_id") in candidates]+ elif candidates is None and execution_id:+ if execution_id in executions:+ continue+ window = legacy+ else:+ window = session_runsdoc = {k: v for k, v in doc.items() if not k.startswith("_")}doc_ts = float(doc.get("started_at") or 0)- if any(_doc_matches_session(doc_ts, s, _SESSION_DOC_MATCH_SECONDS) for s in session_runs):+ if any(_doc_matches_session(doc_ts, s, _SESSION_DOC_MATCH_SECONDS) for s in window):continuemerged.append(doc)merged.sort(key=lambda r: float(r.get("started_at") or 0), reverse=True)diff --git a/hermes_cli/web_routers/sessions.py b/hermes_cli/web_routers/sessions.pyindex 1f175e13be1..d6a5cb947a1 100644--- a/hermes_cli/web_routers/sessions.py+++ b/hermes_cli/web_routers/sessions.py@@ -569,9 +569,12 @@ async def get_session_detail(session_id: str, profile: Optional[str] = None):session["profile"] = _serving_profile(profile)session["is_default_profile"] = session["profile"] == "default"# A cron run's liveness is scheduler ownership, not the 300s activity- # window (#88443): a run inside a long tool call is still owned.+ # window (#88443): a run inside a long tool call is still owned. A+ # unified-runtime run's local id names no job, so stamp its identity first.from hermes_cli.web_routers.cron import cron_run_scheduler_owned+ if session.get("source") == "cron":+ session.update(db.cron_run_identity(sid) or {})owned = cron_run_scheduler_owned(session, profile)if owned is not None:session["scheduler_owned"] = owneddiff --git a/hermes_state_common.py b/hermes_state_common.pyindex 9c8f2181cd5..ca8b040c936 100644--- a/hermes_state_common.py+++ b/hermes_state_common.py@@ -527,6 +527,13 @@ CREATE TABLE IF NOT EXISTS session_admissions ();CREATE INDEX IF NOT EXISTS session_admissions_pendingON session_admissions(target_session_id, status, seq);+-- Cron run history finds a job's unified-runtime runs by the scheduler principal's request ids+-- (``cron:<job>:<execution>``, hermes_state_keys.CRON_PRINCIPAL_ID); without this a lookup walked+-- every cron admission of every job. Partial: interactive turns, the bulk of admissions, pay+-- nothing for it. The constant leading column gives the planner equality + range over a covering+-- index, so it beats the UNIQUE autoindex's bare principal_id prefix even without ANALYZE stats.+CREATE INDEX IF NOT EXISTS idx_session_admissions_cron_request+ ON session_admissions(principal_id, request_id, target_session_id) WHERE principal_id = 'cron-owner';CREATE TABLE IF NOT EXISTS worker_executions (execution_id TEXT PRIMARY KEY,session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE RESTRICT,diff --git a/hermes_state_keys.py b/hermes_state_keys.pyindex 3fdddb71098..1a1339c1361 100644--- a/hermes_state_keys.py+++ b/hermes_state_keys.py@@ -6,6 +6,52 @@ The gateway modules that historically defined these re-export them from here."""import hashlibimport json+import re++# The profile scheduler's principal admits every cron fire under ``cron:<job>:<execution>``+# (``gateway/session_cron.py``). That request id is the pre-image of the run's ``local-*`` session+# id, so its admission row is the run's durable job/execution association. Runs from before the+# unified runtime were named ``cron_{job_id}_{YYYYmmdd_HHMMSS}`` (``cron/scheduler.py::run_job``).+CRON_PRINCIPAL_ID = 'cron-owner'+_CRON_REQUEST_PREFIX = 'cron:'+_LEGACY_CRON_RUN_ID = re.compile(r'^cron_(.+)_\d{8}_\d{6}$')+++def cron_request_id(job_id, execution_id):+ """The admission request id of one cron fire (``execution_id`` is its ledger row id)."""+ return f'{_CRON_REQUEST_PREFIX}{job_id}:{execution_id}'+++def cron_request_range(job_id):+ """Half-open ``[lo, hi)`` bounds of *job_id*'s cron request ids, for an index range scan."""+ lo = cron_request_id(job_id, '')+ return lo, lo[:-1] + chr(ord(lo[-1]) + 1)+++def cron_run_from_request(request_id, job_id=None):+ """``(job_id, execution_id)`` of a cron fire's request id, else None.++ A fresh fire's execution id never holds ``:``, so a request id with exactly one after the+ prefix splits there. More than one is ambiguous (a job id holding ``:``, or an execution id+ admitted with one before that was refused): only the *job_id* its stored policy names splits+ it, and must prefix it."""+ if not isinstance(request_id, str) or not request_id.startswith(_CRON_REQUEST_PREFIX):+ return None+ if job_id is None:+ rest = request_id[len(_CRON_REQUEST_PREFIX):]+ if rest.count(':') != 1:+ return None+ job_id, _, execution_id = rest.partition(':')+ else:+ prefix = cron_request_id(job_id, '')+ execution_id = request_id[len(prefix):] if request_id.startswith(prefix) else ''+ return (job_id, execution_id) if job_id and execution_id else None+++def legacy_cron_run_job(session_id):+ """The job id a pre-unified ``cron_{job_id}_{YYYYmmdd_HHMMSS}`` run session names, else None."""+ match = _LEGACY_CRON_RUN_ID.match(str(session_id or ''))+ return match.group(1) if match else Nonedef admission_fingerprint(*, canonical_target: str, payload: dict) -> str:diff --git a/hermes_state_portability.py b/hermes_state_portability.pyindex c2dbbd10da2..a0bf24ec784 100644--- a/hermes_state_portability.py+++ b/hermes_state_portability.py@@ -16,6 +16,8 @@ from agent.skill_commands import AUTO_LOAD_SCAFFOLD_SQL_LIKE, SKILL_SCAFFOLD_SQLfrom utils import safe_json_loadsfrom hermes_cli.timefmt import coerce_epochfrom hermes_state_ids import new_session_id+from hermes_state_keys import CRON_PRINCIPAL_ID, cron_request_range, cron_run_from_request, legacy_cron_run_job+from hermes_state_local import POLICY_PREFIXfrom hermes_state_common import SCHEMA_SQL, _shape_preview, _sql_preview_raw, _sql_session_last_activefrom hermes_state_messages import _parse_tool_calls, _tool_calls_countimport itertools@@ -87,6 +89,30 @@ def _rich_select(select_cols: str, where: str, tail: str = "", prompt_select: Op_PROMPT_RESOLVED_SQL = "COALESCE(sp.prompt, s.system_prompt) AS _system_prompt_resolved"+# One job's scheduler admissions (``:request_lo``/``:request_hi`` = cron_request_range). The principal+# is inlined so the partial index applies (a bound parameter cannot prove its WHERE). A request id+# whose only ``:`` after ``cron:`` ends the job id is unambiguous (fresh execution ids hold none);+# any other in the range (job ``a`` vs ``a:b``, or an execution id admitted with a ``:`` before that+# was refused) belongs to the job its creation receipt's policy names, never to a ``:`` split.+# A legacy id is the prefix plus exactly ``YYYYmmdd_HHMMSS``: the GLOB keeps job ``daily`` from+# claiming job ``daily_digest``'s ``cron_daily_digest_<ts>`` runs inside the same id range.+_CRON_POLICY_JOB_SQL = (+ "(SELECT CASE WHEN json_valid(r) THEN json_extract(r, '$.cron_job.id') END FROM"+ " (SELECT CASE WHEN json_valid(value) THEN json_extract(value, '$.policy.request_json') END AS r"+ f" FROM state_meta WHERE key = '{POLICY_PREFIX}' || target_session_id))")+_CRON_ADMISSION_SQL = (+ f"principal_id = '{CRON_PRINCIPAL_ID}' AND request_id >= :request_lo AND request_id < :request_hi"+ " AND ((instr(substr(request_id, 6), ':') = length(:request_lo) - 5"+ " AND instr(substr(request_id, length(:request_lo) + 1), ':') = 0)"+ f" OR {_CRON_POLICY_JOB_SQL} = :job_id)")+_CRON_RUN_IDS_SQL = (+ "SELECT id FROM sessions WHERE source = 'cron' AND id >= :prefix AND id < :prefix_hi"+ " AND substr(id, length(:prefix) + 1) GLOB '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]_[0-9][0-9][0-9][0-9][0-9][0-9]'"+ f" UNION ALL SELECT target_session_id FROM session_admissions WHERE {_CRON_ADMISSION_SQL}")+_CRON_EXECUTION_SQL = (+ "(SELECT substr(request_id, length(:request_lo) + 1) FROM session_admissions"+ f" WHERE target_session_id = s.id AND {_CRON_ADMISSION_SQL} LIMIT 1)")+def _export_timings(messages: list[dict[str, Any]], session_id: Optional[str] = None) -> dict[str, Any]:"""Text-free timing evidence for a session export.@@ -217,20 +243,48 @@ class SessionPortabilityMixin:for r in rows]def list_cron_job_runs(self, job_id: str, limit: int = 20, offset: int = 0) -> list[dict[str, Any]]:- """Run sessions of one cron job, newest first, in the ``list_sessions_rich`` row shape.- Cron runs are flat ``cron_{job_id}_{timestamp}`` sessions that never compress or- branch, so this skips ``list_sessions_rich``'s compression-chain CTE /- leading-wildcard ``id_query`` path (which seeds from EVERY ``source='cron'`` row)- for a ``[prefix, prefix_hi)`` id range scan that scales with the window."""+ """Run sessions of one cron job, newest first, in the ``list_sessions_rich`` row shape,+ stamped with ``cron_job_id`` and ``cron_execution_id`` (None for a pre-unified run).++ Pre-unified runs are flat ``cron_{job_id}_{timestamp}`` sessions: a ``[prefix,+ prefix_hi)`` id range. Unified-runtime runs keep their runtime-minted ``local-*`` id, which+ must not change (exact-retry recovery re-derives it), but the scheduler principal admitted+ each under ``cron:<job>:<execution>``: a range of ``idx_session_admissions_cron_request``.+ Both scans scale with this job's runs, never with total cron history or with every local+ session's policy receipt, and skip ``list_sessions_rich``'s compression-chain CTE.++ Limitation (legacy runs had it too): only a run's FIRST session is listed. A run that+ compressed continues in a child session this does not return, and the row's liveness+ (``scheduler_owned``) and detail identity follow that first session, not the tip."""prefix = f"cron_{job_id}_"# Half-open upper bound: bump the final byte so the range covers exactly the prefix.prefix_hi = prefix[:-1] + chr(ord(prefix[-1]) + 1)+ request_lo, request_hi = cron_request_range(job_id)query = _rich_select(- "s.*", "s.source = 'cron' AND s.id >= ? AND s.id < ?",- "\n ORDER BY s.started_at DESC, s.id DESC\n LIMIT ? OFFSET ?",+ f"s.*, {_CRON_EXECUTION_SQL} AS cron_execution_id", f"s.source = 'cron' AND s.id IN ({_CRON_RUN_IDS_SQL})",+ "\n ORDER BY s.started_at DESC, s.id DESC\n LIMIT :limit OFFSET :offset",prompt_select=f",\n {_PROMPT_RESOLVED_SQL}",)- return [self._rich_row(row) for row in self._read_rows(query, (prefix, prefix_hi, limit, offset))]+ rows = self._read_rows(query, {"prefix": prefix, "prefix_hi": prefix_hi, "request_lo": request_lo,+ "request_hi": request_hi, "job_id": job_id, "limit": limit, "offset": offset})+ return [{**self._rich_row(row), "cron_job_id": job_id} for row in rows]++ def cron_run_identity(self, session_id: str) -> Optional[dict[str, Any]]:+ """``{"cron_job_id", "cron_execution_id"}`` of a cron run session, else None: a legacy id+ names its job (no execution), a unified-runtime run is one probe of its scheduler admission+ (and, when its request id is ambiguous, of the job its creation receipt's policy names)."""+ legacy_job = legacy_cron_run_job(session_id)+ if legacy_job is not None:+ return {"cron_job_id": legacy_job, "cron_execution_id": None}+ rows = self._read_rows(+ "SELECT request_id, " + _CRON_POLICY_JOB_SQL + " AS policy_job FROM session_admissions"+ " WHERE principal_id = ? AND target_session_id = ? ORDER BY seq LIMIT 1", (CRON_PRINCIPAL_ID, session_id))+ run = None+ if rows:+ run = cron_run_from_request(rows[0]["request_id"])+ if run is None and isinstance(rows[0]["policy_job"], str):+ run = cron_run_from_request(rows[0]["request_id"], rows[0]["policy_job"])+ return {"cron_job_id": run[0], "cron_execution_id": run[1]} if run else Nonedef _get_session_rich_row(self, session_id: str, compact_rows: bool = False) -> Optional[dict[str, Any]]:"""One session with the ``list_sessions_rich`` enriched columns, or None.diff --git a/tests/hermes_cli/test_cron_run_history_sessions.py b/tests/hermes_cli/test_cron_run_history_sessions.pynew file mode 100644index 00000000000..3f6d7a0fa04--- /dev/null+++ b/tests/hermes_cli/test_cron_run_history_sessions.py@@ -0,0 +1,202 @@+"""Dashboard/Desktop run history for agent cron runs the unified gateway runtime creates (#138812).++A unified-runtime fire is a healthy ``source='cron'`` session under a runtime-minted ``local-*``+id. Run history used to find it only by the legacy ``cron_{job_id}_{timestamp}`` id, so the run+degraded to an inert ``cron_output`` doc row (no transcript, no usage, double-represented) and+session detail could not say whether the scheduler still owned it. These drive the real producer+(``gateway/session_cron.py``) over SQLite, the real execution ledger and output docs, and read+through the real routes in a temp default profile.+"""+from datetime import timedelta+from types import SimpleNamespace++import pytest++import hermes_cli.web_routers.cron as cron_routes+import hermes_cli.web_routers.sessions as session_routes+import hermes_time+from cron import executions, jobs+from gateway import run, session_cron+from gateway.config import GatewayConfig+from gateway.session import SessionStore+from gateway.session_authority import SessionAuthority+from hermes_state import SessionDB+from hermes_state_runtime import begin_runtime_epoch, claim_session_input, settle_session_input+++def owner(tmp_path, monkeypatch):+ """The default profile's gateway authority: admits cron fires through the real producer+ (without running an agent turn) into the state.db the dashboard routes read."""+ from hermes_cli import profiles++ home = tmp_path / '.hermes'+ (home / 'cron').mkdir(parents=True)+ (home / 'config.yaml').write_text('model: test-model\n', encoding='utf-8')+ monkeypatch.setattr(profiles, '_get_default_hermes_home', lambda: home)+ monkeypatch.setattr(profiles, '_get_profiles_root', lambda: home / 'profiles')+ monkeypatch.setenv('HERMES_HOME', str(home))+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'model': {}, 'platform_toolsets': {'cli': []}})+ db = SessionDB(home / 'state.db')+ runner = SimpleNamespace(_draining=False, session_store=SessionStore(home / 'sessions', GatewayConfig()),+ adapters={})+ authority = SessionAuthority(runner, profile_id=str(home), instance_id='test', db=db,+ epoch=begin_runtime_epoch(db, instance_id='test'))+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)+ runner.session_authority = authority+ yield authority+ db.close()+++def clock(monkeypatch):+ """Seconds added to the ledger's and the output writer's wall clock."""+ offset = {'seconds': 0.0}++ def shifted():+ return hermes_time.now() + timedelta(seconds=offset['seconds'])++ monkeypatch.setattr(executions, '_hermes_now', shifted)+ monkeypatch.setattr(jobs, '_hermes_now', shifted)+ return offset+++async def _start_fire(authority, job_id):+ """A scheduler fire as it starts: its running ledger row, then the owner admits and claims it."""+ execution_id = executions.create_execution(job_id, source='test')['id']+ executions.mark_execution_running(execution_id)+ receipt = await session_cron.operation(+ authority, 'submit', {'job_id': job_id, 'request_id': execution_id, 'extra_prompt': None})+ session_id = receipt['session_id']+ authority.db.append_message(session_id, role='user', content=f'report for {job_id}')+ claim = claim_session_input(authority.db, epoch=authority.epoch, session_id=session_id)+ return session_id, execution_id, claim+++def _close_run(authority, session_id, claim):+ """The owner's run finishes: the answer is written, the admission settled, the session ended."""+ authority.db.append_message(session_id, role='assistant', content='report done')+ settle_session_input(authority.db, epoch=authority.epoch, admission_id=claim['admission_id'],+ generation=claim['generation'], outcome='completed',+ result={'result': {'cron_result': [True, 'doc', 'report done', None]}, 'usage': {}})+ authority.db.end_session(session_id, 'cron_complete')+++def _runs(job_id):+ return cron_routes._list_cron_job_runs_sync(job_id, profile='default', limit=20)['runs']+++async def _detail(session_id):+ return await session_routes.get_session_detail(session_id, profile='default')+++async def test_unified_run_is_one_owned_session_row_and_detail_agrees(owner, clock):+ job = jobs.create_job(prompt='report', schedule='every 1h', deliver='local')['id']+ other = jobs.create_job(prompt='other report', schedule='every 1h', deliver='local')['id']+ session_id, execution_id, claim = await _start_fire(owner, job)+ await _start_fire(owner, other)++ # While it runs: the transcript is a row of this job only, owned by the scheduler.+ [running] = _runs(job)+ assert (running['id'], running['source'], running['scheduler_owned']) == (session_id, 'cron', True)+ detail = await _detail(session_id)+ assert detail.get('scheduler_owned') is True+ assert running.get('cron_execution_id') == execution_id+ assert (detail.get('cron_job_id'), detail.get('cron_execution_id')) == (job, execution_id)++ # Done: the agent fire's output doc is the same execution as its session, not a second row.+ _close_run(owner, session_id, claim)+ clock['seconds'] = 5+ jobs.save_job_output(job, '# Cron Job: report\n\nreport done')+ executions.finish_execution(execution_id, success=True)++ [finished] = _runs(job)+ assert (finished['id'], finished['source'], finished['message_count']) == (session_id, 'cron', 2)+ assert finished['scheduler_owned'] is False+ assert (await _detail(session_id))['scheduler_owned'] is False+++async def test_detail_still_recognises_legacy_runs_and_leaves_other_sessions_alone(owner):+ job = jobs.create_job(prompt='report', schedule='every 1h', deliver='local')['id']+ legacy = f'cron_{job}_20261011_120000'+ owner.db.create_session(legacy, source='cron')+ owner.db.end_session(legacy, 'cron_complete')+ owner.db.create_session('20261015_120000_abc123', source='cli')++ assert (await _detail(legacy))['scheduler_owned'] is False+ assert 'scheduler_owned' not in await _detail('20261015_120000_abc123')+ assert [r['id'] for r in _runs(job)] == [legacy]+++async def test_a_fire_that_failed_beside_a_unified_run_keeps_its_own_row(owner, clock):+ """Output rows pair with sessions per execution: the next fire failing a minute later, before+ it created a session, is its own run, not swallowed by its neighbour's time window."""+ job = jobs.create_job(prompt='report', schedule='every 1m', deliver='local')['id']+ session_id, first, claim = await _start_fire(owner, job)+ _close_run(owner, session_id, claim)+ clock['seconds'] = 20+ jobs.save_job_output(job, '# Cron Job: report\n\nreport done')+ executions.finish_execution(first, success=True)+ clock['seconds'] = 60+ second = executions.create_execution(job, source='test')['id']+ executions.mark_execution_running(second)+ clock['seconds'] = 70+ executions.finish_execution(second, success=False, error='owner_unavailable')++ runs = _runs(job)++ assert [r['source'] for r in runs] == ['cron_output', 'cron']+ assert runs[0]['title'].startswith('FAILED') and runs[0]['preview'] == 'owner_unavailable'+ assert (runs[1]['id'], runs[1]['cron_execution_id']) == (session_id, first)++[email protected]('neighbour_doc_survives', [True, False])+async def test_a_same_second_output_doc_is_not_pinned_on_the_earlier_execution(+ owner, monkeypatch, neighbour_doc_survives):+ """Output docs never record their execution; the filename keeps whole seconds only. An agent+ fire claimed at ``:00.500`` writing at ``:00.750`` files its doc as ``:00``, before its claim,+ while an earlier script-only fire that failed within the grace also spans that second. The+ guess must not decide the doc is that neighbour's: one row per execution, and the neighbour's+ failure keeps its own row."""+ import hermes_time+ from datetime import timedelta++ start = hermes_time.now().replace(microsecond=0) - timedelta(hours=1)+ wall = {'at': start}+ monkeypatch.setattr(executions, '_hermes_now', lambda: wall['at'])+ monkeypatch.setattr(jobs, '_hermes_now', lambda: wall['at'])++ def at(seconds):+ wall['at'] = start + timedelta(seconds=seconds)+ return wall['at'].timestamp()++ job = jobs.create_job(prompt='report', schedule='every 1m', deliver='local')['id']+ at(0)+ neighbour = executions.create_execution(job, source='test')['id'] # a script-only fire+ executions.mark_execution_running(neighbour)+ at(1)+ neighbour_doc = jobs.save_job_output(job, '# Cron Job: report\n\nscript failed')+ executions.finish_execution(neighbour, success=False, error='script_failed')+ if not neighbour_doc_survives:+ neighbour_doc.unlink()++ at(60.5) # the job switched to agent mode; its next fire is claimed mid-second+ session_id, fire, claim = await _start_fire(owner, job)+ _close_run(owner, session_id, claim)+ at(60.75)+ jobs.save_job_output(job, '# Cron Job: report\n\nreport done') # filed as second 60+ executions.finish_execution(fire, success=True)+ owner.db._conn.execute('UPDATE sessions SET started_at = ?, ended_at = ? WHERE id = ?',+ (start.timestamp() + 60.6, start.timestamp() + 60.9, session_id))+ owner.db._conn.commit()++ runs = _runs(job)++ assert [r['source'] for r in runs] == ['cron', 'cron_output'], runs+ assert (runs[0]['id'], runs[0]['cron_execution_id']) == (session_id, fire)+ assert runs[1]['title'].startswith('FAILED')+ assert ('script failed' if neighbour_doc_survives else 'script_failed') in runs[1]['preview']diff --git a/tests/hermes_state/test_cron_run_sessions.py b/tests/hermes_state/test_cron_run_sessions.pynew file mode 100644index 00000000000..2cb44401371--- /dev/null+++ b/tests/hermes_state/test_cron_run_sessions.py@@ -0,0 +1,156 @@+"""A cron job's run history includes the runs the unified gateway runtime creates (#138812).++Since the unified runtime, an agent fire is created through the session authority+(``gateway/session_cron.py``) under a runtime-minted ``local-*`` id; only runs from before it+carry ``cron_{job_id}_{timestamp}``. These drive that real producer over SQLite (admission only,+no agent turn) and read back through ``SessionDB.list_cron_job_runs``.+"""+import sqlite3+from types import SimpleNamespace++import pytest++from cron import executions, jobs+from gateway import run, session_cron+from gateway.config import GatewayConfig+from gateway.session import SessionStore+from gateway.session_authority import SessionAuthority+from hermes_state import SessionDB+from hermes_state_runtime import RuntimeStoreError, begin_runtime_epoch+++def owner(tmp_path, monkeypatch):+ """A real SessionAuthority over ``tmp_path/state.db`` that admits cron fires without running them."""+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ (tmp_path / 'config.yaml').write_text('model: test-model\n', encoding='utf-8')+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'model': {}, 'platform_toolsets': {'cli': []}})+ db = SessionDB(tmp_path / 'state.db')+ runner = SimpleNamespace(_draining=False, session_store=SessionStore(tmp_path / 'sessions', GatewayConfig()),+ adapters={})+ authority = SessionAuthority(runner, profile_id=str(tmp_path), instance_id='test', db=db,+ epoch=begin_runtime_epoch(db, instance_id='test'))+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)+ runner.session_authority = authority+ yield authority+ db.close()+++async def _fire(authority, job_id):+ """One scheduler fire through the real producer: its ledger row, then the owner's submit."""+ execution_id = executions.create_execution(job_id, source='test')['id']+ receipt = await session_cron.operation(+ authority, 'submit', {'job_id': job_id, 'request_id': execution_id, 'extra_prompt': None})+ authority.db.append_message(receipt['session_id'], role='user', content=f'run {job_id}')+ return receipt['session_id'], execution_id+++async def test_unified_runs_are_listed_with_legacy_runs_and_only_for_their_job(owner):+ db = owner.db+ alpha = jobs.create_job(prompt='alpha report', schedule='every 1h', deliver='local')['id']+ beta = jobs.create_job(prompt='beta report', schedule='every 1h', deliver='local')['id']+ legacy = f'cron_{alpha}_20261011_120000'+ db.create_session(legacy, source='cron') # a run from before the unified runtime+ db._conn.execute('UPDATE sessions SET started_at = started_at - 86400 WHERE id = ?', (legacy,))+ db._conn.commit()+ alpha_run, alpha_fire = await _fire(owner, alpha)+ beta_run, beta_fire = await _fire(owner, beta)+ assert alpha_run.startswith('local-') and beta_run.startswith('local-')++ alpha_runs = db.list_cron_job_runs(alpha)+ beta_runs = db.list_cron_job_runs(beta)++ assert [r['id'] for r in alpha_runs] == [alpha_run, legacy] # newest first+ assert [r['id'] for r in beta_runs] == [beta_run]+ assert [(r.get('cron_job_id'), r.get('cron_execution_id')) for r in alpha_runs] == [+ (alpha, alpha_fire), (alpha, None)]+ assert beta_runs[0].get('cron_execution_id') == beta_fire+ assert alpha_runs[0]['preview'] == f'run {alpha}'+ assert [r['id'] for r in db.list_cron_job_runs(alpha, limit=1, offset=1)] == [legacy]+++async def test_a_fresh_execution_id_with_a_colon_is_refused_before_it_can_misfile_a_run(owner):+ """``cron:<job>:<execution>`` splits at its last ``:``, so a fire ``x:y`` of job ``a`` would read+ as job ``a:x``: missing from ``a``'s history while its detail names another job."""+ job = jobs.create_job(prompt='report', schedule='every 1h', deliver='local')['id']+ params = {'job_id': job, 'request_id': 'fire:1', 'extra_prompt': None}+ with pytest.raises(RuntimeStoreError, match='invalid_params'):+ await session_cron.operation(owner, 'submit', params)+ assert await session_cron.operation(owner, 'recover', params) == {'status': 'missing', 'result': None}+ assert owner.db.list_cron_job_runs(job) == []+ assert owner.db.list_cron_job_runs(f'{job}:fire') == []+++class _PreUpgradeRequestId(str):+ """An execution id as the producer saw it before ``:`` was refused: the guard finds none."""++ def __contains__(self, item):+ return item != ':' and super().__contains__(item)+++async def test_an_execution_id_admitted_with_a_colon_before_the_upgrade_keeps_its_admission(owner):+ """A durable ``cron:<job>:fire:1`` admission from before the guard is still recovered and+ retried under its original identity: same admission back, a changed payload refused, nothing+ replayed, and history files it under its job by the stored policy, not the last ``:``."""+ job = jobs.create_job(prompt='report', schedule='every 1h', deliver='local')['id']+ params = {'job_id': job, 'request_id': 'fire:1', 'extra_prompt': 'extra'}+ receipt = await session_cron.operation(+ owner, 'submit', dict(params, request_id=_PreUpgradeRequestId('fire:1')))++ def admissions():+ return owner.db._conn.execute('SELECT admission_id, request_id FROM session_admissions').fetchall()+ before = [tuple(r) for r in admissions()]++ assert await session_cron.operation(owner, 'submit', params) == receipt+ recovered = await session_cron.operation(owner, 'recover', params)+ assert (recovered['session_id'], recovered['admission_id']) == (receipt['session_id'], receipt['admission_id'])+ for operation in ('submit', 'recover'):+ with pytest.raises(RuntimeStoreError, match='admission_conflict'):+ await session_cron.operation(owner, operation, dict(params, extra_prompt='changed'))+ assert [tuple(r) for r in admissions()] == before == [(receipt['admission_id'], f'cron:{job}:fire:1')]++ sid = receipt['session_id']+ assert [(r['id'], r['cron_job_id'], r['cron_execution_id']) for r in owner.db.list_cron_job_runs(job)] == [+ (sid, job, 'fire:1')]+ assert owner.db.list_cron_job_runs(f'{job}:fire') == []+ assert owner.db.cron_run_identity(sid) == {'cron_job_id': job, 'cron_execution_id': 'fire:1'}+++def test_legacy_runs_of_a_job_whose_id_extends_another_stay_with_their_own_job(tmp_path):+ """``cron_daily_`` is a prefix of job ``daily_digest``'s run ids too; only an exact+ ``YYYYmmdd_HHMMSS`` suffix makes a legacy run ``daily``'s."""+ with SessionDB(tmp_path / 'state.db') as db:+ db.create_session('cron_daily_20261011_120000', source='cron')+ db.create_session('cron_daily_digest_20261011_130000', source='cron')++ daily = db.list_cron_job_runs('daily')+ digest = db.list_cron_job_runs('daily_digest')++ assert [(r['id'], r['cron_job_id']) for r in daily] == [('cron_daily_20261011_120000', 'daily')]+ assert [(r['id'], r['cron_job_id']) for r in digest] == [('cron_daily_digest_20261011_130000', 'daily_digest')]+++def test_run_lookup_is_index_served_on_new_and_upgraded_stores(tmp_path, monkeypatch):+ """A job's unified runs come from an index range bounded by that job's runs, not from a scan+ that grows with every session. An older store gains the index on its next open."""+ path = tmp_path / 'state.db'+ with SessionDB(path):+ pass+ raw = sqlite3.connect(path)+ raw.execute('DROP INDEX IF EXISTS idx_session_admissions_cron_request') # an older store+ raw.commit()+ raw.close()+ with SessionDB(path): # reopening migrates it; doing it twice must be a no-op+ pass+ with SessionDB(path) as db:+ queries = []+ read_rows = db._read_rows+ monkeypatch.setattr(db, '_read_rows', lambda sql, params=(): queries.append((sql, params)) or read_rows(sql, params))+ assert db.list_cron_job_runs('alpha') == []+ [(sql, params)] = queries+ with db._read_ctx() as conn:+ plan = ' '.join(str(r[-1]) for r in conn.execute('EXPLAIN QUERY PLAN ' + sql, params))+ assert 'idx_session_admissions_cron_request' in plan, plandiff --git a/tests/hermes_state/test_hermes_state.py b/tests/hermes_state/test_hermes_state.pyindex 1926bfaccec..4946afb4f6f 100644--- a/tests/hermes_state/test_hermes_state.py+++ b/tests/hermes_state/test_hermes_state.py@@ -5131,7 +5131,7 @@ class TestListCronJobRuns:"""def _seed_run(self, db, job_id: str, idx: int, started_at: float):- sid = f"cron_{job_id}_{idx:08d}"+ sid = f"cron_{job_id}_20261011_{idx:06d}" # the scheduler's cron_{job}_{YYYYmmdd_HHMMSS}db.create_session(session_id=sid, source="cron")db.append_message(sid, role="user", content=f"run {idx} for {job_id}")db.append_message(sid, role="assistant", content="done")