gcf-board 0.22.0 → 0.24.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.
@@ -140,11 +140,18 @@ export function talkSpec(p, board, mcp, start = null) {
140
140
  return {
141
141
  agent: process.env.GCF_SESSION_AGENT ?? DEFAULT_AGENT,
142
142
  rules: {
143
- deny: [...rules.deny, { kind: 'edit', pattern: '.gcf-session/**' }, ...homeRules()],
143
+ // A rule of a run's own (`run_only`, Play-Setup-Plan d32) is no thread's: the chat agent
144
+ // builds the game when the human asks.
145
+ deny: [
146
+ ...rules.deny.filter((r) => !r.run_only),
147
+ { kind: 'edit', pattern: '.gcf-session/**' },
148
+ ...homeRules(),
149
+ ],
144
150
  // Claude holds ask over allow: the blanket edit ask would shadow the start's edits. The
145
- // agent's own instructions and settings still ask, whatever the project allows.
151
+ // agent's own instructions and settings still ask, whatever the project allows. A start
152
+ // with no edits of its own keeps the edit ask: it would write files without a card.
146
153
  ask: [
147
- ...(own ? [...ASK.filter((r) => r.kind !== 'edit'), ...OWN_FILES] : ASK),
154
+ ...(own?.edits?.length ? [...ASK.filter((r) => r.kind !== 'edit'), ...OWN_FILES] : ASK),
148
155
  ...chat.confirm,
149
156
  ],
150
157
  // The center's own MCP server only proposes: the proposal card's Create is the
@@ -189,6 +196,49 @@ function commitsOf(dir, id) {
189
196
  const lines = git(dir, 'log', '--format=%h %s', '-n', '500', '-F', `--grep=${id}`).split('\n');
190
197
  return lines.filter((l) => word.test(l.slice(l.indexOf(' ') + 1))).slice(0, CONTEXT_LINES);
191
198
  }
199
+ /**
200
+ * Whether a card waiting for play can be played, in the words a chat answers from: this thread is
201
+ * not the run that built it, and without these facts it would say another agent did the work.
202
+ */
203
+ function playLines(board, item) {
204
+ if (!['awaiting-verdict', 'unplayed'].includes(item.status) || board.play === undefined)
205
+ return [];
206
+ if (board.play === null)
207
+ return [
208
+ '',
209
+ 'To play it: how to play is not set up (no `play:` in gcf/config.yml), so it has no build.',
210
+ 'Find in the project (AGENTS.md, its build and serve scripts) the command that builds the',
211
+ 'game into a folder git ignores and the one that starts it from there, and call',
212
+ 'propose_play_setup; never ask the human for the commands. If the project has none, propose',
213
+ 'a tech card with propose_item_new that adds them and names them in AGENTS.md.',
214
+ '',
215
+ ];
216
+ const b = item.build;
217
+ const targets = board.play.targets.map((t) => `${t.name} (${t.open})`).join(', ') || 'none';
218
+ const shared = b?.shared_with?.length ? ` The same build as ${b.shared_with.join(', ')}.` : '';
219
+ const said = b?.building
220
+ ? 'its build is being made now.'
221
+ : b?.ok
222
+ ? `its build is ready: commit ${b.commit?.slice(0, 7) ?? 'unknown'}, built ${b.built_at}, ` +
223
+ `${b.source === 'click' ? 'by hand, so it may hold later cards' : 'by its run'}.${shared}`
224
+ : 'it has no build yet: its Play button builds it first.';
225
+ const running = board.play.running?.id === item.id
226
+ ? [`It plays now on ${board.play.running.target}: ${board.play.running.open}.`]
227
+ : [];
228
+ return [
229
+ '',
230
+ `To play it: ${said}`,
231
+ ...(b?.problem ? [`The last build failed: ${b.problem.split('\n')[0]}`] : []),
232
+ ...running,
233
+ `Targets: ${targets}.`,
234
+ 'Never answer that you cannot build it: the card has its Play button, which builds first;',
235
+ 'offer it here with propose_play (its id and a target), or the checkout as it is with',
236
+ 'propose_play_main. When the human asks you to build, run',
237
+ '`ai-factory gcf playtest build <id>` or `ai-factory gcf playtest build --main` yourself.',
238
+ 'Cards on the same code share one build. The verdict stops the player.',
239
+ '',
240
+ ];
241
+ }
192
242
  /**
193
243
  * What a thread bound to `item` is given to read (AD-47): paths, not their text, but the ones a
194
244
  * session would need a git command or a search for. Empty for a thread of no item.
@@ -220,6 +270,8 @@ export function contextOf(p, board, item) {
220
270
  if (last)
221
271
  lines.push(`- its file as last committed: git show ${last.split(' ')[0]}^:gcf/work/${item}.md (${last})`);
222
272
  }
273
+ if (live)
274
+ lines.push(...playLines(board, live));
223
275
  for (const [what, rel] of [
224
276
  ["its run's log", `.gcf-session/runs/${item}.log`],
225
277
  ["its run's chat", `.gcf-session/runs/${item}.chat.jsonl`],
@@ -349,10 +401,11 @@ export function designTalk(p, board, start, given) {
349
401
  }
350
402
  }
351
403
  const say = s.say
352
- .replaceAll('{file}', file)
353
- .replaceAll('{unit}', given.unit ?? '')
354
- .replaceAll('{system}', given.system ?? '')
355
- .replaceAll('{text}', text);
404
+ // Functions: a `$` in the words (a shell command) is no replacement pattern.
405
+ .replaceAll('{file}', () => file)
406
+ .replaceAll('{unit}', () => given.unit ?? '')
407
+ .replaceAll('{system}', () => given.system ?? '')
408
+ .replaceAll('{text}', () => text);
356
409
  return { id: t, say };
357
410
  }
358
411
  /**
@@ -494,7 +547,10 @@ export function deniedGroupOf(events) {
494
547
  const start = events.findLastIndex((e) => e.type === 'session' && e.kind === 'start');
495
548
  const denied = events.slice(Math.max(0, start)).filter((e) => e.type === 'denied');
496
549
  const group = denied.at(-1)?.group ?? null;
497
- return group && !['git-history', 'git-destroy', 'human-moves'].includes(group) ? group : null;
550
+ // `run-play`: a run builds by the harness, never by its agent (Play-Setup-Plan d32).
551
+ return group && !['git-history', 'git-destroy', 'human-moves', 'run-play'].includes(group)
552
+ ? group
553
+ : null;
498
554
  }
499
555
  export function chatEvents(file) {
500
556
  let text = '';
@@ -1,17 +1,11 @@
1
1
  // The account's usage limits, asked of Claude's `/usage` (Board-PRD decision 39): what the top
2
2
  // bar shows over the last limit a run reported. The command is free (no model call) and answers
3
3
  // in a second or two; it still starts a claude process, so it is asked only while a page is open.
4
- import { spawn, spawnSync } from 'node:child_process';
5
- import os from 'node:os';
4
+ import { lastReading, limitsOf as sessionLimitsOf, readUsage, reasonOf as sessionReasonOf, } from 'gcf-session';
6
5
  import { broadcast, watched } from './events.js';
7
6
  /** How often an open page's bar is read again, and how long one ask may take. */
8
7
  export const USAGE_EVERY_MS = 5 * 60_000;
9
8
  const ASK_TIMEOUT_MS = 30_000;
10
- // No user or local settings, no MCP, no saved session: the user's hooks and plugins do not run
11
- // for a reading, and the operator's session list gets no entry per ask. The cwd is the temp
12
- // folder, whose project settings are no one's.
13
- const FLAGS = '-p "/usage" --output-format stream-json --verbose --no-session-persistence ' +
14
- '--setting-sources project --strict-mcp-config';
15
9
  let command = null;
16
10
  let askTimeout = ASK_TIMEOUT_MS;
17
11
  let last = null;
@@ -33,48 +27,14 @@ export function configureUsage(agent, timeoutMs = ASK_TIMEOUT_MS) {
33
27
  }
34
28
  /** The last reading, with the last ask's failure when the ask after it failed; null before any. */
35
29
  export const lastUsage = () => last;
36
- const isLimit = (l) => typeof l === 'object' &&
37
- l !== null &&
38
- typeof l.kind === 'string' &&
39
- typeof l.percent === 'number';
30
+ /** The limits of `/usage`'s answer (gcf-session `limitsOf`). */
31
+ export const limitsOf = (out) => sessionLimitsOf(out);
32
+ /** Why an ask failed (gcf-session `reasonOf`), with this board's ask time. */
33
+ export const reasonOf = (e, err) => sessionReasonOf(e, err, askTimeout);
40
34
  /**
41
- * The limits of `/usage`'s stream-json answer: its assistant event's
42
- * `usage_report.rate_limits.limits`; null when no line carries them (an API-key account has no
43
- * plan limits, an older claude no report).
44
- */
45
- export function limitsOf(out) {
46
- for (const line of out.split(/\r?\n/)) {
47
- let e;
48
- try {
49
- e = JSON.parse(line);
50
- }
51
- catch {
52
- continue;
53
- }
54
- const limits = e?.usage_report?.rate_limits?.limits;
55
- if (Array.isArray(limits))
56
- return limits.filter(isLimit);
57
- }
58
- return null;
59
- }
60
- /**
61
- * Why an ask failed: a timeout, else the last two lines of its stderr (cmd's "not recognized"
62
- * spans two), else the error itself.
63
- */
64
- export function reasonOf(e, err) {
65
- if (!e)
66
- return 'claude answered /usage without the plan limits (an API key has none)';
67
- // A stuck ask is told by its timeout, not by a warning it printed before it hung.
68
- if (e.killed)
69
- return `no answer in ${askTimeout / 1000} s`;
70
- const tail = err.trim();
71
- if (tail)
72
- return tail.split(/\r?\n/).slice(-2).join(' ').slice(0, 300);
73
- return e.message.slice(0, 300);
74
- }
75
- /**
76
- * Ask `/usage` now, once at a time: a second ask while one goes waits for it. A reading tells
77
- * every page (`quota`); a failed ask keeps the last reading and says why beside it.
35
+ * Ask `/usage` now, once at a time: a second ask while one goes waits for it. The reading goes to
36
+ * the account's `usage.json`, which the runs read too (Hold-Plan d10), and tells every page
37
+ * (`quota`); a failed ask keeps the last reading and says why beside it.
78
38
  */
79
39
  export function askUsage() {
80
40
  if (!command)
@@ -83,70 +43,50 @@ export function askUsage() {
83
43
  return asking;
84
44
  askedAt = Date.now();
85
45
  const mine = generation;
86
- asking = new Promise((resolve) => {
87
- let late = false;
88
- let out = '';
89
- let err = '';
90
- const windows = process.platform === 'win32';
91
- // Off Windows the shell leads a group of its own: a timeout signals the group, so a claude
92
- // the shell forked ends with it.
93
- const child = spawn(`${command} ${FLAGS}`, {
94
- shell: true,
95
- cwd: os.tmpdir(),
96
- windowsHide: true,
97
- detached: !windows,
98
- });
99
- // The answer is a few KB; a runaway one keeps its last 4 MB. Text, so a character split
100
- // between two chunks comes whole.
101
- const keep = (s, d) => (s + d).slice(-(4 << 20));
102
- child.stdout.setEncoding('utf8').on('data', (d) => (out = keep(out, d)));
103
- child.stderr.setEncoding('utf8').on('data', (d) => (err = keep(err, d)));
104
- let ended = false;
105
- // A spawn error is followed by a close: the first one tells.
106
- const done = (e) => {
107
- if (ended)
108
- return;
109
- ended = true;
110
- clearTimeout(timer);
111
- if (mine !== generation)
112
- return resolve();
113
- const limits = limitsOf(out);
114
- const at = new Date().toISOString();
115
- const why = e && late ? Object.assign(e, { killed: true }) : e;
116
- if (limits)
117
- last = { at, limits };
118
- else
119
- last = { ...(last ?? { at: null, limits: [] }), failed: { at, error: reasonOf(why, err) } };
120
- asking = null;
121
- broadcast({ type: 'quota' });
122
- resolve();
123
- };
124
- child.on('error', done);
125
- child.on('close', (code, signal) => done(code === 0 ? null : new Error(`${command} /usage ended with ${code ?? signal}`)));
126
- // Not the shell alone: on Windows a killed shell leaves the claude under it running.
127
- const timer = setTimeout(() => {
128
- late = true;
129
- if (!child.pid)
130
- return;
131
- if (windows)
132
- spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
133
- else
134
- try {
135
- process.kill(-child.pid, 'SIGKILL');
136
- }
137
- catch {
138
- // The group ended on its own meanwhile.
139
- }
140
- // A process outside the tree that holds the pipes would hold the ask for good: the board
141
- // would read no quota until its restart.
142
- child.stdout.destroy();
143
- child.stderr.destroy();
144
- }, askTimeout).unref();
46
+ const agent = command;
47
+ // Through the account's lock and file (Codex review): a run's ask at the same time is the same.
48
+ asking = readUsage({ command: agent, maxAgeMs: 0, timeoutMs: askTimeout })
49
+ .then((reading) => reading,
50
+ // A folder or a lock the board cannot write: a failed ask, said beside the last reading.
51
+ (e) => ({
52
+ ...(last ?? { at: null, limits: [] }),
53
+ failed: { at: new Date().toISOString(), error: e.message.slice(0, 300) },
54
+ }))
55
+ .then((reading) => {
56
+ if (mine !== generation)
57
+ return;
58
+ last = reading;
59
+ asking = null;
60
+ broadcast({ type: 'quota' });
61
+ afterRead();
145
62
  });
146
63
  return asking;
147
64
  }
148
- /** Ask when a page is open and the last ask is older than `everyMs`. */
65
+ /** What else needs a reading with no page open: the automation standing on the reserve (d11). */
66
+ let needed = () => false;
67
+ export function needUsageWhen(fn) {
68
+ needed = fn;
69
+ }
70
+ /** What a new reading wakes: the queues and autopilots the reserve held (runs.ts). */
71
+ let afterRead = () => { };
72
+ export function onUsageRead(fn) {
73
+ afterRead = fn;
74
+ }
75
+ /**
76
+ * Ask when a page is open, or the automation stands on the reserve, and the last reading - this
77
+ * board's or a run's in `usage.json` - is older than `everyMs`.
78
+ */
149
79
  export function askIfDue(everyMs = USAGE_EVERY_MS, now = Date.now()) {
150
- if (command && watched() && now - askedAt >= everyMs)
80
+ if (!command || !(watched() || needed()))
81
+ return;
82
+ const kept = lastReading();
83
+ const keptAt = kept?.at ? Date.parse(kept.at) : 0;
84
+ if (keptAt > askedAt && now - keptAt < everyMs && !kept?.failed) {
85
+ last = kept;
86
+ askedAt = keptAt;
87
+ afterRead();
88
+ return;
89
+ }
90
+ if (now - askedAt >= everyMs)
151
91
  void askUsage();
152
92
  }