moonlighting-factory 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. moonlighting_factory-0.1.0/.gitignore +19 -0
  2. moonlighting_factory-0.1.0/.nwave/config.json +5 -0
  3. moonlighting_factory-0.1.0/AGENTS.md +90 -0
  4. moonlighting_factory-0.1.0/CLAUDE.md +74 -0
  5. moonlighting_factory-0.1.0/PKG-INFO +5 -0
  6. moonlighting_factory-0.1.0/PLAN.md +154 -0
  7. moonlighting_factory-0.1.0/README.md +157 -0
  8. moonlighting_factory-0.1.0/docs/flow.md +85 -0
  9. moonlighting_factory-0.1.0/docs/runbook.md +144 -0
  10. moonlighting_factory-0.1.0/docs/work-order-template.md +52 -0
  11. moonlighting_factory-0.1.0/night-shift/NIGHT-SHIFT.md +50 -0
  12. moonlighting_factory-0.1.0/night-shift/QA-SHIFT.md +25 -0
  13. moonlighting_factory-0.1.0/night-shift/locks/.gitkeep +0 -0
  14. moonlighting_factory-0.1.0/night-shift/logs/.gitkeep +0 -0
  15. moonlighting_factory-0.1.0/night-shift/logs/2026-11-22-wo-001.err.log +0 -0
  16. moonlighting_factory-0.1.0/night-shift/logs/2026-11-22-wo-001.out.md +23 -0
  17. moonlighting_factory-0.1.0/night-shift/logs/2026-11-22-wo-002.err.log +0 -0
  18. moonlighting_factory-0.1.0/night-shift/logs/2026-11-22-wo-002.out.md +41 -0
  19. moonlighting_factory-0.1.0/night-shift/logs/2026-11-22-wo-003.err.log +0 -0
  20. moonlighting_factory-0.1.0/night-shift/logs/2026-11-22-wo-003.out.md +17 -0
  21. moonlighting_factory-0.1.0/night-shift/logs/2026-11-22-wo-004.err.log +0 -0
  22. moonlighting_factory-0.1.0/night-shift/logs/2026-11-22-wo-004.out.md +30 -0
  23. moonlighting_factory-0.1.0/night-shift/logs/2026-11-22.md +15 -0
  24. moonlighting_factory-0.1.0/night-shift/worktrees/.gitkeep +0 -0
  25. moonlighting_factory-0.1.0/pyproject.toml +22 -0
  26. moonlighting_factory-0.1.0/repos/.gitkeep +0 -0
  27. moonlighting_factory-0.1.0/src/moonlighting/__init__.py +1 -0
  28. moonlighting_factory-0.1.0/src/moonlighting/accept.py +108 -0
  29. moonlighting_factory-0.1.0/src/moonlighting/answer.py +39 -0
  30. moonlighting_factory-0.1.0/src/moonlighting/approve.py +34 -0
  31. moonlighting_factory-0.1.0/src/moonlighting/cli.py +55 -0
  32. moonlighting_factory-0.1.0/src/moonlighting/factory.py +656 -0
  33. moonlighting_factory-0.1.0/src/moonlighting/feedback.py +39 -0
  34. moonlighting_factory-0.1.0/src/moonlighting/lint_orders.py +52 -0
  35. moonlighting_factory-0.1.0/src/moonlighting/new_order.py +146 -0
  36. moonlighting_factory-0.1.0/src/moonlighting/rotate_logs.py +70 -0
  37. moonlighting_factory-0.1.0/src/moonlighting/run.py +447 -0
  38. moonlighting_factory-0.1.0/src/moonlighting/schedule.py +120 -0
  39. moonlighting_factory-0.1.0/src/moonlighting/status.py +116 -0
  40. moonlighting_factory-0.1.0/tests/test_factory.py +738 -0
  41. moonlighting_factory-0.1.0/uv.lock +248 -0
  42. moonlighting_factory-0.1.0/work-orders/.gitkeep +0 -0
@@ -0,0 +1,19 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ .pytest_cache/
5
+ dist/
6
+ repos/*
7
+ !repos/.gitkeep
8
+ work-orders/*
9
+ !work-orders/.gitkeep
10
+ night-shift/logs/errors.log
11
+ night-shift/locks/*
12
+ !night-shift/locks/.gitkeep
13
+ night-shift/worktrees/*
14
+ !night-shift/worktrees/.gitkeep
15
+ night-shift/logs/cron.log
16
+ night-shift/sessions.json
17
+ # nWave config (keep .nwave/config.json trackable)
18
+ .nwave/*
19
+ !.nwave/config.json
@@ -0,0 +1,5 @@
1
+ {
2
+ "enabled": true,
3
+ "jev": "authorized",
4
+ "schema-version": 1
5
+ }
@@ -0,0 +1,90 @@
1
+ # AGENTS.md — moonlighting
2
+
3
+ A software factory. Humans work the day shift (deciding), pi agents work the
4
+ night shift (doing). Work moves through the factory as **work orders**: small
5
+ markdown files in `work-orders/` whose `status:` frontmatter line is the
6
+ contract between shifts.
7
+
8
+ ## Layout
9
+
10
+ - `work-orders/<sha>-short-title.md` — one file per unit of work. Each order carries a unique 7-char sha id
11
+ - `moonlighting night` — executes approved orders headlessly
12
+ - `night-shift/NIGHT-SHIFT.md` — the night agent's operating manual
13
+ - `moonlighting status` — floor report · `moonlighting accept ID` — squash-merge an order into its target repo
14
+ - `repos/` — target repos cloned from git URLs (gitignored)
15
+ - `docs/runbook.md` — shift checklists · `docs/work-order-template.md` — order template · `PLAN.md` — roadmap
16
+
17
+ ## Status lifecycle
18
+
19
+ ```
20
+ draft → approved → review → done
21
+ │ │
22
+ ▼ ▼
23
+ blocked ◄────┘ rejected (from anywhere)
24
+ ```
25
+
26
+ Only humans move work into or out of `approved`, `blocked`, `done`, `rejected`.
27
+ The night runner moves `approved → review` (or `→ blocked` when a run fails).
28
+
29
+ ## Rules for agents in this repo
30
+
31
+ - Execute only orders whose status is `approved`, only through the night-shift flow.
32
+ - Work on the order's own branch (`wo/NNN`). Never merge, never push, never commit to `main`.
33
+ - Never edit order files — not statuses, not logs, not decision sections.
34
+ Those belong to humans and the runner. Reading orders is expected.
35
+ - An order may target another repo (`repo:` field). The runner places you in
36
+ a throwaway git worktree of that repo with your branch checked out — the
37
+ same rules apply there: never `main`, never push, never touch order files.
38
+ - Unclear order? Stop and report BLOCKED. Never guess.
39
+ - Humans append answers under an order's *Day shift decisions* section and
40
+ re-approve blocked orders; re-read the order file at the start of every run.
41
+
42
+ <!-- BEGIN nWave-beta-section (managed by nwave-ai; do not edit) -->
43
+
44
+ ## nWave (beta) — How to Work in This Project
45
+
46
+ Three routes are open to a Request:
47
+ - Spine waves (whole-feature default): wave gates, independent review and
48
+ source-blind EXAMINE where applicable; durable authorities. Evolution retains
49
+ lasting facts; integration closes delivered work.
50
+ - Host-led nwdes steps: the root runs roles with generated prompts. Roles record
51
+ typed values with kind verbs and close. nwdes builds and
52
+ writes authority/run records; the host submits/retains no role reply.
53
+ Public oracle before code; nwdes launches no model. Details: nw-nwdes and nwdes --help.
54
+ - Working directly: fastest; nothing attests the result.
55
+
56
+ The LLM chooses the route by what survives and the cost of late refusal,
57
+ and invokes the applicable waves. The final whole-candidate review and integration happen once per Request; embedded per-slice refinement reviews provide early feedback, not final approval.
58
+ Each Request opens with the LLM's working S/M/L assessment and why, which never decides the route.
59
+ The LLM revises it as evidence changes and suggests the fastest route that
60
+ keeps what must survive; the user decides scope and trade-offs.
61
+ Working directly remains open when little must survive.
62
+ Human WIP limit: 2. Finish open work before starting new work.
63
+ One close receipt closes only that invocation: keep ready work moving; a refused close is unfinished work.
64
+ When a review or EXAMINE rejects work, or new work is ready, the Lane flow
65
+ of the nw-throughput skill holds what comes next.
66
+ Whichever route this Request takes, say which one.
67
+
68
+ nWave is in **active development**.
69
+
70
+ DISCUSS/DESIGN resolve only real gaps. Human authority decides genuine scope/trade-offs.
71
+
72
+ Several lanes in parallel: skill `nw-swarm` (a host without skill loading reads its `SKILL.md` from the installed skills folder).
73
+
74
+ **Batch independent tool calls in one turn (one per turn is a violation); sequence only when one result feeds the next.**
75
+
76
+ ### Asking the User a Question
77
+
78
+ Fixed shape, every time: **context** -> **recommendation** -> **options** (each
79
+ with its consequence/risk) -> one direct question. Real section headers and
80
+ bold labels — never a wall of text. User-facing output follows **ASD-STE100**
81
+ (Simplified Technical English).
82
+
83
+ Owner answer pending: independent ready work continues; only dependent work waits. Boundary and durable record: `nw-auto` §4.
84
+
85
+ ### Privacy — Non-Negotiable
86
+
87
+ nWave stores workflow data locally and collects no telemetry. Jev, a remote question service, is on by default for supported questions and sends only permitted data classes; switch it with `"jev": "authorized"` or `"jev": "unauthorized"` in `.nwave/config.json`. `TYPESAFE_API_KEY` is only Jev's technical prerequisite, not its authorization. See [PRIVACY.md](../../PRIVACY.md) for the complete policy. Feedback on nWave itself is welcome via GitHub Issues on the experimental repo, at your discretion — never a required step of doing the work.
88
+
89
+ <!-- END nWave-beta-section -->
90
+
@@ -0,0 +1,74 @@
1
+ <!-- BEGIN nWave-beta-section (managed by nwave-ai; do not edit) -->
2
+
3
+ ## nWave (beta) — How to Work in This Project
4
+
5
+ Three routes are open to a Request:
6
+ - Spine waves (whole-feature default): wave gates, independent review and
7
+ source-blind EXAMINE where applicable; durable authorities. Evolution retains
8
+ lasting facts; integration closes delivered work.
9
+ - Host-led nwdes steps: the root runs roles with generated prompts. Roles record
10
+ typed values with kind verbs and close. nwdes builds and
11
+ writes authority/run records; the host submits/retains no role reply.
12
+ Public oracle before code; nwdes launches no model. Details: nw-nwdes and nwdes --help.
13
+ - Working directly: fastest; nothing attests the result.
14
+
15
+ The LLM chooses the route by what survives and the cost of late refusal,
16
+ and invokes the applicable waves. The final whole-candidate review and integration happen once per Request; embedded per-slice refinement reviews provide early feedback, not final approval.
17
+ Each Request opens with the LLM's working S/M/L assessment and why, which never decides the route.
18
+ The LLM revises it as evidence changes and suggests the fastest route that
19
+ keeps what must survive; the user decides scope and trade-offs.
20
+ Working directly remains open when little must survive.
21
+ Human WIP limit: 2. Finish open work before starting new work.
22
+ One close receipt closes only that invocation: keep ready work moving; a refused close is unfinished work.
23
+ When a review or EXAMINE rejects work, or new work is ready, the Lane flow
24
+ of the nw-throughput skill holds what comes next.
25
+ Whichever route this Request takes, say which one.
26
+
27
+ nWave is a spine-driven delivery framework. Wave commands (`/nw-*`) carry the
28
+ gates; skills carry on-demand knowledge; agents execute. This section is an
29
+ INDEX.
30
+
31
+ Human authority decides genuine scope/trade-offs.
32
+
33
+ | User wants... | Load / run |
34
+ |---|---|
35
+ | Validate a problem is real | `/nw-discover` |
36
+ | Compare solution directions | `/nw-diverge` |
37
+ | Clarify jobs, journeys, outcomes | `/nw-discuss` |
38
+ | Architecture, reuse, boundaries | `/nw-design` |
39
+ | Deployment / operational constraints | `/nw-devops` |
40
+ | Executable public oracle | `/nw-distill` |
41
+ | Dispatch one Request | `/nw-deliver` |
42
+ | Fix one observed defect | `/nw-bugfix` |
43
+ | Review an artifact or diff | `/nw-review` |
44
+ | Reduce a noisy test suite | `/nw-optimize-tests` |
45
+ | Explicit mutation probe | `/nw-mutation-test` |
46
+ | Resume after an interruption | Read-only: `git worktree list`, then `lanes/<feature>/docs/feature/<feature>/handoff.json` and skill `nw-nwdes` |
47
+ | Run several lanes in parallel | skill `nw-swarm` |
48
+ | Fuller S/M/L evidence, splitting a Request | skill `nw-auto` |
49
+ | Anything else — methodology, routing, "what do I do" | skill `nw-buddy` |
50
+
51
+ **Batch independent tool calls in one turn (one per turn is a violation); sequence only when one result feeds the next.**
52
+
53
+ ### Asking the User a Question
54
+
55
+ Fixed shape, every time: **context** -> **recommendation** -> **options** (each
56
+ with its consequence/risk) -> one direct question. Real section headers and
57
+ bold labels — never a wall of text. User-facing output follows **ASD-STE100**
58
+ (Simplified Technical English).
59
+
60
+ Owner answer pending: independent ready work continues; only dependent work waits. Boundary and durable record: `nw-auto` §4.
61
+
62
+ ### Communication
63
+
64
+ <!-- GENERATED:communication-rules START — source of truth: nwave_ai.platform.effective_config() (ADR-CFG-001 Slice 2 -- ~/.nwave/config.json + .nwave/config.json); do not hand-edit (docgen renders this region) -->
65
+ - Communication verbosity: **standard**
66
+ - Commit attribution: **enabled**
67
+ <!-- GENERATED:communication-rules END -->
68
+
69
+ ### Privacy — Non-Negotiable
70
+
71
+ nWave stores workflow data locally and collects no telemetry. Jev, a remote question service, is on by default for supported questions and sends only permitted data classes; switch it with `"jev": "authorized"` or `"jev": "unauthorized"` in `.nwave/config.json`. `TYPESAFE_API_KEY` is only Jev's technical prerequisite, not its authorization ([PRIVACY.md](../../PRIVACY.md)). Feedback via GitHub Issues is welcome, never required.
72
+
73
+ <!-- END nWave-beta-section -->
74
+
@@ -0,0 +1,5 @@
1
+ Metadata-Version: 2.5
2
+ Name: moonlighting-factory
3
+ Version: 0.1.0
4
+ Summary: A software factory: people decide by day, agents type by night.
5
+ Requires-Python: >=3.9
@@ -0,0 +1,154 @@
1
+ # Moonlighting — Plan
2
+
3
+ > **Status:** Phases 0–2 built and live with pi — four real runs executed
4
+ > end to end (wo-001..004, 2026-11-22). The first `--engine claude` run is
5
+ > still pending. Engines now: pi, claude and opencode. The factory is a uv
6
+ > project with a pytest suite (`uv run pytest`).
7
+
8
+ A software factory where **humans work the day shift** (deciding) and **agents work the night shift** (doing). Built on [pi](https://pi.dev), Claude Code and opencode as the night-shift workforce.
9
+
10
+ ## The core idea
11
+
12
+ Work enters the factory as **work orders** — small markdown files with a status line. The status line is the contract between the two shifts:
13
+
14
+ - A work order marked `approved` is a standing instruction: the night shift may execute it autonomously.
15
+ - Anything else (`draft`, `blocked`, `review`, `done`, `rejected`) means "hands off" — it's waiting on a human decision.
16
+
17
+ The factory is just a git repo + a runner script + conventions. No server, no database, no UI. Git history is the audit log.
18
+
19
+ ```
20
+ Day (human) Night (pi agent)
21
+ ──────────── ────────────────
22
+ write draft orders
23
+ review yesterday's diff ◄──────── execute approved orders
24
+ approve / reject / block ────────► log sessions, flip status to review
25
+ ```
26
+
27
+ ## Work order lifecycle
28
+
29
+ ```
30
+ draft ──► approved ──► review ──► done
31
+ │ │
32
+ ▼ ▼
33
+ blocked ◄──────┘ (human answers question, re-approves)
34
+ │
35
+ └──► rejected
36
+ ```
37
+
38
+ Work order file: `work-orders/NNN-short-title.md`
39
+
40
+ ```markdown
41
+ ---
42
+ id: NNN
43
+ title: Short title
44
+ status: approved # draft | approved | review | blocked | done | rejected
45
+ created: YYYY-MM-DD
46
+ branch: wo/NNN # branch the night shift works on
47
+ ---
48
+
49
+ ## Goal
50
+ What "done" means, in one or two sentences.
51
+
52
+ ## Tasks
53
+ Concrete steps the night agent should take.
54
+
55
+ ## Constraints
56
+ What the agent must NOT do, standards to follow.
57
+
58
+ ## Night shift log <!-- appended by the night runner -->
59
+ ## Day shift decisions <!-- appended by humans -->
60
+ ```
61
+
62
+ ## Phases
63
+
64
+ ### Phase 0 — Factory floor (structure + conventions) *~1 hour*
65
+
66
+ Everything is files and folders. No code yet.
67
+
68
+ - [x] `README.md` — the factory handbook: shifts, roles, lifecycle, how to run a night
69
+ - [x] `AGENTS.md` — standing instructions for any pi session that enters this repo (what a work order is, what it may touch, when to stop and set `blocked`)
70
+ - [x] `docs/work-order-template.md` — the template above
71
+ - [x] `night-shift/` — runner scripts and `logs/`
72
+ - [x] `docs/runbook.md` — day-shift checklist (what to review each morning) and night-shift checklist (how to kick off the run)
73
+
74
+ **Done.**
75
+
76
+ ### Phase 1 — The night shift runs *the MVP*
77
+
78
+ One script, one command, end-to-end.
79
+
80
+ - [x] `night-shift/run.py` (evolved beyond the sketch: engine `--engine pi|claude`, target repos via `repo:`, per-repo locks, WIP auto-commit sweep, output captured outside the working tree):
81
+ 1. Find work orders with `status: approved` (oldest first)
82
+ 2. For each (stopping after `--max-orders`, default 1):
83
+ - create/checkout its `wo/NNN` branch in the order's target repo
84
+ - run the engine headless with `NIGHT-SHIFT.md` as appended system prompt and the order embedded in the prompt
85
+ - append the agent's final report to the order's *Night shift log*
86
+ - flip `status: approved` → `status: review` (→ `blocked` on failure or dirty target)
87
+ - self-repo: return to `main`; external targets: stay on the order branch
88
+ 3. Write a run summary to `night-shift/logs/YYYY-MM-DD.md`
89
+ - [x] `night-shift/NIGHT-SHIFT.md` — the agent's operating manual (in small scope, test before declaring done, never flip status itself, set `blocked` + a question in the log if stuck)
90
+
91
+ **Done:** live with pi — wo-001..004 ran end to end on 2026-11-22. The claude path ran against stub engines only.
92
+
93
+ ### Phase 2 — The day shift decides *make the loop a habit*
94
+
95
+ - [x] `day-shift/status.py` — factory floor report: queued orders, orders in review, branches awaiting merge, per-repo with locks
96
+ - [x] Decision conventions: a human reviews `wo/NNN`, then either
97
+ - merges the branch and marks `done` (`day-shift/accept.py NNN`), or
98
+ - sets `blocked` with a question for tonight, or
99
+ - sets `rejected` with a reason
100
+ - [x] Squash-merge convention: the night agent must never merge; only day shift merges
101
+
102
+ **Built. Real cycles started 2026-11-22** (wo-001..004).
103
+
104
+ ### Phase 3 — Hardening *once the loop is trusted*
105
+
106
+ - [x] **Isolation** — pulled forward, live fire demanded it: every order runs
107
+ in a throwaway `git worktree` under `night-shift/worktrees/` (removed after
108
+ the run); working copies are never switched, so dirty targets no longer
109
+ block; parallel orders in one repo become possible.
110
+ - [x] **Auditability** — every run archives the engine's full JSON event stream (`night-shift/logs/*.events.jsonl`, `*.qa.jsonl`); the final report is extracted from it
111
+ - [x] **Validation** — `night-shift/lint-order.py` for the day shift; the runner lint-blocks approved malformed orders before spending tokens
112
+ - [x] **Scheduling** — `night-shift/schedule.py install|remove|status`; nightly cron, harmlessly no-ops on an empty queue
113
+ - [~] **Budget rails**: per-order time cap done (`NIGHT_TIMEOUT_SECS`, default 7200s → killed and marked blocked); token cap — now unblocked, since usage data lives in the archived event streams (parse, abort, mark blocked)
114
+ - [ ] **Log rotation** — `logs/` and `cron.log` grow forever; rotate or cap someday (small)
115
+ - [ ] **Claude engine live-fire** — implemented and stub-tested. The first real `--engine claude` order is still pending.
116
+ - [ ] **Multi-machine locks** — pid locks are machine-local; factories on different machines targeting the same repo won't collide-detect (per-repo clone pattern sidesteps this; revisit only for multi-box setups)
117
+ - [ ] **Secrets framework** — beyond the night manual's “never commit secrets” rule: decide what credentials agents may see, and how
118
+
119
+ ### Phase 4 — Expansion *only if the loop proves out*
120
+
121
+ The loop proved out. Pulled forward and shipped:
122
+
123
+ - [x] **QA pre-shift** — a second agent pass reviews every night's diff and writes a SHIP/BLOCK/UNSURE verdict into the order file (opt out: `FACTORY_QA=0`)
124
+ - [x] **Multi-repo** — orders name a target repo (`repo:` path or git URL, cloned under `repos/`); day shift merges and pushes target repos themselves
125
+ - [x] **Parallel shifts** — one factory process per repo, each in its own clone, launched concurrently; worktree isolation + locks make it safe (proven live)
126
+ - [x] **Claude Code engine** — same flow, `--engine claude`, sessions tracked per order
127
+ - [x] **opencode engine** — same flow via `--engine opencode`. The host picks the session id (`ses_...`) and the runner keeps it in `night-shift/sessions.json`
128
+
129
+ Still open:
130
+
131
+ - [ ] **Skills** for recurring job types ("add a CLI command", "write a migration") loaded via `pi --skill`. Deferred until real nights show the recurring job types
132
+ - [ ] **Prompt templates** for authoring work orders consistently. Deferred until the order format settles
133
+ - [x] **Morning report** — the night writes `logs/YYYY-MM-DD-morning.md` with review and blocked orders and their latest QA verdicts
134
+
135
+ ## Scope discipline (what "minimal" means)
136
+
137
+ In scope for now: **Phases 0–2 only.** Plain Python (stdlib) + markdown.
138
+ Hosts: pi and Claude Code (engine per run), both under the nWave guard.
139
+ Orders may target external repos; one factory process per repo. One order per night run by default.
140
+
141
+ Explicitly out of scope until Phase 3+: worktrees (done), JSON event archives (done), cron (done), token budgets (pending, see Phase 3), parallel orders within one repo. Every phase must leave the factory usable on its own — no half-built scaffolding.
142
+
143
+ **Build pause.** The machinery is done; the next feature should come from a real night's friction, not speculation. Run the factory for a month, then revisit this list.
144
+
145
+ ## Risks & guardrails (baked in from Phase 1)
146
+
147
+ | Risk | Guardrail |
148
+ |---|---|
149
+ | Agent merges its own work | Merging is a day-shift-only convention; night runner never merges |
150
+ | Agent runs away on a vague order | Night manual: if acceptance criteria are unclear → set `blocked`, ask a question, stop |
151
+ | Secrets/credentials exposed to the agent | Orders reference files, never inline secrets; `.env`-style files gitignored from day one |
152
+ | Night run corrupts the repo | Each order works on its own branch in its own worktree; `main` only moves via day-shift merges |
153
+ | Two machines, same target repo | Locks are machine-local — out of scope by design; keep one factory (on one machine) per target repo |
154
+ | Silent failures | The runner records every order attempt in `night-shift/logs/` and never deletes logs. Pre-flight failures land in the gitignored `night-shift/logs/errors.log` |
@@ -0,0 +1,157 @@
1
+ # moonlighting
2
+
3
+ A software factory where **people work the day shift and agents work the night
4
+ shift**. People decide. Agents type. The workforce is the engine you select
5
+ for the run: pi, Claude Code or opencode.
6
+
7
+ ## How it works
8
+
9
+ Work moves through the factory as **work orders** — small markdown files in
10
+ `work-orders/` whose `status:` line is the contract between the shifts.
11
+ Marking an order `approved` is a standing instruction: tonight, an agent
12
+ executes it autonomously. In the morning it sits at `review` — with a report,
13
+ a branch, and a diff, waiting for a human decision.
14
+
15
+ ```text
16
+ day shift (people) night shift (selected engine)
17
+ decide what problems matter ──────► implement approved orders
18
+ review branches & reports ◄────── flip orders to review/blocked
19
+ merge, block, or reject never merge, never touch main
20
+ ```
21
+
22
+ The whole lifecycle is one binary, `moonlighting`, with a subcommand per workflow:
23
+
24
+ ```text
25
+ moonlighting new-order "Title" create an order; it asks, then offers to approve
26
+ moonlighting status see every order: approved, blocked, review, draft, done
27
+ moonlighting approve ID approve a draft
28
+ moonlighting night run the queue (--repo, --engine, --model, --max-orders)
29
+ moonlighting accept ID merge a reviewed order into its target repo
30
+ moonlighting answer ID "text" answer a blocked order; it re-approves for tonight
31
+ moonlighting feedback ID "text" send a review back with feedback; it goes to blocked
32
+ moonlighting lint-orders check every order before spending tokens
33
+ moonlighting rotate-logs --days 90 gzip old logs (never deletes)
34
+ moonlighting schedule install nightly cron at 00:01 (remove and status too)
35
+ ```
36
+
37
+ uv runs everything under the hood. Commands work through
38
+ `uv run moonlighting ...` inside a factory checkout, or globally after
39
+ `uv tool install moonlighting-factory`.
40
+
41
+ ## Layout
42
+
43
+ ```text
44
+ work-orders/ order files (input, gitignored; FACTORY_ORDERS_DIR relocates it)
45
+ night-shift/NIGHT-SHIFT.md the night agent's operating manual
46
+ night-shift/QA-SHIFT.md the QA pre-shift reviewer's manual
47
+ night-shift/logs/ run reports, QA packets, event streams, morning digest (append-only)
48
+ night-shift/sessions.json engine session ids per order (local state, gitignored)
49
+ night-shift/locks/ run locks (gitignored)
50
+ night-shift/worktrees/ per-run worktrees of target repos (gitignored, removed after each run)
51
+ repos/ target repos cloned from git URLs (gitignored)
52
+ src/moonlighting/ the library; every workflow is a moonlighting subcommand
53
+ bin/ misc scripts (the factory greeting)
54
+ docs/work-order-template.md how orders are written
55
+ docs/runbook.md shift checklists (morning, handover, forensics)
56
+ docs/flow.md mermaid diagrams: the day/night work flow
57
+ PLAN.md phased roadmap
58
+ tests/ pytest suite for the factory scripts
59
+ pyproject.toml uv project; publishes the factory command
60
+ AGENTS.md standing instructions for any agent in this repo
61
+ ```
62
+
63
+ ## The rules
64
+
65
+ - The night shift executes only `approved` orders, each on its own branch (`wo/NNN`).
66
+ - Only the day shift merges code into `main` (squash, via `day-shift/accept.py`).
67
+ Night bookkeeping (run logs) commits straight to `main` — but never contains code.
68
+ The factory treats order files as input: gitignored, relocatable via
69
+ `FACTORY_ORDERS_DIR`.
70
+ - A blocked or ambiguous order stops the agent. It asks; it never guesses.
71
+ - The night shift produces **options, not answers**: when the problem is
72
+ unknown, an order asks for variants, and the day shift decides among them.
73
+ - Orders can target other repos: `repo:` frontmatter takes a path or a git
74
+ URL (URLs are cloned under `repos/` and refreshed each night). Night work
75
+ happens in a throwaway git worktree of the target repo — your working
76
+ copies are never switched or touched; only the day shift merges there, and
77
+ the factory never pushes.
78
+
79
+ ## Engines
80
+
81
+ Three hosts run the same work orders through the same flow:
82
+
83
+ | engine | headless invocation | sessions | model syntax |
84
+ | --- | --- | --- | --- |
85
+ | pi (default) | `pi --print` | deterministic: `wo-NNN` | `provider/id`, optional `:thinking` |
86
+ | claude | `claude -p` | uuid per order, kept in `night-shift/sessions.json` | alias or full model id |
87
+ | opencode | `opencode run` | host picks the id (`ses_...`), kept in `night-shift/sessions.json` | `provider/model#variant` |
88
+
89
+ Pick per run with `--engine` (or `FACTORY_ENGINE`). All three run under the
90
+ nWave tool-call guard (`nwave-ai mode all`). Agent commits carry nWave
91
+ attribution.
92
+
93
+ Set the model in three places, most specific first: a `model:` field,
94
+ `--model` (or `FACTORY_MODEL`), or the host default. The string passes
95
+ verbatim to the selected engine. Write it in that engine's syntax from the
96
+ table. Each run header records the model that ran.
97
+
98
+ The QA pass can run its own model. Use `--qa-model` (or env
99
+ `FACTORY_QA_MODEL`). Without it, QA uses the order model.
100
+
101
+ Every run is double-checked by default:
102
+
103
+ - **JSON audit** — the engine's full event stream is archived to
104
+ `night-shift/logs/*.events.jsonl`; the final report is extracted from it.
105
+ Opt out with `FACTORY_JSON_AUDIT=0`.
106
+ - **QA pre-shift** — a second agent pass reviews the night's diff against the
107
+ acceptance criteria and writes a verdict (SHIP/BLOCK/UNSURE) into the order
108
+ file, so the morning decision takes minutes. Opt out with `FACTORY_QA=0`.
109
+
110
+ ## Several factories, several repos
111
+
112
+ One factory process per target repo; processes run in parallel:
113
+
114
+ ```bash
115
+ factory night --repo ~/repos/shop
116
+ factory night --repo git@github.com:acme/api.git --engine claude
117
+ ```
118
+
119
+ Locks make collisions visible: one night per target repo, one night per
120
+ factory checkout. For true parallel nights, clone this factory once per repo
121
+ and run one process in each:
122
+
123
+ ```bash
124
+ git clone ~/repos/moonlighting ~/factories/shop-factory
125
+ cd ~/factories/shop-factory
126
+ factory night --repo ~/repos/shop
127
+ # in another terminal, another clone, another repo, same time — no conflict
128
+ ```
129
+
130
+ The morning is still one command per factory:
131
+
132
+ ```bash
133
+ factory status
134
+ ```
135
+
136
+ ## Requirements
137
+
138
+ - git, Python 3.9+, and [uv](https://docs.astral.sh/uv/). The factory code
139
+ is stdlib-only. uv runs everything: `uv sync` installs the `moonlighting`
140
+ command into the checkout, `uv run pytest` runs the suite. Publish to
141
+ PyPI with `uv build` and `uv publish`.
142
+ - the host CLI for your selected engine, logged in. Pick [pi](https://pi.dev)
143
+ (`pi` → `/login` once), Claude Code (`claude` installed and logged in)
144
+ and/or [opencode](https://opencode.ai) (`opencode auth login` once). Or
145
+ point `PI_BIN`, `CLAUDE_BIN` or `OPENCODE_BIN` at a compatible binary
146
+ - for self-running nights: `crontab` (install with `night-shift/schedule.py install`)
147
+
148
+ ## First night
149
+
150
+ 1. `moonlighting new-order "My task"` — answer the prompts, then approve
151
+ 2. `moonlighting night`
152
+ 3. Tomorrow: `moonlighting status` shows the verdicts. Review the diff, then
153
+ `moonlighting accept ID`, `moonlighting feedback ID "..."` or
154
+ `moonlighting answer ID "..."`
155
+ 4. Optional: `moonlighting schedule install` runs the night daily at 00:01
156
+
157
+ The full shift checklists live in [`docs/runbook.md`](docs/runbook.md).
@@ -0,0 +1,85 @@
1
+ # How work flows through the factory
2
+
3
+ Two views of the same loop: a **flowchart** of the work-order lifecycle
4
+ (who may do what), and a **sequence diagram** of one full day/night cycle.
5
+
6
+ ## Flowchart — the work-order lifecycle
7
+
8
+ ```mermaid
9
+ flowchart TD
10
+ subgraph DAY ["☀️ Day shift — people decide"]
11
+ A["write order\n(status: draft)"] --> B["moonlighting lint-orders"]
12
+ B -->|"problems"| B2["fix the order"]
13
+ B2 --> B
14
+ B -->|"clean"| C["status: approved\nthis is the handover"]
15
+ M["morning: moonlighting status"] --> N{"verdict"}
16
+ N -->|"good"| O["moonlighting accept ID\nsquash-merge into target main"]
17
+ O --> P["done — push the target\n(factory never pushes)"]
18
+ N -->|"not there yet"| Q["status: blocked\n+ question under Day shift decisions"]
19
+ Q --> RE["re-approve for tonight\n(rerun resumes the session)"]
20
+ N -->|"wrong direction"| R["rejected, with a reason"]
21
+ end
22
+
23
+ subgraph NIGHT ["🌙 Night shift — agents execute"]
24
+ S["00:01 cron fires\nmoonlighting night --max-orders 3"] --> T{"approved orders?"}
25
+ T -->|"none"| U["log the no-op\nexit 0 — zero tokens"]
26
+ T -->|"yes"| V["lint gate"]
27
+ V -->|"malformed"| W["blocked — no tokens spent\nhealthy orders still run"]
28
+ V -->|"clean"| X["throwaway worktree\nbranch wo/<id> from local main"]
29
+ X --> Y["engine pass\npi, claude or opencode, headless"]
30
+ Y --> Z["QA pre-shift\nSHIP / BLOCK / UNSURE"]
31
+ Z --> AA["bookkeeping on factory main:\nreport + events archived, status → review"]
32
+ end
33
+
34
+ C --> S
35
+ AA --> M
36
+ RE -.->|"next 00:01"| S
37
+ ```
38
+
39
+ ## Sequence diagram — one full day/night cycle
40
+
41
+ ```mermaid
42
+ sequenceDiagram
43
+ actor H as Day shift (human)
44
+ participant C as cron (00:01)
45
+ participant R as run.py (runner)
46
+ participant E as Engine (pi / claude / opencode)
47
+ participant T as Target repo
48
+
49
+ H->>H: write order · lint · approve
50
+ Note over H,T: evening — the handover
51
+
52
+ C->>R: nightly fire
53
+ R->>R: factory lock · clean-tree check
54
+ R->>R: collect queue (approved, linted)
55
+ loop each order (max N per night)
56
+ R->>T: repo lock · base_ref (ff local main)
57
+ R->>T: git worktree add wo/NNN
58
+ R->>E: headless pass (manual + order embedded)
59
+ E->>T: implement + commit on wo/NNN
60
+ E-->>R: JSON event stream → report
61
+ R->>E: QA pre-shift (run the criteria)
62
+ E-->>R: verdict SHIP / BLOCK / UNSURE
63
+ R->>T: sweep WIP · remove worktree
64
+ R->>R: bookkeeping on factory main\nreport archived · status → review
65
+ end
66
+ Note over H,T: morning — decisions only
67
+
68
+ H->>R: status.py (floor report)
69
+ H->>H: read QA verdict + diff
70
+ alt good
71
+ H->>T: accept.py NNN (squash-merge, done)
72
+ H->>T: push the target
73
+ else not there yet
74
+ H->>T: status: blocked + question
75
+ H->>H: re-approve for tomorrow night
76
+ end
77
+ ```
78
+
79
+ ## The invariants both diagrams rely on
80
+
81
+ - Only the **day shift** moves work into or out of `approved`, `blocked`,
82
+ `done`, `rejected` — and only the day shift merges or pushes.
83
+ - The **night shift** never touches a working copy: every order runs in a
84
+ throwaway worktree on its own branch.
85
+ - Blocked or ambiguous → the night **stops and asks**; it never guesses.