Skip to content

cron: persist last_fired, append output to daily memory, post to channels - #79

Merged
FMXExpress merged 2 commits into
mainfrom
claude/cron-state-and-sinks
May 29, 2026
Merged

FMXExpress merged 2 commits into
mainfrom
claude/cron-state-and-sinks

Conversation

@FMXExpress

Copy link
Copy Markdown
Owner

The cron scheduler used to be best-effort: a 2-minute look-back window meant any downtime longer than that silently skipped jobs (and restarts within the window could double-fire them), and the unit's docstring promised "write output to the memory store for the cron session, and optionally post to a channel" — neither of which was actually wired. Both fixed here.

What landed

PasClaw.Cron.State — last_fired persistence

TCronState loads/saves a per-id map at $PASCLAW_HOME/workspace/cron/state.json:

{ "entries": [
    { "id": "daily-summary",  "last_fired": 1700009999 },
    { "id": "ping-discord",   "last_fired": 1700010500 }
] }

Atomic writes via temp + rename — a crash mid-save leaves the previous state intact rather than producing half-written JSON. Array-of-objects shape because TJsonObject doesn't expose key enumeration; sticking with ChildArray + ItemObject keeps it on the cross-target abstraction.

PasClaw.Cron.Sinks — memory write + channel post

Sink What it does
AppendCronToDaily(Id, Skill, Output) Appends a dated section to workspace/memory/<today>.md so the FTS5 memory index picks it up and BuildMemorySection auto-injects it on subsequent turns. Truncated to 2 KB; the full string still goes to the gateway log.
PostCronToChannel(Kind, Target, Text) Dispatches to the existing outbound adapters: TDiscordWebhook, TSlackWebhook, TTeamsWebhook, TGenericWebhook, TLinePush, TWhatsAppPush. Webhook-style kinds use the URL as Target; LINE and WhatsApp pull their credentials from the same env vars pasclaw post uses.

Each failure logs warn and returns False so a Slack outage doesn't block the memory write and vice versa.

PasClaw.Cron.Scheduler — wired together

RunOnce now anchors NextFireAfter on the persisted last-fired time (or Now - 60s for a brand-new entry — so a freshly-added cron doesn't backfire for every minute of history). If a fire was missed, NextFireAfter returns the earliest missed slot and we fire exactly once; subsequent ticks catch up the rest. last_fired is persisted regardless of skill success so a permanently-failing job doesn't retry on every tick forever — fix the skill, the next due slot fires.

After a successful fire RunOnce calls AppendCronToDaily and, if the entry has a ChannelKind, PostCronToChannel.

TCronEntry + CLI

TCronEntry = record
  Id, Spec, Skill, Args, ChannelKind, ChannelTarget: string;
  Enabled: Boolean;
end;

CronToJSON only emits the new fields when non-empty so existing config.json files round-trip byte-identical; the parser defaults both to '' so older configs read as channel-disabled.

pasclaw cron add daily-summary "0 9 * * *" summarize "workspace/memory"
pasclaw cron add ping-discord  "*/15 * * * *" healthcheck \
  --channel discord:https://discord.com/api/webhooks/...
pasclaw cron add line-status   "0 * * * *" status_skill \
  --channel line:U1234abcd

Help text grows the list of valid kinds (discord / slack / teams / webhook / line / whatsapp). Malformed --channel values (missing : separator) error out instead of silently storing a broken entry.

Verification

  • make — clean build under FPC 3.2.2.
  • Standalone state smoke test — 7 cases: empty load, set, overwrite, save, round-trip via a fresh instance. All pass.
  • pasclaw cron help shows --channel. Pre-existing list / add / disable / enable / remove byte-identical otherwise. pasclaw --help unchanged.

Notable trade-offs

  • No durable queue, no retries. A failed channel post is logged and dropped. Cron's natural cadence (next tick on the schedule) is the retry mechanism.
  • No backpressure. If a skill takes longer than the 30s tick, the scheduler's single thread is still busy and the next tick is delayed. That's pre-existing; not addressed here.
  • last_fired is per cron id, not per (id, slot). If you rename a cron, the new id starts cold (correct) but the old state file entry sticks around forever (small leak; cleaned by hand).

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon


Generated by Claude Code

…nels

The cron scheduler used to be best-effort: a 2-minute look-back
window meant any downtime longer than that silently skipped jobs
(and restarts within the window double-fired them), and the unit's
docstring promised "write output to the memory store for the cron
session, and optionally post to a channel" — neither of which was
actually wired. Both are fixed here.

src/pkg/cron/PasClaw.Cron.State.pas
  TCronState: load / save / GetLastFired / SetLastFired backed by
  <home>/workspace/cron/state.json. Format is
    { "entries": [ { "id": "...", "last_fired": <unix-s> }, ... ] }
  because TJsonObject doesn't expose key enumeration (an
  array-of-objects shape uses ChildArray + ItemObject which are
  already on the abstraction). Writes are atomic via temp + rename
  so a crash mid-save leaves the previous state intact.

src/pkg/cron/PasClaw.Cron.Sinks.pas
  AppendCronToDaily(Id, Skill, Output) appends a dated section to
  workspace/memory/<today>.md so the FTS5 memory index picks it up
  and BuildMemorySection auto-injects it on subsequent turns. Output
  is truncated to MAX_CRON_OUTPUT_TO_MEMORY (2 KB) to keep daily
  notes readable; the full string still goes to the gateway log.

  PostCronToChannel(Kind, Target, Text) dispatches to the existing
  outbound adapters (TDiscordWebhook, TSlackWebhook, TTeamsWebhook,
  TGenericWebhook, TLinePush, TWhatsAppPush). Webhook-style kinds
  take the URL as Target; LINE and WhatsApp pull their credentials
  from the same env vars `pasclaw post` uses ($PASCLAW_LINE_TOKEN,
  $PASCLAW_WHATSAPP_TOKEN, $PASCLAW_WHATSAPP_PHONE_ID). Each
  failure logs warn and returns False so a Slack outage doesn't
  block the memory write and vice versa.

src/pkg/cron/PasClaw.Cron.Scheduler.pas
  RunOnce now anchors NextFireAfter on the persisted last-fired time
  (or Now-60s for a brand-new entry — so a freshly-added cron
  doesn't backfire for every minute of history). If a fire was
  missed, NextFireAfter returns the earliest missed slot and we fire
  exactly once; subsequent ticks catch up the rest. last_fired is
  persisted regardless of skill success so a permanently-failing
  job doesn't retry on every tick forever — fix the skill, the
  next due slot fires.

  After a successful fire RunOnce calls AppendCronToDaily and, if
  the entry has a ChannelKind, PostCronToChannel.

src/pkg/config/PasClaw.Config.pas
  TCronEntry gains ChannelKind + ChannelTarget. CronToJSON only emits
  the new fields when non-empty so existing config.json files round-
  trip byte-identical; the parser defaults both to '' so older
  config.json reads as channel-disabled.

src/cmd/PasClaw.Cmd.Cron.pas
  `pasclaw cron add` accepts an optional `--channel <kind>:<target>`
  arg anywhere after the required positional args. Help text grows
  the list of valid kinds. ColonPos <= 1 means "no kind before the
  colon" — error out instead of silently storing a malformed entry.

src/pasclaw/PasClaw.dproj
  DCCReference entries for the two new units.

README.md
  Cron section gains channel-add examples and a paragraph explaining
  the persistence + memory-write + channel-post behavior so users
  know cron isn't best-effort anymore.

Verified locally:
  make builds clean under FPC 3.2.2.
  Standalone state smoke (7 cases: empty load, set, overwrite, save,
  round-trip via a fresh instance) — all pass.
  `pasclaw cron` help shows --channel; pre-existing
  list/add/disable/enable/remove byte-identical otherwise.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1d95035cc4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/pkg/cron/PasClaw.Cron.Scheduler.pas Outdated

{ Persist last-fired regardless of skill success — we don't want
a permanently-failing job to retry on every tick forever. }
State.SetLastFired(Entry.Id, DateTimeToUnix(Now_));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Record the fired slot instead of current time

When the scheduler has been down long enough to miss multiple scheduled slots, this stores Now_ as last_fired after running only the earliest missed Next slot. On the next tick NextFireAfter starts from the current time rather than from that fired slot, so all intervening missed runs are skipped instead of being caught up one per tick; e.g. an hourly job last fired yesterday will run once and then jump to today, dropping the rest of yesterday's slots.

Useful? React with 👍 / 👎.

Comment thread src/pkg/cron/PasClaw.Cron.State.pas Outdated
Comment on lines +163 to +164
if FileExists(FPath) then DeleteFile(FPath);
if not RenameFile(Tmp, FPath) then

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve the old state until the replacement is installed

If the process crashes after DeleteFile(FPath) or if RenameFile fails after the delete, the existing state.json is lost and the next scheduler startup treats every cron entry as never fired. That can re-fire or skip jobs incorrectly after exactly the crash/failure scenario this state file is meant to survive; the replacement should be installed without removing the only durable copy first.

Useful? React with 👍 / 👎.

Two P2s on PR #79, both material:

P2 #1: SetLastFired(DateTimeToUnix(Now_)) after firing the earliest
       missed slot means the next tick's NextFireAfter starts from
       "now" and walks forward to a FUTURE slot, silently dropping
       every intervening missed slot. Stamp the SLOT we just handled
       (Next) instead — now subsequent ticks find the next missed
       slot and fire it, one per tick, until caught up. This is the
       behaviour the PR description claimed in the first place.

P2 #2: Save sequence was
         WriteFileText(Tmp); DeleteFile(FPath); RenameFile(Tmp,FPath);
       which opens a window where a crash (or rename failure) leaves
       neither FPath nor a recoverable copy — exactly the failure
       mode the state file was supposed to survive. Fix with a
       backup-file dance that keeps a known-good copy at every
       point:
         1. WriteFileText(Tmp)
         2. Clear stale .bak from a prior aborted save
         3. RenameFile(FPath -> .bak)  (skip if no current state)
         4. RenameFile(Tmp -> FPath)
         5. DeleteFile(.bak)
       If step 4 fails, restore .bak so the previous state survives.
       Load checks for .bak when FPath is missing and recovers from
       it, then promotes it back to the primary path so a future
       clean Save doesn't have to handle the .bak existing. No
       IFDEFs needed; works the same on POSIX rename (atomic) and
       Windows RenameFile (which fails on existing destination —
       the .bak clear in step 2 avoids that).

Standalone recovery smoke covers the new paths:
  - normal save leaves no .bak (success path cleanup)
  - second save still no .bak (dance idempotent)
  - state.json absent + .bak present → Load recovers AND promotes
  - stale .bak from aborted save → cleared on next Save
  - round-trip survives the dance with the latest value
11 assertions, all pass.

https://claude.ai/code/session_01TBcLtmpj7dqA5tyFbGnQon
@FMXExpress
FMXExpress merged commit 1f35240 into main May 29, 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