Skip to content

feat(chat): run scheduled jobs on the minute tick (W3-01) - #2003

Merged
gkhngyk merged 11 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-schedule-worker
Nov 3, 2026
Merged

gkhngyk merged 11 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-schedule-worker

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

Chat's scheduled jobs (CHAT-12) now run by themselves on the server's minute tick, behind CHAT_AGENTIC. Stacked on #1990 (W3-DB, migrations 00457–00459): merge it first. Until then, this PR's diff also shows #1990's commit. No migration of its own, and no new env var (the tick uses CHAT_INTERNAL_SECRET, as the agents' tick does). Plan: Chat waves plan, W3-01.

Also stacked on #1994 (W2-03, which is on #1993): merge those first; conflicts with them are already resolved here.

There is no screen yet: the schedule card comes in W3-02 and the Scheduled page in W3-03. Until then a job is only a chat_schedules row, so there is no Help article in this PR.

Shared parts (refactor commit, no behaviour change)

  • The RRULE subset (DAILY / WEEKLY / MONTHLY on a time zone's clock) moves from agent-schedule.ts to lib/chat/schedule/rule.ts. agent-schedule.ts re-exports it, and nextJobRun adds a chat_schedules row's next slot. No rrule package.
  • openHeadlessRun (headless-run.ts) is taken out of openAgentRun. It writes the chat, the message, the answer, the Chat run and its state, in the same order as before. Agent runs use it; the agent tests pass unchanged.

The worker (lib/chat/schedule/worker.ts), each minute:

  • It settles open runs (Needs you, Paused · AI limit reached, done, failed), lets jobs paused at the AI limit go on, then runs the jobs that are due.
  • It claims a due job by moving next_run_at (or retry_at) from the value it read, so two workers run a slot only once. The unique (schedule_id, slot_at, attempt) in chat_schedule_runs is the backstop.
  • A recurring slot more than an hour late is skipped: missed slots aren't caught up. A one-time job runs late.
  • A workspace (or creator) with every run slot busy waits for the next minute.
  • Before each run it checks the job's creator again:
    • still an Admin or a Manager, and still able to use the job's brand (else the job turns off, owner_role);
    • the brand is still there (else missing_source), and the skill is still on (else skill_off);
    • the AI limit isn't used up (else the run is paused_cap and the job pauses with cap).
  • A read-only workspace skips the slot and leaves the job on. With Chat off, nothing is read or written. A slot whose job's last run is still open is skipped.
  • The run opens in the job's own chat, as its creator (openHeadlessRun): Queued, then claimRunSlot. It always runs on Auto · Normal (Wave 3 decision 11), with no session behind it.
  • A failed run is tried once more 10 minutes later. Three failures in a row turn the job off (failed). After the monthly reset, a job paused at the cap goes on from its next slot.

The tick

  • New POST /api/internal/chat/schedules/tick (CHAT_INTERNAL_SECRET; 404 with the new Chat off).
  • The server's existing minute cron (chat-agents.js) calls it right after the agents' tick, in the same minute. There is no second cron, and one tick failing doesn't stop the other.
  • node src/scripts/chat-agents-tick.js (development) now calls both.

Engine (thin hooks)

  • A job's own run is metered as feature schedule with its scheduleId (budget.ts meteredAs). The server passes p_schedule_id to reserve_chat_ai_usage. A person's own message in the job's chat stays theirs.
  • Nobody watches a job's run. A question takes its Recommended option (step "Nobody was watching · used {option}"), and the answer lists what was assumed at its top (schedule/unattended.ts).

Notes

Related issue

None. Chat waves plan, W3-01 (CHAT-12).

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

Unit tests:

  • schedule/worker.test.ts:
    • a due job runs in its own chat as its creator, on Auto · Normal, and moves to its next slot;
    • two workers run a slot once; a busy workspace waits; no catch-up past an hour;
    • the checks before each run: role, brand access, deleted brand, skill off, read-only, Chat off, AI limit, a run still open;
    • one retry after 10 minutes, off after 3 failures, a lost or stopped run;
    • paused at the cap, going on after the reset;
    • the driver runs with no session, so every change asks first.
  • schedule/rule.test.ts, schedule/unattended.test.ts, api/internal/chat/schedules/tick/route.test.ts, budget.test.ts (meteredAs), engine.test.ts (metering and the unattended question), subscription-guard-coverage.test.ts.
  • Server: chat-agents.test.js (the cron calls both ticks), chat-budget.test.js and internal-chat-budget.test.js (scheduleId).

Manually (dev database with #1990's migrations, CHAT_AGENTIC=true and CHAT_INTERNAL_SECRET set for web and server, web on :3000):

  1. Add a one-time job for the demo brand as the demo Admin (no screen yet):
    insert into chat_schedules
      (organization_id, kind, due_at, next_run_at, timezone, title, prompt, brand_id, created_by)
    values
      ('<demo org id>', 'once', now(), now(), 'Europe/Istanbul', 'Visibility check',
       'How did our AI visibility change this week?', '<demo brand id>', '<demo admin user id>');
  2. From server/, run node src/scripts/chat-agents-tick.js. It prints agents 200 … and then schedules 200 …, with one job started.
  3. The demo Admin's chat list has a new chat for the job, running the prompt. chat_schedule_runs has one row for the slot. A later tick follows its Chat run: done once the answer is ready, or needs_you while a change waits on its card.
  4. Run the tick again: the job doesn't run twice.

Checklist

  • Branch follows the naming convention
  • Commits follow Conventional Commits
  • yarn lint passes
  • yarn typecheck passes
  • yarn format:check passes
  • Changes are focused — one concern per PR
  • Help article updated under help/ (or no user-visible change)

CI passed on this branch (004b0ed), run on the fork (https://github.com/cihan-gyk/ansvisor/actions/runs/41440869086): schema is up to date; web format:check, lint, typecheck, all tests and yarn build pass; server lint, format:check and all tests pass.

🤖 Generated with Claude Code

cihan-gyk and others added 6 commits November 2, 2026 09:12
…3-DB, 00457–00459)

Chat's Wave 3 tables in one PR (one DB PR per wave), behind CHAT_AGENTIC:
nothing reads or writes them while the flag is off. Tables, types, tests
and the demo's coverage only; the code that uses them comes in W3-01,
W3-06 and W3-11. Every new table has row level security on; members only
ever read, anon gets nothing, and every write is the server's.

- 00457: chat_schedules (CHAT-12): once, recurring or a follow-up check;
  run at / ready by, due and next run, the RRULE and time zone; title,
  prompt or skill, the brand fixed at creation, the creator it acts as and
  its own chat; delivery to chat and/or email, recipients only people of
  the workspace (a trigger checks), change-only with the last fingerprint;
  mode, model, effort; on/off with the reason, failures in a row, the one
  retry; a follow-up check's target, metric and who set it (card or
  full_auto, the latter only for follow-up checks). A job whose brand or
  creator is deleted turns off (missing_source, owner_role) instead of
  running on without them. chat_schedule_runs: slot and attempt (unique,
  so a slot never runs twice), Run now, the Chat run and answer, status,
  parts done, fingerprint, usage as a share, email outcome.
  chat_conversations.schedule_id with origin 'schedule' (one live chat per
  job; it stays the creator's), prompt_improve_usage.schedule_id, and
  reserve_chat_ai_usage taking p_schedule_id (default null, old calls still
  match): the row is named by the chat's job, a job that isn't the chat's
  is refused. Creator and Admins read a job, within their brands.
- 00458: chat_skills (CHAT-13): name unique in the workspace in the
  format's rules, body up to 50 KB, licenses MIT, Apache-2.0,
  BSD-2-Clause, BSD-3-Clause, ISC (an import needs one), source user or
  import with the pinned commit and checksum, scan and removed parts,
  review status (only an approved skill can be on), private or workspace.
  Private or unapproved: creator and Admins; approved workspace skills:
  every member. chat_settings.disabled_skills for library skills.
- 00459: chat_memory_items (CHAT-14): Me, brand and workspace lines, 1–300
  characters, at most 4,000 a scope (a trigger under a lock per scope,
  deleted lines left out), one profile line a person, deleted_at for Undo;
  brand lines go with the brand, Me lines with the account and when the
  person leaves the workspace (trigger on profiles). Me: only its person;
  brand lines: brand access; workspace lines: every member.
  chat_settings.memory_enabled and chat_user_prefs.memory_enabled, both on.

web/src/types/supabase.ts carries the new tables and columns; schema.test.ts
checks the Wave 3 policies, limits, vocabularies, triggers and the hold's
signature from the SQL; brand-access-policies.test.js lists the new tables;
the demo coverage skips chat_schedules and chat_memory_items.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-09)

Each / menu shortcut (CHAT-08) now has a hidden playbook in skills/
(metadata.hidden: "true"): its allowed reads, default scope, output,
question rules and next moves, checked by the same format, scan and CI as
the library skills. The menu gains /start, /optimize, /opportunities and
/audit; "Create a report on" moves to /new-report, as /report is the
Weekly report skill's.

The composer sends shortcutId with the message while its trigger words
stay (rewritten, it drops), and keeps it on Retry. Home chips whose job
is a shortcut's send its id; chips for the focus areas' skills ask with
the skill's /name. The server takes the id only for a message that is
still that shortcut's, writes chat_messages.shortcut_id, loads the
playbook first as one of the run's three skill bodies, offers only the
reads in its data plan, and tells the model in one line what the plan
leaves out.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rt (W2-03)

Before work in several like parts (drafts, pages, tasks), the model calls
the engine's plan_parts with how many; the server counts how many the AI
limit left covers (fitChatUnits and POST /api/internal/chat/budget/fit,
each part one write step's worst case, an agent run's own cap included):
a count, never dollars.

All covered, the work goes on. None, the run pauses at the AI limit as
before. Some, a question card asks "Your remaining AI limit covers about
{k} of the {n} ...": Do the first {k} now (Recommended), Get more AI
credits (pauses at the limit) or Cancel (stops). With no one there (an
agent's or a scheduled run), the first {k} are done and filed and the run
stops at the AI limit as it ends. A skill's run is checked as it starts,
before anything is read. Nothing is checked on the workspace's own key.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…duled jobs

Move the RRULE subset (DAILY/WEEKLY/MONTHLY on a zone's clock) from
agent-schedule.ts to schedule/rule.ts, which agent-schedule.ts re-exports,
and add nextJobRun for a chat_schedules row. Extract openHeadlessRun
(headless-run.ts) from openAgentRun: the chat, the message, the answer,
the Chat run and its state, written in the same order; agent runs use it
unchanged. No behaviour change: the agent tests pass as they are.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Chat's scheduled jobs (CHAT-12) now run by themselves, behind
CHAT_AGENTIC. The server's minute cron calls the new
/api/internal/chat/schedules/tick (CHAT_INTERNAL_SECRET) right after the
agents' tick; it settles open runs, resumes jobs the AI limit paused and
runs the due ones (schedule/worker.ts):

- A due job is claimed by moving next_run_at (or retry_at) from what was
  read, so two workers run a slot once; chat_schedule_runs' unique slot
  and attempt is the backstop. A recurring slot over an hour late is
  skipped (no catch-up); a busy workspace waits for the next minute.
- Each run re-checks its creator: Admin or Manager and the brand still
  theirs (else owner_role), brand there (missing_source), skill on
  (skill_off), AI limit (paused_cap, the job pauses at cap). A read-only
  workspace skips the slot; with Chat off nothing is touched.
- The run opens in the job's own chat as its creator (openHeadlessRun),
  Queued then claimRunSlot, always Auto · Normal, with no session, so
  every change waits as a card.
- A failed run retries once 10 minutes on; 3 failures in a row turn the
  job off. After the reset a cap-paused job goes on at its next slot.

Engine (thin hooks): a job's own run is metered as feature 'schedule'
with its scheduleId (budget.ts meteredAs; the server passes
p_schedule_id), and a question in it takes the Recommended option and
lists it at the top of the answer (schedule/unattended.ts).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Nov 2, 2026
gkhngyk
gkhngyk previously approved these changes Nov 2, 2026

@gkhngyk gkhngyk 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.

LGTM

…heck hits

The fit check (fitChatUnits) took the smaller of what is left of the
month's AI limit and what an agent run's own cap leaves, but only returned
the count. The engine then paused every new cap path (a skill's run that
can't start, a job none of whose parts fit, Get more AI credits, and the
parts done with no one there) at the month's limit. For a triggered run
stopped by its own cap, the agent driver read capHit 'month' and paused
the whole agent until the month resets instead of ending the run as
"Stopped at its limit".

The server now returns which limit binds ('run' when the run's cap leaves
no more than the month, as reserveChatStep's run_cap), the route passes it
on, and the web client reads it (the month's when absent). The engine
pauses with that limit, keeping it on the parts card and on limitStop, as
modelStep already does for run_cap refusals.
# Conflicts:
#	help/chat/chat.md
#	server/src/lib/chat-budget.test.js
#	server/src/routes/internal-chat-budget.js
#	server/src/routes/internal-chat-budget.test.js
#	web/messages/en.json
#	web/src/lib/chat/engine.test.ts
#	web/src/lib/chat/engine.ts
# Conflicts:
#	server/src/lib/brand-access-policies.test.js
#	server/src/lib/chat-budget.js
#	supabase/schema.sql
#	web/src/lib/chat/agent-driver.ts
#	web/src/lib/chat/schema.test.ts
#	web/src/types/supabase.ts
@github-actions github-actions Bot removed the needs-migration Adds or edits a migration — apply it to the hosted database label Nov 2, 2026
gkhngyk
gkhngyk previously approved these changes Nov 2, 2026
# Conflicts:
#	help/chat/chat.md
#	server/src/lib/chat-budget.test.js
#	web/messages/en.json
#	web/src/lib/chat/budget.test.ts
#	web/src/lib/chat/engine.test.ts
#	web/src/lib/chat/engine.ts

@gkhngyk gkhngyk 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.

LGTM

@gkhngyk
gkhngyk merged commit d60ac0a into ansvisor:main Nov 3, 2026
5 checks passed
cihan-gyk added a commit to cihan-gyk/ansvisor that referenced this pull request Nov 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants