gcf-board 0.22.0 → 0.23.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/README.md CHANGED
@@ -6,6 +6,7 @@ A local web board for game projects on [GCF](../gcf-aif-ext): the items by statu
6
6
 
7
7
  - Node.js ≥ 22.18
8
8
  - [`ai-factory`](https://www.npmjs.com/package/ai-factory) installed globally, and in each project [`gcf-aif-ext`](../gcf-aif-ext) ≥ 0.18 (`gcf board --json` with `schema: 4`: the columns, the moves, the item's fields, the blocks and the Help terms come from it as data)
9
+ - for 0.23: `gcf-aif-ext` ≥ 0.25 and `gcf-harness-aif-ext` ≥ 0.24 for **Play** (an older core shows no bar)
9
10
  - for 0.22: `gcf-aif-ext` ≥ 0.24 and `gcf-harness-aif-ext` ≥ 0.23 for the **shelved** chip (an older pair stops a main batch at a card's loose code, as before)
10
11
  - for 0.21: `gcf-aif-ext` ≥ 0.23 for **amend** (an older core offers no such move)
11
12
  - for 0.20: `gcf-aif-ext` ≥ 0.22 for **Changes** (an older core shows neither the screen nor its marker)
@@ -45,6 +46,7 @@ The board knows no domain by name: the project's board read gives its columns, m
45
46
  - **An item** (a window over the screen, dragged by its head; a page on a phone; board 0.14.0): its **Status** (why it is blocked or waits, its fields, its dependencies; it opens there when it is blocked or waits), its file (the front matter folded, a `key:` body by sections), its plan and its run log as it grows, its **Lessons**, and the moves the core offers for it (`items[].moves`, Methodology §4.1): run, verdict, decide, block, unblock, drop, close, submit, depends. Each move's form comes from the core; the core still checks the rest itself, and the board shows its answer. **Dependencies**: what it needs that has not ended in history (an item with its column, a design unit with its TBDs or the questions that block it, a graveyard line, an unknown id) and the items that need it, each a link; **Edit…** opens the picker of the board's items and design units (search by id and title, or type an id), and Save sends the `depends` move's adds and removes. **History** (core 0.13.0): its moves newest first, when, which, who (a run, your session, you; unknown on a commit older than the framework's marks), the commit and its subject; then its runs, as on the Runs screen. **Related**: its feature's other children, and the graveyard lines tagged with its system ("did we kill this before?"). An item that ended opens from **Ended** with its History.
46
47
  - **Runs** (harness 0.13.0): what runs now with the run's model and effort, its last log lines, **Whole log** and **Stop**; the queue with what each item will run on; the past runs of the harness's run log, newest first, 50 at a time: start, end, mode, cost, and per item its result word, the reason word for word, cost, tokens, turns, handoffs, a broken step and what it ran on. **log** opens the part of the item's log that run wrote, **chat** that run's chat. Every start the operator asks for (Run selected, Run next, a drop on running, this screen) asks first with a model and effort picker for that run only (**default: each item's own**); the drawer's Run is one click. An older harness shows the active runs only, and the dialog has no pickers. The API: `GET /api/p/<project>/runs/past?limit=` (`gcf-harness runs --json`; 404 without a harness that keeps them), `GET …/item/<id>/history` (`{id, moves, runs}`), `GET …/log/<id>?from=&to=` (a past run's part, once: `{text, cut}`, at most its last 2 MB; without `from` and `to` the log as it grows), `POST …/run` with `model` and `effort`, `POST …/inbox/<entry>/draft` (`{thread, created}`).
47
48
  - **Log** (board 0.20.1, gcf-session 0.18.1): a subagent's lines say so (`subagent:`, `subagent tool:`, `subagent tool error:`), drawn as the main agent's kinds; the pulse's current action names a subagent's call as one.
49
+ - **Play** (board 0.23.0, core 0.25.0): a card waiting for play shows its own build, **Play** per target of `play:`, **Stop** and **Build**, on its run's end card, in its window and on Playtest; a verdict stops the player and removes the build.
48
50
  - **Amend** (board 0.21.0, core 0.23.0): under "more" on a card: the form opens on its text, shows old and new lines before the move, and refuses an edit made meanwhile with the text you typed kept beside it. A chat agent's proposal shows the same lines. During that card's run it is refused, and the proposal offers **Send to the run**, to a live session only.
49
51
  - **Run again** (board 0.20.1): an item a main batch has ended, blocked for one, can be run again while the batch goes on: it queues behind the batch. An item the batch works or has yet to reach is still refused with `already running from this board`, and so is every item of a worktree batch until that batch ends.
50
52
  - **Changes** (board 0.20.0, core 0.22.0): what is not committed and how it differs, view only: the agent commits. The header's `● 7 changed` counts the main checkout, and says `run writing in main` while a run works there; the screen switches between the main checkout and each run's worktree. A text file opens its diff, a picture its before and after; a binary file, the project's `no_diff:` globs (one glob a line in Settings), links, submodules, nested repositories and Git LFS files are listed and open nothing. It follows a move, a commit or an add at once, a save in an editor within 30 s.
@@ -76,12 +78,14 @@ The board knows no domain by name: the project's board read gives its columns, m
76
78
  - **Design**: where a game starts and its design changes. The steps from an empty project to the first work (the design, the pillars, the open questions, a ready unit), each with what does it: **Import GDD** (a markdown file), **Review GDD first**, **Create with agent**, **Draft with agent** for the glossary, **Pillars interview**, **Name with agent** for pillars without a name; each opens a project chat thread that follows its own skill and writes the design files without a card. **Record design** commits what a thread wrote, and **Discard draft…** takes an agent's unrecorded draft back (`gcf design discard`); a form save of the drafted part takes the draft along. The pillars, the vision, the glossary, a subsystem's purpose and each unit open in a form whose fields come from the core; a save goes through the core's checks, a refusal says why. A pillar is edited by its name, its id read-only (a changed name renames the id after the save); Retire. **Add unit** asks a subsystem, a type and a title, no id, and opens the new unit. A subsystem's purpose has **Draft with agent**. A unit's Drop, the design questions with their answer box, the designer's Export and Import. Until the first work, while steps are left, Command says how many and opens Design.
77
79
  - **Keys**: `/` search, `i` a new inbox entry, `n` a new item, `j` / `k` between cards, Enter opens one, `r` runs the focused card (it asks), `1`–`7` a column, `?` Help, `g` then a letter goes to a screen (`g c` Command, `g b` Board, `g t` Chat, `g i` Inbox, `g d` Design, `g r` Runs, `g p` Playtest, `g e` Ended, `g a` Agent, `g m` Metrics, `g s` Settings; the nav's icons say theirs), Esc closes a dialog, Help, the item's or the detail window; none while a field has the focus. Board 0.16.0: the nav is a rail of icons, the project switcher sits at the header's left.
78
80
  - **Lessons** (core 0.7.10, harness 0.9.2): what got in an agent's way, asked at the end of each session, lands in the inbox as the category Lesson, its kind (`tool`, `rules`, `framework`, `template`, `other`) the detail, with its item. The inbox filters them; a card shows `N lessons`, and the item's **Lessons** tab lists them with the inbox's buttons. A run's report line ends with `, N lessons`, and with `— code written outside aif-implement` when a session skipped that skill.
79
- - **Playtest**: `gcf playtest session` with the checklist grouped by subsystem; keep, tune or kill each item from the list. **Build** runs `dod.build`. A note goes to the inbox as `--category playtest`.
81
+ - **Playtest**: `gcf playtest session` with the checklist grouped by subsystem; keep, tune or kill each item from the list. Each card has its own **Play** bar. A note goes to the inbox as `--category playtest`.
80
82
  - **Ended**: history (accepted) and graveyard (killed, dropped, won't-fix); a line opens the item's History.
81
83
  - **Metrics**: `gcf-harness metrics --json` of the project — how many runs reached submit or close, what they cost, handoffs, plan checks, DoD attempts, guard firings, block reasons — and, with harness 0.9.5, the cost per item over all its runs and per week and day.
82
84
 
83
85
  The page updates by itself: the server watches each project's `gcf/` and `.gcf-session/runs/`.
84
86
 
87
+ Hold: a card's Hold (its chat and window), the project's hold chip, and `quota_reserve_pct` in Settings: the queue and the autopilot leave that share of each usage window to you.
88
+
85
89
  ## Security
86
90
 
87
91
  The board starts agents that write code and commit: whoever can talk to it runs code on this machine.
@@ -24,9 +24,9 @@ import { isUpload, saveUpload, UPLOAD_MAX } from './upload.js';
24
24
  import { addProject, homeDir, listProjects, projectOf, removeProject, yoloFile, } from './registry.js';
25
25
  import { allThemes } from './themes.js';
26
26
  import { askIfDue, askUsage, configureUsage, lastUsage } from './usage.js';
27
- import { activeRuns, adoptRuns, busyCheck, keepProjects, sweepRuns, closeReport, forgetProject, resumeQueue, retryWaiting, runsOf, setAutopilot, startRun, unqueue, } from './runs.js';
27
+ import { activeRuns, adoptRuns, busyCheck, keepProjects, sweepRuns, closeReport, forgetProject, resumeQueue, holdProject, retryWaiting, runsOf, setAutopilot, startRun, unqueue, whileClickBuilds, } from './runs.js';
28
28
  import { acceptProposal, agentDefaults, agentPresets, chatCard, deniedGroupIn, lastDeniedOf, lastRunEnd, chatOf, entryTalk, listTalks, openTalk, pickTalk, prepareTalk, startDesign, startTalk, stopTalk, talkEntry, talkId, talkLive, talkSaid, talkWaits, watchTalks, writeTalk, } from './talks.js';
29
- import { threadDir, threadOfEntry } from 'gcf-session';
29
+ import { accountSettings, saveAccountSettings, threadDir, threadOfEntry } from 'gcf-session';
30
30
  const send = (res, status, body) => {
31
31
  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
32
32
  res.end(JSON.stringify(body));
@@ -75,6 +75,9 @@ const treeArgs = (url) => {
75
75
  return tree && tree !== 'main' ? [`--worktree=${tree}`] : [];
76
76
  };
77
77
  /** Parse the JSON a command printed, or say what it printed instead. */
78
+ // How long the board waits for a build: the core ends it by the project's `dod_timeout_min`, and
79
+ // the board must not cut it sooner, on POSIX with its engine still going.
80
+ const PLAY_BUILD_MS = 24 * 60 * 60_000;
78
81
  function jsonOf(r, what) {
79
82
  try {
80
83
  return JSON.parse(r.out);
@@ -379,6 +382,19 @@ export function createApp(o) {
379
382
  send(res, 200, { on: b.on });
380
383
  },
381
384
  ],
385
+ // The account's settings (Hold-Plan d10): the quota's reserve, one for every project.
386
+ ['GET', /^\/api\/settings$/, async (_req, res) => send(res, 200, accountSettings())],
387
+ [
388
+ 'PUT',
389
+ /^\/api\/settings$/,
390
+ async (req, res) => {
391
+ const pct = (await bodyOf(req)).quota_reserve_pct;
392
+ if (typeof pct !== 'number' || !Number.isInteger(pct) || pct < 0 || pct > 50)
393
+ throw new HttpError(400, 'quota_reserve_pct is a whole percent, 0 to 50');
394
+ saveAccountSettings({ ...accountSettings(), quota_reserve_pct: pct });
395
+ send(res, 200, accountSettings());
396
+ },
397
+ ],
382
398
  ['GET', /^\/api\/projects$/, async (_req, res) => send(res, 200, await listProjects())],
383
399
  ['GET', /^\/api\/themes$/, async (_req, res) => send(res, 200, await allThemes())],
384
400
  [
@@ -737,14 +753,37 @@ export function createApp(o) {
737
753
  },
738
754
  ],
739
755
  [
740
- // A build runs the project's own command: a write, so a POST with its Origin checked.
756
+ // Playing a card: the project's own commands, so POSTs with their Origin checked. A refusal
757
+ // comes back as an error with its words; a build that failed is an answer (`ok: false`).
741
758
  'POST',
742
- /^\/api\/p\/([^/]+)\/playtest\/build$/,
743
- async (_req, res, m) => {
744
- const args = ['gcf', 'playtest', 'session', '--json', '--build'];
759
+ /^\/api\/p\/([^/]+)\/play\/(build|start|stop)$/,
760
+ async (req, res, m) => {
761
+ const p = await projectOf(m[1]);
762
+ const body = await bodyOf(req);
763
+ const word = (v, what) => {
764
+ if (typeof v !== 'string' || !/^[\w][\w-]*$/.test(v))
765
+ throw new HttpError(400, `${what} is one word`);
766
+ return v;
767
+ };
768
+ const args = m[2] === 'stop'
769
+ ? ['gcf', 'playtest', 'stop', '--json']
770
+ : m[2] === 'build'
771
+ ? ['gcf', 'playtest', 'build', word(body.id, 'id'), '--json']
772
+ : [
773
+ ...['gcf', 'playtest', 'start', word(body.id, 'id'), '--json'],
774
+ ...['--target', word(body.target, 'target')],
775
+ ];
745
776
  // A build of a real game takes minutes.
746
- const r = await cli(await projectOf(m[1]), args, 30 * 60_000);
747
- send(res, 200, jsonOf(r, 'gcf playtest session --build'));
777
+ const r = m[2] === 'build'
778
+ ? await whileClickBuilds(p, () => cli(p, args, PLAY_BUILD_MS))
779
+ : await cli(p, args);
780
+ broadcast({ type: 'board', project: p.name });
781
+ try {
782
+ send(res, 200, JSON.parse(r.out));
783
+ }
784
+ catch {
785
+ throw new HttpError(409, briefError(r.err || r.out));
786
+ }
748
787
  },
749
788
  ],
750
789
  [
@@ -1161,6 +1200,36 @@ export function createApp(o) {
1161
1200
  send(res, 200, { ok: r.ok, out: r.out.trim(), err: briefError(r.err) });
1162
1201
  },
1163
1202
  ],
1203
+ [
1204
+ // The operator's Hold of a card (Hold-Plan d6, d20): its session hands over at the next
1205
+ // call, its work waits ready; the harness keeps the mark, so a restart keeps the hold.
1206
+ 'POST',
1207
+ /^\/api\/p\/([^/]+)\/hold\/([^/]+)$/,
1208
+ async (_req, res, m) => {
1209
+ const p = await projectOf(m[1]);
1210
+ const [id] = runIds({ ids: [decodeURIComponent(m[2])] });
1211
+ const r = await cli(p, [await harnessOf(p), 'hold', id]);
1212
+ broadcast({ type: 'board', project: p.name });
1213
+ send(res, r.ok ? 200 : 409, { ok: r.ok, out: r.out.trim(), err: briefError(r.err) });
1214
+ },
1215
+ ],
1216
+ [
1217
+ // The operator holds the whole project, or releases it (Hold-Plan d20).
1218
+ 'POST',
1219
+ /^\/api\/p\/([^/]+)\/hold$/,
1220
+ async (_req, res, m) => {
1221
+ const p = await projectOf(m[1]);
1222
+ send(res, 200, await holdProject(o.entry, p, await harnessOf(p), true));
1223
+ },
1224
+ ],
1225
+ [
1226
+ 'DELETE',
1227
+ /^\/api\/p\/([^/]+)\/hold$/,
1228
+ async (_req, res, m) => {
1229
+ const p = await projectOf(m[1]);
1230
+ send(res, 200, await holdProject(o.entry, p, await harnessOf(p), false));
1231
+ },
1232
+ ],
1164
1233
  [
1165
1234
  'POST',
1166
1235
  /^\/api\/p\/([^/]+)\/queue\/resume$/,
@@ -187,11 +187,34 @@ export function runsState(dir, ttlMin = SESSION_TTL_MIN, now = Date.now()) {
187
187
  // so the page reads an open plan again when the count moves.
188
188
  const planRevs = new Map();
189
189
  export const planRev = (project) => planRevs.get(project) ?? 0;
190
+ /** What of a card's builds and its player the board shows: a build ends, a game is closed. */
191
+ export function playState(project) {
192
+ const session = path.join(project, '.gcf-session');
193
+ let builds = [];
194
+ try {
195
+ builds = readdirSync(path.join(session, 'builds'))
196
+ .filter((f) => f.endsWith('.json'))
197
+ .map((f) => `${f}:${statSync(path.join(session, 'builds', f)).mtimeMs}`)
198
+ .sort();
199
+ }
200
+ catch {
201
+ // None yet.
202
+ }
203
+ let player = '';
204
+ try {
205
+ const p = JSON.parse(readFileSync(path.join(session, 'play.json'), 'utf8'));
206
+ player = `${p.pid}:${alive(p.pid)}`;
207
+ }
208
+ catch {
209
+ // None plays.
210
+ }
211
+ return `${builds.join(',')}|${player}`;
212
+ }
190
213
  /**
191
214
  * Watch a project: `gcf/` (every move writes there), `.ai-factory/plans` (a plan is written and
192
- * edited) and `.gcf-session/runs` (a run's lock or session mark comes, goes or goes stale). The
193
- * runs directory may not exist yet, so it is polled, not watched. Bursts of writes make one
194
- * event. Returns the stop.
215
+ * edited), `.gcf-session/runs` (a run's lock or session mark comes, goes or goes stale) and its
216
+ * builds and player. The session folder may not exist yet, so it is polled, not watched. Bursts
217
+ * of writes make one event. Returns the stop.
195
218
  */
196
219
  export function watchProject(p, debounceMs = 300, ttlMin = () => SESSION_TTL_MIN) {
197
220
  let timer = null;
@@ -236,11 +259,16 @@ export function watchProject(p, debounceMs = 300, ttlMin = () => SESSION_TTL_MIN
236
259
  }
237
260
  };
238
261
  let read = quotaAt();
262
+ let playing = playState(p.path);
239
263
  const poll = setInterval(() => {
240
264
  const now = runsState(runs, ttlMin());
241
265
  if (now !== last)
242
266
  fire();
243
267
  last = now;
268
+ const nowPlaying = playState(p.path);
269
+ if (nowPlaying !== playing)
270
+ fire();
271
+ playing = nowPlaying;
244
272
  // The limit is the account's: a new reading here changes every project's top bar.
245
273
  const quota = quotaAt();
246
274
  if (quota !== read)
@@ -16,7 +16,8 @@ import { briefError, runCli } from './cli.js';
16
16
  import { alive, broadcast } from './events.js';
17
17
  import { HttpError } from './http-error.js';
18
18
  import { homeDir } from './registry.js';
19
- import { askUsage } from './usage.js';
19
+ import { accountSettings, lastReading, reserveOfReading } from 'gcf-session';
20
+ import { askUsage, needUsageWhen, onUsageRead } from './usage.js';
20
21
  // The source runs relay.ts, the package its build beside this file.
21
22
  const RELAY = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? 'relay.ts' : 'relay.js', import.meta.url));
22
23
  const flightsDir = () => path.join(homeDir(), 'runs');
@@ -28,8 +29,26 @@ const BEAT_STALE_MS = 90_000;
28
29
  // A board that stops leaves its runs going: killing one would lose its integrate step.
29
30
  const active = new Set();
30
31
  const queues = new Map();
32
+ // The projects whose folder a click build holds: a run now would only be refused, and a refused
33
+ // run stalls the queue and turns the autopilot off. They wait for it instead.
34
+ const clickBuilds = new Set();
35
+ /** Run a click build with the project's runs held back; they go when it ends. */
36
+ export async function whileClickBuilds(p, build) {
37
+ clickBuilds.add(p.name);
38
+ try {
39
+ return await build();
40
+ }
41
+ finally {
42
+ clickBuilds.delete(p.name);
43
+ advance(p.name);
44
+ setImmediate(() => void pilot(p.name));
45
+ }
46
+ }
31
47
  // Projects whose queue waits after a failure the next run would repeat (`stalled`).
32
48
  const paused = new Set();
49
+ // The projects the operator holds (Hold-Plan d20): no queued or autopilot run starts; the
50
+ // operator's own Run goes at once. Apart from `paused`: Release resumes the queue, nothing else.
51
+ const projectHolds = new Set();
33
52
  // The paused projects whose pause the usage limit set: a run that ended paused by it (AD-19).
34
53
  const limitPaused = new Set();
35
54
  // When the usage limit that paused a project's queue resets, ISO; none when it was not one.
@@ -66,6 +85,7 @@ function save() {
66
85
  const names = new Set([
67
86
  ...queues.keys(),
68
87
  ...paused,
88
+ ...projectHolds,
69
89
  ...reports.keys(),
70
90
  ...acts.keys(),
71
91
  ...pilots.keys(),
@@ -79,7 +99,9 @@ function save() {
79
99
  path: where,
80
100
  // `waiting` stays behind: a board started again tries it, the dependency may have ended.
81
101
  queue: (queues.get(name) ?? []).map(({ entry: _e, p: _p, waiting: _w, ...q }) => q),
82
- paused_by: runsOf(name).paused_by,
102
+ // The queue's own pause; the hold beside it, so a restart keeps both.
103
+ paused_by: paused.has(name) ? (limitPaused.has(name) ? 'limit' : 'failure') : null,
104
+ held: projectHolds.has(name),
83
105
  paused_until: pausedUntil.get(name) ?? null,
84
106
  reports: reports.get(name) ?? [],
85
107
  acts: acts.get(name) ?? [],
@@ -209,6 +231,8 @@ function restore(entry, p) {
209
231
  queues.set(p.name, queue.map((q) => ({ ...q, entry, p })));
210
232
  if (s.paused_by === 'limit' || s.paused_by === 'failure')
211
233
  paused.add(p.name);
234
+ if (s.paused_by === 'hold' || s.held === true)
235
+ projectHolds.add(p.name);
212
236
  if (s.paused_by === 'limit')
213
237
  limitPaused.add(p.name);
214
238
  const until = s.paused_by === 'limit' ? s.paused_until : null;
@@ -238,13 +262,15 @@ export function runsOf(project) {
238
262
  queued: (queues.get(project) ?? []).flatMap((q) => q.ids),
239
263
  // The pick a queued item goes with, by its id: only the ones that have one.
240
264
  queued_with: Object.fromEntries((queues.get(project) ?? []).flatMap((q) => q.agent && (q.agent.model || q.agent.effort) ? q.ids.map((id) => [id, q.agent]) : [])),
241
- paused: paused.has(project),
242
- // Why it waits: a run the usage limit ended paused, or a failure; the operator resumes it.
243
- paused_by: (paused.has(project)
244
- ? limitPaused.has(project)
245
- ? 'limit'
246
- : 'failure'
247
- : null),
265
+ paused: paused.has(project) || projectHolds.has(project),
266
+ // Why it waits: the operator's hold, a run the usage limit ended paused, or a failure.
267
+ paused_by: (projectHolds.has(project)
268
+ ? 'hold'
269
+ : paused.has(project)
270
+ ? limitPaused.has(project)
271
+ ? 'limit'
272
+ : 'failure'
273
+ : null),
248
274
  // When the usage limit that paused it resets, ISO: none for a pause of another kind.
249
275
  paused_until: paused.has(project) ? (pausedUntil.get(project) ?? null) : null,
250
276
  reports: reports.get(project) ?? [],
@@ -258,6 +284,7 @@ export function forgetProject(project) {
258
284
  forgotten.add(r);
259
285
  queues.delete(project);
260
286
  paused.delete(project);
287
+ projectHolds.delete(project);
261
288
  limitPaused.delete(project);
262
289
  pausedUntil.delete(project);
263
290
  reports.delete(project);
@@ -299,17 +326,80 @@ function limited(run, result) {
299
326
  function advance(project) {
300
327
  if (adopting.has(project))
301
328
  return;
302
- if (paused.has(project) || activeRuns(project).some((r) => r.mode === 'main'))
329
+ if (paused.has(project) || projectHolds.has(project) || clickBuilds.has(project))
330
+ return;
331
+ if (activeRuns(project).some((r) => r.mode === 'main'))
303
332
  return;
304
333
  const queue = queues.get(project) ?? [];
305
334
  const at = queue.findIndex((q) => !q.waiting);
306
335
  if (at < 0)
307
336
  return;
337
+ // The quota at its reserve: the queue waits for a reading under it (Hold-Plan d11).
338
+ const reserve = reserveStand(project);
339
+ if (reserve) {
340
+ if (!reserveWaits.has(project))
341
+ trace(project, 'queue-reserve', reserve.text);
342
+ reserveWaits.add(project);
343
+ return;
344
+ }
345
+ reserveWaits.delete(project);
308
346
  const [next] = queue.splice(at, 1);
309
347
  trace(project, 'queue-run', `the queue starts ${next.ids.join(', ')}`);
310
348
  // Nobody clicked it now: it waits while the usage limit's reset is ahead.
311
349
  spawnRun({ ...next, waitLimit: true, queued: true }, next.mode);
312
350
  }
351
+ // The projects a run reported stopped by the reserve: the board does not know the run's model,
352
+ // so it judges every model's week until a reading under the reserve in all (Codex review).
353
+ const reserveStrict = new Set();
354
+ // The projects whose queue waits on the quota's reserve: a new reading wakes them.
355
+ const reserveWaits = new Set();
356
+ /**
357
+ * Why automation stands on the quota's reserve, by the account's last reading (Hold-Plan d10,
358
+ * d11): the 5-hour window's wait or the week's stop; null to go, as with no reading.
359
+ */
360
+ function reserveStand(project) {
361
+ const strict = reserveStrict.has(project);
362
+ const reading = lastReading();
363
+ // A run said the reserve stops it: no reading, or a failed one, tells the board nothing new.
364
+ if (strict && (!reading || reading.failed))
365
+ return { kind: 'limit', text: reserveText({ weekly: true }) };
366
+ const model = strict ? '*' : null;
367
+ const d = reserveOfReading(reading, model, accountSettings().quota_reserve_pct);
368
+ if ('go' in d) {
369
+ reserveStrict.delete(project);
370
+ return null;
371
+ }
372
+ return {
373
+ kind: 'limit',
374
+ text: reserveText('stop' in d ? d.reserve : { until: d.until.toISOString() }),
375
+ };
376
+ }
377
+ /**
378
+ * A queued run the reserve stopped (Codex review): its held items go back to the queue's head
379
+ * and the queue waits as the autopilot does, so it is not drained run after refused run.
380
+ */
381
+ function requeueReserved(q, result) {
382
+ const held = (result?.items ?? []).filter((i) => i.held === 'reserve').map((i) => i.id);
383
+ if (!q.queued || !held.length)
384
+ return;
385
+ const project = q.p.name;
386
+ reserveStrict.add(project);
387
+ reserveWaits.add(project);
388
+ const { waitLimit: _w, queued: _q, pilot: _p, ...back } = q;
389
+ queues.set(project, [{ ...back, ids: held }, ...(queues.get(project) ?? [])]);
390
+ trace(project, 'queue-reserve', `${held.join(', ')} back in the queue: the quota is at its reserve`);
391
+ }
392
+ /** A reading came: the queues and the autopilots the reserve held look again. */
393
+ export function reserveRead() {
394
+ for (const project of [...reserveWaits])
395
+ advance(project);
396
+ for (const [project, s] of pilots)
397
+ if (s.on && s.stop?.kind === 'limit')
398
+ void pilot(project);
399
+ }
400
+ onUsageRead(reserveRead);
401
+ // The reserve needs readings with no page open: a standing automation waits for them (d11).
402
+ needUsageWhen(() => reserveWaits.size > 0 || [...pilots.values()].some((s) => s.on && s.stop?.kind === 'limit'));
313
403
  /** What waits on a dependency is tried again; whether anything did. */
314
404
  function clearWaiting(project) {
315
405
  const queue = queues.get(project) ?? [];
@@ -340,6 +430,35 @@ function keepWaiting(q, waits, gate) {
340
430
  ...(queues.get(q.p.name) ?? []),
341
431
  ]);
342
432
  }
433
+ /**
434
+ * The operator holds the project, or releases it (Hold-Plan d20): the harness keeps the mark
435
+ * (`gcf-harness hold --project`), so its runs' sessions hand over; the autopilot goes off; the
436
+ * queue waits. Release lifts the hold and resumes the queue; the autopilot stays off.
437
+ */
438
+ export async function holdProject(entry, p, harness, on) {
439
+ const args = [harness, 'hold', '--project', ...(on ? [] : ['--release'])];
440
+ const r = await runCli(entry, p.path, args);
441
+ if (!r.ok)
442
+ throw new Error(`${harness} hold: ${briefError(r.err || r.out)}`);
443
+ paths.set(p.name, p.path);
444
+ if (on) {
445
+ projectHolds.add(p.name);
446
+ const s = pilots.get(p.name);
447
+ if (s?.on)
448
+ s.on = false;
449
+ trace(p.name, 'project-held', 'the operator held the project');
450
+ }
451
+ else {
452
+ projectHolds.delete(p.name);
453
+ trace(p.name, 'project-released', 'the operator released the project');
454
+ // Release lifts the hold, nothing else: a pause for a failure or the limit stays (review 6).
455
+ clearWaiting(p.name);
456
+ advance(p.name);
457
+ }
458
+ save();
459
+ changed(p.name);
460
+ return runsOf(p.name);
461
+ }
343
462
  /** The operator resumes a paused queue (after fixing what stopped it). */
344
463
  export function resumeQueue(project) {
345
464
  if (paused.has(project))
@@ -410,9 +529,10 @@ function spawnRun(q, mode) {
410
529
  // The board says where it goes: it queued it by that mode (an item's own, the run's pick). A
411
530
  // card session works the main checkout too, with no item yet.
412
531
  const args = q.kind === 'card'
413
- ? [entry, harness, 'card', ...ids, '--json']
532
+ ? [entry, harness, 'card', ...ids, '--json', ...(q.waitLimit ? ['--wait-limit'] : [])]
414
533
  : [entry, harness, 'run', ...ids, '--json', '--mode', mode];
415
- // A card session takes none of a run's flags: `gcf-harness card` knows only --agent, --json.
534
+ // A card session takes none of a run's flags: `gcf-harness card` knows --agent, --json and,
535
+ // for the autopilot, --wait-limit (Hold-Plan d11).
416
536
  if (q.kind !== 'card') {
417
537
  if (q.fresh)
418
538
  args.push('--fresh');
@@ -522,6 +642,8 @@ function land(q, run, rid, live, message = '') {
522
642
  message = "the run's relay ended without a result";
523
643
  // A run of a project removed meanwhile only reports: it pauses nothing.
524
644
  const kept = !forgotten.has(run);
645
+ if (kept)
646
+ requeueReserved(q, result);
525
647
  const stop = kept && mode === 'main' && queues.get(p.name)?.length && stalled(ok, result);
526
648
  if (stop) {
527
649
  paused.add(p.name);
@@ -744,7 +866,8 @@ export function startRun(entry, p, ids, mode = 'worktree', fresh = false, harnes
744
866
  busyCheck(p, ids);
745
867
  const { active: going } = runsOf(p.name);
746
868
  // A paused queue holds a new main run too: it would repeat the failure, and jump the queue.
747
- if (mode === 'main' && (paused.has(p.name) || going.some((r) => r.mode === 'main'))) {
869
+ const held = paused.has(p.name) || clickBuilds.has(p.name);
870
+ if (mode === 'main' && (held || going.some((r) => r.mode === 'main'))) {
748
871
  queues.set(p.name, [
749
872
  ...(queues.get(p.name) ?? []),
750
873
  { entry, p, ids, mode, fresh, harness, agent },
@@ -757,9 +880,10 @@ export function startRun(entry, p, ids, mode = 'worktree', fresh = false, harnes
757
880
  const pilots = new Map();
758
881
  // The projects whose autopilot is asking the harness now: one ask at a time.
759
882
  const piloting = new Set();
760
- // The batch size the autopilot asks for.
883
+ // The batch size the autopilot asks for. A main-mode plan runs its first card only: the run's
884
+ // end calls pilot() again, which reads the switch, loose work and the milestone before the next.
761
885
  const PILOT_BATCH = 3;
762
- const STOPS = ['play', 'empty', 'idle', 'dirty', 'no-move', 'error'];
886
+ const STOPS = ['play', 'empty', 'idle', 'dirty', 'no-move', 'error', 'limit', 'hold'];
763
887
  const savedPilot = ({ on, stop, guard, harness }) => ({
764
888
  on,
765
889
  stop,
@@ -867,8 +991,11 @@ function piloted(project, ok, result) {
867
991
  return off('error', `its run ended with no result${result?.gate ? ` (${result.gate})` : ''}`);
868
992
  // A stop is the operator's word: the autopilot takes it, it does not start the item again.
869
993
  const stopped = items.filter((i) => /stopped/.test(`${i.result ?? ''} ${i.error ?? ''}`));
870
- // A timeout or a usage limit cut a session a rerun is meant to go on with.
871
- const cut = (i) => i.limit_resets !== undefined || /timed out/.test(`${i.result ?? ''} ${i.error ?? ''}`);
994
+ // A timeout or a usage limit cut a session a rerun is meant to go on with; so did a Hold or
995
+ // the quota's reserve (Hold-Plan d9, d11): paused, not stopped.
996
+ const cut = (i) => i.limit_resets !== undefined ||
997
+ Boolean(i.held) ||
998
+ /timed out/.test(`${i.result ?? ''} ${i.error ?? ''}`);
872
999
  // `skipped`: no session looked at it, so its next ask is no repeat of this one.
873
1000
  const none = items.filter((i) => !MOVED.test(i.result ?? 'merged') && !cut(i) && i.result !== 'skipped');
874
1001
  for (const i of none)
@@ -883,10 +1010,22 @@ function piloted(project, ok, result) {
883
1010
  if (refused)
884
1011
  return off('dirty', refused.reason ?? `${refused.id} did not start`);
885
1012
  if (none.length && none.length === items.filter((i) => i.result !== 'skipped').length)
886
- off('no-move', `a run of ${items.map((i) => i.id).join(', ')} made no move`);
1013
+ return off('no-move', `a run of ${items.map((i) => i.id).join(', ')} made no move`);
1014
+ // The quota's reserve held it: the autopilot stands on the limit, it stays on, until a reading
1015
+ // newer than this one (the run knows its model's week, the board does not; review 2).
1016
+ if (items.some((i) => i.held === 'reserve')) {
1017
+ reserveStrict.add(project);
1018
+ stand(project, { kind: 'limit', text: reserveText(items.find((i) => i.reserve)?.reserve) });
1019
+ }
887
1020
  }
1021
+ /** Why the autopilot stands on the quota's reserve, as the header says it. */
1022
+ export const reserveText = (r) => r?.weekly
1023
+ ? "the quota is at its reserve: the automation stands until the week's reset"
1024
+ : `the quota is at its reserve: the automation waits for the reset${r?.until ? ` at ${r.until}` : ''}`;
888
1025
  /** Whether the project is idle for the autopilot: no run, no queue to go, no pause. */
889
1026
  const idle = (project) => !paused.has(project) &&
1027
+ !projectHolds.has(project) &&
1028
+ !clickBuilds.has(project) &&
890
1029
  !activeRuns(project).length &&
891
1030
  !queues.get(project)?.some((q) => !q.waiting);
892
1031
  /** Main's loose work outside gcf/ a main batch would carry; none when the gate cannot say. */
@@ -909,6 +1048,10 @@ async function pilot(project) {
909
1048
  const s = pilots.get(project);
910
1049
  if (!s?.on || piloting.has(project) || adopting.has(project) || !idle(project))
911
1050
  return;
1051
+ // The quota at its reserve: it stands, still on, and a reading under it starts it (d11).
1052
+ const reserve = reserveStand(project);
1053
+ if (reserve)
1054
+ return stand(project, reserve);
912
1055
  piloting.add(project);
913
1056
  try {
914
1057
  const skip = guardedOf(s);
@@ -934,7 +1077,7 @@ async function pilot(project) {
934
1077
  stand(project, null);
935
1078
  trace(project, 'autopilot-card', `the autopilot cards ${plan.units.join(', ')}`);
936
1079
  const q = { entry, p, ids: plan.units, mode: 'main', harness };
937
- spawnRun({ ...q, kind: 'card', pilot: true }, 'main');
1080
+ spawnRun({ ...q, kind: 'card', pilot: true, waitLimit: true }, 'main');
938
1081
  changed(project);
939
1082
  return;
940
1083
  }
@@ -966,8 +1109,9 @@ async function pilot(project) {
966
1109
  if (!s.on || !idle(project))
967
1110
  return;
968
1111
  stand(project, null);
969
- trace(project, 'autopilot-run', `the autopilot runs ${plan.ids.join(', ')}`);
970
- spawnRun({ entry, p, ids: plan.ids, mode, harness, pilot: true, waitLimit: true }, mode);
1112
+ const ids = mode === 'main' ? plan.ids.slice(0, 1) : plan.ids;
1113
+ trace(project, 'autopilot-run', `the autopilot runs ${ids.join(', ')}`);
1114
+ spawnRun({ entry, p, ids, mode, harness, pilot: true, waitLimit: true }, mode);
971
1115
  changed(project);
972
1116
  }
973
1117
  finally {
@@ -189,6 +189,42 @@ function commitsOf(dir, id) {
189
189
  const lines = git(dir, 'log', '--format=%h %s', '-n', '500', '-F', `--grep=${id}`).split('\n');
190
190
  return lines.filter((l) => word.test(l.slice(l.indexOf(' ') + 1))).slice(0, CONTEXT_LINES);
191
191
  }
192
+ /**
193
+ * Whether a card waiting for play can be played, in the words a chat answers from: this thread is
194
+ * not the run that built it, and without these facts it would say another agent did the work.
195
+ */
196
+ function playLines(board, item) {
197
+ if (!['awaiting-verdict', 'unplayed'].includes(item.status) || board.play === undefined)
198
+ return [];
199
+ if (board.play === null)
200
+ return [
201
+ '',
202
+ 'To play it: how to play is not set up (no `play:` in gcf/config.yml), so it has no build.',
203
+ "If the project's AGENTS.md says how the game builds and starts, call propose_play_setup.",
204
+ '',
205
+ ];
206
+ const b = item.build;
207
+ const targets = board.play.targets.map((t) => `${t.name} (${t.open})`).join(', ') || 'none';
208
+ const said = b?.building
209
+ ? 'its build is being made now.'
210
+ : b?.ok
211
+ ? `its build is ready: commit ${b.commit ?? 'unknown'}, built ${b.built_at}, ` +
212
+ `${b.source === 'click' ? 'by hand, so it may hold later cards' : 'by its run'}.`
213
+ : 'it has no build yet.';
214
+ const running = board.play.running?.id === item.id
215
+ ? [`It plays now on ${board.play.running.target}: ${board.play.running.open}.`]
216
+ : [];
217
+ return [
218
+ '',
219
+ `To play it: ${said}`,
220
+ ...(b?.problem ? [`The last build failed: ${b.problem.split('\n')[0]}`] : []),
221
+ ...running,
222
+ `Targets: ${targets}.`,
223
+ 'Do not ask the human to build or start it by hand: the card has its Play and Build buttons;',
224
+ 'to offer one here call propose_play with its id and a target. The verdict stops the player.',
225
+ '',
226
+ ];
227
+ }
192
228
  /**
193
229
  * What a thread bound to `item` is given to read (AD-47): paths, not their text, but the ones a
194
230
  * session would need a git command or a search for. Empty for a thread of no item.
@@ -220,6 +256,8 @@ export function contextOf(p, board, item) {
220
256
  if (last)
221
257
  lines.push(`- its file as last committed: git show ${last.split(' ')[0]}^:gcf/work/${item}.md (${last})`);
222
258
  }
259
+ if (live)
260
+ lines.push(...playLines(board, live));
223
261
  for (const [what, rel] of [
224
262
  ["its run's log", `.gcf-session/runs/${item}.log`],
225
263
  ["its run's chat", `.gcf-session/runs/${item}.chat.jsonl`],