gcf-board 0.5.1 → 0.6.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.
@@ -0,0 +1,498 @@
1
+ // The project chat (Board-PRD §5.13, docs/Session-Engine.md AD-1…AD-51): its threads ("talks")
2
+ // live in `.gcf-session/chats/<t>/`, run by the session engine (gcf-session). The board writes
3
+ // what a thread runs by before it starts it: `spec.json` (the agent, its rules, its MCP config,
4
+ // its limits), `moves.json` and `mcp.json` (the center's MCP server, mcp.ts), `context.md` (an
5
+ // item's paths, AD-47). It writes the operator's input into `chat-in.jsonl`, and starts the
6
+ // engine's `open` through the relay when no session of the thread lives. The agent's proposals
7
+ // and what became of them (AD-33) are in `proposals.json`.
8
+ import { spawn, spawnSync } from 'node:child_process';
9
+ import { randomBytes } from 'node:crypto';
10
+ import { appendFileSync, existsSync, lstatSync, mkdirSync, readFileSync, statSync, writeFileSync, } from 'node:fs';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import { fileURLToPath } from 'node:url';
14
+ import { THREAD_ID, createThread, listThreads, readThread, threadDir, threadOf, } from 'gcf-session';
15
+ import { writeAtomic } from './atomic.js';
16
+ import { alive } from './events.js';
17
+ import { HttpError } from './http-error.js';
18
+ import { IMAGE_EXT } from './chat.js';
19
+ import { homeDir } from './registry.js';
20
+ // The source runs the .ts files, the package its build beside this file.
21
+ const own = (name) => fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? `${name}.ts` : `${name}.js`, import.meta.url));
22
+ const RELAY = own('relay');
23
+ const MCP = own('mcp');
24
+ const OPEN = fileURLToPath(new URL('./cli.js', import.meta.resolve('gcf-session')));
25
+ // The harness's own agent command (gcf-harness-aif-ext DEFAULT_AGENT): a thread's sessions are
26
+ // claude's too. GCF_SESSION_AGENT puts a fake in its place in tests.
27
+ const DEFAULT_AGENT = 'claude -p --output-format stream-json --verbose';
28
+ // The git commands a thread asks for each time (AD-5): they change the checkout.
29
+ const ASK = [
30
+ { kind: 'edit', pattern: '' },
31
+ { kind: 'shell', pattern: 'git *' },
32
+ ];
33
+ /** A thread's id, or a 404. */
34
+ export function talkId(t) {
35
+ if (!THREAD_ID.test(t))
36
+ throw new HttpError(404, `no thread ${t}`);
37
+ return t;
38
+ }
39
+ const dirOf = (p, t) => threadDir(p.path, talkId(t));
40
+ /**
41
+ * Thread `t`'s folder for a write, refused when a link stands anywhere on its way from
42
+ * `.gcf-session`: an agent's approved command could plant one, and the board's writes (the
43
+ * operator's input, the thread's spec) would land elsewhere.
44
+ */
45
+ function writeDir(p, t) {
46
+ const td = dirOf(p, t);
47
+ const chats = path.dirname(td);
48
+ for (const f of [path.dirname(chats), chats, td]) {
49
+ const st = existsSync(f) ? lstatSync(f) : null;
50
+ if (st?.isSymbolicLink())
51
+ throw new HttpError(400, `${t}'s folder goes through a link: refused`);
52
+ }
53
+ return td;
54
+ }
55
+ /**
56
+ * The project chat needs a core that says how (AD-38): its skill and the commands to ask for
57
+ * (`domain.chat`), and the neutral deny rules (`agent.rules`).
58
+ */
59
+ export function chatOf(board) {
60
+ const chat = board.domain.chat;
61
+ const rules = board.agent?.rules;
62
+ if (!chat || !rules)
63
+ throw new HttpError(400, 'the project chat needs gcf-aif-ext 0.12 or later: update it');
64
+ return { chat, rules };
65
+ }
66
+ /**
67
+ * The deny rules that keep a thread off the board's own folder, where its token lies (AD-31):
68
+ * read, search, and a shell command that names it: as written, with `/`, as Git Bash names a
69
+ * drive (`/c/…`), or from the home folder (`~`, `$HOME`, `%USERPROFILE%`).
70
+ * shortcut: a command that spells the path another way (another variable, an encoding) still
71
+ * reads it; a secret of its own for the card's answer comes with the remote board.
72
+ */
73
+ function homeRules() {
74
+ const home = path.resolve(homeDir());
75
+ const slashed = home.replaceAll('\\', '/');
76
+ const spellings = new Set([home, slashed]);
77
+ const drive = /^([A-Za-z]):\/(.*)$/.exec(slashed);
78
+ if (drive)
79
+ spellings.add(`/${drive[1].toLowerCase()}/${drive[2]}`);
80
+ const rel = path.relative(os.homedir(), home);
81
+ if (rel && !rel.startsWith('..') && !path.isAbsolute(rel))
82
+ for (const from of ['~', '$HOME', '%USERPROFILE%', '$env:USERPROFILE'])
83
+ for (const sep of ['/', '\\'])
84
+ spellings.add(`${from}${sep}${rel.replaceAll(/[\\/]/g, sep)}`);
85
+ return [
86
+ { kind: 'read', pattern: `${home}/**` },
87
+ { kind: 'search', pattern: `${home}/**` },
88
+ ...[...spellings].map((s) => ({ kind: 'shell', pattern: `*${s}*` })),
89
+ ];
90
+ }
91
+ /** What a thread of the project runs by (AD-5, AD-29, AD-31, AD-43), `spec.json`. */
92
+ export function talkSpec(p, board, mcp) {
93
+ const { chat, rules } = chatOf(board);
94
+ return {
95
+ agent: process.env.GCF_SESSION_AGENT ?? DEFAULT_AGENT,
96
+ rules: {
97
+ deny: [...rules.deny, { kind: 'edit', pattern: '.gcf-session/**' }, ...homeRules()],
98
+ ask: [...ASK, ...chat.confirm],
99
+ allow: [],
100
+ },
101
+ mcp: [mcp],
102
+ answerMin: board.chat?.answer_timeout_min,
103
+ handoffPct: board.context?.handoff_pct,
104
+ ...(board.context?.window ? { window: board.context.window } : {}),
105
+ skill: chat.skill,
106
+ mainLock: path.join(p.path, '.gcf-session', 'runs', '.main-run.lock'),
107
+ };
108
+ }
109
+ /** A command's output in the project, or empty. */
110
+ const git = (cwd, ...args) => spawnSync('git', args, { cwd, encoding: 'utf8' }).stdout?.trim() ?? '';
111
+ // The most lines of a log or of commits a thread's context gives: it goes into every session.
112
+ const CONTEXT_LINES = 30;
113
+ /** The last lines of a csv log (no header, Harness-PRD §11) whose fields include the id. */
114
+ function rowsOf(file, id) {
115
+ try {
116
+ const rows = readFileSync(file, 'utf8').split(/\r?\n/).filter(Boolean);
117
+ return rows.filter((r) => r.split(',').includes(id)).slice(-CONTEXT_LINES);
118
+ }
119
+ catch {
120
+ return [];
121
+ }
122
+ }
123
+ /**
124
+ * The item's commits, newest first: a subject that names the id as a word (`gcf(close): <id>`),
125
+ * not one that only holds it (`ui` in "build").
126
+ */
127
+ function commitsOf(dir, id) {
128
+ const word = new RegExp(`(^|[^a-z0-9-])${id}([^a-z0-9-]|$)`);
129
+ // Its own format: `--oneline` adds the refs a config may decorate it with.
130
+ const lines = git(dir, 'log', '--format=%h %s', '-n', '500', '-F', `--grep=${id}`).split('\n');
131
+ return lines.filter((l) => word.test(l.slice(l.indexOf(' ') + 1))).slice(0, CONTEXT_LINES);
132
+ }
133
+ /**
134
+ * What a thread bound to `item` is given to read (AD-47): paths, not their text, but the ones a
135
+ * session would need a git command or a search for. Empty for a thread of no item.
136
+ */
137
+ export function contextOf(p, board, item) {
138
+ if (!item)
139
+ return '';
140
+ const live = board.items.find((i) => i.id === item);
141
+ const done = board.history?.find((h) => h.id === item);
142
+ const dead = board.graveyard?.find((g) => g.id === item);
143
+ const exists = (rel) => existsSync(path.join(p.path, rel));
144
+ const lines = [`# This thread is about item ${item}`, ''];
145
+ if (live) {
146
+ lines.push(`${live.title ?? item}: ${live.status}.`, '', 'Read first:');
147
+ lines.push(`- its file: ${live.file}`);
148
+ if (live.plan_file)
149
+ lines.push(`- its plan: ${live.plan_file}`);
150
+ }
151
+ else {
152
+ lines.push(done
153
+ ? `It is accepted: history ${[done.event, done.date].filter(Boolean).join(', ')}.`
154
+ : dead
155
+ ? `It is in the graveyard: ${dead.reason ?? 'no reason given'}.`
156
+ : 'It is not on the board any more.', '', 'Read first:');
157
+ const plan = `.ai-factory/archive/plans/${item}.md`;
158
+ if (exists(plan))
159
+ lines.push(`- its archived plan: ${plan}`);
160
+ const last = git(p.path, 'log', '-1', '--format=%h %s', '--', `gcf/work/${item}.md`);
161
+ if (last)
162
+ lines.push(`- its file as last committed: git show ${last.split(' ')[0]}^:gcf/work/${item}.md (${last})`);
163
+ }
164
+ for (const [what, rel] of [
165
+ ["its run's log", `.gcf-session/runs/${item}.log`],
166
+ ["its run's chat", `.gcf-session/runs/${item}.chat.jsonl`],
167
+ ])
168
+ if (exists(rel))
169
+ lines.push(`- ${what}: ${rel}`);
170
+ const worktree = `.gcf-session/worktrees/${item}`;
171
+ if (board.run_mode === 'worktree')
172
+ lines.push(`- its branch: work/${item}${exists(worktree) ? `, its worktree: ${worktree}` : ''}`);
173
+ const rows = rowsOf(path.join(p.path, 'gcf', '.metrics', 'run-log.csv'), item);
174
+ if (rows.length)
175
+ lines.push('', 'Its runs (gcf/.metrics/run-log.csv):', '', ...rows);
176
+ const commits = commitsOf(p.path, item);
177
+ if (commits.length)
178
+ lines.push('', 'Its commits, newest first:', '', ...commits);
179
+ return `${lines.join('\n')}\n`;
180
+ }
181
+ /**
182
+ * Write what thread `t` runs by, fresh from the board read: its spec, the center's MCP server
183
+ * with the domain's moves an agent may propose, its item's context.
184
+ */
185
+ export async function prepareTalk(p, board, t) {
186
+ const td = writeDir(p, t);
187
+ const proposable = Object.fromEntries(Object.entries(board.domain.moves).filter(([, m]) => m.propose));
188
+ const moves = path.join(td, 'moves.json');
189
+ const mcp = path.join(td, 'mcp.json');
190
+ const spec = talkSpec(p, board, mcp);
191
+ await writeAtomic(moves, `${JSON.stringify(proposable, null, 2)}\n`);
192
+ const server = { type: 'stdio', command: process.execPath, args: [MCP, moves] };
193
+ await writeAtomic(mcp, `${JSON.stringify({ mcpServers: { gcf: server } }, null, 2)}\n`);
194
+ await writeAtomic(path.join(td, 'context.md'), contextOf(p, board, readThread(p.path, t).item));
195
+ await writeAtomic(path.join(td, 'spec.json'), `${JSON.stringify(spec, null, 2)}\n`);
196
+ }
197
+ /** Whether thread `t` waits for the usage limit's reset: its last session event is `limit`. */
198
+ export function talkWaits(p, t) {
199
+ const last = eventsOf(dirOf(p, t)).findLast((e) => ['session', 'session_end', 'limit'].includes(e.type));
200
+ return last?.type === 'limit';
201
+ }
202
+ /** Whether a session of thread `t` lives: its `open` holds the thread's lock. */
203
+ export function talkLive(p, t) {
204
+ try {
205
+ return alive(Number(readFileSync(path.join(dirOf(p, t), 'open.lock'), 'utf8').split('\n')[0]));
206
+ }
207
+ catch {
208
+ return false;
209
+ }
210
+ }
211
+ // When the board last started each thread: a second start meanwhile only finds the lock held.
212
+ const starts = new Map();
213
+ /**
214
+ * Start thread `t`'s engine (`gcf-session open`) through the relay, detached: it outlives the
215
+ * board, and the agent it starts opens no console window. The relay's end file is its beat too.
216
+ */
217
+ export function startTalk(p, t) {
218
+ const td = dirOf(p, t);
219
+ const end = path.join(td, 'open.end.json');
220
+ starts.set(td, Date.now());
221
+ spawn(process.execPath, [RELAY, end, end, OPEN, 'open', p.path, t], {
222
+ cwd: p.path,
223
+ detached: true,
224
+ stdio: 'ignore',
225
+ windowsHide: true,
226
+ })
227
+ // A start that fails (the folder gone) must not take the board down: the next one tries.
228
+ .on('error', () => starts.delete(td))
229
+ .unref();
230
+ }
231
+ /** A new thread, or the one bound to `item` (AD-46): its id, and whether it is new. */
232
+ export function openTalk(p, item) {
233
+ const had = item ? threadOf(p.path, item) : null;
234
+ return { id: had ?? createThread(p.path, { item }), created: !had };
235
+ }
236
+ const lineId = () => randomBytes(6).toString('hex');
237
+ /**
238
+ * Write the operator's input into thread `t` (AD-35: each line its `id`); a message's pictures
239
+ * go into its `att/`, never through a link. Returns the line.
240
+ */
241
+ export function writeTalk(p, t, input) {
242
+ const td = writeDir(p, t);
243
+ for (const f of [path.join(td, 'att'), path.join(td, 'chat-in.jsonl')]) {
244
+ const st = existsSync(f) ? lstatSync(f) : null;
245
+ if (st?.isSymbolicLink())
246
+ throw new HttpError(400, `${t}'s chat goes through a link: refused`);
247
+ }
248
+ let line = { ...input, id: lineId() };
249
+ if (input.type === 'say') {
250
+ const images = (input.images ?? []).map((im) => {
251
+ const name = `${randomBytes(4).toString('hex')}${IMAGE_EXT[im.media_type]}`;
252
+ mkdirSync(path.join(td, 'att'), { recursive: true });
253
+ writeFileSync(path.join(td, 'att', name), Buffer.from(im.data, 'base64'));
254
+ return `att/${name}`;
255
+ });
256
+ line = { type: 'say', id: lineId(), text: input.text, ...(images.length ? { images } : {}) };
257
+ }
258
+ appendFileSync(path.join(td, 'chat-in.jsonl'), `${JSON.stringify(line)}\n`);
259
+ return line;
260
+ }
261
+ /** A thread's chat events; a line that is not one is skipped. */
262
+ function eventsOf(td) {
263
+ let text = '';
264
+ try {
265
+ text = readFileSync(path.join(td, 'chat.jsonl'), 'utf8');
266
+ }
267
+ catch {
268
+ return [];
269
+ }
270
+ return text.split('\n').flatMap((l) => {
271
+ try {
272
+ return l ? [JSON.parse(l)] : [];
273
+ }
274
+ catch {
275
+ return [];
276
+ }
277
+ });
278
+ }
279
+ const recordsFile = (td) => path.join(td, 'proposals.json');
280
+ function readRecords(td) {
281
+ try {
282
+ return JSON.parse(readFileSync(recordsFile(td), 'utf8'));
283
+ }
284
+ catch {
285
+ return {};
286
+ }
287
+ }
288
+ // One write of a thread's records at a time: each reads, changes and writes the whole file.
289
+ const writing = new Map();
290
+ function setRecord(td, id, rec) {
291
+ const next = (writing.get(td) ?? Promise.resolve()).then(() => writeAtomic(recordsFile(td), `${JSON.stringify({ ...readRecords(td), [id]: rec }, null, 2)}\n`));
292
+ writing.set(td, next.catch(() => { }));
293
+ return next;
294
+ }
295
+ // The proposals whose move runs now, `<td> <id>`: a second click waits for none.
296
+ const accepting = new Set();
297
+ /**
298
+ * Make proposal `id` of thread `t` by its move (AD-16, AD-33): `accepting` is written first,
299
+ * with the item it makes and whether that id was taken already; then `accepted` or `refused`
300
+ * with the framework's words. `run` is the move; `ids` the items on the board now. A proposal
301
+ * made already is made once: a second click, an edited id too, is refused (409), also when a
302
+ * board that stopped mid-move left its record `accepting`.
303
+ */
304
+ export async function acceptProposal(p, t, id, move, item, ids, run) {
305
+ const td = writeDir(p, t);
306
+ const offered = eventsOf(td).find((e) => e.type === 'proposal' && e.id === id);
307
+ if (offered?.type !== 'proposal')
308
+ throw new HttpError(404, `no proposal ${id} in thread ${t}`);
309
+ if (offered.move !== move)
310
+ throw new HttpError(400, `proposal ${id} is ${offered.move}, not ${move}`);
311
+ const key = `${td} ${id}`;
312
+ if (accepting.has(key))
313
+ throw new HttpError(409, `proposal ${id} is being made already`);
314
+ // Taken at once: a second click while an old record settles waits for none.
315
+ accepting.add(key);
316
+ try {
317
+ const made = await settled(td, id, readRecords(td)[id], async () => ids, true);
318
+ if (made?.state === 'accepted')
319
+ throw new HttpError(409, `proposal ${id} is made already: ${made.item ?? ''}`);
320
+ await setRecord(td, id, { state: 'accepting', item, existed: ids.has(item), at: now() });
321
+ const r = await run();
322
+ await setRecord(td, id, {
323
+ ...(r.ok ? { state: 'accepted', item } : { state: 'refused', error: r.err || r.out }),
324
+ at: now(),
325
+ });
326
+ return r;
327
+ }
328
+ finally {
329
+ accepting.delete(key);
330
+ }
331
+ }
332
+ const now = () => new Date().toISOString();
333
+ /**
334
+ * A proposal's record, an `accepting` one a board that stopped meanwhile left (AD-33) settled by
335
+ * the board read (`ids()`, the items on it): its item there and not before, it was made.
336
+ */
337
+ async function settled(td, id, rec, ids, mine = false) {
338
+ if (rec?.state !== 'accepting' || (!mine && accepting.has(`${td} ${id}`)))
339
+ return rec;
340
+ let board;
341
+ try {
342
+ board = await ids();
343
+ }
344
+ catch {
345
+ // No board read now: it stays accepting until one settles it.
346
+ return rec;
347
+ }
348
+ // A click may have settled or taken it while the board was read: its record wins.
349
+ const latest = readRecords(td)[id];
350
+ if (latest?.state !== 'accepting' || (!mine && accepting.has(`${td} ${id}`)))
351
+ return latest;
352
+ const made = !rec.existed && Boolean(rec.item) && board.has(rec.item ?? '');
353
+ const next = made
354
+ ? { state: 'accepted', item: rec.item, at: now() }
355
+ : { state: 'refused', error: 'the board stopped while it was made: try again', at: now() };
356
+ await setRecord(td, id, next);
357
+ return next;
358
+ }
359
+ /**
360
+ * Thread `td`'s proposals in the order offered, each with its record. One left `accepting` by
361
+ * a board that stopped meanwhile (AD-33) is settled by the board read (`ids()`, the items on
362
+ * it): its item there and not before, it was made.
363
+ */
364
+ async function proposalsOf(td, events, ids) {
365
+ const records = readRecords(td);
366
+ const out = [];
367
+ for (const e of events) {
368
+ if (e.type !== 'proposal')
369
+ continue;
370
+ const rec = await settled(td, e.id, records[e.id], ids);
371
+ const shown = { ...(rec ?? { state: 'offered' }) };
372
+ delete shown.existed;
373
+ out.push({ id: e.id, move: e.move, ...shown });
374
+ }
375
+ return out;
376
+ }
377
+ /** Whether a card waits for the operator: an approval or a question not answered yet. */
378
+ function waitingIn(events) {
379
+ const open = new Set();
380
+ for (const e of events) {
381
+ if (e.type === 'approval' || e.type === 'question')
382
+ open.add(e.request_id);
383
+ else if (e.type === 'session_end')
384
+ open.clear();
385
+ else if ('request_id' in e && e.request_id)
386
+ open.delete(e.request_id);
387
+ }
388
+ return open.size > 0;
389
+ }
390
+ /** The text of the operator's first message to a thread, as written; null before one. */
391
+ function sayOf(td) {
392
+ let text = '';
393
+ try {
394
+ text = readFileSync(path.join(td, 'chat-in.jsonl'), 'utf8');
395
+ }
396
+ catch {
397
+ return null;
398
+ }
399
+ for (const l of text.split('\n')) {
400
+ try {
401
+ const e = JSON.parse(l);
402
+ if (e.type === 'say' && typeof e.text === 'string')
403
+ return e.text;
404
+ }
405
+ catch {
406
+ // A torn or empty line: the next one.
407
+ }
408
+ }
409
+ return null;
410
+ }
411
+ /** What the list shows of thread `th` (Board-PRD §5.13). */
412
+ async function talkOf(p, th, ids) {
413
+ const td = threadDir(p.path, th.id);
414
+ const events = eventsOf(td);
415
+ const first = sayOf(td);
416
+ const title = first ? first.trim().split('\n')[0].slice(0, 120) : null;
417
+ const cost = events.reduce((sum, e) => sum + (e.type === 'session_end' ? (e.cost_usd ?? 0) : 0), 0);
418
+ return {
419
+ id: th.id,
420
+ title,
421
+ item: th.item,
422
+ created_at: th.created_at,
423
+ last_at: events.at(-1)?.at ?? null,
424
+ cost_usd: Math.round(cost * 100) / 100,
425
+ live: talkLive(p, th.id),
426
+ waiting: waitingIn(events),
427
+ proposals: await proposalsOf(td, events, ids),
428
+ };
429
+ }
430
+ /**
431
+ * The project's threads, newest first; with `item`, its bound one only. `ids()` reads the
432
+ * board's items when a proposal needs settling.
433
+ */
434
+ export async function listTalks(p, ids, item) {
435
+ const threads = listThreads(p.path).filter((th) => !item || th.item === item);
436
+ // One board read at most, and only when a proposal needs it.
437
+ let read = null;
438
+ const once = () => (read ??= ids());
439
+ return Promise.all(threads.map((th) => talkOf(p, th, once)));
440
+ }
441
+ /** Where a thread's input is read to, and how far it is written. */
442
+ function unread(td) {
443
+ try {
444
+ const at = Number(JSON.parse(readFileSync(path.join(td, 'thread.json'), 'utf8')).in_at) || 0;
445
+ return statSync(path.join(td, 'chat-in.jsonl')).size > at;
446
+ }
447
+ catch {
448
+ return false;
449
+ }
450
+ }
451
+ /**
452
+ * Watch a project's threads every `ms`: `onChange` when what the list shows may have changed
453
+ * (a thread, its chat, its lock, its proposals). A thread with input no session read and none
454
+ * live (a message written as its session idled out) starts again, once for that input, after
455
+ * `prepare(t)` wrote what it runs by afresh (prepareTalk). Returns the stop.
456
+ */
457
+ export function watchTalks(p, onChange, prepare, ms = 1500, pauseMs = 30_000) {
458
+ const tried = new Map();
459
+ const state = () => listThreads(p.path)
460
+ .map((th) => {
461
+ const td = threadDir(p.path, th.id);
462
+ const stamp = (f) => {
463
+ try {
464
+ return statSync(path.join(td, f)).mtimeMs;
465
+ }
466
+ catch {
467
+ return 0;
468
+ }
469
+ };
470
+ const live = talkLive(p, th.id);
471
+ const input = `${th.in_at}:${stamp('chat-in.jsonl')}`;
472
+ const recent = Date.now() - (starts.get(td) ?? 0) < pauseMs;
473
+ if (!live &&
474
+ !recent &&
475
+ unread(td) &&
476
+ tried.get(td) !== input &&
477
+ existsSync(path.join(td, 'spec.json'))) {
478
+ tried.set(td, input);
479
+ // A board that cannot read the project now starts nothing: the input waits.
480
+ // A board read that failed (a busy lock, a hiccup) tries again after the start's
481
+ // pause, not at each poll.
482
+ prepare(th.id).then(() => startTalk(p, th.id), () => {
483
+ tried.delete(td);
484
+ starts.set(td, Date.now());
485
+ });
486
+ }
487
+ return `${th.id} ${live} ${stamp('chat.jsonl')} ${stamp('proposals.json')}`;
488
+ })
489
+ .join('\n');
490
+ let last = state();
491
+ const poll = setInterval(() => {
492
+ const next = state();
493
+ if (next !== last)
494
+ onChange();
495
+ last = next;
496
+ }, ms);
497
+ return () => clearInterval(poll);
498
+ }