@mobcomputing/mob 0.0.0-stage → 0.2.0
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.
- package/LICENSE +21 -0
- package/README.md +224 -2
- package/bin/mob.mjs +341 -0
- package/examples/wordfreq/README.md +13 -0
- package/examples/wordfreq/index.js +15 -0
- package/examples/wordfreq/mob.config.mjs +29 -0
- package/examples/wordfreq-py/README.md +11 -0
- package/examples/wordfreq-py/mob.config.mjs +29 -0
- package/examples/wordfreq-py/wordfreq.py +19 -0
- package/package.json +38 -4
- package/src/agents-section.md +12 -0
- package/src/config-template.mjs +54 -0
- package/src/gate.mjs +217 -0
- package/src/runner.py +163 -0
- package/src/sandbox.mjs +96 -0
- package/src/selftest.mjs +267 -0
- package/src/worker.mjs +328 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mob contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,225 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<img src="web/assets/m-logo.png" alt="Mob" width="240">
|
|
3
|
+
</p>
|
|
2
4
|
|
|
3
|
-
|
|
5
|
+
<h1 align="center">
|
|
6
|
+
Mob
|
|
7
|
+
<a href="https://discord.gg/Ymfn99CrvM"><img src="https://img.shields.io/badge/Discord-join%20the%20Mob-5865F2?logo=discord&logoColor=white" alt="Discord"></a>
|
|
8
|
+
<a href="https://x.com/mobcomputing"><img src="https://img.shields.io/badge/X-@mobcomputing-000000?logo=x&logoColor=white" alt="X: @mobcomputing"></a>
|
|
9
|
+
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="License: MIT"></a>
|
|
10
|
+
</h1>
|
|
11
|
+
|
|
12
|
+
## Fuck it, push to main
|
|
13
|
+
|
|
14
|
+
Mob is a merge gate for agent swarms, built around a checker that runs your code. Point a swarm at one repo and let it push straight to main: no pull requests, code review or CI queue. Mob checks every push against a recording of what your code does today, and lands it only if the recorded behavior stays exactly the same (and, if you choose, only if it gets faster). It removes the friction for swarms without giving up correctness, and without a human checking every diff. Bring your own model keys and agents. Mob is not an orchestrator, planner or harness.
|
|
15
|
+
|
|
16
|
+
## Why
|
|
17
|
+
|
|
18
|
+
Pull requests, code review and CI queues were built for a few humans making a few careful changes a day. Agents now write code faster than developers can review it. Review is now the bottleneck.
|
|
19
|
+
|
|
20
|
+
We think the answer isn't better review, but no review. Write down once what "correct" means, in a form a machine can check in seconds, and let that check decide. Every push is judged by running the code, never by a model's opinion or a human reviewing the diff. Wrong changes can't land unnoticed on anything you recorded, so agents can work in parallel, push straight to main, and fail cheaply.
|
|
21
|
+
|
|
22
|
+
In the swarm era, progress should be a function of tokens, ambition and the quality of the check. Mob is the check, and it lets developers set their swarms free. Its answer key is a recording of what your code does today, and Mob tests that answer key before trusting it. It plants bugs in your code and reports which ones your recording would miss, so you know how much it covers. Humans stop reading diffs and do the one job left: choosing the goal.
|
|
23
|
+
|
|
24
|
+
## Use cases
|
|
25
|
+
|
|
26
|
+
Mob is intended for large, ambitious projects where many agents attack one codebase at once, and where "correct" can be checked by running the code:
|
|
27
|
+
|
|
28
|
+
- **Speed-ups.** "Make this 10× faster without changing a single output." The swarm tries thousands of ideas, and only the real wins land.
|
|
29
|
+
- **Rewrites and ports.** Move a library to new internals, a new language target or a new architecture. The old version's outputs are the spec the new one must match.
|
|
30
|
+
- **Refactors and cleanups at scale.** Remove a dependency, split a module or modernize a codebase, with `goal: 'same'` guaranteeing behavior doesn't move.
|
|
31
|
+
- **Anything with a clear answer key.** Parsers, formatters, compilers, engines, converters, data pipelines: code where the same input should always give the same output.
|
|
32
|
+
|
|
33
|
+
It is NOT for work where "correct" is a matter of taste, such as UI design or product copy. It also doesn't fit code whose output changes from run to run.
|
|
34
|
+
|
|
35
|
+
## How it works
|
|
36
|
+
|
|
37
|
+
1. `mob init` runs your code on many inputs and records every output. It then runs them again, in the opposite order, to make sure the unchanged code repeats itself; code whose output depends on what ran before it is stopped here, with the input that shows it.
|
|
38
|
+
2. Agents push with `git push mob HEAD:main`.
|
|
39
|
+
3. For each push, Mob checks that nothing protected changed, that every recorded output is byte-identical, and, for goal `faster`, that the change is faster than main in two independent paired timing runs (95% lower bound ≥ 1.0).
|
|
40
|
+
4. The change lands, or the push is refused with the reason and the first differing input.
|
|
41
|
+
|
|
42
|
+
## Try it
|
|
43
|
+
|
|
44
|
+
Five minutes on a tiny example project, with you playing the swarm.
|
|
45
|
+
|
|
46
|
+
**Requirements:** Node 22.13+ and git. On Linux, also bubblewrap (`sudo apt install bubblewrap`); macOS needs nothing extra. Python projects also need `python3`.
|
|
47
|
+
|
|
48
|
+
**1. Install Mob.**
|
|
49
|
+
|
|
50
|
+
```sh
|
|
51
|
+
npm install -g @mobcomputing/mob
|
|
52
|
+
mob --help
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Run the same command again to update Mob. If `mob` is not found, npm put it in a folder that is not on your PATH: run `ln -s "$(npm prefix -g)/bin/mob" ~/.local/bin/mob` (if `~/.local/bin` is on your PATH), or use `npx @mobcomputing/mob` wherever these steps say `mob`.
|
|
56
|
+
|
|
57
|
+
**2. Turn on the gate for the example.**
|
|
58
|
+
|
|
59
|
+
```sh
|
|
60
|
+
cp -r "$(npm root -g)/@mobcomputing/mob/examples/wordfreq" /tmp/wordfreq && cd /tmp/wordfreq
|
|
61
|
+
git init -q -b main && git add -A && git commit -qm wordfreq
|
|
62
|
+
mob init
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
The example already has its contract (`mob.config.mjs`), so `mob init` records 305 outputs, runs the self-test, and turns on the gate. It also writes a Mob section into `AGENTS.md` for agents to read, and leaves it uncommitted. Land it through the gate, the same way every change will land from now on:
|
|
66
|
+
|
|
67
|
+
```sh
|
|
68
|
+
git add AGENTS.md && git commit -qm "Add Mob section to AGENTS.md"
|
|
69
|
+
git push mob HEAD:main
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
**3. Be an agent.** Each agent works in its own clone of the gate:
|
|
73
|
+
|
|
74
|
+
```sh
|
|
75
|
+
git clone -q -o mob /tmp/wordfreq/.mob/gate.git /tmp/agent && cd /tmp/agent
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Make `topWords` in `index.js` faster (for example, count words with a `Map` instead of `indexOf`), then:
|
|
79
|
+
|
|
80
|
+
```sh
|
|
81
|
+
git commit -qam "topWords: count with a Map"
|
|
82
|
+
git push mob HEAD:main
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
The push prints `LANDED` with the speed-up, or `REFUSED` with the reason and the first input whose output changed. Try changing what `topWords` returns to see a refusal.
|
|
86
|
+
|
|
87
|
+
**4. Check progress.**
|
|
88
|
+
|
|
89
|
+
```sh
|
|
90
|
+
cd /tmp/wordfreq
|
|
91
|
+
mob status # speed vs the original, what landed, what was refused and why
|
|
92
|
+
git pull mob main # landed changes live in the gate; this brings them into the repo
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## Use it on your own project
|
|
96
|
+
|
|
97
|
+
**Using a coding agent?** Tell it to set up Mob and give it your goal. It follows [`SKILL.md`](SKILL.md), the step-by-step guide written for agents, which matches the steps below. In Amp, `amp skill add knownquantity/Mob` installs that guide as a skill. Any other agent can read `SKILL.md` or [mob.computer/llms.txt](https://mob.computer/llms.txt).
|
|
98
|
+
|
|
99
|
+
**Doing it yourself?** Mob works on JavaScript, TypeScript and Python code whose output is the same every time for the same input. Same requirements as above. In your repo, on `main`, with your work committed:
|
|
100
|
+
|
|
101
|
+
1. **Run `mob init`.** The first run writes two files and stops: `mob.config.mjs`, the contract, and a Mob section in `AGENTS.md`.
|
|
102
|
+
2. **Fill in `mob.config.mjs`.** The file explains each field:
|
|
103
|
+
- `entry`: the module Mob loads.
|
|
104
|
+
- `goal`: `'faster'` for speed-ups, or `'same'` for rewrites, refactors and cleanups.
|
|
105
|
+
- `inputs()`: the inputs to record. These are the whole guarantee: a change that breaks only inputs you didn't record will land. Cover every option, edge cases, errors and large inputs; several thousand is normal.
|
|
106
|
+
- `run(lib, input)`: how to get the output for one input.
|
|
107
|
+
- Python: `language: 'python'`, `entry: 'pkg/module.py'`, `function: 'name'` and no `run()` (see [`examples/wordfreq-py`](examples/wordfreq-py)).
|
|
108
|
+
- Code that must be compiled first, such as a Rust extension: a `build` command (see [`experiments/chardet`](experiments/chardet)).
|
|
109
|
+
3. **Commit both files:** `git add mob.config.mjs AGENTS.md && git commit -m "Mob contract"`.
|
|
110
|
+
4. **Run `mob init` again.** It records every output, checks that the code repeats them, and turns on the gate.
|
|
111
|
+
5. **Read the self-test.** `mob init` then plants small bugs in your code, one at a time, and reports how many the recorded outputs caught. This tells you how far to trust the gate.
|
|
112
|
+
- **Good result:** most planted bugs refused, and no line saying Mob found inputs that show a bug.
|
|
113
|
+
- **If Mob found inputs that show a bug,** run `mob init --force --fix`. It adds those inputs, commits them, and records again. On js-yaml this found 175 missing inputs, and a real bug that had slipped through is now refused ([details](results/js-yaml-trial.md)).
|
|
114
|
+
- **"Never run" functions** are ones no input reaches, so the swarm could break them unnoticed. Add inputs that reach them, commit, and run `mob init --force`.
|
|
115
|
+
6. **If `mob init` says it changed `AGENTS.md`,** commit it and land it: `git push mob HEAD:main`. From now on, main changes only through the gate.
|
|
116
|
+
7. **Start your swarm.** Mob doesn't run agents; use whatever you already use. Give each agent its own clone, `git clone -o mob <your repo>/.mob/gate.git <folder>`, and the same brief:
|
|
117
|
+
|
|
118
|
+
```text
|
|
119
|
+
Goal: <make X faster | rewrite X in Y | remove dependency Z>, without changing any output.
|
|
120
|
+
Work in <folder>. Land each improvement with `git push mob HEAD:main`; read the Mob section of AGENTS.md first.
|
|
121
|
+
A refused push prints why. Fix it or try another idea; never work around the gate.
|
|
122
|
+
If refused as stale, run `git pull --rebase mob main` and push again.
|
|
123
|
+
Keep pushing small improvements until you run out of ideas.
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
8. **Watch it.** In your repo, `mob status` shows the speed, what landed and why the rest was refused. `git pull mob main` brings landed changes into your repo, or run init with `--forward=origin` to push each landed change on to your usual remote automatically.
|
|
127
|
+
|
|
128
|
+
**Rules agents can't break:** they cannot change `mob.config.mjs` or `.mob/` (the gate refuses those commits), and their code runs in an operating-system sandbox with no network, no writes outside the check's own files, no view of your home folder, and none of your environment variables, so API keys in your shell never reach it. Linux uses bubblewrap; macOS uses its built-in `sandbox-exec`.
|
|
129
|
+
|
|
130
|
+
`mob init --force` clears the gate and its history, so don't run it while a swarm is pushing.
|
|
131
|
+
|
|
132
|
+
## Swarm riding
|
|
133
|
+
|
|
134
|
+
Mob doesn't run your agents, so how you run the swarm is up to you. These habits worked well in our runs.
|
|
135
|
+
|
|
136
|
+
- **Keep reasoning modest.** Each push is one small, checkable change, so agents rarely need deep thinking. High reasoning settings slow each attempt and can use up a reply before any code is written.
|
|
137
|
+
- **Give agents roles.** Profile the code and split agents across its slowest or most important parts, so they don't all chase the same idea and clash. Once small wins dry up, move a few agents to bigger structural rewrites.
|
|
138
|
+
- **Keep the brief short and strict.** One small change per push, read the refusal and try again, never work around the gate. The gate already says what "correct" means, so the brief only needs the goal.
|
|
139
|
+
- **Set stop rules for long runs.** Decide ahead of time when the run ends, such as a few hours with no meaningful gain (our runs: 4 hours without a landing at least 3% faster) or a total time limit. Pauses, such as a hit usage limit, shouldn't count toward either. `mob status` shows what you need to decide.
|
|
140
|
+
- **Don't touch the run.** Changing code by hand mid-run muddies the result. Change the swarm, not the code.
|
|
141
|
+
- **Start from a working example.** [`experiments/commonmark/`](experiments/commonmark/) is the runner behind our results: roles, briefs, stop rules, and the final checks on hidden tests and unseen inputs.
|
|
142
|
+
|
|
143
|
+
## Results
|
|
144
|
+
|
|
145
|
+
### commonmark.js speed-up
|
|
146
|
+
|
|
147
|
+
Two swarms of 20 agents, one per model, each pushed to its own private copy of [commonmark.js](https://github.com/commonmark/commonmark.js). No humans reviewed the diffs. The 699 official tests and the 10,013 real documents (GitHub READMEs, the Rust book, Vue docs, tldr pages) were hidden from both swarms and used only at the end.
|
|
148
|
+
|
|
149
|
+
| | DeepSeek V4.1 Flash | GLM-5.3 |
|
|
150
|
+
|---|---|---|
|
|
151
|
+
| Active hours | 7.8 | 5.0 (cancelled) |
|
|
152
|
+
| Agents | 20 | 20 |
|
|
153
|
+
| Speed vs the original, recorded documents | **2.45×** | **2.46×** |
|
|
154
|
+
| Speed vs the original, 10,013 unseen documents | 2.14× | 1.59× |
|
|
155
|
+
| Reached 2× | after 3.6 hours (change 35) | after 4.3 hours (change 55) |
|
|
156
|
+
| Official tests broken (of 699) | **0** | **0** |
|
|
157
|
+
| Differences on unseen documents (of 40,052 comparisons) | **0** | **0** |
|
|
158
|
+
| Changes landed | 41 | 69 |
|
|
159
|
+
| Changes refused | 1,463 | 1,240 |
|
|
160
|
+
| · not faster | 1,155 | 831 |
|
|
161
|
+
| · changed the output | 120 | 197 |
|
|
162
|
+
| · clashed with a newer main | 36 | 83 |
|
|
163
|
+
| · malformed | 100 | 8 |
|
|
164
|
+
| · edit could not be applied | 12 | 55 |
|
|
165
|
+
| · crashed | 6 | 23 |
|
|
166
|
+
| · speed-up not reproducible | 26 | 41 |
|
|
167
|
+
| · timed out | 1 | 2 |
|
|
168
|
+
| · touched forbidden files | 7 | 0 |
|
|
169
|
+
| Wrong-output changes that passed every official test | 29 | 39 |
|
|
170
|
+
| Model calls | 3,144 | 1,395 |
|
|
171
|
+
| Failed calls | 0 | 51 |
|
|
172
|
+
| Empty replies | 1,635 | 35 |
|
|
173
|
+
| Tokens | 100.9M | 24.6M |
|
|
174
|
+
| · input | 38.4M | 15.9M |
|
|
175
|
+
| · output (thinking) | 62.5M (60.8M) | 8.7M (7.1M) |
|
|
176
|
+
|
|
177
|
+
Without Mob, the wrong-output changes that passed every official test would have reached main. Examples from real READMEs: `<proto` rendered as raw `<`, bullet lists rendered as plain text, quotes left unescaped.
|
|
178
|
+
|
|
179
|
+
Full reports, with each run's speed-over-time chart, are in [`results/commonmark-speedup/`](results/commonmark-speedup/): DeepSeek ([data](results/commonmark-speedup/deepseek-v4.1-flash.json), [chart](results/commonmark-speedup/deepseek-v4.1-flash.svg)), GLM-5.3 ([data](results/commonmark-speedup/glm-5.3.json), [chart](results/commonmark-speedup/glm-5.3.svg)), and the [analysis](results/commonmark-speedup/analysis.md).
|
|
180
|
+
|
|
181
|
+
The DeepSeek code: [`mob-speedup`](https://github.com/knownquantity/commonmark.js/tree/mob-speedup), the original 0.31.2 plus the 41 landed changes, one commit each, as the gate let them in.
|
|
182
|
+
|
|
183
|
+
## Layout
|
|
184
|
+
|
|
185
|
+
```text
|
|
186
|
+
Mob/
|
|
187
|
+
├── bin/
|
|
188
|
+
│ └── mob.mjs # The `mob` command: init, status, check
|
|
189
|
+
├── src/
|
|
190
|
+
│ ├── gate.mjs # Decides whether one push lands
|
|
191
|
+
│ ├── worker.mjs # Runs agent code and compares or times its outputs
|
|
192
|
+
│ ├── sandbox.mjs # The OS sandbox every check runs in
|
|
193
|
+
│ ├── runner.py # Runs Python code for the gate
|
|
194
|
+
│ ├── selftest.mjs # Plants bugs to test your recorded inputs
|
|
195
|
+
│ ├── config-template.mjs # Starting mob.config.mjs written by `mob init`
|
|
196
|
+
│ └── agents-section.md # Instructions `mob init` adds to AGENTS.md
|
|
197
|
+
├── test/
|
|
198
|
+
│ └── gate.test.mjs # End-to-end tests of init and the gate
|
|
199
|
+
├── examples/
|
|
200
|
+
│ ├── wordfreq/ # A small project to try Mob on
|
|
201
|
+
│ └── wordfreq-py/ # The same, in Python
|
|
202
|
+
├── experiments/
|
|
203
|
+
│ ├── commonmark/ # The 20-agent commonmark.js run
|
|
204
|
+
│ ├── prettier/ # Prettier speed-up harness (next run)
|
|
205
|
+
│ ├── stockfish/ # Plan for a Stockfish-to-TypeScript port
|
|
206
|
+
│ ├── chardet/ # chardet (Python) to Rust port: setup and judge
|
|
207
|
+
│ └── provider.mjs # Calls the model API for experiment swarms
|
|
208
|
+
├── results/
|
|
209
|
+
│ ├── commonmark-speedup/ # DeepSeek and GLM-5.3 runs: data, charts, analysis
|
|
210
|
+
│ ├── prettier-speedup/ # Setup now; results after the run
|
|
211
|
+
│ ├── chardet-rewrite/ # How good the chardet port's inputs are
|
|
212
|
+
│ ├── stockfish-rewrite/ # Results after the run
|
|
213
|
+
│ ├── js-yaml-trial.md # Mob on js-yaml, a library not built for it
|
|
214
|
+
│ └── pdfminer-trial.md # Mob on pdfminer.six, the first Python library
|
|
215
|
+
├── SKILL.md # Setup guide for coding agents
|
|
216
|
+
└── web/
|
|
217
|
+
├── index.html # mob.computer
|
|
218
|
+
├── llms.txt # mob.computer/llms.txt: what agents read
|
|
219
|
+
├── assets/ # Logo, favicons, social cards
|
|
220
|
+
└── font/ # Geist Mono
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
## License
|
|
224
|
+
|
|
225
|
+
Mob is MIT-licensed.
|
package/bin/mob.mjs
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// mob: let your agent swarm push straight to main.
|
|
3
|
+
// mob init set up the gate in this repo (run twice: once to write
|
|
4
|
+
// mob.config.mjs, once after you have filled it in).
|
|
5
|
+
// The second run also tests the recorded inputs by
|
|
6
|
+
// planting small bugs; --fix adds the inputs it finds
|
|
7
|
+
// mob status [--json] what has landed, what was refused, and why
|
|
8
|
+
// mob check [rev] run the gate on a commit without landing it
|
|
9
|
+
// mob hook ... called by git; not for direct use
|
|
10
|
+
import fs from 'node:fs'
|
|
11
|
+
import path from 'node:path'
|
|
12
|
+
import { execFileSync } from 'node:child_process'
|
|
13
|
+
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
14
|
+
import { appendLog, buildTree, exportTree, git, judge, mobPaths, readLog, readMeta, runJob, withLock } from '../src/gate.mjs'
|
|
15
|
+
import { neverRun, plantAll, selfTest } from '../src/selftest.mjs'
|
|
16
|
+
import { sandboxProblem } from '../src/sandbox.mjs'
|
|
17
|
+
|
|
18
|
+
const SRC = path.join(path.dirname(fileURLToPath(import.meta.url)), '../src')
|
|
19
|
+
const SELF = fileURLToPath(import.meta.url)
|
|
20
|
+
const say = (...xs) => console.log(...xs)
|
|
21
|
+
const fail = (message) => { console.error(`mob: ${message}`); process.exit(1) }
|
|
22
|
+
const flag = (name, fallback) => {
|
|
23
|
+
const hit = process.argv.find((a) => a === `--${name}` || a.startsWith(`--${name}=`))
|
|
24
|
+
if (!hit) return fallback
|
|
25
|
+
return hit.includes('=') ? hit.slice(hit.indexOf('=') + 1) : true
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function repoRoot() {
|
|
29
|
+
try { return execFileSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() } catch { fail('not inside a git repository') }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function init() {
|
|
33
|
+
const root = repoRoot()
|
|
34
|
+
const configFile = path.join(root, 'mob.config.mjs')
|
|
35
|
+
const p = mobPaths(path.join(root, '.mob'))
|
|
36
|
+
const sh = (...args) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8' }).trim()
|
|
37
|
+
|
|
38
|
+
// Step 1: no config yet. Write the template and the AGENTS.md section.
|
|
39
|
+
if (!fs.existsSync(configFile)) {
|
|
40
|
+
fs.copyFileSync(path.join(SRC, 'config-template.mjs'), configFile)
|
|
41
|
+
writeAgentsSection(root, 'faster')
|
|
42
|
+
say(`Wrote mob.config.mjs and a Mob section in AGENTS.md.
|
|
43
|
+
|
|
44
|
+
Next:
|
|
45
|
+
1. Fill in mob.config.mjs: the entry module, the goal, the inputs to record, and how to run one.
|
|
46
|
+
2. Commit both files.
|
|
47
|
+
3. Run \`mob init\` again to record the current outputs and turn on the gate.`)
|
|
48
|
+
return
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Step 2: record and turn on the gate.
|
|
52
|
+
const branch = flag('branch', 'main')
|
|
53
|
+
try { sh('rev-parse', '--verify', '--quiet', 'HEAD') } catch { fail('this repository has no commits yet; commit your code and mob.config.mjs first') }
|
|
54
|
+
if (sh('rev-parse', '--abbrev-ref', 'HEAD') !== branch) fail(`check out ${branch} first (or pass --branch=<name>)`)
|
|
55
|
+
if (sh('status', '--porcelain', '--', 'mob.config.mjs', 'mob.inputs.json')) fail('commit mob.config.mjs (and mob.inputs.json) first; the gate records from the committed version')
|
|
56
|
+
// One mob init per repo at a time: a second one with --force would delete
|
|
57
|
+
// the first one's work while it runs.
|
|
58
|
+
const initLock = path.join(sh('rev-parse', '--absolute-git-dir'), 'mob-init.lock')
|
|
59
|
+
try { fs.writeFileSync(initLock, String(process.pid), { flag: 'wx' }) } catch {
|
|
60
|
+
const holder = Number(fs.readFileSync(initLock, 'utf8'))
|
|
61
|
+
let alive = false
|
|
62
|
+
try { process.kill(holder, 0); alive = true } catch {}
|
|
63
|
+
if (alive) fail(`another mob init (process ${holder}) is running in this repository; wait for it or stop it`)
|
|
64
|
+
fs.writeFileSync(initLock, String(process.pid))
|
|
65
|
+
}
|
|
66
|
+
process.on('exit', () => { try { if (fs.readFileSync(initLock, 'utf8') === String(process.pid)) fs.rmSync(initLock) } catch {} })
|
|
67
|
+
if (fs.existsSync(p.dir)) {
|
|
68
|
+
if (!flag('force')) fail('.mob/ already exists; pass --force to start over (this clears the gate and its history)')
|
|
69
|
+
fs.rmSync(p.dir, { recursive: true, force: true })
|
|
70
|
+
}
|
|
71
|
+
fs.mkdirSync(p.dir, { recursive: true })
|
|
72
|
+
const extraFile = path.join(root, 'mob.inputs.json')
|
|
73
|
+
const exclude = path.join(sh('rev-parse', '--git-path', 'info/exclude').replace(/^(?!\/)/, root + '/'))
|
|
74
|
+
fs.mkdirSync(path.dirname(exclude), { recursive: true })
|
|
75
|
+
if (!fs.existsSync(exclude) || !fs.readFileSync(exclude, 'utf8').split('\n').includes('.mob/')) fs.appendFileSync(exclude, '\n.mob/\n')
|
|
76
|
+
|
|
77
|
+
// Workers load a snapshot, so agents' later edits to the repo cannot change
|
|
78
|
+
// the contract. Inputs are collected once, from the repo's own file, so a
|
|
79
|
+
// config may read sample files relative to itself. mob.inputs.json holds
|
|
80
|
+
// inputs the self-test found (`mob init --fix`).
|
|
81
|
+
fs.copyFileSync(configFile, p.config)
|
|
82
|
+
const config = (await import(pathToFileURL(configFile).href)).default
|
|
83
|
+
const language = config.language ?? 'javascript'
|
|
84
|
+
if (!['javascript', 'python'].includes(language)) fail(`language must be 'javascript' or 'python', not ${JSON.stringify(language)}`)
|
|
85
|
+
for (const key of ['entry', 'inputs', language === 'python' ? 'function' : 'run']) if (!config[key]) fail(`mob.config.mjs is missing "${key}"`)
|
|
86
|
+
const goal = config.goal ?? 'faster'
|
|
87
|
+
if (!['faster', 'same'].includes(goal)) fail(`goal must be 'faster' or 'same', not ${JSON.stringify(goal)}`)
|
|
88
|
+
if (config.sandbox !== false) { const problem = sandboxProblem(); if (problem) fail(problem) }
|
|
89
|
+
if (config.build && !config.build.command) fail('build needs a command, such as build: { command: [\'sh\', \'build.sh\'] }')
|
|
90
|
+
const own = await config.inputs()
|
|
91
|
+
if (!Array.isArray(own) || own.length === 0) fail('inputs() must return a non-empty array')
|
|
92
|
+
let extra = fs.existsSync(extraFile) ? JSON.parse(fs.readFileSync(extraFile, 'utf8')) : []
|
|
93
|
+
let head = sh('rev-parse', 'HEAD')
|
|
94
|
+
const meta = {
|
|
95
|
+
root, branch, goal, language, python: config.python ?? null, sandbox: config.sandbox !== false, original: head, inputs: 0, protect: config.protect ?? [], docs: config.docs ?? [], build: config.build ?? null,
|
|
96
|
+
samples: Number(flag('samples', 11)), minMs: Number(flag('min-ms', 100)), alpha: 0.05, minSpeedup: Number(flag('min-speedup', 1)),
|
|
97
|
+
benchCores: process.env.MOB_BENCH_CORES ?? null, forward: flag('forward', null), createdAt: new Date().toISOString()
|
|
98
|
+
}
|
|
99
|
+
const coverage = path.join(p.dir, 'coverage')
|
|
100
|
+
// Records the outputs of `head` for own + extra inputs, with coverage.
|
|
101
|
+
const recordAt = async () => {
|
|
102
|
+
const inputs = [...own, ...extra]
|
|
103
|
+
const json = JSON.stringify(inputs)
|
|
104
|
+
if (JSON.stringify(JSON.parse(json)) !== json) fail('inputs must survive a JSON round trip unchanged')
|
|
105
|
+
fs.writeFileSync(p.inputs, json)
|
|
106
|
+
fs.writeFileSync(p.expected, '[]')
|
|
107
|
+
Object.assign(meta, { original: head, inputs: inputs.length })
|
|
108
|
+
fs.writeFileSync(p.meta, JSON.stringify(meta, null, 2) + '\n')
|
|
109
|
+
say(`Recording ${inputs.length} outputs from ${head.slice(0, 7)}…`)
|
|
110
|
+
const tree = exportTree(p, sh('rev-parse', '--absolute-git-dir'), head, root)
|
|
111
|
+
if (meta.build) {
|
|
112
|
+
say('Building…')
|
|
113
|
+
const built = await buildTree(meta, tree)
|
|
114
|
+
if (!built.ok) fail(`the unchanged code does not build, so there is nothing to record: ${built.detail}`)
|
|
115
|
+
}
|
|
116
|
+
fs.rmSync(coverage, { recursive: true, force: true })
|
|
117
|
+
fs.mkdirSync(coverage)
|
|
118
|
+
const recorded = await runJob(p, meta, { mode: 'record', lib: tree, out: p.expected, coverage })
|
|
119
|
+
if (!recorded.ok) fail(`recording failed: ${recorded.reason ?? ''} ${recorded.detail ?? ''}`)
|
|
120
|
+
if (recorded.throws === recorded.inputs) fail('every input threw an error; check entry and run() in mob.config.mjs')
|
|
121
|
+
return { tree, recorded }
|
|
122
|
+
}
|
|
123
|
+
let { tree, recorded } = await recordAt()
|
|
124
|
+
|
|
125
|
+
// The unchanged code must give the same outputs again, in the opposite
|
|
126
|
+
// order too; otherwise the gate would refuse changes at random.
|
|
127
|
+
say('Checking that the unchanged code repeats its own outputs…')
|
|
128
|
+
const again = await runJob(p, meta, { mode: 'check', lib: tree })
|
|
129
|
+
if (!again.ok) {
|
|
130
|
+
const f = again.first
|
|
131
|
+
fail(`the unchanged code does not repeat its own outputs, so Mob cannot tell an agent's change from noise.
|
|
132
|
+
${f ? `input #${f.input} ${f.given} gave a different output when the inputs ran ${f.pass === 'backward' ? 'in the opposite order (state carries over from one input to the next)' : 'a second time'}.
|
|
133
|
+
expected: ${f.expected.slice(0, 200)}
|
|
134
|
+
got: ${f.got.slice(0, 200)}` : `${again.reason}: ${again.detail ?? ''}`}
|
|
135
|
+
Make run() start from a clean state each time${language === 'python' ? ", or set isolate: true to run each input in a fresh Python process" : ''}, or leave such inputs out.`)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Plant a small bug at every place one fits, and see which the check misses.
|
|
139
|
+
const bugs = flag('bugs', 'all')
|
|
140
|
+
const count = bugs === 'all' ? Infinity : Number(bugs)
|
|
141
|
+
const huntMs = Number(flag('hunt-ms', 2000))
|
|
142
|
+
let selftest = null
|
|
143
|
+
if (count > 0) {
|
|
144
|
+
say('Self-test: planting small bugs, one at a time, to see if the recorded outputs notice…')
|
|
145
|
+
selftest = await selfTest(p, meta, { tree, coverageDir: coverage, count, huntMs, log: say })
|
|
146
|
+
if (flag('fix') && selftest.inputsToAdd.length) {
|
|
147
|
+
const seen = new Set(extra.map((v) => JSON.stringify(v)))
|
|
148
|
+
const added = selftest.inputsToAdd.filter((v) => !seen.has(JSON.stringify(v)))
|
|
149
|
+
extra = [...extra, ...added]
|
|
150
|
+
fs.writeFileSync(extraFile, JSON.stringify(extra, null, 1) + '\n')
|
|
151
|
+
sh('add', 'mob.inputs.json')
|
|
152
|
+
sh('commit', '--quiet', '-m', `mob: add ${added.length} inputs found by the self-test`, '--', 'mob.inputs.json')
|
|
153
|
+
const old = tree
|
|
154
|
+
head = sh('rev-parse', 'HEAD')
|
|
155
|
+
;({ tree, recorded } = await recordAt())
|
|
156
|
+
fs.rmSync(old, { recursive: true, force: true })
|
|
157
|
+
// The proof: the bugs those inputs exposed are now refused by the check itself.
|
|
158
|
+
say('Checking the exposed bugs again with the new inputs…')
|
|
159
|
+
const again = await plantAll(p, meta, tree, selftest.exposed, { hunt: false })
|
|
160
|
+
selftest.fixed = { added: added.length, nowCaught: again.filter((r) => r.caught).length, of: again.length, commit: head }
|
|
161
|
+
selftest.neverRun = neverRun(tree, coverage)
|
|
162
|
+
}
|
|
163
|
+
fs.writeFileSync(p.selftest, JSON.stringify(selftest, null, 2) + '\n')
|
|
164
|
+
}
|
|
165
|
+
fs.rmSync(coverage, { recursive: true, force: true })
|
|
166
|
+
|
|
167
|
+
// The same tree against itself: shows how noisy timing is on this machine.
|
|
168
|
+
let noise = null
|
|
169
|
+
if (goal === 'faster') {
|
|
170
|
+
say('Measuring timing noise (main against itself)…')
|
|
171
|
+
const twin = path.join(p.trees, `${head}-twin`)
|
|
172
|
+
fs.cpSync(tree, twin, { recursive: true, verbatimSymlinks: true })
|
|
173
|
+
const aa = await runJob(p, meta, { mode: 'bench', lib: twin, current: tree, samples: meta.samples, minMs: meta.minMs, alpha: meta.alpha })
|
|
174
|
+
fs.rmSync(twin, { recursive: true, force: true })
|
|
175
|
+
// Without timing, every push for goal 'faster' would be refused.
|
|
176
|
+
if (!aa.ok) fail(`timing the code failed, so the gate could not judge speed: ${aa.reason} ${aa.detail ?? ''}`)
|
|
177
|
+
noise = { speedup: aa.speedup, lower: aa.lower, msPerPass: aa.currentMs }
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// The gate repository: a bare copy of main whose hooks run the gate.
|
|
181
|
+
execFileSync('git', ['clone', '--bare', '--quiet', '--branch', branch, root, p.gate])
|
|
182
|
+
git(p.gate, ['config', 'receive.denyNonFastForwards', 'true'])
|
|
183
|
+
git(p.gate, ['config', 'receive.denyDeletes', 'true'])
|
|
184
|
+
git(p.gate, ['symbolic-ref', 'HEAD', `refs/heads/${branch}`])
|
|
185
|
+
for (const hook of ['pre-receive', 'post-receive']) {
|
|
186
|
+
const file = path.join(p.gate, 'hooks', hook)
|
|
187
|
+
fs.writeFileSync(file, `#!/bin/sh\nexec "${process.execPath}" "${SELF}" hook ${hook} "${p.dir}"\n`)
|
|
188
|
+
fs.chmodSync(file, 0o755)
|
|
189
|
+
}
|
|
190
|
+
sh('remote', sh('remote').split('\n').includes('mob') ? 'set-url' : 'add', 'mob', p.gate)
|
|
191
|
+
sh('fetch', '--quiet', 'mob')
|
|
192
|
+
|
|
193
|
+
appendLog(p, { event: 'init', sha: head, inputs: meta.inputs, throws: recorded.throws, goal, noise, selftest: selftest && { planted: selftest.planted, caught: selftest.caught, exposed: selftest.exposed.length, unresolved: selftest.unresolved.length, fixed: selftest.fixed ?? null, neverRun: selftest.neverRun.length } })
|
|
194
|
+
const agentsNote = writeAgentsSection(root, goal) ? '\n AGENTS.md: added the Mob section; commit it and land it through the gate (git push mob HEAD:main) so agents see it' : ''
|
|
195
|
+
say(`
|
|
196
|
+
Mob is on.
|
|
197
|
+
recorded: ${meta.inputs} inputs (${recorded.throws} of them throw, which is recorded too)
|
|
198
|
+
goal: ${goal === 'faster' ? 'identical outputs, measurably faster' : 'identical outputs'}${noise ? `\n timing: one pass ${noise.msPerPass.toFixed(0)} ms; main vs itself ${noise.speedup.toFixed(3)}× (should be close to 1)` : ''}
|
|
199
|
+
gate: git push mob HEAD:main (agents: see the Mob section in AGENTS.md)
|
|
200
|
+
clone: git clone -o mob ${p.gate} <dir> (one copy per agent)
|
|
201
|
+
progress: mob status${agentsNote}`)
|
|
202
|
+
if (selftest) say(selftestReport(selftest))
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function selftestReport(t) {
|
|
206
|
+
const site = (m) => ` ${m.file}:${m.line}:${m.col + 1} ${m.to ? `${m.from.trim()} → ${m.to.trim()} ${m.code}` : `delete ${m.code}`}`
|
|
207
|
+
const show = (x, n) => { const j = JSON.stringify(x); return j.length > n ? j.slice(0, n) + '…' : j }
|
|
208
|
+
const lines = ['', `Self-test: planted ${t.planted} bugs, one at a time${t.planted === t.sites ? ', at every place in the code where one fits' : ` (of ${t.sites} places)`}.`, ` ${t.caught} refused by the recorded outputs.`]
|
|
209
|
+
if (t.fixed) {
|
|
210
|
+
lines.push(` ${t.exposed.length} got past them, but Mob found an input that shows each one. Added ${t.fixed.added} inputs to mob.inputs.json (committed ${t.fixed.commit.slice(0, 7)}) and recorded again.`)
|
|
211
|
+
lines.push(` Checked again: ${t.fixed.nowCaught} of those ${t.fixed.of} are now refused. In total ${t.caught + t.fixed.nowCaught} of ${t.planted} planted bugs are refused.`)
|
|
212
|
+
} else if (t.exposed.length) {
|
|
213
|
+
lines.push(` ${t.exposed.length} got past them, but Mob found an input that shows each one (${t.inputsToAdd.length} distinct inputs). For example:`)
|
|
214
|
+
for (const m of t.exposed.slice(0, 6)) lines.push(site(m), ` input ${show(m.input, 60)}`, ` right: ${show(m.expected, 70)}`, ` with bug: ${show(m.got, 70)}`)
|
|
215
|
+
lines.push(' Run `mob init --force --fix` to add these inputs, commit them, and record again.')
|
|
216
|
+
}
|
|
217
|
+
if (t.unresolved.length) {
|
|
218
|
+
lines.push(` ${t.unresolved.length} got past them, and no input Mob tried shows any difference. These probably change nothing; look over them:`)
|
|
219
|
+
for (const m of t.unresolved.slice(0, 10)) lines.push(site(m) + (m.reached ? '' : ' (never run)') + (m.hung ? ' (hangs)' : ''))
|
|
220
|
+
if (t.unresolved.length > 10) lines.push(` … and ${t.unresolved.length - 10} more`)
|
|
221
|
+
}
|
|
222
|
+
if (t.neverRun.length) {
|
|
223
|
+
lines.push(` Never run by any recorded input (${t.neverRun.length} function${t.neverRun.length === 1 ? '' : 's'}):`)
|
|
224
|
+
for (const f of t.neverRun.slice(0, 10)) lines.push(` ${f.file}:${f.line} ${f.name}`)
|
|
225
|
+
if (t.neverRun.length > 10) lines.push(` … and ${t.neverRun.length - 10} more`)
|
|
226
|
+
}
|
|
227
|
+
lines.push(' Full list: .mob/selftest.json')
|
|
228
|
+
return lines.join('\n')
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function writeAgentsSection(root, goal) {
|
|
232
|
+
const file = path.join(root, 'AGENTS.md')
|
|
233
|
+
const section = fs.readFileSync(path.join(SRC, 'agents-section.md'), 'utf8').replace('{{goal}}', goal === 'faster' ? ' and the code gets measurably faster' : '')
|
|
234
|
+
const current = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : ''
|
|
235
|
+
const next = current.includes('<!-- mob:start -->')
|
|
236
|
+
? current.replace(/<!-- mob:start -->[\s\S]*?<!-- mob:end -->\n?/, section)
|
|
237
|
+
: (current ? current.replace(/\n*$/, '\n\n') : '') + section
|
|
238
|
+
if (next === current) return false
|
|
239
|
+
fs.writeFileSync(file, next)
|
|
240
|
+
return true
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function mobDirHere() {
|
|
244
|
+
const p = mobPaths(path.join(repoRoot(), '.mob'))
|
|
245
|
+
if (!fs.existsSync(p.meta)) fail('Mob is not set up here; run `mob init`')
|
|
246
|
+
return p
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// git calls pre-receive with "<old> <new> <ref>" lines on stdin. Checks run one
|
|
250
|
+
// at a time under a lock; a refused push prints the reason back to the pusher.
|
|
251
|
+
async function preReceive(mobDir) {
|
|
252
|
+
const p = mobPaths(mobDir)
|
|
253
|
+
const meta = readMeta(p)
|
|
254
|
+
const lines = fs.readFileSync(0, 'utf8').trim().split('\n').filter(Boolean)
|
|
255
|
+
const tell = (msg) => { for (const line of String(msg).split('\n')) console.error(`mob: ${line}`) }
|
|
256
|
+
for (const line of lines) {
|
|
257
|
+
const [oldSha, newSha, ref] = line.split(' ')
|
|
258
|
+
if (ref !== `refs/heads/${meta.branch}`) { tell(`only ${meta.branch} can be pushed here`); process.exit(1) }
|
|
259
|
+
const result = await withLock(p, async () => {
|
|
260
|
+
const main = git(p.gate, ['rev-parse', `refs/heads/${meta.branch}`])
|
|
261
|
+
if (oldSha !== main) return { landed: false, reason: 'stale', detail: 'another change landed first; git pull --rebase mob main, then push again' }
|
|
262
|
+
tell(`checking ${newSha.slice(0, 7)}…`)
|
|
263
|
+
return judge(p, { gitDir: p.gate, baseSha: main, newSha, log: tell })
|
|
264
|
+
})
|
|
265
|
+
const subject = (() => { try { return git(p.gate, ['log', '-1', '--format=%s', newSha]) } catch { return '' } })()
|
|
266
|
+
const author = (() => { try { return git(p.gate, ['log', '-1', '--format=%an', newSha]) } catch { return '' } })()
|
|
267
|
+
appendLog(p, { event: result.landed ? 'landed' : 'refused', sha: newSha, base: oldSha, subject, author, ...result })
|
|
268
|
+
if (!result.landed) {
|
|
269
|
+
fs.rmSync(path.join(p.trees, newSha), { recursive: true, force: true })
|
|
270
|
+
tell(`REFUSED (${result.reason}): ${result.detail}`)
|
|
271
|
+
if (result.first) tell(`first difference: input #${result.first.input} ${result.first.given}\n expected: ${result.first.expected}\n got: ${result.first.got}`)
|
|
272
|
+
process.exit(1)
|
|
273
|
+
}
|
|
274
|
+
fs.rmSync(path.join(p.trees, oldSha), { recursive: true, force: true })
|
|
275
|
+
tell(`LANDED: ${result.detail}`)
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function postReceive(mobDir) {
|
|
280
|
+
const p = mobPaths(mobDir)
|
|
281
|
+
const meta = readMeta(p)
|
|
282
|
+
fs.readFileSync(0, 'utf8')
|
|
283
|
+
if (!meta.forward) return
|
|
284
|
+
try { git(p.gate, ['push', '--quiet', meta.forward, `refs/heads/${meta.branch}:refs/heads/${meta.branch}`]) } catch (error) {
|
|
285
|
+
console.error(`mob: landed, but forwarding to ${meta.forward} failed: ${String(error.message).split('\n')[0]}`)
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
async function check() {
|
|
290
|
+
const p = mobDirHere()
|
|
291
|
+
const meta = readMeta(p)
|
|
292
|
+
const root = meta.root
|
|
293
|
+
const rev = process.argv[3] && !process.argv[3].startsWith('--') ? process.argv[3] : 'HEAD'
|
|
294
|
+
const sh = (...args) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8' }).trim()
|
|
295
|
+
sh('fetch', '--quiet', 'mob')
|
|
296
|
+
const newSha = sh('rev-parse', `${rev}^{commit}`)
|
|
297
|
+
const baseSha = sh('rev-parse', `refs/remotes/mob/${meta.branch}`)
|
|
298
|
+
const result = await withLock(p, () => judge(p, { gitDir: sh('rev-parse', '--absolute-git-dir'), baseSha, newSha, log: (m) => console.error(`mob: ${m}`) }))
|
|
299
|
+
if (!result.landed && newSha !== baseSha) fs.rmSync(path.join(p.trees, newSha), { recursive: true, force: true })
|
|
300
|
+
say(result.landed ? `WOULD LAND: ${result.detail}` : `WOULD BE REFUSED (${result.reason}): ${result.detail}`)
|
|
301
|
+
if (result.first) say(`first difference: input #${result.first.input} ${result.first.given}\n expected: ${result.first.expected}\n got: ${result.first.got}`)
|
|
302
|
+
process.exitCode = result.landed ? 0 : 1
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function status() {
|
|
306
|
+
const p = mobDirHere()
|
|
307
|
+
const meta = readMeta(p)
|
|
308
|
+
const log = readLog(p)
|
|
309
|
+
const landed = log.filter((e) => e.event === 'landed')
|
|
310
|
+
const refused = log.filter((e) => e.event === 'refused')
|
|
311
|
+
const reasons = {}
|
|
312
|
+
for (const e of refused) reasons[e.reason] = (reasons[e.reason] ?? 0) + 1
|
|
313
|
+
const speedup = landed.reduce((x, e) => x * (e.speedup ?? 1), 1)
|
|
314
|
+
const main = git(p.gate, ['rev-parse', `refs/heads/${meta.branch}`])
|
|
315
|
+
const summary = { goal: meta.goal, main, inputs: meta.inputs, landed: landed.length, refused: refused.length, reasons, speedup: meta.goal === 'faster' ? Number(speedup.toFixed(3)) : null, selftest: log.find((e) => e.event === 'init')?.selftest ?? null, recent: log.filter((e) => e.event !== 'init').slice(-8) }
|
|
316
|
+
if (flag('json')) return say(JSON.stringify(summary, null, 2))
|
|
317
|
+
say(`main ${main.slice(0, 7)} · goal: ${meta.goal === 'faster' ? 'identical outputs, faster' : 'identical outputs'} · ${meta.inputs} recorded inputs`)
|
|
318
|
+
if (meta.goal === 'faster') say(`speed: ${speedup.toFixed(2)}× the original`)
|
|
319
|
+
if (summary.selftest) { const t = summary.selftest; say(`self-test: ${t.caught + (t.fixed?.nowCaught ?? 0)} of ${t.planted} planted bugs refused; ${t.unresolved ?? 0} probably change nothing`) }
|
|
320
|
+
say(`landed: ${landed.length} refused: ${refused.length}${refused.length ? ' (' + Object.entries(reasons).sort((a, b) => b[1] - a[1]).map(([r, n]) => `${n} ${r}`).join(', ') + ')' : ''}`)
|
|
321
|
+
if (summary.recent.length) {
|
|
322
|
+
say('\nrecent:')
|
|
323
|
+
for (const e of summary.recent) say(` ${e.at.slice(11, 19)} ${e.event === 'landed' ? 'LANDED ' : 'refused'} ${e.sha.slice(0, 7)} ${e.event === 'landed' ? e.detail : `${e.reason}: ${e.detail}`}${e.subject ? ` "${e.subject.slice(0, 60)}"` : ''}`)
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
const HELP = `mob: let your agent swarm push straight to main.
|
|
328
|
+
|
|
329
|
+
mob init set up the gate in this git repo
|
|
330
|
+
mob status [--json] what landed, what was refused, and why
|
|
331
|
+
mob check [rev] run the gate on a commit without landing it
|
|
332
|
+
|
|
333
|
+
Agents push with: git push mob HEAD:main`
|
|
334
|
+
|
|
335
|
+
const [command, ...rest] = process.argv.slice(2)
|
|
336
|
+
if (command === 'init') await init()
|
|
337
|
+
else if (command === 'status') status()
|
|
338
|
+
else if (command === 'check') await check()
|
|
339
|
+
else if (command === 'hook' && rest[0] === 'pre-receive') await preReceive(rest[1])
|
|
340
|
+
else if (command === 'hook' && rest[0] === 'post-receive') postReceive(rest[1])
|
|
341
|
+
else { say(HELP); if (command && !['help', '--help', '-h'].includes(command)) process.exitCode = 1 }
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Example: wordfreq
|
|
2
|
+
|
|
3
|
+
A tiny library with a deliberately slow function, for trying Mob end to end.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
cp -r examples/wordfreq /tmp/wordfreq && cd /tmp/wordfreq
|
|
7
|
+
git init -q -b main && git add -A && git commit -qm "wordfreq"
|
|
8
|
+
mob init
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Then make `topWords` faster (for example, count with a `Map` instead of
|
|
12
|
+
`indexOf`), commit, and `git push mob HEAD:main`. Change what it returns, and
|
|
13
|
+
the push is refused with the first input whose output differs.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// Returns the n most frequent words in a text, most frequent first; ties are
|
|
2
|
+
// broken alphabetically. Words are lowercase runs of letters and digits.
|
|
3
|
+
// Deliberately slow, so a swarm has something to speed up.
|
|
4
|
+
export function topWords(text, n) {
|
|
5
|
+
const words = text.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((w) => w.length > 0)
|
|
6
|
+
const seen = []
|
|
7
|
+
const counts = []
|
|
8
|
+
for (const word of words) {
|
|
9
|
+
const i = seen.indexOf(word)
|
|
10
|
+
if (i === -1) { seen.push(word); counts.push(1) } else counts[i] += 1
|
|
11
|
+
}
|
|
12
|
+
const pairs = seen.map((word, i) => [word, counts[i]])
|
|
13
|
+
pairs.sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
|
|
14
|
+
return pairs.slice(0, n).map(([word, count]) => `${word} ${count}`)
|
|
15
|
+
}
|