v0.23.0: Routine, first public version

This commit is contained in:
2026-11-15 02:22:09 -08:00
commit 5ea848bddc
285 changed files with 23886 additions and 0 deletions
+218
View File
@@ -0,0 +1,218 @@
#!/usr/bin/env python3
"""Fill a scratch ROUTINE_HOME with a believable FAKE history, for testing without touching anyone's real data.
python3 tools/fake_history.py DIR [--days 400] [--seed 1] [--force]
ROUTINE_HOME=DIR python3 -m routine
Writes DIR/schedule.json (its own made-up routine, FAKE_SCHEDULE below: blocks, sub-tasks, a
weekend block, weekday-only tasks, calm tasks, a suggestion), DIR/routine.db (DAYS days up to today:
ticks, skips, misses, sick days, notes of every length, a play log, long streaks with cheat days
used) and DIR/config.json (no sync token: nothing syncs). Today is part done. A few tasks sit one tick short of a streak level today
(it prints which), so ticking them by hand plays a streak animation. Deterministic per --seed.
Never point it at the real data folder (~/.local/share/routine, ~/Library/Application Support/Routine): it refuses.
"""
import argparse
import datetime as dt
import json
import os
import random
import sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
WORDS = ("slept well tired team meeting long walk rain sun garden tomatoes friends dinner pasta phone call bike "
"fixed the shelf read a chapter wrote code bug finally inbox zero coffee too much tea quiet day busy "
"errands bank post office sore back stretched swam cold water laundry cleaned kitchen idea for a project "
"talked with neighbours market bread cheese movie late night early start headache better now").split()
FAKE_SCHEDULE = {"rev": 3, "dayStartsAt": 4, "blocks": [
{"id": "am", "label": "Morning", "start": 7, "end": 9, "color": "#FFE08A", "items": [
{"id": "water", "label": "glass of water"},
{"id": "stretch", "label": "stretch", "items": [{"id": "tip", "label": "a few minutes is plenty", "hint": True}]},
{"id": "plan", "label": "plan the day", "items": [
{"id": "calendar", "label": "look at the calendar"},
{"id": "three", "label": "pick three things", "items": [{"id": "small", "label": "one of them small"}]}]},
{"id": "cat", "label": "feed the cat"},
{"id": "tea", "label": "make tea"},
{"id": "weather", "label": "check the weather"},
{"id": "windows", "label": "open the windows"}]},
{"id": "work", "label": "Work", "start": 9, "end": 17, "color": "#B8DAFF", "items": [
{"id": "inbox", "label": "inbox"},
{"id": "focus", "label": "focus hour", "items": [{"id": "drawer", "label": "phone in a drawer"}]},
{"id": "standup", "label": "stand up and move"},
{"id": "break", "label": "lunch break", "items": [{"id": "away", "label": "away from the desk"}]},
{"id": "tomorrow", "label": "write tomorrow's list"},
{"id": "plants", "label": "water the plants", "days": [1, 4]},
{"id": "backup", "label": "back up the laptop", "days": [5]},
{"id": "review", "label": "review the week", "days": [5]}]},
{"id": "errands", "label": "Errands", "start": 17, "end": 19, "color": "#FFC9A8", "items": [
{"id": "post", "label": "post and parcels"},
{"id": "shop", "label": "groceries", "days": [2, 5], "items": [{"id": "bags", "label": "bring the bags"}]},
{"id": "bins", "label": "bins out", "days": [3]}]},
{"id": "weekend", "label": "Weekend", "start": 10, "end": 13, "color": "#B5EBC8", "days": [0, 6], "items": [
{"id": "walk", "label": "long walk"},
{"id": "friend", "label": "call a friend"}]},
{"id": "eve", "label": "Evening", "start": 19, "end": 23, "color": "#D9C2FF", "items": [
{"id": "cook", "label": "cook dinner"},
{"id": "tidy", "label": "tidy the kitchen"},
{"id": "wash", "label": "wash up"},
{"id": "clothes", "label": "lay out clothes"},
{"id": "floss", "label": "floss"},
{"id": "alarm", "label": "set an alarm"},
{"id": "charge", "label": "phone on charge, out of reach"},
{"id": "lights", "label": "lights low"},
{"id": "pages", "label": "a few pages of a book"}]}]}
CALM = ["am/windows", "eve/lights", "eve/pages"] # marked calm in the fake schedule
SHORT = [("am/water", 7), ("eve/cook", 21), ("work/inbox", 42), ("eve/pages", 7),
("am/stretch", 66)] # one tick short of these today
RELIABLE = ("am/water", "eve/floss") # done nearly every day
LONG = "eve/floss" # a long streak with cheat days used
def sentence(rng):
n = rng.randint(4, 14)
w = [rng.choice(WORDS) for _ in range(n)]
return " ".join(w).capitalize() + rng.choice(".....!?")
def note(rng):
r = rng.random()
if r < 0.35:
return ""
if r < 0.7:
return sentence(rng)
if r < 0.92:
return " ".join(sentence(rng) for _ in range(rng.randint(2, 5)))
return "\n\n".join(" ".join(sentence(rng) for _ in range(rng.randint(3, 6))) for _ in range(rng.randint(2, 4)))
def fake_schedule():
s = json.loads(json.dumps(FAKE_SCHEDULE))
for b in s["blocks"]:
for it in b["items"]:
if b["id"] + "/" + it["id"] in CALM:
it["calm"] = True
return s
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("dir")
ap.add_argument("--days", type=int, default=400)
ap.add_argument("--seed", type=int, default=1)
ap.add_argument("--force", action="store_true", help="replace a fake routine.db already there")
a = ap.parse_args()
home = os.path.realpath(a.dir)
from routine import system
env = {k: v for k, v in os.environ.items() if k != "ROUTINE_HOME"}
real = {os.path.realpath(f(plat, env)) for plat in ("linux", "darwin") for f in (system.data_dir, system.config_dir)}
if home in real:
raise SystemExit("refusing: that's the real data folder")
os.makedirs(home, exist_ok=True)
db = os.path.join(home, "routine.db")
if os.path.exists(db):
if not a.force:
raise SystemExit("%s exists: --force to replace it" % db)
os.remove(db)
os.environ["ROUTINE_HOME"] = home
from routine import model
from routine.store import Store
rng = random.Random(a.seed)
sch = fake_schedule()
with open(os.path.join(home, "schedule.json"), "w") as f:
json.dump(sch, f, indent=2)
with open(os.path.join(home, "config.json"), "w") as f:
json.dump({"sync_token": "", "sync_url": ""}, f)
with open(os.path.join(ROOT, "shared", "animations.json")) as f:
anims = json.load(f)
names = [x["name"] for x in anims["animations"]]
calm_names = [x["name"] for x in anims.get("calm", [])] or names
today = model.routine_date(sch)
first = today - dt.timedelta(days=a.days - 1)
days = []
reliab = {}
short = dict(SHORT)
for k in range(a.days):
d = first + dt.timedelta(days=k)
day = model.new_day(sch, d)
sick = rng.random() < 0.04
lazy = rng.random() < 0.12 # an off day: more misses
is_today = d == today
tasks = [it for b in day["blocks"] for it in b["items"] if not it.get("hint")]
hour = 7.0
for it in tasks:
iid = it["id"]
if iid not in reliab:
reliab[iid] = 0.97 if iid in RELIABLE else rng.uniform(0.45, 0.95)
p = reliab[iid] * (0.15 if sick else 0.7 if lazy else 1.0)
if is_today:
p = p if hour < 12 else 0.0 # today: only the morning so far
r = rng.random()
s = model.DONE if r < p else model.SKIPPED if r < p + 0.04 else model.PENDING
if s == model.PENDING and it["id"].count("/") > 1:
parent = it["id"].rpartition("/")[0]
if model.state(day, parent) == model.DONE: # ticked along with its parent
s = model.DONE
if s != model.PENDING:
day["states"][iid] = {"s": s, "t": int(dt.datetime(d.year, d.month, d.day, int(hour) % 24).timestamp() * 1000)}
hour += 0.25
# the play log: one per task ticked by hand (not those ticked along with a parent)
n = 0
for it in tasks:
iid = it["id"]
par = iid.rpartition("/")[0]
if model.state(day, iid) == model.DONE and not (par.count("/") and model.state(day, par) == model.DONE):
lo, hi, set_no, _ = model.anim_set(n, anims["sets"])
if it.get("calm"):
pick, set_no = rng.choice(calm_names), model.CALM_SET
else:
pick = rng.choice(names[lo:hi])
day.setdefault("plays", []).append({"t": day["states"][iid]["t"], "a": pick, "i": iid, "s": set_no})
n += 1
if not is_today:
day["note"] = {"text": note(rng), "t": 1}
days.append(day)
# streaks one short of a level today: done for the last (level - 1) days the task was on, and
# two misses in a row before that (so no cheat day can join it to an older run); pending today
for iid, level in short.items():
on = [dd for dd in days[:-1] if any(it["id"] == iid for b in dd["blocks"] for it in b["items"])]
if len(on) < level + 1:
continue
for dd in on[-(level - 1):]:
dd["states"][iid] = {"s": model.DONE, "t": 1}
for dd in on[-(level + 1):-(level - 1)]:
dd["states"].pop(iid, None)
dd["plays"] = [p for p in dd.get("plays", []) if p["i"] != iid]
days[-1]["states"].pop(iid, None)
days[-1]["plays"] = [p for p in days[-1].get("plays", []) if p["i"] != iid]
# a long streak with cheat days used: LONG done nearly every day, a miss every ~30
for m, dd in enumerate(days[:-1]):
if any(it["id"] == LONG for b in dd["blocks"] for it in b["items"]):
if m % 31 == 17:
dd["states"].pop(LONG, None)
else:
dd["states"][LONG] = {"s": model.DONE, "t": 1}
store = Store(db)
for dd in days:
store.put(dd, dirty=False)
store.set_meta("first_date", first.isoformat())
h = model.history(days, today.isoformat())
print("wrote %d fake days (%s .. %s) to %s" % (len(days), first, today, home))
for iid, level in short.items():
dd = json.loads(json.dumps(days[-1]))
model.set_state(dd, iid, model.DONE)
n = model.streak_ending(days[:-1] + [dd], iid, today.isoformat())
print(" tick %-24s today -> streak %d%s" % (iid, n, " (calm)" if iid in CALM else ""))
st = h.items.get(LONG)
if st:
print(" %s: current %d, longest %d, cheat days used %d" % (
LONG, st.current, st.longest, sum(len(r.cheats) for r in st.runs)))
print("run: ROUTINE_HOME=%s python3 -m routine" % home)
if __name__ == "__main__":
main()