@dibssoftware/dibs 0.0.0-stage → 0.0.179

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 (75) hide show
  1. package/CHANGELOG.md +594 -0
  2. package/LICENSE +670 -0
  3. package/README.md +85 -2
  4. package/bin/dibs-guard.mjs +7 -0
  5. package/bin/dibs.mjs +548 -0
  6. package/docs/benchmarks.md +193 -0
  7. package/docs/files.md +30 -0
  8. package/docs/guard.md +91 -0
  9. package/docs/later.md +43 -0
  10. package/docs/machines.md +147 -0
  11. package/docs/questions.md +78 -0
  12. package/docs/reference.md +157 -0
  13. package/docs/relay.md +196 -0
  14. package/docs/releasing.md +27 -0
  15. package/docs/scheduling.md +163 -0
  16. package/docs/simulators.md +17 -0
  17. package/package.json +45 -4
  18. package/skills/dibs/SKILL.md +183 -0
  19. package/src/acquire.mjs +700 -0
  20. package/src/admin.mjs +145 -0
  21. package/src/agents.mjs +145 -0
  22. package/src/alerts.mjs +499 -0
  23. package/src/answers.mjs +65 -0
  24. package/src/board.mjs +202 -0
  25. package/src/broker.mjs +369 -0
  26. package/src/commands.mjs +810 -0
  27. package/src/config.mjs +324 -0
  28. package/src/connect.mjs +106 -0
  29. package/src/cool.mjs +160 -0
  30. package/src/diskwarn.mjs +154 -0
  31. package/src/events.mjs +96 -0
  32. package/src/files.mjs +1123 -0
  33. package/src/guard.mjs +613 -0
  34. package/src/history.mjs +247 -0
  35. package/src/hogs.mjs +227 -0
  36. package/src/later.mjs +487 -0
  37. package/src/measure.mjs +262 -0
  38. package/src/news.mjs +101 -0
  39. package/src/nodecheck.mjs +17 -0
  40. package/src/notes.mjs +171 -0
  41. package/src/notices.mjs +160 -0
  42. package/src/ondemand.mjs +572 -0
  43. package/src/overlap.mjs +151 -0
  44. package/src/override.mjs +360 -0
  45. package/src/owner.mjs +30 -0
  46. package/src/plain.mjs +470 -0
  47. package/src/platform.mjs +357 -0
  48. package/src/preempt.mjs +438 -0
  49. package/src/primer.mjs +89 -0
  50. package/src/proc.mjs +99 -0
  51. package/src/progress.mjs +187 -0
  52. package/src/qr.mjs +204 -0
  53. package/src/questions.mjs +389 -0
  54. package/src/quota.mjs +81 -0
  55. package/src/reads.mjs +54 -0
  56. package/src/relay.mjs +779 -0
  57. package/src/remote.mjs +584 -0
  58. package/src/reset.mjs +127 -0
  59. package/src/schedule.mjs +1020 -0
  60. package/src/scratch.mjs +61 -0
  61. package/src/serve.mjs +742 -0
  62. package/src/service.mjs +221 -0
  63. package/src/shard.mjs +59 -0
  64. package/src/simctl.mjs +42 -0
  65. package/src/simpool.mjs +258 -0
  66. package/src/state.mjs +201 -0
  67. package/src/stats.mjs +328 -0
  68. package/src/style.mjs +44 -0
  69. package/src/talk.mjs +702 -0
  70. package/src/thin.sh +130 -0
  71. package/src/trust.mjs +152 -0
  72. package/src/util.mjs +184 -0
  73. package/src/version.mjs +2 -0
  74. package/src/web.mjs +1119 -0
  75. package/src/worker.mjs +318 -0
@@ -0,0 +1,187 @@
1
+ // dibs progress: agents narrating their work as they go, as often as they
2
+ // commit. Each post is one line in progress.jsonl: who, which task, what just
3
+ // happened, and when the task should be done. The person reads it on the web
4
+ // page (src/web.mjs) and through its MCP tools; agents read each other's with
5
+ // plain `dibs progress`.
6
+ //
7
+ // Appends only, one write per post, so no lock: a line under the size cap goes
8
+ // down whole even with several agents posting at once. Past MAX_FILE the file is
9
+ // renamed to progress.1.jsonl (replacing the one before) and a new one starts. A
10
+ // rename loses nothing: a post being written lands in whichever file it opened.
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import { HOME } from './config.mjs';
14
+ import { identity, sessionFiles } from './proc.mjs';
15
+ import { die, now, deadline, dur, clock } from './util.mjs';
16
+ import { bold, dim } from './style.mjs';
17
+
18
+ export const FILE = path.join(HOME, 'progress.jsonl');
19
+ const OLDER = path.join(HOME, 'progress.1.jsonl');
20
+ // A post is a paragraph or two. Verbose is the point; a pasted log is not.
21
+ const MAX_TEXT = 2000;
22
+ const MAX_TASK = 80;
23
+ // About 10,000 posts a file, two files kept. Plenty of scrollback, and reading stays fast.
24
+ const MAX_FILE = 4 * 1024 ** 2;
25
+ // The plain list shows this many unless asked for more.
26
+ const RECENT = 30;
27
+ const STATES = ['doing', 'done', 'blocked'];
28
+ // A task still in progress past its ETA reads overdue. With no post for this long past
29
+ // both its last post and its ETA, it's taken for dropped (an agent that shipped and never
30
+ // said --done, a session that ended) and reads expired, not in progress. The page, the
31
+ // app (app/Dibs/Models/Progress.swift) and the notices use the same numbers.
32
+ export const EXPIRE_AFTER = 3 * 36e5;
33
+ // An open task whose agent hasn't posted this long: the agent hears about it once (src/notices.mjs).
34
+ export const QUIET_AFTER = 45 * 6e4;
35
+
36
+ function parse(args) {
37
+ const o = { words: [] };
38
+ for (let i = 0; i < args.length; i++) {
39
+ const a = args[i];
40
+ const val = () => args[++i] ?? die(`${a} needs a value`);
41
+ if (a === '--task' || a === '-t') o.task = val();
42
+ else if (a === '--eta') o.eta = val();
43
+ else if (a === '--done') o.state = 'done';
44
+ else if (a === '--blocked') o.state = 'blocked';
45
+ else if (a === '--as') o.as = val();
46
+ else if (a === '--agent') o.agent = val();
47
+ else if (a === '-n') o.n = Number(val());
48
+ else if (a === '--json') o.json = true;
49
+ else if (a === '--all') o.all = true;
50
+ else if (a.startsWith('-') && a.length > 1) die(`unknown flag ${a}. Try: dibs progress "ran the auth tests: 41 pass, 2 fail on token expiry" --task auth --eta 20m`);
51
+ else o.words.push(a);
52
+ }
53
+ o.text = o.words.join(' ').trim();
54
+ return o;
55
+ }
56
+
57
+ // The branch the agent is on, read straight from .git so posting costs no git process.
58
+ function branch(dir) {
59
+ for (let d = dir, i = 0; i < 20; i++, d = path.dirname(d)) {
60
+ const g = path.join(d, '.git');
61
+ try {
62
+ let head;
63
+ if (fs.statSync(g).isFile()) {
64
+ const real = fs.readFileSync(g, 'utf8').match(/gitdir: (.+)/)?.[1]?.trim();
65
+ head = fs.readFileSync(path.join(path.resolve(d, real), 'HEAD'), 'utf8');
66
+ } else head = fs.readFileSync(path.join(g, 'HEAD'), 'utf8');
67
+ return { root: d, branch: head.match(/ref: refs\/heads\/(.+)/)?.[1]?.trim() || head.trim().slice(0, 8) };
68
+ } catch {}
69
+ if (d === path.dirname(d)) break;
70
+ }
71
+ return { root: null, branch: null };
72
+ }
73
+
74
+ export async function post(args) {
75
+ const o = parse(args);
76
+ // dibs progress list: the open tasks. One word "list" is the command, never a post (2026-11-03: crews kept typing it).
77
+ if (o.words.length === 1 && o.words[0] === 'list' && !o.task && !o.state && !o.eta) return openTasks(o);
78
+ if (o.all) die('--all goes with dibs progress list');
79
+ if (!o.text) return list(o);
80
+ if (o.text.length > MAX_TEXT) die(`that's ${o.text.length} characters; keep a post under ${MAX_TEXT} and post again as you go. Nothing was posted.`);
81
+ if (o.task && o.task.length > MAX_TASK) die(`--task is a short name (under ${MAX_TASK} characters), not a description. Nothing was posted.`);
82
+ // Line breaks belong in the text; anywhere else they could make a post pass for someone else's line.
83
+ if (o.task && /[\u0000-\u001f\u007f]/.test(o.task)) die('--task is one line, without control characters. Nothing was posted.');
84
+ o.text = o.text.replace(/[\u0000-\u0009\u000b-\u001f\u007f]/g, ' ');
85
+ let eta = null;
86
+ if (o.eta) {
87
+ eta = deadline(o.eta);
88
+ if (!(eta > now())) die(`--eta takes how long (20m, 2h) or a clock time (17:30), not ${o.eta}. Nothing was posted.`);
89
+ }
90
+ const id = identity(o);
91
+ const session = process.env.CLAUDE_CODE_SESSION_ID || sessionFiles().find(f => f.pid === id.spid)?.sessionId || null;
92
+ const where = branch(process.cwd());
93
+ // Which subagent of the session posts, as the hook saw it ask (src/files.mjs):
94
+ // its task is its own, and so is the nudge when it goes quiet. On 2026-11-03 a
95
+ // lead got overdue notices for its teammates' tasks.
96
+ const by = session ? (await import('./files.mjs')).takeAgent('progress', [], (await import('./files.mjs')).talkKey('progress', args)) : null;
97
+ const p = {
98
+ at: now(), who: id.who, ...((id.label || by?.agentType) && { label: id.label || by.agentType }), ...(session && { session }),
99
+ ...(by?.agentId && by.agentId !== 'main' && { agentId: by.agentId }),
100
+ project: path.basename(where.root || process.cwd()), ...(where.branch && { branch: where.branch }),
101
+ ...(o.task && { task: o.task }), state: o.state || 'doing', ...(eta && { eta }), text: o.text,
102
+ };
103
+ fs.mkdirSync(HOME, { recursive: true });
104
+ fs.appendFileSync(FILE, `${JSON.stringify(p)}\n`);
105
+ rotate();
106
+ // "done by" read as done to agents; and a closing post needs no nudge to keep posting.
107
+ if (p.state !== 'doing') return console.log(`Posted${o.task ? ` to ${o.task}` : ''}, marked ${p.state}.`);
108
+ console.log(`Posted${o.task ? ` to ${o.task}` : ''}${eta ? `, expected by ${clock(eta)}` : ''}. Keep posting as you go: dibs progress "..."`);
109
+ }
110
+
111
+ function rotate() {
112
+ try { if (fs.statSync(FILE).size > MAX_FILE) fs.renameSync(FILE, OLDER); } catch {}
113
+ }
114
+
115
+ // Posts, oldest first. A torn or hand-edited line is skipped, not fatal.
116
+ export function read({ since = 0, agent = null, limit = Infinity } = {}) {
117
+ let raw = '';
118
+ for (const f of [OLDER, FILE]) { try { raw += fs.readFileSync(f, 'utf8'); } catch {} }
119
+ const out = [];
120
+ for (const line of raw.split('\n')) {
121
+ if (!line) continue;
122
+ let p;
123
+ try { p = JSON.parse(line); } catch { continue; }
124
+ if (typeof p.at !== 'number' || typeof p.text !== 'string' || typeof p.who !== 'string') continue;
125
+ if (p.at <= since || (agent && p.who !== agent)) continue;
126
+ if (!STATES.includes(p.state)) p.state = 'doing';
127
+ out.push(p);
128
+ }
129
+ return Number.isFinite(limit) ? out.slice(-limit) : out;
130
+ }
131
+
132
+ // Each agent's tasks, from its posts: the latest word on each, when it started,
133
+ // and when it should end. A post without --task belongs to the agent's
134
+ // untitled task in that project. One still doing past its ETA is overdue; one
135
+ // quiet past EXPIRE_AFTER is expired.
136
+ export function tasks(posts, at = now()) {
137
+ const by = new Map();
138
+ for (const p of posts) {
139
+ // A subagent's task is its own, apart from its lead's of the same name.
140
+ const key = `${p.who}\0${p.agentId || ''}\0${p.task || ''}\0${p.task ? '' : p.project || ''}`;
141
+ let t = by.get(key);
142
+ if (!t) by.set(key, t = { who: p.who, label: p.label || null, ...(p.agentId && { agentId: p.agentId }), task: p.task || null, project: p.project || null, branch: p.branch || null, started: p.at, posts: 0 });
143
+ Object.assign(t, { last: p.at, state: p.state, text: p.text, branch: p.branch || t.branch, project: p.project || t.project, session: p.session || t.session || null });
144
+ if (p.eta) t.eta = p.eta;
145
+ if (p.state === 'doing' && t.state === 'doing' && t.doneAt) delete t.doneAt;
146
+ if (p.state === 'done') t.doneAt = p.at;
147
+ t.posts++;
148
+ }
149
+ for (const k of by.values()) {
150
+ if (k.state !== 'doing') continue;
151
+ const quiet = Math.max(k.last, k.eta || 0);
152
+ if (at - quiet > EXPIRE_AFTER) Object.assign(k, { state: 'expired', expiredAt: quiet + EXPIRE_AFTER });
153
+ else if (k.eta && k.eta < at) k.overdue = true;
154
+ }
155
+ return [...by.values()].sort((a, b) => b.last - a.last);
156
+ }
157
+
158
+ // The open tasks of the caller's session (every agent in it), or every session's with
159
+ // --all: who owns each, its state, its ETA and its last post.
160
+ function openTasks(o) {
161
+ const id = identity(o);
162
+ const session = process.env.CLAUDE_CODE_SESSION_ID || sessionFiles().find(f => f.pid === id.spid)?.sessionId || null;
163
+ const mine = p => o.all || (session ? p.session === session : p.who === id.who);
164
+ const t = now();
165
+ const open = tasks(read().filter(mine), t).filter(k => k.state === 'doing' || k.state === 'blocked');
166
+ if (o.json) return console.log(JSON.stringify(open, null, 1));
167
+ if (!open.length) return console.log(o.all ? 'No open tasks on this machine.' : 'Your session has no open tasks. Every session\'s: dibs progress list --all');
168
+ for (const k of open) {
169
+ const owner = `${k.who}${k.label ? `/${k.label}` : ''}`;
170
+ const due = k.eta ? (k.overdue ? `overdue since ${clock(k.eta)}` : `expected by ${clock(k.eta)}`) : 'no ETA';
171
+ console.log(`${bold(k.task || `(untitled, in ${k.project || 'a folder'})`)} ${owner} ${k.state}, ${due}, last post ${dur(t - k.last)} ago`);
172
+ console.log(` ${k.text.replace(/\s*\n\s*/g, ' ').slice(0, 300)}`);
173
+ }
174
+ console.log(dim(`Close one: dibs progress "what's done" --task <name> --done${o.all ? '' : '. Every session\'s: dibs progress list --all'}`));
175
+ }
176
+
177
+ function list(o) {
178
+ const posts = read({ agent: o.agent, limit: o.n > 0 ? o.n : RECENT });
179
+ if (o.json) return console.log(JSON.stringify(posts, null, 1));
180
+ if (!posts.length) return console.log('No progress posted yet. Post as you work: dibs progress "what just happened" --task <name> --eta 20m');
181
+ const t = now();
182
+ for (const p of posts) {
183
+ const tag = [p.task, p.state !== 'doing' && p.state].filter(Boolean).join(', ');
184
+ console.log(`${dim(`${dur(t - p.at)} ago`)} ${bold(p.who)}${tag ? ` [${tag}]` : ''}${p.eta && p.state === 'doing' ? dim(` expected by ${clock(p.eta)}`) : ''}`);
185
+ console.log(` ${p.text}`);
186
+ }
187
+ }
package/src/qr.mjs ADDED
@@ -0,0 +1,204 @@
1
+ // A QR code for `dibs pair --remote`, so a phone can open the pairing link by
2
+ // pointing its camera at the terminal. Byte mode, error correction level M,
3
+ // the smallest version that fits. Follows ISO/IEC 18004 the way Project Nayuki's
4
+ // reference encoder lays it out; no library, per the no-dependencies rule.
5
+
6
+ // Per version 1..40 (index 0 unused), level M.
7
+ const ECC_PER_BLOCK = [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28];
8
+ const BLOCKS = [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49];
9
+ const FORMAT_M = 0;
10
+
11
+ function rawModules(ver) {
12
+ let n = (16 * ver + 128) * ver + 64;
13
+ if (ver >= 2) {
14
+ const align = Math.floor(ver / 7) + 2;
15
+ n -= (25 * align - 10) * align - 55;
16
+ if (ver >= 7) n -= 36;
17
+ }
18
+ return n;
19
+ }
20
+ const dataCodewords = ver => Math.floor(rawModules(ver) / 8) - ECC_PER_BLOCK[ver] * BLOCKS[ver];
21
+
22
+ function gfMul(x, y) {
23
+ let z = 0;
24
+ for (let i = 7; i >= 0; i--) {
25
+ z = (z << 1) ^ ((z >>> 7) * 0x11d);
26
+ z ^= ((y >>> i) & 1) * x;
27
+ }
28
+ return z;
29
+ }
30
+ function rsDivisor(degree) {
31
+ const r = new Array(degree).fill(0);
32
+ r[degree - 1] = 1;
33
+ let root = 1;
34
+ for (let i = 0; i < degree; i++) {
35
+ for (let j = 0; j < r.length; j++) {
36
+ r[j] = gfMul(r[j], root);
37
+ if (j + 1 < r.length) r[j] ^= r[j + 1];
38
+ }
39
+ root = gfMul(root, 0x02);
40
+ }
41
+ return r;
42
+ }
43
+ function rsRemainder(data, div) {
44
+ const r = div.map(() => 0);
45
+ for (const b of data) {
46
+ const f = b ^ r.shift();
47
+ r.push(0);
48
+ div.forEach((c, i) => { r[i] ^= gfMul(c, f); });
49
+ }
50
+ return r;
51
+ }
52
+
53
+ function alignPositions(ver, size) {
54
+ if (ver === 1) return [];
55
+ const n = Math.floor(ver / 7) + 2;
56
+ const step = Math.floor((ver * 8 + n * 3 + 5) / (n * 4 - 4)) * 2;
57
+ const out = [6];
58
+ for (let pos = size - 7; out.length < n; pos -= step) out.splice(1, 0, pos);
59
+ return out;
60
+ }
61
+
62
+ // The matrix for `text`: rows of booleans, true is dark.
63
+ export function qr(text) {
64
+ const bytes = [...Buffer.from(text, 'utf8')];
65
+ let ver = 1;
66
+ for (; ver <= 40; ver++) if (4 + (ver < 10 ? 8 : 16) + bytes.length * 8 <= dataCodewords(ver) * 8) break;
67
+ if (ver > 40) throw new Error('too long for a QR code');
68
+ const cap = dataCodewords(ver) * 8;
69
+
70
+ const bits = [];
71
+ const put = (v, n) => { for (let i = n - 1; i >= 0; i--) bits.push((v >>> i) & 1); };
72
+ put(0b0100, 4);
73
+ put(bytes.length, ver < 10 ? 8 : 16);
74
+ for (const b of bytes) put(b, 8);
75
+ put(0, Math.min(4, cap - bits.length));
76
+ put(0, (8 - (bits.length % 8)) % 8);
77
+ for (let pad = 0xec; bits.length < cap; pad ^= 0xec ^ 0x11) put(pad, 8);
78
+ const data = [];
79
+ for (let i = 0; i < bits.length; i += 8) data.push(bits.slice(i, i + 8).reduce((a, b) => (a << 1) | b, 0));
80
+
81
+ // Split into blocks, add error correction, interleave.
82
+ const nBlocks = BLOCKS[ver], eccLen = ECC_PER_BLOCK[ver], raw = Math.floor(rawModules(ver) / 8);
83
+ const nShort = nBlocks - (raw % nBlocks), shortLen = Math.floor(raw / nBlocks);
84
+ const div = rsDivisor(eccLen);
85
+ const blocks = [];
86
+ for (let i = 0, k = 0; i < nBlocks; i++) {
87
+ const dat = data.slice(k, k + shortLen - eccLen + (i < nShort ? 0 : 1));
88
+ k += dat.length;
89
+ const ecc = rsRemainder(dat, div);
90
+ if (i < nShort) dat.push(0);
91
+ blocks.push(dat.concat(ecc));
92
+ }
93
+ const words = [];
94
+ for (let i = 0; i < blocks[0].length; i++) blocks.forEach((b, j) => { if (i !== shortLen - eccLen || j >= nShort) words.push(b[i]); });
95
+
96
+ const size = ver * 4 + 17;
97
+ const m = Array.from({ length: size }, () => new Array(size).fill(false));
98
+ const fn = Array.from({ length: size }, () => new Array(size).fill(false));
99
+ const set = (x, y, dark) => { m[y][x] = dark; fn[y][x] = true; };
100
+
101
+ for (let i = 0; i < size; i++) { set(6, i, i % 2 === 0); set(i, 6, i % 2 === 0); }
102
+ for (const [cx, cy] of [[3, 3], [size - 4, 3], [3, size - 4]]) {
103
+ for (let dy = -4; dy <= 4; dy++) for (let dx = -4; dx <= 4; dx++) {
104
+ const d = Math.max(Math.abs(dx), Math.abs(dy)), x = cx + dx, y = cy + dy;
105
+ if (x >= 0 && x < size && y >= 0 && y < size) set(x, y, d !== 2 && d !== 4);
106
+ }
107
+ }
108
+ const al = alignPositions(ver, size), last = al.length - 1;
109
+ al.forEach((ax, i) => al.forEach((ay, j) => {
110
+ if ((i === 0 && j === 0) || (i === 0 && j === last) || (i === last && j === 0)) return;
111
+ for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) set(ax + dx, ay + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);
112
+ }));
113
+ const format = mask => {
114
+ const d = (FORMAT_M << 3) | mask;
115
+ let r = d;
116
+ for (let i = 0; i < 10; i++) r = (r << 1) ^ ((r >>> 9) * 0x537);
117
+ const b = ((d << 10) | r) ^ 0x5412;
118
+ const bit = i => ((b >>> i) & 1) === 1;
119
+ for (let i = 0; i <= 5; i++) set(8, i, bit(i));
120
+ set(8, 7, bit(6)); set(8, 8, bit(7)); set(7, 8, bit(8));
121
+ for (let i = 9; i < 15; i++) set(14 - i, 8, bit(i));
122
+ for (let i = 0; i < 8; i++) set(size - 1 - i, 8, bit(i));
123
+ for (let i = 8; i < 15; i++) set(8, size - 15 + i, bit(i));
124
+ set(8, size - 8, true);
125
+ };
126
+ format(0);
127
+ if (ver >= 7) {
128
+ let r = ver;
129
+ for (let i = 0; i < 12; i++) r = (r << 1) ^ ((r >>> 11) * 0x1f25);
130
+ const b = (ver << 12) | r;
131
+ for (let i = 0; i < 18; i++) {
132
+ const dark = ((b >>> i) & 1) === 1, a = size - 11 + (i % 3), c = Math.floor(i / 3);
133
+ set(a, c, dark); set(c, a, dark);
134
+ }
135
+ }
136
+
137
+ let i = 0;
138
+ for (let right = size - 1; right >= 1; right -= 2) {
139
+ if (right === 6) right = 5;
140
+ for (let v = 0; v < size; v++) for (let j = 0; j < 2; j++) {
141
+ const x = right - j, up = ((right + 1) & 2) === 0, y = up ? size - 1 - v : v;
142
+ if (!fn[y][x] && i < words.length * 8) { m[y][x] = ((words[i >>> 3] >>> (7 - (i & 7))) & 1) === 1; i++; }
143
+ }
144
+ }
145
+
146
+ const masks = [
147
+ (x, y) => (x + y) % 2 === 0, (x, y) => y % 2 === 0, x => x % 3 === 0, (x, y) => (x + y) % 3 === 0,
148
+ (x, y) => (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0, (x, y) => ((x * y) % 2) + ((x * y) % 3) === 0,
149
+ (x, y) => (((x * y) % 2) + ((x * y) % 3)) % 2 === 0, (x, y) => (((x + y) % 2) + ((x * y) % 3)) % 2 === 0,
150
+ ];
151
+ const flip = k => { for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) if (!fn[y][x] && masks[k](x, y)) m[y][x] = !m[y][x]; };
152
+ // Any mask decodes; the standard's penalty picks the one scanners find easiest.
153
+ let best = 0, bestScore = Infinity;
154
+ for (let k = 0; k < 8; k++) {
155
+ flip(k); format(k);
156
+ const s = penalty(m);
157
+ if (s < bestScore) { best = k; bestScore = s; }
158
+ flip(k);
159
+ }
160
+ flip(best); format(best);
161
+ return m;
162
+ }
163
+
164
+ // The standard's four penalty rules, used only to rank masks.
165
+ function penalty(m) {
166
+ const n = m.length;
167
+ let s = 0, dark = 0;
168
+ const line = get => {
169
+ let run = 1, out = 0;
170
+ const seq = [];
171
+ for (let i = 0; i < n; i++) seq.push(get(i));
172
+ for (let i = 1; i <= n; i++) {
173
+ if (i < n && seq[i] === seq[i - 1]) run++;
174
+ else { if (run >= 5) out += run - 2; run = 1; }
175
+ }
176
+ const str = seq.map(b => (b ? 1 : 0)).join('');
177
+ for (const p of ['10111010000', '00001011101']) for (let k = str.indexOf(p); k >= 0; k = str.indexOf(p, k + 1)) out += 40;
178
+ return out;
179
+ };
180
+ for (let y = 0; y < n; y++) s += line(x => m[y][x]);
181
+ for (let x = 0; x < n; x++) s += line(y => m[y][x]);
182
+ for (let y = 0; y < n - 1; y++) for (let x = 0; x < n - 1; x++) {
183
+ const c = m[y][x];
184
+ if (c === m[y][x + 1] && c === m[y + 1][x] && c === m[y + 1][x + 1]) s += 3;
185
+ }
186
+ for (const row of m) for (const c of row) if (c) dark++;
187
+ return s + Math.floor(Math.abs(dark * 20 - n * n * 10) / (n * n)) * 10;
188
+ }
189
+
190
+ // Two rows per line with half blocks, dark on a forced light background so it
191
+ // scans on dark terminals too, with the quiet zone the standard asks for.
192
+ export function render(m, quiet = 4) {
193
+ const n = m.length, at = (x, y) => x >= 0 && y >= 0 && x < n && y < n && m[y][x];
194
+ const lines = [];
195
+ for (let y = -quiet; y < n + quiet; y += 2) {
196
+ let s = '\x1b[30;107m';
197
+ for (let x = -quiet; x < n + quiet; x++) {
198
+ const top = at(x, y), bottom = at(x, y + 1);
199
+ s += top && bottom ? '█' : top ? '▀' : bottom ? '▄' : ' ';
200
+ }
201
+ lines.push(`${s}\x1b[0m`);
202
+ }
203
+ return lines.join('\n');
204
+ }