#!/usr/bin/env python3"""The faces walk's seeding steps that are easier said in Python than inbash, each a subcommand seed.sh runs (lane faces, 23 Oct 2026). Every row itwrites or moves is invented: the tool fixtures under tools/, and the dates ofa household `cotton-headless seed` made up. seed.py packages <tools dir> <out dir> <today> stage, card, date and pack each tool; print the import calls seed.py dedupe <life.db> <tools dir> drop the second copy of each tool's sample rows seed.py touches <life.db> <today> print the update calls: birthdays ahead, wishes, money ahead seed.py artifacts <life.db> <today> file three invented HTML pages as documents seed.py pictures <art dir> print the capture calls: each invented cover, poster and sleeve in art/ seed.py shelves <life.db> <today> <pass> <art> print pass 1-3's create calls: books, films, a series' season and episodes, an album and a song seed.py kept <life.db> drop the second copy of each shelf row the shelves wrote seed.py checked <time output> fail on any refused call but "changes nothing" seed.py counts <life.db> print what the walk's tools hold seed.py state <household> <state dir> the phone's state folder, pages.py fixture's layout"""import base64import datetime as dtimport hashlibimport jsonimport reimport shutilimport sqlite3import subprocessimport sysimport uuidfrom pathlib importPathREPO = Path(__file__).resolve().parents[2]# The day the fixtures' dates are written against; each is moved by as many# days as today is past it, so a renewal "in 6 days" stays 6 days ahead.ANCHOR = dt.date(2026, 10, 23)# An instant in a fixture (a Mac's sampled_at, a quota's checked_at, columns# read "ago") is written against this moment and moved by as much as now is# past it, so "4 min ago" stays four minutes ago on the day the walk is seeded.ANCHOR_AT = dt.datetime(2026, 10, 23, 10, 0, tzinfo=dt.timezone.utc)DAY = re.compile(r"^\d{4}-\d{2}-\d{2}$")INSTANT = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$")TOOLS = ["subscriptions", "machines", "quotas", "money", "birthdays"]# The card blocks the coordinator installs on the owner's tools, by tool and# then by table or view id: packed from here, never from the fixtures, so the# file the coordinator installs is the file the walk proves.CARDS = Path(__file__).resolve().parent / "cards.json"def shifted(value, by, since):if isinstance(value, str) and DAY.match(value):return (dt.date.fromisoformat(value) + dt.timedelta(days=by)).isoformat()if isinstance(value, str) and INSTANT.match(value): at = dt.datetime.fromisoformat(value.replace("Z", "+00:00")) + sincereturn at.strftime("%Y-%m-%dT%H:%M:%SZ")if isinstance(value, list):return [shifted(item, by, since) for item in value]if isinstance(value, dict):return {key: shifted(item, by, since) for key, item in value.items()}return valuedef carded(staged: Path, tool: str, cards: dict) -> None:"""Put each of cards.json's blocks for `tool` on the view or table it names; a block naming neither, or a fixture carrying a card of its own, stops the walk.""" manifest_path = staged / "manifest.json" manifest = json.loads(manifest_path.read_text()) views = {view["id"]: view for view in manifest.get("views") or []}for view in views.values():if"card"in view:raiseSystemExit(f"faces-walk: {tool} view {view['id']} carries its own card; cards.json holds them")for table_path in sorted((staged / "tables").glob("*.json")):if"card"in json.loads(table_path.read_text()):raiseSystemExit(f"faces-walk: {tool} table {table_path.stem} carries its own card; cards.json holds them")for target, card in (cards.get(tool) or {}).items(): table_path = staged / "tables" / f"{target}.json"if target in views: views[target]["card"] = cardelif table_path.is_file() and target in manifest.get("tables", []): table = json.loads(table_path.read_text()) table["card"] = card table_path.write_text(json.dumps(table, indent=2, ensure_ascii=False) + "\n")else:raiseSystemExit(f"faces-walk: cards.json names {tool}/{target}, which is neither its view nor its table") manifest_path.write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n")def packages(tools: Path, out: Path, today: str) -> None: by = (dt.date.fromisoformat(today) - ANCHOR).days now = dt.datetime.now(dt.timezone.utc).replace(microsecond=0)# A walk seeded for another day (FACES_WALK_TODAY) moves its instants by whole days. since = now - ANCHOR_AT if now.date().isoformat() == today else dt.timedelta(days=by) cards = json.loads(CARDS.read_text()) unknown = set(cards) - set(TOOLS)if unknown:raiseSystemExit(f"faces-walk: cards.json names tools the walk does not seed: {sorted(unknown)}")# The staging folder is replaced only inside the walk's own work folder:# seed.sh judged it with refuse_wide_root and marked it `.faces-walk`.ifnot (out.parent / ".faces-walk").is_file():raiseSystemExit(f"faces-walk: {out.parent} is not the walk's work folder (no .faces-walk mark)") calls = []for tool in TOOLS: staged = out / "staged" / toolif staged.exists(): shutil.rmtree(staged) shutil.copytree(tools / tool, staged) (staged / "tables").mkdir(exist_ok=True) carded(staged, tool, cards)for rows in sorted((staged / "records").glob("*.json")) if (staged / "records").is_dir() else []: rows.write_text(json.dumps(shifted(json.loads(rows.read_text()), by, since), indent=2, ensure_ascii=False) + "\n") packed = out / f"{tool}.cottontool" subprocess.run(["node", str(REPO / "scripts/pack-tool.mjs"), str(staged), str(packed)], check=True, stdout=subprocess.DEVNULL) calls.append({"name": f"import {tool}", "method": "tools.import","args": {"bytes": base64.b64encode(packed.read_bytes()).decode(), "with_samples": True}}) print(json.dumps(calls))def dedupe(db_path: Path, tools: Path) -> None:"""`cotton-headless time` runs each call twice (once to warm), so each import wrote its sample rows twice: keep the first copy."""with sqlite3.connect(db_path) as db:for tool in TOOLS:for rows in sorted((tools / tool / "records").glob("*.json")) if (tools / tool / "records").is_dir() else []: table, keep = rows.stem, len(json.loads(rows.read_text())) name = f"cotton_{table}" extra = [r[0] for r in db.execute(f"SELECT id FROM {name} ORDER BY rowid LIMIT -1 OFFSET ?", (keep,))]for row in extra: db.execute(f"DELETE FROM {name} WHERE id = ?", (row,)) db.execute("DELETE FROM _writes WHERE tbl = ? AND row_id = ?", (name, row)) db.execute("DELETE FROM cotton_changes WHERE table_id = ? AND record_id = ?", (table, row)) print(f"{table}: kept {keep}, dropped {len(extra)} repeated sample rows", file=sys.stderr)# The shelves: kit tools the seed leaves empty (Books, Films, Music), filled# with invented rows so their faces draw — a book being read, one read and# rated, one to read; a film watched and rated, one to watch; a series whose# first season holds three episodes, two watched; an artist, an album of# theirs and one of its songs. A series' season needs the series' id, its# episodes the season's, an album its artist's and a song its album's, so# the calls come in passes. Each table's rows are told apart by the column# named here.SHELF_TABLES = {"book": "title", "film": "title", "film_season": "title", "film_episode": "title","artist": "name", "music_album": "title", "track": "title"}# The pictures the shelves keep (art/<name>.png, cut from the Codex round 2# references; invented titles, never in the app): each goes in through the# phone's own capture, which copies the bytes into this household's media# store, writes the photo row and the ledger row that says where the bytes# are, so the phone the walk runs draws them from disk. A row names its# picture by the photo's id, `photo:<sha256 of the bytes>`. A song's cover# is its album's (the core looks it up), so album-2's sleeve has no row here.PICTURES = ["book-1", "book-2", "film-1", "film-2", "album-1"]def pictures(art: Path) -> None: calls = []for name in PICTURES: calls.append({"name": f"picture {name}", "method": "capture.media","args": {"path": str(art / f"{name}.png"), "mime": "image/png", "kind": "photo","filename": f"{name}.png"}}) print(json.dumps(calls, indent=1))def photo_id(art: Path, name: str) -> str:return"photo:" + hashlib.sha256((art / f"{name}.png").read_bytes()).hexdigest()def create(name, table, data):return {"name": name, "method": "write", "args": {"tool": "create_record", "args": {"table": table, "data": data}}}def shelves(db_path: Path, today: str, step: int, art: Path) -> None: day = dt.date.fromisoformat(today) ago = lambda days: (day - dt.timedelta(days=days)).isoformat() calls = []with sqlite3.connect(db_path) as db:if step == 1:for title, author, status, pages, at, rating, done, cover in [ ("An Invented Atlas of Rivers", "Invented Author", "reading", 340, 212, None, None, "book-1"), ("The Invented Lighthouse Keeper", "Synthetic Writer", "read", 288, 288, 4, ago(9), "book-2"), ("Notes Toward an Invented City", "Fictional Essayist", "to_read", 196, None, None, None, None)]: data = {"title": title, "author": author, "status": status, "pages": pages} data.update({k: v for k, v in [("current_page", at), ("rating", rating), ("finished_on", done), ("cover", cover and photo_id(art, cover))] if v isnotNone}) calls.append(create(f"book {title}", "book", data))for title, year, kind, status, rating, seen, poster in [ ("The Invented Harbour", "1998", "film", "watched", 5, ago(3), None), ("A Synthetic Summer", "2021", "film", "watchlist", None, None, "film-1"), ("Invented Detectives", "2019", "series", "watched", 4, ago(1), "film-2")]: data = {"title": title, "year": year, "kind": kind, "status": status} data.update({k: v for k, v in [("rating", rating), ("watched_on", seen), ("poster", poster and photo_id(art, poster))] if v isnotNone}) calls.append(create(f"film {title}", "film", data)) calls.append(create("artist Invented Quartet", "artist", {"name": "Invented Quartet"})) made = lambda table: db.execute("SELECT 1 FROM sqlite_master WHERE name = ?", (f"cotton_{table}",)).fetchone() artist = db.execute("SELECT id FROM cotton_artist WHERE name = 'Invented Quartet' ORDER BY rowid LIMIT 1").fetchone() \if made("artist") elseNone album = db.execute("SELECT id FROM cotton_music_album WHERE title = 'Invented Monsoon' ORDER BY rowid LIMIT 1").fetchone() \if made("music_album") elseNoneif step == 2and artist: calls.append(create("album Invented Monsoon", "music_album", {"title": "Invented Monsoon", "artist": artist[0], "year": "2019","cover": photo_id(art, "album-1")}))if step == 3and artist and album: calls.append(create("song Rain on Tin", "track", {"title": "Rain on Tin", "artist": artist[0], "album": album[0],"track_number": 3, "duration": 222})) series = db.execute("SELECT id FROM cotton_film WHERE kind = 'series' ORDER BY rowid LIMIT 1").fetchone()if step == 2and series: calls.append(create("season 1", "film_season", {"film": series[0], "number": 1, "title": "Season one", "year": "2019"})) season = db.execute("SELECT id FROM cotton_film_season ORDER BY rowid LIMIT 1").fetchone() \if db.execute("SELECT 1 FROM sqlite_master WHERE name = 'cotton_film_season'").fetchone() elseNoneif step == 3and series and season:for number, title, minutes, aired, seen, rating in [ (1, "The Invented Alibi", 48, "2019-03-04", ago(12), 4), (2, "A Synthetic Witness", 51, "2019-03-11", ago(1), 5), (3, "The Fictional Verdict", 55, "2019-03-18", None, None)]: data = {"season": season[0], "series": series[0], "number": number, "title": title,"minutes": minutes, "aired": aired} data.update({k: v for k, v in [("watched_on", seen), ("rating", rating)] if v isnotNone}) calls.append(create(f"episode {number}", "film_episode", data)) print(json.dumps(calls, indent=1))def kept(db_path: Path) -> None:"""`cotton-headless time` runs each call twice: keep each shelf row's first copy."""with sqlite3.connect(db_path) as db:for table, key in SHELF_TABLES.items(): name = f"cotton_{table}"ifnot db.execute("SELECT 1 FROM sqlite_master WHERE name = ?", (name,)).fetchone():continue extra = [r[0] for r in db.execute(f"SELECT id FROM {name} WHERE rowid NOT IN " f"(SELECT min(rowid) FROM {name} GROUP BY {key})")]for row in extra: db.execute(f"DELETE FROM {name} WHERE id = ?", (row,)) db.execute("DELETE FROM _writes WHERE tbl = ? AND row_id = ?", (name, row)) db.execute("DELETE FROM cotton_changes WHERE table_id = ? AND record_id = ?", (table, row)) print(f"{table}: dropped {len(extra)} repeated rows", file=sys.stderr)def update(name, table, row, patch):return {"name": name, "method": "write","args": {"tool": "update_record", "args": {"table": table, "id": row, "patch": patch}}}def touches(db_path: Path, today: str) -> None: day = dt.date.fromisoformat(today) calls = []with sqlite3.connect(db_path) as db:# Four people the seed gave no birthday get one in the weeks ahead. bare = [r for r in db.execute("SELECT id, full_name FROM cotton_people WHERE birth_month IS NULL ""AND archived_at IS NULL ORDER BY full_name LIMIT 4")]for (row, name), (ahead, year, wish) in zip(bare, [(2, 1990, True), (6, 1984, True), (13, 1996, False), (24, 1979, True)]): on = day + dt.timedelta(days=ahead) patch = {"birthday": f"{year}-{on.month:02d}-{on.day:02d}", "own_birthdays__wish": wish}if wish and ahead > 10: patch["own_birthdays__last_wished"] = f"{on.year - 1}-{on.month:02d}-{on.day:02d}" patch["own_birthdays__last_wished_via"] = "whatsapp" calls.append(update(f"birthday {name}", "person", row, patch))# The seed's own birthdays that come round in the next 30 days send wishes too.for row, name, month, dday in db.execute("SELECT id, full_name, birth_month, birth_day FROM cotton_people ""WHERE birth_month IS NOT NULL AND archived_at IS NULL"):try: on = dt.date(day.year, month, dday)exceptValueError:continueif on < day: on = on.replace(year=day.year + 1)if (on - day).days <= 30: calls.append(update(f"wishes {name}", "person", row, {"own_birthdays__wish": True}))# Money's Future view reads the expected movements (Past the actual# ones): the seed dates them all behind today, so each moves ahead —# three due in the weeks ahead (Home's money due), the rest after# the month Home looks at, a week apart. expected = [r[0] for r in db.execute("SELECT id FROM cotton_money_transactions WHERE status = 'expected' ""AND trashed_at IS NULL ORDER BY occurred_on DESC")]for i, row in enumerate(expected): ahead = [4, 11, 19][i] if i < 3else35 + 7 * (i - 3) on = (day + dt.timedelta(days=ahead)).isoformat() patch = {"occurred_on": on, "due_date": on} if i < 3else {"occurred_on": on} calls.append(update(f"due {row[:8]}", "transaction", row, patch)) print(json.dumps(calls))PAGES = [ ("Invented trip planner", "trip-planner.html", "A day-by-day plan for an invented week on the coast, with the ferry times and a packing list.", 2), ("Invented reading tracker", "reading-tracker.html", "A shelf of invented books with how far through each one is and a chart of pages a week.", 9), ("Invented sourdough timer", "sourdough-timer.html", "A timer page for an invented loaf: feed, fold, shape and bake, each with its alarm.", 23),]def artifacts(db_path: Path, today: str) -> None:"""The Artifacts tool reads documents kept as text/html. A document only arrives as its file (create_record refuses one) and filing a file needs an object store this household lacks, so the three invented pages are written as rows the way the seed writes its own documents: no bytes.""" day = dt.datetime.fromisoformat(today + "T09:00:00+00:00")with sqlite3.connect(db_path) as db: workspace, = db.execute("SELECT id FROM cotton_workspaces WHERE kind = 'personal'").fetchone() device = db.execute("SELECT _hlc FROM cotton_documents WHERE _hlc != '' LIMIT 1").fetchone()[0].split(":", 2)[2]for i, (title, name, summary, back) in enumerate(PAGES): body = f"<!doctype html><title>{title}</title><p>{summary}</p>".encode() sha = hashlib.sha256(body).hexdigest()if db.execute("SELECT 1 FROM cotton_documents WHERE sha256 = ?", (sha,)).fetchone():continue row = str(uuid.uuid5(uuid.NAMESPACE_URL, f"faces-walk:{name}")) at = (day - dt.timedelta(days=back)).strftime("%Y-%m-%dT%H:%M:%S.000Z") hlc = f"{int((day - dt.timedelta(days=back)).timestamp() * 1000)}:{9000 + i:04d}:{device}" db.execute("INSERT INTO cotton_documents (id, workspace_id, title, original_name, mime, byte_size, sha256, storage_path, ""status, status_changed_at, doc_type, summary, facts, text_extracted, source, created_at, updated_at, _hlc, _born) ""VALUES (?, ?, ?, ?, 'text/html', ?, ?, ?, 'ready', ?, 'other', ?, '{}', 1, 'agent', ?, ?, ?, ?)", (row, workspace, title, name, len(body), sha, f"{workspace}/{row}/original.html", at, summary, at, at, hlc, hlc)) held = db.execute("SELECT count(*) FROM cotton_documents WHERE mime = 'text/html'").fetchone()[0] print(f"artifacts: {held} HTML documents", file=sys.stderr)def checked(output: Path) -> None: refused = []for line in output.read_text().splitlines():ifnot line.startswith("{"):continue said = json.loads(line)if"error"in said and"changes nothing"notin said["error"]: refused.append(said["error"])if refused:raiseSystemExit("faces-walk: refused:\n " + "\n ".join(refused))def counts(db_path: Path) -> None:with sqlite3.connect(db_path) as db: tools = [r[0] for r in db.execute("SELECT id FROM cotton_tool_definitions ORDER BY id")] one = lambda sql: db.execute(sql).fetchone()[0] print(json.dumps({"tools": tools,"machine": one("SELECT count(*) FROM cotton_machine"),"quota": one("SELECT count(*) FROM cotton_quota"),# A made table's file is made on its first row: none yet reads as none."quota_reading": one("SELECT count(*) FROM cotton_quota_reading")if db.execute("SELECT 1 FROM sqlite_master WHERE name = 'cotton_quota_reading'").fetchone() else0,"subscription": one("SELECT count(*) FROM cotton_subscription"),"subscriptions_due_30d": one("SELECT count(*) FROM cotton_subscription WHERE status = 'active' ""AND next_renewal BETWEEN date('now') AND date('now', '+30 days')"),"transaction": one("SELECT count(*) FROM cotton_money_transactions WHERE trashed_at IS NULL"),"transactions_past": one("SELECT count(*) FROM cotton_money_transactions WHERE status = 'actual' AND trashed_at IS NULL"),"transactions_future": one("SELECT count(*) FROM cotton_money_transactions WHERE status = 'expected' AND trashed_at IS NULL"),"past_dated_after_today": one("SELECT count(*) FROM cotton_money_transactions WHERE status = 'actual' ""AND trashed_at IS NULL AND occurred_on > date('now')"),"future_dated_on_or_before_today": one("SELECT count(*) FROM cotton_money_transactions WHERE status = 'expected' ""AND trashed_at IS NULL AND occurred_on <= date('now')"),"transactions_due_30d": one("SELECT count(*) FROM cotton_money_transactions WHERE status = 'expected' ""AND due_date BETWEEN date('now') AND date('now', '+30 days')"),"money_account": one("SELECT count(*) FROM cotton_money_accounts"),"people_with_birthdays": one("SELECT count(*) FROM cotton_people WHERE birth_month IS NOT NULL"),"people_wished": one("SELECT count(*) FROM cotton_people WHERE own_birthdays__wish = 1"),"html_documents": one("SELECT count(*) FROM cotton_documents WHERE mime = 'text/html'"),"music_album": one("SELECT count(*) FROM cotton_music_album"),"track": one("SELECT count(*) FROM cotton_track"),# The shelves' pictures whose bytes this household holds on disk."pictures_on_disk": one("SELECT count(*) FROM _media WHERE local_path IS NOT NULL"),"covers_kept": one("SELECT (SELECT count(*) FROM cotton_book WHERE cover LIKE 'photo:%') + ""(SELECT count(*) FROM cotton_film WHERE poster LIKE 'photo:%') + ""(SELECT count(*) FROM cotton_music_album WHERE cover LIKE 'photo:%')"), }, indent=2))MARK = ".pages-state"def state(household: Path, out: Path) -> None:"""`scripts/perf/pages.py fixture`, said again here: that script's `fixture` writes its marker through a name a later regex took over (MARK), so it stops after the copies. Same layout, same marker, so pages.py `run` takes this state as its own.""" files = sorted(household.glob("files/*/*/life.db"))ifnot files:raiseSystemExit(f"faces-walk: no database files under {household}/files")if out.exists():ifnot (out / MARK).is_file():raiseSystemExit(f"faces-walk: {out} exists and is not a phone state (no {MARK}); remove it yourself") shutil.rmtree(out) client = out / "client" databases = []for path in files:with sqlite3.connect(path) as db: workspace, owner, kind = db.execute("SELECT id, owner_user_id, kind FROM cotton_workspaces").fetchone() databases.append((path, workspace, owner, kind)) personal = next(d for d in databases if d[3] == "personal") places = [d for d in databases if d isnot personal]for path, workspace, _, _ in databases: target = client / workspace / "replica.db" target.parent.mkdir(parents=True, exist_ok=True)with sqlite3.connect(path) as source, sqlite3.connect(target) as copy: source.backup(copy) (out / MARK).write_text("made by scripts/faces-walk/seed.py state (pages.py fixture's layout)\n") (client / "connection.json").write_text(json.dumps(dict( mode="remote", baseUrl="https://synthetic.invalid", workspaceId=personal[1], ownerId=personal[2], connectedAt="2026-10-16T00:00:00.000Z", places=[dict(id=d[1], name=f"Synthetic project {i}", available=True, unavailableSince=None)for i, d in enumerate(places)])))def main(argv): command, args = argv[0], argv[1:]if command == "packages": packages(Path(args[0]), Path(args[1]), args[2])elif command == "dedupe": dedupe(Path(args[0]), Path(args[1]))elif command == "touches": touches(Path(args[0]), args[1])elif command == "artifacts": artifacts(Path(args[0]), args[1])elif command == "pictures": pictures(Path(args[0]))elif command == "shelves": shelves(Path(args[0]), args[1], int(args[2]), Path(args[3]))elif command == "kept": kept(Path(args[0]))elif command == "checked": checked(Path(args[0]))elif command == "counts": counts(Path(args[0]))elif command == "state": state(Path(args[0]), Path(args[1]))else:raiseSystemExit(__doc__)if __name__ == "__main__": main(sys.argv[1:])