Level 10Lesson 0โฑ๏ธ 150 min

Level 10 Capstone

Ship Dayflow, and Day 2: put the agent on a schedule on your own machine, then learn to look after it

The job

For twelve lessons you have run Dayflow by typing a command and reading what came back. The capstone removes both halves of that. Nobody starts it and nobody is watching when it finishes. By the end, a brief appears in a folder every morning, a notification tells you it is there, and you know what to do on the morning it does not.

Companion repo: posixplus/learn2exel-dayflow, branch main. New: dayflow/ship.py, dayflow/schedule.py, dayflow/vault.py,docs/RUNBOOK.md, and the commands run, schedule, doctor,health, backup, prune, secret. Output marked "real run" is from the course author's Mac, with paths shortened.
When you type the commandWhen a schedule runs it
You see an error and reactAn error nobody sees is the same as no error handling
You approve writes at the terminalThere is no terminal. Every write must wait.
You run it onceIt can fire twice, or while another run is going
Your shell has your environmentThe scheduler has almost none of it
You notice it got slow or expensiveIt can cost ten times as much for a month before anyone looks

A decision first: local, not a server

"Deploy" usually means a server. For Dayflow that would be the wrong first move. It is a single-user agent with a SQLite file and a Google token for one person's mail. Putting it on a server means Postgres in place of SQLite, a real secret store, an authenticated MCP endpoint in place of stdio, and your mail sitting on a machine that is not yours. Each of those is a real project, and none of them makes tomorrow's brief better.

So the capstone ships Dayflow where its data already lives: your own computer, on the operating system's scheduler. Everything you build here (an unattended entry point, preflight checks, health rules, a runbook) is exactly what a server deployment needs too. Only the scheduler and the secret store would change.

Part 1: an entry point for nobody

dayflow brief prints to a terminal. dayflow run is written for a caller that is not a person. It does five things the interactive command never needed:

PropertyWhy
Takes a lockThe scheduler can fire a missed job on wake while you are running one by hand. Two runs both pay, and both propose the same writes.
Runs at most once a dayIf today's brief exists, exit with code 2 and spend nothing.
Queues every writeThe gate from lesson 86, fixed to queue. The brief lists the exact dayflow approve commands.
Resumes instead of restartingLesson 91 left a run that died on an API outage resumable. The next start picks it up and does not pay for finished steps again.
Reports through a file and a notificationThe brief is written to a temporary file and renamed, so a reader never finds half of one. Every failure becomes a notification with a reason.
        except Exception as e:  # unattended: every failure becomes a message someone will see
            reason = str(e) if isinstance(e, (loop.LoopError, oauth.OAuthError)) else f"{type(e).__name__}: {e}"
            notifier("Dayflow failed", f"{reason[:180]}. Run: dayflow doctor")
            return Outcome(FAILED, reason)

        alerts = health(store, now=now())
        tmp = target.with_suffix(".md.tmp")
        tmp.write_text(_document(result.text, store=store, run_id=result.run_id, alerts=alerts), encoding="utf-8")
        os.replace(tmp, target)                      # never leave half a brief where a reader will find it

Exit codes are part of the interface now: 0 a brief was written, 1 it failed, 2 there was nothing to do. A scheduler, a wrapper script or a monitoring tool can act on those without parsing text.

Part 2: the schedule

On macOS the scheduler is launchd. A job is a small property-list file. Four decisions in it matter more than the syntax:

    return {
        "Label": LABEL,
        "ProgramArguments": [python, "-m", "dayflow.main", "run"],   # the exact interpreter, not `python` from a PATH launchd does not share
        "WorkingDirectory": str(workdir),                            # where .env, dayflow.db and briefs/ live
        "StartCalendarInterval": {"Hour": hour, "Minute": minute},
        "EnvironmentVariables": {"MOCK": "1" if mock else "0", "PATH": "/usr/bin:/bin:/usr/sbin:/sbin"},   # no secret: a plist is a plain file
        "StandardOutPath": log,
        "StandardErrorPath": log,
        "RunAtLoad": False,                                          # installing the schedule must not spend tokens
    }
real run
$ dayflow schedule install --at 07:30
installed: ~/Library/LaunchAgents/com.learn2exel.dayflow.plist
runs `dayflow run` daily at 07:30 in ~/Projects/.../learn2exel-dayflow (MOCK=0, real Google)
log: ~/Library/Logs/dayflow.log

$ dayflow schedule status
daily at 07:30
loaded by launchd: yes

$ dayflow schedule kick
started through launchd. Watch: tail -f ~/Library/Logs/dayflow.log

$ tail -2 ~/Library/Logs/dayflow.log
[Dayflow] Brief ready: 2026-11-13.md ยท 2 health alert(s)
2026-11-13 16:29:37 dayflow run: ok: wrote briefs/2026-11-13.md
โš ๏ธ
kick is the test that matters
dayflow run from your terminal proves the code works. It does not prove the schedule works, because your terminal has your PATH, your environment and your current folder, and launchd has none of them. dayflow schedule kick starts the job the way launchd will. A run that works when typed and fails when kicked is the most common deployment bug there is, and this is the cheapest place to find it.

status reports two separate facts: the file is installed, and launchd has loaded it. They can differ, and when they do nothing runs and nothing complains. On Linux,dayflow schedule print --cron prints a crontab line instead.

Part 3: secrets out of files

Lesson 87 kept the Google token in a file only you can read and called that the minimum. Every program you run can still read it, and so can a backup tool. The operating system's keychain encrypts the item and asks before a new program reads it.

real run
$ dayflow auth migrate --to keychain
Google token moved to the system keychain (service dayflow, item google-token); the file copy was deleted.
Now add this line to .env so every command looks there:
  DAYFLOW_TOKEN_STORE=keychain

$ dayflow auth login --drafts
signed in. granted: calendar.readonly, gmail.compose, gmail.readonly
token stored at the system keychain (service dayflow, item google-token)

The migration writes the new copy, reads it back, and only then deletes the old one. The API key can move the same way with dayflow secret set anthropic-api-key, which reads the value from a hidden prompt: never from the command line, where it would land in your shell history.

The check that mattered came next. After the token moved, the job was kicked through launchd again, and it produced a brief from real mail. So a scheduled job can read the keychain item:

real run, after the token moved to the keychain
$ dayflow schedule kick
$ tail -2 ~/Library/Logs/dayflow.log
[Dayflow] Brief ready: 2026-11-13.md ยท 1 health alert(s)
2026-11-13 16:36:11 dayflow run: ok: wrote briefs/2026-11-13.md

Part 4: doctor, and the bug it had

dayflow doctor checks everything an unattended run depends on, at a time when you are there to fix it. It never prints a secret, only whether one is present and where it came from.

real run
$ dayflow doctor --live
  ok   python           3.12.9 at ~/.pyenv/versions/3.12.9/bin/python3.12
  ok   api key          present, from the environment or .env
  ok   model            claude-sonnet-5-5
  ok   api call         one small request succeeded
  ok   mode             this shell is MOCK=1 (fixtures); the schedule runs MOCK=0 (real Google), so Google is checked too
  ok   google token     in the keychain; refresh token yes; scopes: calendar.readonly, gmail.compose, gmail.readonly
  ok   google refresh   Google issued a fresh access token
  ok   database         dayflow.db: integrity ok, writable
  ok   brief folder     ~/Projects/.../learn2exel-dayflow/briefs
  ok   backup folder    ~/Projects/.../learn2exel-dayflow/backups
  ok   disk             253 GB free
  ok   schedule         daily at 07:30; log ~/Library/Logs/dayflow.log
  warn health           3 of the last 10 briefs failed in 7 days. Latest: token budget exceeded at step 6: 424721 > 400000

ready, 1 warning(s)

That is the second version. The first real run of doctor printedmode: MOCK=1: fixtures, no Google access and skipped the Google checks completely. It was telling the truth about the shell it ran in, where .env says MOCK=1. The schedule runs with MOCK=0. A preflight check that inspects a different configuration from the one that will run is worse than no check, because it says "ready".

Doctor now reads the installed schedule and checks what it will run. This is the same mistake as lesson 87's approval that ran against the wrong backend, one layer up: two environments, and a tool that silently looked at the wrong one.

Part 5: Day 2

Day 1 is getting it running. Day 2 is every day after, when the question changes from "does it work?" to "is it still working, and would I know?" Lesson 90 gave youdayflow stats, which you have to remember to run. health turns the same data into a handful of sentences and attaches them to every brief, so the report comes to you.

RuleWhy this one
Two or more failed briefs in 7 daysOne failure is a bad morning. Two is a pattern.
A run still marked running after an hourIt crashed. It can be resumed.
Last brief above a dollar limit, or above twice the weekly medianAn absolute ceiling, and a relative one that catches drift
Approvals that expired unansweredThe agent proposed something and you never saw it
Google sign-in older than 6 daysApps in Testing mode are signed out at 7. Warn the day before.

Five rules, each one something you would act on. An alert you ignore trains you to ignore alerts, so the list is short on purpose. The very first real report broke that rule:

real run, first version
  warn health           the last brief cost $0.0110, more than twice the 7-day median $0.0000

A median of zero dollars. The database held runs from before lesson 90, which have no recorded cost, and the code counted "unknown" as "free". Lesson 90 had this exact rule for a single run: an unknown price must never print as $0.00. The capstone broke it in aggregate. Runs with no recorded cost are now left out, and the false alert is gone from the second doctor output above.

The alert that remains is true. Three briefs did fail that week, during lesson 87's first contact with a real inbox. It will age out after seven days, which is the right behaviour: health describes the recent past, and the recent past included a bad afternoon.

The database is your mailbox

dayflow.db holds every email body the model read, every brief and every proposal. Two commands follow from that. dayflow backup makes a consistent copy with SQLite's online backup API (copying the file while it is in use is not safe), keeps seven, and sets them to owner-only. It runs before every scheduled brief. dayflow prune --days 30 deletes the transcripts and brief text of old runs and keeps the token counts and costs, so your history of numbers survives and your history of mail does not.

The runbook

docs/RUNBOOK.md is written for the person who installed this six weeks ago and has forgotten how it works. It is organised by what you see, not by how the system is built: no brief this morning, the brief is wrong, it costs more than it used to. Every row ends in a command.

๐Ÿ–ฅ๏ธHANDS-ON EXERCISEโฑ 150 min

Your capstone: ship it

Do it on fixtures first (MOCK=1 costs about four cents a run), then on real mail if you connected Google in lesson 87.

  1. Run `pytest tests/test_ship.py -v`. Nothing in it calls launchctl, osascript or a keychain. Find how the tests replace each of those, and say why that also let the code be checked on Linux.
  2. Run `dayflow doctor`. Fix every FAIL. Then run `dayflow run` twice and `ls briefs`. Explain the second exit code.
  3. Read the plist before you install it: `dayflow schedule print --at 07:30`. Find the four decisions from Part 2. Is any secret in it?
  4. Install it for fixtures first: `dayflow schedule install --at 07:30 --mock`, then `dayflow schedule status`. Delete today's brief, run `dayflow schedule kick`, wait a minute, and read `~/Library/Logs/dayflow.log`. If it failed here but worked when typed, find out why before going on.
  5. Break it on purpose, three ways, and write down what you saw each time: rename .env and kick; run `DAYFLOW_FAULTS="read_inbox=always" dayflow run --force`; create briefs/.dayflow.lock by hand and run. Which produced a notification, which a degraded brief, which a skip?
  6. Move a secret: `pip install keyring`, `dayflow secret set anthropic-api-key`, remove the key from .env, then `dayflow doctor --live` and a kick. If you use Google: `dayflow auth migrate --to keychain` and kick again.
  7. Day 2 drill. Without looking at the code, use only `dayflow doctor`, `dayflow health`, `dayflow stats`, `dayflow trace` and the log to answer: what did yesterday's brief cost, did any tool fail, and is anything waiting for your approval?
  8. Add one health rule of your own, with its test first. Decide what you would do when it fires. If the answer is "nothing", do not add it.
  9. Let it run on its own for three mornings. Then run `dayflow stats` and `dayflow health`, and write five lines: what worked, what surprised you, what you would change before trusting it for a month.
  10. Write your own runbook entry for one failure you hit that docs/RUNBOOK.md does not cover.

What "Great" Looks Like

A strong capstone:
  • A brief has appeared on its own, on a schedule, at least three times, and you can show the log lines.
  • dayflow schedule kick works, not only dayflow run.
  • No secret is in the plist, in the repo, or in a screenshot. At least one lives in the keychain.
  • You made it fail three ways and can say what a person would have seen each time.
  • Every write it proposed waited for you. Nothing was created that you did not approve.
  • You can answer "what did it cost last week?" in one command.
  • You know how to turn it off, and you have tried it: dayflow schedule uninstall.

What was verified, and what was not

On a real MacResult
launchd install, status and kickWorked first time
A run through launchd on real Gmail and CalendarBrief written, twice
Google token moved to the Keychain, then read by the scheduled jobWorked
A fresh Google sign-in stored straight into the KeychainWorked
doctor --live: one API call and one Google token refreshBoth succeeded

Not verified, so not claimed:

  • That the job fires by itself at the scheduled time, and after the laptop has been asleep. It was started with kick.
  • That the macOS notification banner is shown. The log proves the notifier was called.
  • The API key in the Keychain. The verified runs read it from .env.
  • The cron path on Linux, and keyring on Windows or Linux.
  • Restoring from a backup, beyond the unit test that opens one and checks its integrity.

What You Have Learned in Level 10

  • L81 - The agent loop by hand: stop reasons, tool results, step and token limits
  • L82 - Tools as an API surface: strict schemas, one result envelope, idempotency keys
  • L83 - State: a checkpoint per step, resume without paying twice
  • L84 - The Claude Agent SDK: what a framework does for you, and what it hides
  • L85 - Orchestration: specialists, a synthesiser, and the contract between them
  • L86 - Permissions: allow, deny, ask; a queue a person works through
  • L87 - Real Google: OAuth by hand, least scope, and what fixtures hid
  • L88 - Security: injection, exfiltration, and controls that do not depend on the model behaving
  • L89 - Evals: rates with sample sizes, graders you test, a judge you calibrate
  • L90 - Observability and cost: one event per call, a trace, a price table, caching measured
  • L91 - Reliability: what to retry, what never to, and degrading honestly
  • L92 - MCP: the same tools and the same gate, served to someone else's model
You have built and shipped a production-shaped agent. Look at what kept happening across these lessons. The model was rarely the problem. It refused the attacks, degraded gracefully, and told the user what was waiting. What broke was everything around it: a budget sized for five emails, an approval run in the wrong place, a health check that counted unknown as free, a preflight that looked at the wrong configuration. Each one was found by running the real thing and reading what came back.

That is the craft. The loop is the small part. The engineering is the guards, the gates, the evals, the traces and the runbook around it, and the habit of not believing a result you have not looked behind.

Build the agent. Then build everything that lets you trust it.

๐Ÿง  Check your understanding

5 quick questions on Level 10. Answer each, then check your score.

1. An agent loop receives stop_reason "tool_use". What is the correct next step?
2. Why should side-effecting tools carry an idempotency key?
3. Where should untrusted content such as an email body be placed?
4. What does a trajectory eval assert on that an output eval does not?
5. A tool your agent depends on is down. Which is the reliability-engineering response?
๐Ÿ’ฌ

How was Level 10?

Your feedback helps improve this course. Takes 30 seconds.

Overall rating *

Select a star rating to submit.