gcf-board 0.10.0 → 0.12.1

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
@@ -8,6 +8,8 @@ A local web board for game projects on [GCF](../gcf-aif-ext): the items by statu
8
8
  - [`ai-factory`](https://www.npmjs.com/package/ai-factory) installed globally, and in each project [`gcf-aif-ext`](../gcf-aif-ext) ≥ 0.10 (`gcf board --json` with `schema: 3`: the columns, the moves, the item's fields, the blocks and the Help terms come from it as data)
9
9
  - for runs: [`gcf-harness-aif-ext`](../gcf-harness-aif-ext) ≥ 0.11 (every board run opens its chat: `--chat`, `gcf-harness chat`; it waits the project's answer time) and Claude Code (`claude -p`); ≥ 0.12 to wait for the usage limit's reset and for queued runs (`--wait-limit`)
10
10
  - for the project chat: `gcf-aif-ext` ≥ 0.12 (`domain.chat`, `agent.rules`) and Claude Code
11
+ - for 0.12: `gcf-aif-ext` ≥ 0.16 for the chat's proposals of moves on items and inbox entries (an older core proposes only new items) and an item's own run mode; `gcf-harness-aif-ext` ≥ 0.16 to run main and worktree side by side safely (the main run's queue in the gate, a merge that waits)
12
+ - for 0.11: `gcf-aif-ext` ≥ 0.12.1 for **waiting for me** and the human columns of Command (an older core marks no column `human`: they stay empty); ≥ 0.15 names a session mark's life (`domain.session_ttl_min`; older: 120 minutes)
11
13
  - for 0.10: `gcf-aif-ext` ≥ 0.14 for an item's attachments and the project's model and effort; `gcf-harness-aif-ext` ≥ 0.14 for the run gate's refusal before the click (an older one: the click is gated, as before)
12
14
  - for board v2 (0.9): `gcf-aif-ext` ≥ 0.13 for an item's History, `needs`, the design units, filters and lanes; `gcf-harness-aif-ext` ≥ 0.13 for past runs and a run's model and effort. On older ones these hide or say which version they need
13
15
  - gcf-board 0.2 needs `gcf-aif-ext` ≥ 0.7 (priority, questions, session marks, `run_mode`)
@@ -45,9 +47,9 @@ The board knows no domain by name: the project's board read gives its columns, m
45
47
  - a card onto **graveyard** drops it.
46
48
 
47
49
  Every other move is a button.
48
- - **Run**: **run** on an item, or select ready cards and **Run selected**. It starts `ai-factory gcf-harness run <ids> --json` in the project's run mode:
49
- - `run_mode: worktree`: one worktree and one agent session per item, all at once, then the integrator;
50
- - `run_mode: main`: one item at a time in the project folder. A run asked for meanwhile waits in the board's **queue**; **remove from queue** takes it out.
50
+ - **Run**: **run** on an item, or select ready cards and **Run selected**. It starts `ai-factory gcf-harness run <ids> --json --mode <mode>`, each item where it runs: the start dialog's **Where this run goes**, else the item's own **run mode** (core 0.16: the drawer's fact and **More**, `gcf item mode`), else the project's `run_mode` (board 0.12.0, Board-PRD decision 28). A start with both kinds is two runs; the dialog's hints say only what the framework knows (a spike on main, a merge or a main run that waits):
51
+ - worktree: one worktree and one agent session per item, all at once, then the integrator; while a main run works in the project folder its green branch reads **verified** and merges when that run ends (core and harness 0.16);
52
+ - main: one item at a time in the project folder. A main run asked for meanwhile waits in the board's **queue**; **remove from queue** takes it out.
51
53
 
52
54
  A run asks first: it spends the subscription. **Stop** on a running item ends its session; the item stays ready and its work is kept. **Stop** during the wait for the usage limit's reset leaves the item **paused: limit** with its reset, and the queue goes on. A queued main run that the next one would repeat (the harness did not start, or another run works the checkout) pauses the queue: the header shows **queue paused — resume**; fix the cause, then resume. A card marked **interrupted** had a run that stopped (a timeout, a stop, a crash, the usage limit): **resume** continues its agent session with all its context, **start fresh** drops it. After the usage limit the run itself waits for the reset and goes on in the same session (harness 0.12): the card reads **limit: resumes HH:MM**, and **Stop** ends the wait. A run that could not wait (the week's limit, an unknown reset) ends **paused: limit** and pauses the main queue; **resume** on the header goes on after the reset. When a run ends, a report card lists each item's result and stays until closed, across page reloads. **What the board did by itself** lists its automatic acts with their times: a usage limit, a context handoff, the queue paused, resumed or started. A run confirmation names what each interrupted item picks up. The header shows the usage limit as the last run read it, from the newest `.gcf-session/runs/quota.json` of the board's projects: `quota 19% left · resets 03:00`, the window with the least left, every window in its tooltip; `quota ?` before any reading, or once every window has reset since. The queue, its pause, the reports and that list live in the board home too (`~/.gcf/queue.json`, board 0.10): a board started again goes on with them. It first takes in its runs; then a queue not paused, with no main run going, goes on (`queue-restored` in the list); a run that died while the board was down (a restart of the machine) pauses it, and a limit's pause shows its reset time. Two boards on one home both go on with the same queue: start one. A run itself outlives the board: closing it or Ctrl+C in its console leaves the run going, and the board started again shows it running, then its report (a run in flight keeps its record in `~/.gcf/runs/`).
53
55
  - **Who runs it** (core 0.7.13): a running card tells a console run and **your session** (a `gcf claim` mark) from the board's own run; a session offers **release mark** instead of **stop**. A ready card whose dependencies are not built yet shows **waits for <dep>**; the drawer shows when an item began to wait (`since_at`).
@@ -57,11 +59,12 @@ The board knows no domain by name: the project's board read gives its columns, m
57
59
  - **New item**: `gcf item new … --commit`, its form from the core: a bug asks its severity, a release its version and channel. The item's `model` and `effort` go to its run.
58
60
  - **Help** (**?**): the domain's terms, columns, moves and field values with what each means, and the words of runs, under one filter.
59
61
  - **Settings**: the keys of `gcf/config.yml` and the agents' language (`language.ui`, `language.artifacts` of `.ai-factory/config.yaml`), by the core's groups, each a `gcf config set` commit.
62
+ - **Theme** (board 0.11.0, Board-PRD decision 26): Settings, "Board · this browser": **Dark (built-in)** or a theme file of `~/.gcf/themes/<id>.json` — `{"gcf_theme": 1, "name", "scheme": "light" | "dark", "tokens": {…}}`, the colour tokens of `web/tokens.css` without `--gcf-` over the built-in dark (a template: docs/design/theme-sample.json). Each browser keeps its own choice; a file that cannot be read is listed with its reason, and the page falls back to dark when the chosen one is gone. Reload the page after changing a file. `GET /api/themes` lists the files.
60
63
  - **Agent**: the deny groups to tick, the rules the ticked groups add, the operator's own deny rules (add, remove) and the allow rules of `agent.allow`, apart; the context limits, read only.
61
64
  - **An item's chat** (its drawer's **Chat** tab; harness 0.11.1, core 0.11.1): every run the board starts keeps its agent sessions open; the project's `chat:` settings (Settings: `chat.ask`, `chat.answer_timeout_min`) say what the agent asks and how long a question waits. The tab shows the run's chat, then the item's own thread of the project chat: the talk, question cards (picks, several questions, **Submit**), the run's milestones, its sessions, the limit wait, the context share. A message goes where the server puts it: the live run (its limit wait too), else the item's thread, and the line under the box says where it went. `GET /api/p/<project>/chat/<id>` follows the item's chat from its start, in raw chunks of JSON lines (the page splits them). `POST` there sends `{type: 'say', text, images?, attach?}`, `{type: 'interrupt'}` or `{type: 'answer', request_id, answers}` through `gcf-harness chat`; with no live run a message goes to the item's thread (answer `{talk}`), else a message with no session to read it gets 409, bad input 400. `attach` (`[{kind: item | unit | file, ref}]`) goes into the message's text as a line the agent reads; a design unit (the composer's **+ unit**, from the board read's `units`) goes as `unit <id> (<file>)`. `GET /api/p/<project>/chat/<id>/att/<file>` serves a chat picture; **attach to item…** under a picture gives it to an item (`gcf item attach`).
62
65
  - **Functional base A** (board 0.10.0, core and harness 0.14.0; docs/Base-A-Plan.md): Settings has `session_timeout_min` and the project's `agent.model` / `agent.effort` (suggested from the agent's presets); the drawer shows the project's model on an item without its own, "(project)". The drawer's Run is off with the run gate's reason when the gate refuses the item now, and the start dialog marks each refused item and runs the rest (`GET /api/p/<project>/gate?ids=` runs `gcf-harness gate --each`). An item's attachments and an inbox entry's pictures are links (`GET /api/p/<project>/attachment?path=`: only `gcf/work/<id>/attachments/` and `gcf/inbox/in-<hex>/attachments/`, no `..`, no link on the way, a picture shown, any other file a download, `nosniff` and `default-src 'none'`), and a picture or link in File or Plan that points there loads through it. A permission card for one MCP tool offers Always, saying it allows every call of the tool with any arguments.
63
66
  - **Model and effort** (board 0.8.0, core 0.12.3): pickers in the New item form, in the drawer (**change** beside the model and effort, and **model / effort** under **More**) and in a thread's composer: **default** (the agent picks), the agent's presets, or an own word. An item's next run takes them; a thread's next session does (`chats/<t>/agent.json`), and its line in the chat says so.
64
- - **Project chat** (the **Chat** screen; core 0.12): threads of an agent in the project's folder, listed newest first and filtered by their item; a new thread is made when its first message is sent. Each thread is run by the bundled session engine (`gcf-session`) through the same detached relay as runs. It asks a card before each edit, git command and framework move (**allow once**, **always** — saved in `.claude/settings.local.json`; the card says saved only when it was — or **deny**); a new item it proposes through the board's MCP server `gcf` (tool `propose_item_new`, asked with no card: the proposal card is the question), the proposal card shows every field it proposed, and the operator's **Create** makes it with `POST /move` (`proposal: {talk, id}`), **Edit…** first in the new-item form. A thread's list entry names the card that waits in it and its limit wait (`card`, `limit_until`); a running item names the card of its run's chat (`chat_card`). A long talk hands over to a fresh agent from a summary; an idle agent closes after `chat.answer_timeout_min` (0 means 15) and the next message resumes it. Each item has at most one thread: a message to an item with no live run goes there. `GET /api/p/<project>/talks[?item=]` lists the threads with their proposals' states; `POST` there makes one (`{item?}`); `GET /api/p/<project>/talk/<t>` follows a thread's events; `POST` there sends `say`, `interrupt`, `answer`, `allow`, `deny` or `handoff`; `POST …/talk/<t>/stop` is the composer's **close agent** (board 0.8.1): the thread's agent ends with everything it started, or its limit wait does, and what it had not taken in is dropped with a "not sent" line; the next message resumes the talk; `GET …/talk/<t>/att/<file>` serves its pictures. The files live in `.gcf-session/chats/` (docs/Chat-Plan.md §3).
67
+ - **Project chat** (the **Chat** screen; core 0.12): threads of an agent in the project's folder, listed newest first and filtered by their item; a new thread is made when its first message is sent. Each thread is run by the bundled session engine (`gcf-session`) through the same detached relay as runs. It asks a card before each edit, git command and framework move (**allow once**, **always** — saved in `.claude/settings.local.json`; the card says saved only when it was — or **deny**); a new item it proposes through the board's MCP server `gcf` (tool `propose_item_new`, asked with no card: the proposal card is the question), the proposal card shows every field it proposed, and the operator's **Create** makes it with `POST /move` (`proposal: {talk, id}`), **Edit…** first in the new-item form. With core 0.16 (board 0.12.0, Board-PRD decision 27) it also proposes a move on an item or an inbox entry already there — `block`, `drop`, `depends`, and the inbox's `add`, `tag` and erase — naming it in `id`: the card shows the item's id, title and status now (or the entry's first line), warns when the item does not take the move now or is not on the board, its button is the move's name (a drop or an erase asks first), and **Edit…** opens that move's form. A thread's list entry names the card that waits in it and its limit wait (`card`, `limit_until`); a running item names the card of its run's chat (`chat_card`). A long talk hands over to a fresh agent from a summary; an idle agent closes after `chat.answer_timeout_min` (0 means 15) and the next message resumes it. Each item has at most one thread: a message to an item with no live run goes there. `GET /api/p/<project>/talks[?item=]` lists the threads with their proposals' states; `POST` there makes one (`{item?}`); `GET /api/p/<project>/talk/<t>` follows a thread's events; `POST` there sends `say`, `interrupt`, `answer`, `allow`, `deny` or `handoff`; `POST …/talk/<t>/stop` is the composer's **close agent** (board 0.8.1): the thread's agent ends with everything it started, or its limit wait does, and what it had not taken in is dropped with a "not sent" line; the next message resumes the talk; `GET …/talk/<t>/att/<file>` serves its pictures. The files live in `.gcf-session/chats/` (docs/Chat-Plan.md §3).
65
68
  - **Inbox**: add an entry (Enter adds, Shift+Enter breaks the line; its source and tags), tag it, erase it, or turn it into an item (its first line the title, the rest the note); search the entries, filter them by tag and by lesson kind. The D1 questions and the agent's D2 assumptions are listed there too. **Draft with agent** opens a project chat thread bound to the entry and sends "Draft an item from inbox entry <id>:" with its text; a second click opens the same thread. The first proposal's **Create** takes the entry (it is erased); a later one makes an item with no entry. Off while the usage limit holds.
66
69
  - **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, Esc closes a dialog, Help or the drawer; none while a field has the focus.
67
70
  - **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 with its kind (`tool`, `rules`, `framework`, `template`, `other`) and its item. The inbox filters them; a card shows `N lessons`, and the drawer lists the item's lessons 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.
@@ -90,7 +93,8 @@ Do not put the port on a network. Remote and phone access is planned for v2, beh
90
93
 
91
94
  - `~/.gcf/projects.json`: the projects on the board, `{projects: [{name, path}]}`.
92
95
  - `~/.gcf/board-token`: the token.
93
- - `~/.gcf/runs/`: the record of each run in flight, which a board started again finds.
96
+ - `~/.gcf/runs/`: the record of each run in flight, which a board started again finds; a board's start drops the ended runs of projects no longer on it.
97
+ - `~/.gcf/themes/`: the theme files.
94
98
  - `GCF_BOARD_HOME` moves them all; `GCF_BOARD_AIF` points at another `ai-factory` entry script; `GCF_SESSION_AGENT` puts another agent command in place of `claude` in project chats (tests).
95
99
 
96
100
  ## Roadmap (v2)
@@ -101,7 +105,8 @@ Do not put the port on a network. Remote and phone access is planned for v2, beh
101
105
 
102
106
  ```bash
103
107
  npm install
104
- npm test # server and web tests on Node's type stripping
108
+ npx playwright install chromium # once: the browser the browser scenarios use
109
+ npm test # server and web tests on Node's type stripping; the browser scenarios need npm run build first
105
110
  npm run typecheck
106
111
  npm run build # vite → dist/web, tsc → dist/server
107
112
  node dist/server/main.js --port 4318
@@ -11,16 +11,17 @@ import { lstat, mkdtemp, readFile, rm, stat } from 'node:fs/promises';
11
11
  import { pipeline } from 'node:stream/promises';
12
12
  import os from 'node:os';
13
13
  import path from 'node:path';
14
- import { BOARD_SCHEMA, } from '../shared/board.js';
14
+ import { BOARD_SCHEMA, runModeOf, } from '../shared/board.js';
15
15
  import { admit, cookieName, hostAllowed, tokenInUrl } from './auth.js';
16
16
  import { briefError, runCli } from './cli.js';
17
- import { broadcast, planRev, subscribe, watchProject } from './events.js';
17
+ import { broadcast, planRev, SESSION_TTL_MIN, subscribe, watchProject } from './events.js';
18
18
  import { attachesUnit, CHAT_BODY_MAX, chatInput, IMAGE_EXT, talkInput, } from './chat.js';
19
19
  import { attachmentOf, follow, followLog, logPart, readShown, shownShape } from './files.js';
20
20
  import { HttpError } from './http-error.js';
21
21
  import { isCenterMove, moveArgs, moveInput, runIds } from './moves.js';
22
22
  import { addProject, listProjects, projectOf, removeProject } from './registry.js';
23
- import { adoptRuns, keepProjects, closeReport, forgetProject, resumeQueue, runsOf, startRun, unqueue, } from './runs.js';
23
+ import { readThemes } from './themes.js';
24
+ import { adoptRuns, busyCheck, keepProjects, sweepRuns, closeReport, forgetProject, resumeQueue, runsOf, startRun, unqueue, } from './runs.js';
24
25
  import { acceptProposal, agentPresets, chatCard, chatOf, entryTalk, listTalks, openTalk, pickTalk, prepareTalk, startTalk, stopTalk, talkEntry, talkId, talkLive, talkSaid, talkWaits, watchTalks, writeTalk, } from './talks.js';
25
26
  import { threadDir, threadOfEntry } from 'gcf-session';
26
27
  const send = (res, status, body) => {
@@ -162,13 +163,14 @@ export function createApp(o) {
162
163
  const projects = await listProjects();
163
164
  // The kept queues of projects no longer on the board go: one added back starts empty.
164
165
  keepProjects(projects.map((p) => p.name));
166
+ sweepRuns(projects);
165
167
  // A watcher set up after the server closed would keep the process alive.
166
168
  if (closed)
167
169
  return;
168
170
  for (const p of projects)
169
171
  if (!watchers.has(p.name)) {
170
172
  const stops = [
171
- watchProject(p),
173
+ watchProject(p, undefined, () => domains.get(p.name)?.session_ttl_min ?? SESSION_TTL_MIN),
172
174
  watchTalks(p, () => broadcast({ type: 'talks', project: p.name }), async (t) => prepareTalk(p, await boardOf(p), t)),
173
175
  ];
174
176
  watchers.set(p.name, () => stops.forEach((stop) => stop()));
@@ -260,6 +262,7 @@ export function createApp(o) {
260
262
  const routes = [
261
263
  ['GET', /^\/api\/events$/, async (_req, res) => subscribe(res)],
262
264
  ['GET', /^\/api\/projects$/, async (_req, res) => send(res, 200, await listProjects())],
265
+ ['GET', /^\/api\/themes$/, async (_req, res) => send(res, 200, await readThemes())],
263
266
  [
264
267
  'POST',
265
268
  /^\/api\/projects$/,
@@ -713,13 +716,25 @@ export function createApp(o) {
713
716
  async (req, res, m) => {
714
717
  const p = await projectOf(m[1]);
715
718
  const body = await bodyOf(req);
716
- const { run_mode: mode, domain } = await boardOf(p);
717
- if (!domain.harness)
719
+ const board = await boardOf(p);
720
+ const { harness } = board.domain;
721
+ if (!harness)
718
722
  throw new HttpError(400, 'this project has no harness: its items run from a console');
723
+ if (body.mode !== undefined && body.mode !== 'main' && body.mode !== 'worktree')
724
+ throw new HttpError(400, `mode is main or worktree: ${String(body.mode)}`);
719
725
  const ids = runIds(body);
720
726
  const fresh = body.fresh === true;
721
727
  const agent = runAgent(body);
722
- send(res, 202, startRun(o.entry, p, ids, mode, fresh, domain.harness, agent));
728
+ // One run per mode: a main one queues behind the main run going, a worktree one starts.
729
+ const parts = Map.groupBy(ids, (id) => runModeOf(board, id, body.mode));
730
+ // Each part checks first: a refused one starts no other.
731
+ for (const part of parts.values())
732
+ busyCheck(p, part);
733
+ const started = [...parts].map(([mode, part]) => startRun(o.entry, p, part, mode, fresh, harness, agent));
734
+ send(res, 202, {
735
+ started: started.flatMap((s) => s.started ?? []),
736
+ queued: started.flatMap((s) => s.queued ?? []),
737
+ });
723
738
  },
724
739
  ],
725
740
  [
@@ -25,10 +25,9 @@ export function broadcast(event) {
25
25
  for (const c of clients)
26
26
  c.write(line);
27
27
  }
28
- // The core's SESSION_TTL_MS (session-mark.js): a mark nobody refreshed for this long is a session
29
- // that stopped. shortcut: a copy of the core's constant, read it from the board JSON once the core
30
- // reports a mark's expiry.
31
- const SESSION_TTL_MS = 120 * 60_000;
28
+ // Minutes a session mark stays fresh before the project's board read names its own
29
+ // (`domain.session_ttl_min`, core 0.15), and with a core older than that.
30
+ export const SESSION_TTL_MIN = 120;
32
31
  const LOG_STEP_MS = 10_000;
33
32
  export const alive = (pid) => {
34
33
  if (!Number.isInteger(pid) || pid <= 0)
@@ -46,7 +45,7 @@ export const alive = (pid) => {
46
45
  * lives, whether each session mark is fresh; and how recently each run log was written. A run
47
46
  * that died or a session that expired changes it with no file written.
48
47
  */
49
- export function runsState(dir, now = Date.now()) {
48
+ export function runsState(dir, ttlMin = SESSION_TTL_MIN, now = Date.now()) {
50
49
  let names;
51
50
  try {
52
51
  names = readdirSync(dir).sort();
@@ -61,7 +60,7 @@ export function runsState(dir, now = Date.now()) {
61
60
  if (n.endsWith('.lock'))
62
61
  return `${n} ${alive(Number(readFileSync(file, 'utf8').split('\n')[0]))}`;
63
62
  if (n.endsWith('.session'))
64
- return `${n} ${now - statSync(file).mtimeMs < SESSION_TTL_MS}`;
63
+ return `${n} ${now - statSync(file).mtimeMs < ttlMin * 60_000}`;
65
64
  // A session writes its log many times a second: its card's activity time moves by steps
66
65
  // of LOG_STEP_MS, each one a board read, not one per line.
67
66
  if (n.endsWith('.log'))
@@ -84,7 +83,7 @@ export const planRev = (project) => planRevs.get(project) ?? 0;
84
83
  * runs directory may not exist yet, so it is polled, not watched. Bursts of writes make one
85
84
  * event. Returns the stop.
86
85
  */
87
- export function watchProject(p, debounceMs = 300) {
86
+ export function watchProject(p, debounceMs = 300, ttlMin = () => SESSION_TTL_MIN) {
88
87
  let timer = null;
89
88
  const fire = () => {
90
89
  if (timer)
@@ -112,7 +111,7 @@ export function watchProject(p, debounceMs = 300) {
112
111
  fire();
113
112
  });
114
113
  const runs = path.join(p.path, '.gcf-session', 'runs');
115
- let last = runsState(runs);
114
+ let last = runsState(runs, ttlMin());
116
115
  const quotaAt = () => {
117
116
  try {
118
117
  return statSync(path.join(runs, 'quota.json')).mtimeMs;
@@ -123,7 +122,7 @@ export function watchProject(p, debounceMs = 300) {
123
122
  };
124
123
  let read = quotaAt();
125
124
  const poll = setInterval(() => {
126
- const now = runsState(runs);
125
+ const now = runsState(runs, ttlMin());
127
126
  if (now !== last)
128
127
  fire();
129
128
  last = now;
@@ -6,6 +6,16 @@ const TAG = '^[a-z0-9][a-z0-9:-]{0,39}$';
6
6
  export const toolOf = (key) => `propose_${key.replaceAll('-', '_')}`;
7
7
  /** The fields an agent may propose: the form's, without the hidden ones and the run's. */
8
8
  export const proposed = (spec) => spec.fields.filter((f) => !f.hidden && !NOT_PROPOSED.has(f.key));
9
+ /**
10
+ * Whether a move acts on an item or an inbox entry already there (`{id}` in its words, no field
11
+ * of its own names it): the agent names it in `id`.
12
+ */
13
+ export const targeted = (spec) => spec.args.includes('{id}') && !spec.fields.some((f) => f.key === 'id');
14
+ const TARGET = {
15
+ type: 'string',
16
+ pattern: SLUG,
17
+ description: 'The id of the item it acts on (of the inbox entry, for an inbox move).',
18
+ };
9
19
  /** The schema of one field by its kind; every kind has one (`never` holds the switch whole). */
10
20
  export function fieldSchema(f) {
11
21
  const about = [f.label, f.help].filter(Boolean).join(': ');
@@ -53,10 +63,17 @@ export function fieldSchema(f) {
53
63
  /** A move's tool input schema: an object of its proposed fields, nothing else. */
54
64
  export function toolSchema(spec) {
55
65
  const fields = proposed(spec);
66
+ const target = targeted(spec);
56
67
  return {
57
68
  type: 'object',
58
- properties: Object.fromEntries(fields.map((f) => [f.key, fieldSchema(f)])),
59
- required: fields.filter((f) => f.required && !f.when).map((f) => f.key),
69
+ properties: {
70
+ ...(target && { id: TARGET }),
71
+ ...Object.fromEntries(fields.map((f) => [f.key, fieldSchema(f)])),
72
+ },
73
+ required: [
74
+ ...(target ? ['id'] : []),
75
+ ...fields.filter((f) => f.required && !f.when).map((f) => f.key),
76
+ ],
60
77
  additionalProperties: false,
61
78
  };
62
79
  }
@@ -70,8 +87,13 @@ export function checkProposal(spec, args) {
70
87
  const fields = new Map(spec.fields.map((f) => [f.key, f]));
71
88
  const values = Object.fromEntries(spec.fields.filter((f) => f.default !== undefined).map((f) => [f.key, f.default]));
72
89
  const problems = [];
90
+ const target = targeted(spec);
91
+ if (target && (typeof args.id !== 'string' || !new RegExp(SLUG).test(args.id)))
92
+ problems.push('id is required: the item (or inbox entry) it acts on');
73
93
  for (const [key, v] of Object.entries(args)) {
74
94
  const f = fields.get(key);
95
+ if (target && key === 'id')
96
+ continue;
75
97
  if (!f)
76
98
  problems.push(`${key} is not a field of this move`);
77
99
  else if (f.hidden || NOT_PROPOSED.has(key))
@@ -358,7 +358,8 @@ function spawnRun(q, mode) {
358
358
  const effort = q.agent?.effort ?? null;
359
359
  const run = { project: p.name, ids, started: new Date().toISOString(), mode, model, effort };
360
360
  active.add(run);
361
- const args = [entry, harness, 'run', ...ids, '--json'];
361
+ // The board says where it goes: it queued it by that mode (an item's own, the run's pick).
362
+ const args = [entry, harness, 'run', ...ids, '--json', '--mode', mode];
362
363
  if (q.fresh)
363
364
  args.push('--fresh');
364
365
  // This run's pick: the items keep their own (Board-V2-Data-Plan §2.5).
@@ -520,13 +521,41 @@ function going(rid, pid) {
520
521
  return false;
521
522
  }
522
523
  }
524
+ /**
525
+ * Drop the run records of projects no longer on the board (removed while no board was up, so none
526
+ * took their ends), once their runs are over: nothing would ever read them.
527
+ */
528
+ export function sweepRuns(projects) {
529
+ let names;
530
+ try {
531
+ names = readdirSync(flightsDir());
532
+ }
533
+ catch {
534
+ return;
535
+ }
536
+ for (const name of names) {
537
+ if (!name.endsWith('.json') || name.endsWith('.end.json'))
538
+ continue;
539
+ const rid = name.slice(0, -'.json'.length);
540
+ if (flights.has(rid))
541
+ continue;
542
+ try {
543
+ const f = JSON.parse(readFileSync(recordOf(rid), 'utf8'));
544
+ if (projects.some((p) => p.name === f.project && p.path === f.path) || going(rid, f.pid))
545
+ continue;
546
+ rmSync(endOf(rid), { force: true });
547
+ rmSync(recordOf(rid), { force: true });
548
+ }
549
+ catch {
550
+ // Unreadable or gone meanwhile: the next start looks again.
551
+ }
552
+ }
553
+ }
523
554
  /**
524
555
  * What a board before this one left for the project: first its queue, pause, reports and trace
525
556
  * (`queue.json`), then its runs: one going shows as active until it ends, one that ended
526
557
  * meanwhile as its report, one whose relay died with no end as a failure, which pauses the
527
558
  * queue. Only then a queue not paused and with no main run going goes on.
528
- * shortcut: the records of a project removed while no board was up stay in the board home until
529
- * it is added back; sweep the ones of unregistered projects at the start if they pile up.
530
559
  */
531
560
  export function adoptRuns(entry, p) {
532
561
  try {
@@ -594,20 +623,25 @@ export function adoptRuns(entry, p) {
594
623
  }
595
624
  changed(p.name);
596
625
  }
626
+ /** A 409 for the ids a run of this board drives or queues: a second click on the same card. */
627
+ export function busyCheck(p, ids) {
628
+ const { active: going, queued } = runsOf(p.name);
629
+ const busy = ids.filter((id) => queued.includes(id) || going.some((r) => r.ids.includes(id)));
630
+ if (busy.length)
631
+ throw new HttpError(409, `already running from this board: ${busy.join(', ')}`);
632
+ }
597
633
  /**
598
- * Start a batch in the project's run mode, or queue it behind the main run going on. Its end
599
- * is a run report with the harness report, or what went wrong. `fresh` starts new agent
600
- * sessions where the harness would resume the interrupted ones. `harness` is the domain's
601
- * (`domain.harness`); the tests take GCF's. Its sessions are open to the operator's chat.
602
- * `agent`: a model and effort for this run only, over each item's own.
634
+ * Start a batch in run mode `mode` (the harness's `--mode`), or queue a main one behind the
635
+ * main run going on. Its end is a run report with the harness report, or what went wrong.
636
+ * `fresh` starts new agent sessions where the harness would resume the interrupted ones.
637
+ * `harness` is the domain's (`domain.harness`); the tests take GCF's. Its sessions are open to
638
+ * the operator's chat. `agent`: a model and effort for this run only, over each item's own.
603
639
  */
604
640
  export function startRun(entry, p, ids, mode = 'worktree', fresh = false, harness = 'gcf-harness', agent) {
605
641
  // A second click on the same card: the harness would refuse it on its lock, noisily.
606
642
  paths.set(p.name, p.path);
607
- const { active: going, queued } = runsOf(p.name);
608
- const busy = ids.filter((id) => queued.includes(id) || going.some((r) => r.ids.includes(id)));
609
- if (busy.length)
610
- throw new HttpError(409, `already running from this board: ${busy.join(', ')}`);
643
+ busyCheck(p, ids);
644
+ const { active: going } = runsOf(p.name);
611
645
  // A paused queue holds a new main run too: it would repeat the failure, and jump the queue.
612
646
  if (mode === 'main' && (paused.has(p.name) || going.some((r) => r.mode === 'main'))) {
613
647
  queues.set(p.name, [
@@ -12,6 +12,7 @@ import os from 'node:os';
12
12
  import path from 'node:path';
13
13
  import { fileURLToPath } from 'node:url';
14
14
  import { THREAD_ID, createThread, listThreads, presetsOf, readThread, setThreadAgent, threadAgent, threadDir, threadOf, threadOfEntry, } from 'gcf-session';
15
+ import { runModeOf } from '../shared/board.js';
15
16
  import { writeAtomic } from './atomic.js';
16
17
  import { alive } from './events.js';
17
18
  import { HttpError } from './http-error.js';
@@ -197,7 +198,7 @@ export function contextOf(p, board, item) {
197
198
  if (exists(rel))
198
199
  lines.push(`- ${what}: ${rel}`);
199
200
  const worktree = `.gcf-session/worktrees/${item}`;
200
- if (board.run_mode === 'worktree')
201
+ if (runModeOf(board, item) === 'worktree')
201
202
  lines.push(`- its branch: work/${item}${exists(worktree) ? `, its worktree: ${worktree}` : ''}`);
202
203
  const rows = rowsOf(path.join(p.path, 'gcf', '.metrics', 'run-log.csv'), item);
203
204
  if (rows.length)
@@ -0,0 +1,75 @@
1
+ // The operator's themes: one JSON file each in `<board home>/themes/<id>.json`, made by the
2
+ // designer or by hand. A theme sets design tokens (`--gcf-<name>` of web/tokens.css) over the
3
+ // built-in dark; the page checks the names, it owns the tokens. Read anew on each request.
4
+ import { readdir, readFile, stat } from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { homeDir } from './registry.js';
7
+ export const themesDir = () => path.join(homeDir(), 'themes');
8
+ const ID_RE = /^[a-z0-9-]{1,40}$/;
9
+ const FILE_MAX = 64 * 1024;
10
+ const VALUE_MAX = 200;
11
+ // The page sets each value through the CSSOM, which cannot be broken out of; a function outside
12
+ // the colour and arithmetic ones (`url(`, `image-set(`, `src(`) could fetch from the network.
13
+ const BAD_VALUE = /[;{}<>\\]/;
14
+ const FUNCTIONS = new Set('rgb rgba hsl hsla hwb lab lch oklab oklch color color-mix light-dark var calc min max clamp'.split(' '));
15
+ const badFunction = (v) => [...v.matchAll(/([a-z-]*)\(/gi)].find((m) => m[1] && !FUNCTIONS.has(m[1].toLowerCase()))?.[1];
16
+ const BOM = new RegExp(`^${String.fromCharCode(0xfeff)}`);
17
+ /** A theme file's problem, or null when it is good. */
18
+ export function themeProblem(id, data) {
19
+ if (id === 'dark')
20
+ return 'the name dark is the built-in theme: rename the file';
21
+ if (!ID_RE.test(id))
22
+ return 'a file name takes a-z, 0-9 and -, up to 40';
23
+ if (typeof data !== 'object' || data === null)
24
+ return 'not a JSON object';
25
+ const t = data;
26
+ if (t.gcf_theme !== 1)
27
+ return 'gcf_theme must be 1';
28
+ if (typeof t.name !== 'string' || !t.name.trim())
29
+ return 'name is required';
30
+ if (t.scheme !== 'light' && t.scheme !== 'dark')
31
+ return 'scheme must be light or dark';
32
+ if (typeof t.tokens !== 'object' || t.tokens === null || Array.isArray(t.tokens))
33
+ return 'tokens must be an object';
34
+ for (const [k, v] of Object.entries(t.tokens)) {
35
+ if (!/^[a-z0-9-]+$/.test(k))
36
+ return `token ${k}: a name without --gcf-, a-z, 0-9 and -`;
37
+ if (typeof v !== 'string' || !v.trim() || v.length > VALUE_MAX || BAD_VALUE.test(v))
38
+ return `token ${k}: a CSS value up to ${VALUE_MAX} characters, no ; { } < > \\`;
39
+ const fn = badFunction(v);
40
+ if (fn)
41
+ return `token ${k}: ${fn}( is not a colour function (oklch, rgb, color-mix, var…)`;
42
+ }
43
+ return null;
44
+ }
45
+ /** Every `*.json` of the themes folder: a good theme, or its id and what is wrong with it. */
46
+ export async function readThemes(dir = themesDir()) {
47
+ let names;
48
+ try {
49
+ names = (await readdir(dir)).filter((n) => n.endsWith('.json')).sort();
50
+ }
51
+ catch {
52
+ return [];
53
+ }
54
+ const themes = [];
55
+ for (const n of names) {
56
+ const id = n.slice(0, -'.json'.length);
57
+ const file = path.join(dir, n);
58
+ try {
59
+ if ((await stat(file)).size > FILE_MAX)
60
+ throw new Error(`larger than ${FILE_MAX / 1024} KB`);
61
+ // A file saved by a Windows editor may start with a byte order mark.
62
+ const text = (await readFile(file, 'utf8')).replace(BOM, '');
63
+ const data = JSON.parse(text);
64
+ const problem = themeProblem(id, data);
65
+ if (problem)
66
+ themes.push({ id, error: problem });
67
+ else
68
+ themes.push({ id, name: data.name, scheme: data.scheme, tokens: data.tokens });
69
+ }
70
+ catch (e) {
71
+ themes.push({ id, error: e.message });
72
+ }
73
+ }
74
+ return themes;
75
+ }
@@ -9,3 +9,13 @@ const ATTACHED = [
9
9
  ];
10
10
  /** Whether project path `rel` lies where attachments are: the board serves it as one. */
11
11
  export const attachedShape = (rel) => ATTACHED.some((r) => r.test(rel));
12
+ /**
13
+ * Where item `id`'s run goes (Methodology §7): the run's pick, else the item's own `run_mode`
14
+ * (core 0.16, Board-PRD decision 28), else the project's.
15
+ */
16
+ export function runModeOf(board, id, asked) {
17
+ if (asked === 'main' || asked === 'worktree')
18
+ return asked;
19
+ const own = board.items.find((i) => i.id === id)?.run_mode;
20
+ return own === 'main' || own === 'worktree' ? own : board.run_mode;
21
+ }