gcf-board 0.8.2 → 0.10.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
@@ -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.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
+ - 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
11
13
  - gcf-board 0.2 needs `gcf-aif-ext` ≥ 0.7 (priority, questions, session marks, `run_mode`)
12
14
 
13
15
  ## Run
@@ -31,11 +33,12 @@ It puts **GCF Board** on the desktop (Windows: a shortcut whose server console s
31
33
 
32
34
  ## What it does
33
35
 
34
- The board knows no domain by name: the project's board read gives its columns, moves with their forms, item fields, blocks and Help terms (`domain`, Board-PRD decision 16). The page follows design B (`docs/design/mockup`): a left nav with the project switcher (add a project, take one off the board), the screens **Command**, **Board**, **Chat**, **Inbox**, **Playtest**, **Ended**, **Agent**, **Settings** and **Metrics** (a domain without a block has no screen for it, a project without a harness no Metrics), and a header with the phase, the runs, the limit wait, the quota, WIP, the release, **waiting for me**, **+ item** and **?**. The project and the screen are in the URL hash. On a phone a bottom bar holds Command, Board, Chat, Inbox and More. When the server is gone, the page says so and reconnects by itself. For a GCF project:
36
+ The board knows no domain by name: the project's board read gives its columns, moves with their forms, item fields, blocks and Help terms (`domain`, Board-PRD decision 16). The page follows design B (`docs/design/mockup`): a left nav with the project switcher (add a project, take one off the board), the screens **Command**, **Board**, **Chat**, **Inbox**, **Runs**, **Playtest**, **Ended**, **Agent**, **Settings** and **Metrics** (a domain without a block has no screen for it, a project without a harness no Runs and no Metrics), and a header with the phase, the runs, the limit wait, the quota, WIP, the release, **waiting for me**, **+ item** and **?**. The project and the screen are in the URL hash. On a phone a bottom bar holds Command, Board, Chat, Inbox and More. When the server is gone, the page says so and reconnects by itself. For a GCF project:
35
37
 
36
38
  - **Command**: **waiting for me**, what only the operator moves on (Board-PRD §1.3), by group: failed run reports and a paused queue, a card waiting in a chat (a permission is answered right there, **Always** naming the rule it saves), D1 questions, the items to play and judge, to decide, to unblock (the columns the domain marks `human`), and a `paused: limit` item to resume. Beside it **Live**: the runs going on with their plan progress, **Follow** and **Stop**, the console runs and sessions, **Run next**, the queue, the run reports, and what the board did by itself.
37
- - **Board**: columns ready, running, blocked, awaiting-verdict, awaiting-decision, unplayed, parked. A card shows the type, the gate, the plan progress (`2/5`), the severity, `verified`, the model. A running card shows when its run log was last written (`active 12 s ago`), and `quiet 6 min` when the log has been silent for 5 minutes or more. A run's end report gives each item's cost when the agent reported it.
38
- - **An item**: its file, its plan and its run log as it grows, its fields, 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.
39
+ - **Board**: columns ready, running, blocked, awaiting-verdict, awaiting-decision, unplayed, parked. A card shows the type, the gate, the plan progress (`2/5`), the severity, `verified`, the model, **needs N** and **needed by N**. A running card shows when its run log was last written (`active 12 s ago`), and `quiet 6 min` when the log has been silent for 5 minutes or more. A run's end report gives each item's cost when the agent reported it. Pointing at a card (or focusing it from the keyboard) lights up the cards it needs and the cards that need it, each saying how, and dims the rest. The toolbar (board 0.9.0, core 0.13.0) searches ids and titles, keeps **waiting for me**, filters by the fields the domain marks `filter` (GCF: type, gate, severity, system, milestone; several values at once, each a chip to take off) and lays the board out in lanes by a field it marks `group` (system, parent, milestone): an item with two systems stands in both lanes, one with none in **none**, a parent lane is named by the feature's title. The mouse drags the board sideways from its empty space; the wheel over a column with no scroll of its own pans it.
40
+ - **An item**: its file, its plan and its run log as it grows, its fields, 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.
41
+ - **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}`).
39
42
  - **Drag**:
40
43
  - a ready card into **running** starts its run;
41
44
  - a blocked or parked card into **ready** unblocks it;
@@ -46,7 +49,7 @@ The board knows no domain by name: the project's board read gives its columns, m
46
49
  - `run_mode: worktree`: one worktree and one agent session per item, all at once, then the integrator;
47
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.
48
51
 
49
- 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, the reports and that list live in the board's memory: a board restart forgets them. 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/`).
52
+ 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/`).
50
53
  - **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`).
51
54
  - **Run next N independent**: the framework's gate picks the ready items that can run together now, by priority, and the board runs them after asking.
52
55
  - **Priority**: drop a ready card on another to put it before; the column's ranks are committed (`gcf prioritize`).
@@ -55,13 +58,15 @@ The board knows no domain by name: the project's board read gives its columns, m
55
58
  - **Help** (**?**): the domain's terms, columns, moves and field values with what each means, and the words of runs, under one filter.
56
59
  - **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.
57
60
  - **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.
58
- - **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 | file, ref}]`) goes into the message's text as a line the agent reads. `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`).
61
+ - **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
+ - **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.
59
63
  - **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.
60
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).
61
- - **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.
65
+ - **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
+ - **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.
62
67
  - **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.
63
68
  - **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 `--source playtest`.
64
- - **Ended**: history (accepted) and graveyard (killed, dropped, won't-fix).
69
+ - **Ended**: history (accepted) and graveyard (killed, dropped, won't-fix); a line opens the item's History.
65
70
  - **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.
66
71
 
67
72
  The page updates by itself: the server watches each project's `gcf/` and `.gcf-session/runs/`.
@@ -90,7 +95,6 @@ Do not put the port on a network. Remote and phone access is planned for v2, beh
90
95
 
91
96
  ## Roadmap (v2)
92
97
 
93
- - **The chat**: a design unit picked by name as a message's attachment (today a project path).
94
98
  - **Phone and remote access**: Tailscale or Claude Remote Control, with their own authentication; push notifications when an item blocks or waits for a verdict.
95
99
 
96
100
  ## Develop
@@ -3,24 +3,26 @@
3
3
  // (`ai-factory <harness> metrics`, the domain's harness), the project chat's threads. Writes: a
4
4
  // project on the board, a move, a run, a project chat message. Every write of the project is a
5
5
  // command of the framework; a project chat's agent asks the operator for each one (talks.ts).
6
+ import { execFile } from 'node:child_process';
6
7
  import { randomBytes } from 'node:crypto';
7
8
  import { createServer } from 'node:http';
8
- import { existsSync, statSync, writeFileSync } from 'node:fs';
9
- import { lstat, mkdtemp, readFile, rm } from 'node:fs/promises';
9
+ import { createReadStream, existsSync, statSync, writeFileSync } from 'node:fs';
10
+ import { lstat, mkdtemp, readFile, rm, stat } from 'node:fs/promises';
11
+ import { pipeline } from 'node:stream/promises';
10
12
  import os from 'node:os';
11
13
  import path from 'node:path';
12
14
  import { BOARD_SCHEMA, } from '../shared/board.js';
13
15
  import { admit, cookieName, hostAllowed, tokenInUrl } from './auth.js';
14
16
  import { briefError, runCli } from './cli.js';
15
17
  import { broadcast, planRev, subscribe, watchProject } from './events.js';
16
- import { CHAT_BODY_MAX, chatInput, IMAGE_EXT, talkInput } from './chat.js';
17
- import { follow, followLog, readShown, shownShape } from './files.js';
18
+ import { attachesUnit, CHAT_BODY_MAX, chatInput, IMAGE_EXT, talkInput, } from './chat.js';
19
+ import { attachmentOf, follow, followLog, logPart, readShown, shownShape } from './files.js';
18
20
  import { HttpError } from './http-error.js';
19
21
  import { isCenterMove, moveArgs, moveInput, runIds } from './moves.js';
20
22
  import { addProject, listProjects, projectOf, removeProject } from './registry.js';
21
- import { adoptRuns, closeReport, forgetProject, resumeQueue, runsOf, startRun, unqueue, } from './runs.js';
22
- import { acceptProposal, agentPresets, chatCard, chatOf, listTalks, openTalk, pickTalk, prepareTalk, startTalk, stopTalk, talkId, talkLive, talkWaits, watchTalks, writeTalk, } from './talks.js';
23
- import { threadDir } from 'gcf-session';
23
+ import { adoptRuns, keepProjects, closeReport, forgetProject, resumeQueue, runsOf, startRun, unqueue, } from './runs.js';
24
+ import { acceptProposal, agentPresets, chatCard, chatOf, entryTalk, listTalks, openTalk, pickTalk, prepareTalk, startTalk, stopTalk, talkEntry, talkId, talkLive, talkSaid, talkWaits, watchTalks, writeTalk, } from './talks.js';
25
+ import { threadDir, threadOfEntry } from 'gcf-session';
24
26
  const send = (res, status, body) => {
25
27
  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
26
28
  res.end(JSON.stringify(body));
@@ -46,6 +48,23 @@ async function bodyOf(req, limit = 1_000_000) {
46
48
  throw new HttpError(400, 'the body must be a JSON object');
47
49
  }
48
50
  }
51
+ /**
52
+ * A file of the project, never read as a page: no type sniffing, no script, no fetch from it;
53
+ * streamed, as an attachment may be large. `disposition`: a download's, for one not a picture.
54
+ */
55
+ async function sendFile(res, type, file, disposition = null) {
56
+ const { size } = await stat(file);
57
+ res.writeHead(200, {
58
+ 'content-type': type,
59
+ 'content-length': size,
60
+ 'cache-control': 'private',
61
+ 'x-content-type-options': 'nosniff',
62
+ 'content-security-policy': "default-src 'none'",
63
+ ...(disposition ? { 'content-disposition': disposition } : {}),
64
+ });
65
+ // A read that breaks after the head is sent can only cut the answer short.
66
+ await pipeline(createReadStream(file), res).catch(() => res.destroy());
67
+ }
49
68
  /** Parse the JSON a command printed, or say what it printed instead. */
50
69
  function jsonOf(r, what) {
51
70
  try {
@@ -62,6 +81,27 @@ const idsOf = (b) => new Set([
62
81
  ...(b.graveyard ?? []).map((g) => g.id),
63
82
  ]);
64
83
  const SLUG = /^[a-z0-9][a-z0-9-]*$/;
84
+ // A model or effort word for one run: plain, as the harness takes it.
85
+ const WORD = /^[A-Za-z0-9][\w.-]{0,63}$/;
86
+ /** A run's pick of model and effort from a request body (Board-PRD §5.9); none: each item's own. */
87
+ function runAgent(body) {
88
+ const pick = { model: null, effort: null };
89
+ for (const k of ['model', 'effort']) {
90
+ const v = body[k];
91
+ if (v === undefined || v === null || v === '' || v === 'default')
92
+ continue;
93
+ if (typeof v !== 'string' || !WORD.test(v))
94
+ throw new HttpError(400, `${k} is one plain word: ${String(v)}`);
95
+ pick[k] = v;
96
+ }
97
+ return pick.model || pick.effort ? pick : undefined;
98
+ }
99
+ // The Drafts whose first message goes now, `<project path> <entry>`: a second click sends none.
100
+ const drafting = new Set();
101
+ /** The project's HEAD commit, or null: a new commit (a move, a merge) tells an open History. */
102
+ const headOf = (dir) => new Promise((resolve) => execFile('git', ['rev-parse', 'HEAD'], { cwd: dir, windowsHide: true }, (e, out) => resolve(e ? null : out.trim())));
103
+ /** Whether the usage limit holds for the account now (decision 22): Draft waits for its reset. */
104
+ const limitHolds = (q) => q?.info.status === 'rejected' && (q.info.resetsAt ?? 0) * 1000 > Date.now();
65
105
  /** The ISO time a file was last written, or null when it is not there. */
66
106
  const activeAt = (file) => {
67
107
  try {
@@ -120,6 +160,8 @@ export function createApp(o) {
120
160
  let closed = false;
121
161
  const watchAll = async () => {
122
162
  const projects = await listProjects();
163
+ // The kept queues of projects no longer on the board go: one added back starts empty.
164
+ keepProjects(projects.map((p) => p.name));
123
165
  // A watcher set up after the server closed would keep the process alive.
124
166
  if (closed)
125
167
  return;
@@ -135,6 +177,8 @@ export function createApp(o) {
135
177
  }
136
178
  };
137
179
  const cli = (p, args, timeout, input) => runCli(o.entry, p.path, args, timeout, input);
180
+ // The run gate's answers being worked out, by project and ids (GET …/gate).
181
+ const gates = new Map();
138
182
  // The last domain each project's board read gave: an item move is built from its form.
139
183
  const domains = new Map();
140
184
  /**
@@ -188,6 +232,23 @@ export function createApp(o) {
188
232
  * the board read knows the item: the answer that says so (the thread, the input line's id),
189
233
  * else null.
190
234
  */
235
+ /** The design units of the board read, when a message attaches one; else none to read. */
236
+ const unitsFor = async (p, body) => attachesUnit(body)
237
+ ? new Map(((await boardOf(p)).units ?? []).map((u) => [u.id, u.file]))
238
+ : undefined;
239
+ /**
240
+ * A harness reading of past runs (`runs --json`, board v2): null when the project has no
241
+ * harness or its harness is older than the command.
242
+ */
243
+ const pastRuns = async (p, args) => {
244
+ const harness = await harnessOf(p).catch(() => null);
245
+ if (!harness)
246
+ return null;
247
+ const r = await cli(p, [harness, 'runs', '--json', ...args]);
248
+ if (!r.ok && /unknown command/.test(r.err))
249
+ return null;
250
+ return jsonOf(r, `${harness} runs`).runs;
251
+ };
191
252
  const toThread = async (p, item, line) => {
192
253
  const board = await boardOf(p).catch(() => null);
193
254
  if (!board?.domain.chat || !board.agent?.rules || !idsOf(board).has(item))
@@ -237,6 +298,7 @@ export function createApp(o) {
237
298
  board_version: o.version,
238
299
  quota: await lastQuota(),
239
300
  presets: agentPresets(),
301
+ head: await headOf(p.path),
240
302
  };
241
303
  const board = await boardOf(p);
242
304
  // A running item's last log write tells a working session from a stuck one; a run's
@@ -272,8 +334,16 @@ export function createApp(o) {
272
334
  [
273
335
  'GET',
274
336
  /^\/api\/p\/([^/]+)\/log\/([a-z0-9][a-z0-9-]*)$/,
275
- async (_req, res, m) => {
276
- followLog((await projectOf(m[1])).path, m[2], res);
337
+ async (_req, res, m, url) => {
338
+ const root = (await projectOf(m[1])).path;
339
+ const [from, to] = ['from', 'to'].map((k) => url.searchParams.get(k));
340
+ // Without a part: the log as it grows. With one: the bytes a past run wrote, once.
341
+ if (from === null && to === null)
342
+ return followLog(root, m[2], res);
343
+ const [a, b] = [from, to].map((v) => (/^\d{1,15}$/.test(v ?? '') ? Number(v) : NaN));
344
+ if (Number.isNaN(a) || Number.isNaN(b) || a > b)
345
+ throw new HttpError(400, 'a log part is from and to, whole numbers, 0 ≤ from ≤ to');
346
+ send(res, 200, await logPart(root, m[2], a, b));
277
347
  },
278
348
  ],
279
349
  [
@@ -296,12 +366,47 @@ export function createApp(o) {
296
366
  const file = path.join(att, m[3]);
297
367
  for (const f of [session, path.dirname(att), att, file]) {
298
368
  const st = await lstat(f).catch(() => null);
299
- if (!st || st.isSymbolicLink())
369
+ if (!st || st.isSymbolicLink() || (f === file && !st.isFile()))
300
370
  throw new HttpError(404, `no picture ${m[3]}`);
301
371
  }
302
372
  const type = m[4] === 'jpg' ? 'jpeg' : m[4];
303
- res.writeHead(200, { 'content-type': `image/${type}`, 'cache-control': 'private' });
304
- res.end(await readFile(file));
373
+ await sendFile(res, `image/${type}`, file);
374
+ },
375
+ ],
376
+ [
377
+ // A file given to an item or an inbox entry (`gcf item attach`, an entry's pictures).
378
+ 'GET',
379
+ /^\/api\/p\/([^/]+)\/attachment$/,
380
+ async (_req, res, m, url) => {
381
+ const p = await projectOf(m[1]);
382
+ const rel = url.searchParams.get('path') ?? '';
383
+ const { file, type, download } = await attachmentOf(p.path, rel);
384
+ // RFC 5987: encodeURIComponent leaves ' ( ) * and ! as they are.
385
+ const name = encodeURIComponent(path.basename(file)).replace(/['()*!]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
386
+ await sendFile(res, type, file, download ? `attachment; filename*=UTF-8''${name}` : null);
387
+ },
388
+ ],
389
+ [
390
+ // The run gate of each named item (none: every ready one) alone now (Board-PRD §5.3):
391
+ // what a Run would be refused for, before the click. An older harness: nothing known.
392
+ 'GET',
393
+ /^\/api\/p\/([^/]+)\/gate$/,
394
+ async (_req, res, m, url) => {
395
+ const p = await projectOf(m[1]);
396
+ const names = (url.searchParams.get('ids') ?? '').split(',').filter(Boolean);
397
+ const ids = names.length ? runIds({ ids: names }) : [];
398
+ const harness = await harnessOf(p);
399
+ // One audit for the same question at once: a drawer and a dialog may ask together.
400
+ const key = `${p.name}/${ids.join(',')}`;
401
+ let asked = gates.get(key);
402
+ if (!asked) {
403
+ asked = cli(p, [harness, 'gate', '--each', ...ids, '--json']).finally(() => gates.delete(key));
404
+ gates.set(key, asked);
405
+ }
406
+ const r = await asked;
407
+ if (!r.ok && /unknown option '--each'/.test(r.err))
408
+ return send(res, 200, { items: {} });
409
+ send(res, 200, jsonOf(r, `${harness} gate --each`));
305
410
  },
306
411
  ],
307
412
  [
@@ -312,7 +417,8 @@ export function createApp(o) {
312
417
  // and that a live session takes it, so a message nobody would read is refused (409).
313
418
  async (req, res, m) => {
314
419
  const p = await projectOf(m[1]);
315
- const line = chatInput(await bodyOf(req, CHAT_BODY_MAX));
420
+ const body = await bodyOf(req, CHAT_BODY_MAX);
421
+ const line = chatInput(body, await unitsFor(p, body));
316
422
  let harness;
317
423
  try {
318
424
  harness = await harnessOf(p);
@@ -408,7 +514,8 @@ export function createApp(o) {
408
514
  const t = talkId(m[2]);
409
515
  if (!existsSync(threadDir(p.path, t)))
410
516
  throw new HttpError(404, `no thread ${t}`);
411
- const line = await sendTalk(p, t, talkInput(await bodyOf(req, CHAT_BODY_MAX)));
517
+ const body = await bodyOf(req, CHAT_BODY_MAX);
518
+ const line = await sendTalk(p, t, talkInput(body, await unitsFor(p, body)));
412
519
  send(res, 202, { ok: true, ...(typeof line.id === 'string' ? { id: line.id } : {}) });
413
520
  },
414
521
  ],
@@ -452,12 +559,11 @@ export function createApp(o) {
452
559
  const chats = path.dirname(td);
453
560
  for (const f of [path.dirname(chats), chats, td, path.dirname(file), file]) {
454
561
  const st = await lstat(f).catch(() => null);
455
- if (!st || st.isSymbolicLink())
562
+ if (!st || st.isSymbolicLink() || (f === file && !st.isFile()))
456
563
  throw new HttpError(404, `no picture ${m[3]}`);
457
564
  }
458
565
  const type = m[4] === 'jpg' ? 'jpeg' : m[4];
459
- res.writeHead(200, { 'content-type': `image/${type}`, 'cache-control': 'private' });
460
- res.end(await readFile(file));
566
+ await sendFile(res, `image/${type}`, file);
461
567
  },
462
568
  ],
463
569
  [
@@ -497,6 +603,20 @@ export function createApp(o) {
497
603
  const domain = isCenterMove(body.cmd)
498
604
  ? undefined
499
605
  : (domains.get(p.name) ?? (await boardOf(p)).domain);
606
+ // A proposal of a Draft thread makes the entry's item (Board-V2-Data-Plan §2.7): the
607
+ // entry goes with it while it is there; a second proposal, or one after it went, has none.
608
+ const proposal = (body.proposal ?? {});
609
+ if (typeof proposal.talk === 'string' && body.from === undefined) {
610
+ // A thread that is not there has no entry: acceptProposal says it is not there.
611
+ const entry = existsSync(threadDir(p.path, talkId(proposal.talk)))
612
+ ? talkEntry(p, proposal.talk)
613
+ : null;
614
+ const board = entry ? await boardOf(p) : null;
615
+ if (board &&
616
+ board.domain.new_item === body.cmd &&
617
+ board.inbox?.some((e) => e.id === entry))
618
+ body.from = entry;
619
+ }
500
620
  const args = moveArgs(body, domain?.moves);
501
621
  const run = () => cli(p, args, undefined, moveInput(body, domain?.moves));
502
622
  // An agent's proposal made (AD-16, AD-33): its record goes with the move.
@@ -524,6 +644,69 @@ export function createApp(o) {
524
644
  /^\/api\/p\/([^/]+)\/runs$/,
525
645
  async (_req, res, m) => send(res, 200, runsOf((await projectOf(m[1])).name)),
526
646
  ],
647
+ [
648
+ // The past runs, newest first (Board-PRD §5.9): the harness's run log; none without one.
649
+ 'GET',
650
+ /^\/api\/p\/([^/]+)\/runs\/past$/,
651
+ async (_req, res, m, url) => {
652
+ const p = await projectOf(m[1]);
653
+ const limit = String(Math.max(1, Math.min(1000, Number(url.searchParams.get('limit')) || 50)));
654
+ const runs = await pastRuns(p, ['--limit', limit]);
655
+ if (!runs)
656
+ throw new HttpError(404, 'no past runs: the project has no harness that keeps them');
657
+ send(res, 200, { runs });
658
+ },
659
+ ],
660
+ [
661
+ // An item's moves and runs (Board-PRD §5.3 History): an ended item keeps them too.
662
+ 'GET',
663
+ /^\/api\/p\/([^/]+)\/item\/([a-z0-9][a-z0-9-]*)\/history$/,
664
+ async (_req, res, m) => {
665
+ const p = await projectOf(m[1]);
666
+ const read = await cli(p, ['gcf', 'item', 'history', m[2], '--json']);
667
+ if (!read.ok)
668
+ throw new HttpError(read.code === 1 ? 400 : 500, briefError(read.err || read.out));
669
+ const { moves } = jsonOf(read, 'gcf item history');
670
+ // A run log the harness cannot read leaves the moves shown: no runs then.
671
+ const runs = (await pastRuns(p, ['--item', m[2], '--limit', '1000']).catch(() => null)) ?? [];
672
+ send(res, 200, { id: m[2], moves, runs });
673
+ },
674
+ ],
675
+ [
676
+ // Draft with agent (decision 22): the entry's own thread asks an agent for an item. A
677
+ // second click opens the same thread and sends nothing.
678
+ 'POST',
679
+ /^\/api\/p\/([^/]+)\/inbox\/([a-z0-9][a-z0-9-]*)\/draft$/,
680
+ async (_req, res, m) => {
681
+ const p = await projectOf(m[1]);
682
+ const board = await boardOf(p);
683
+ chatOf(board);
684
+ const e = board.inbox?.find((x) => x.id === m[2]);
685
+ if (!e)
686
+ throw new HttpError(404, `no inbox entry ${m[2]}`);
687
+ const key = `${p.path} ${e.id}`;
688
+ const had = threadOfEntry(p.path, e.id);
689
+ // A thread whose first message never went (a failed send) takes it now; a second
690
+ // click while the first one sends takes the same thread and sends nothing.
691
+ const fresh = (!had || !talkSaid(p, had)) && !drafting.has(key);
692
+ if (fresh && limitHolds(await lastQuota()))
693
+ throw new HttpError(409, 'the usage limit holds for the account: draft after its reset');
694
+ const { id, created } = entryTalk(p, e.id);
695
+ // Asked again after the quota's read: a click that sent meanwhile said it already.
696
+ if (fresh && !drafting.has(key) && !talkSaid(p, id)) {
697
+ drafting.add(key);
698
+ try {
699
+ await prepareTalk(p, board, id);
700
+ await sendTalk(p, id, { type: 'say', text: `Draft an item from inbox entry ${e.id}:\n${e.text}` }, board);
701
+ }
702
+ finally {
703
+ drafting.delete(key);
704
+ }
705
+ }
706
+ broadcast({ type: 'talks', project: p.name });
707
+ send(res, created ? 201 : 200, { thread: id, created });
708
+ },
709
+ ],
527
710
  [
528
711
  'POST',
529
712
  /^\/api\/p\/([^/]+)\/run$/,
@@ -535,7 +718,8 @@ export function createApp(o) {
535
718
  throw new HttpError(400, 'this project has no harness: its items run from a console');
536
719
  const ids = runIds(body);
537
720
  const fresh = body.fresh === true;
538
- send(res, 202, startRun(o.entry, p, ids, mode, fresh, domain.harness));
721
+ const agent = runAgent(body);
722
+ send(res, 202, startRun(o.entry, p, ids, mode, fresh, domain.harness, agent));
539
723
  },
540
724
  ],
541
725
  [
@@ -1,3 +1,4 @@
1
+ import { renameSync, rmSync, writeFileSync } from 'node:fs';
1
2
  import { rename, writeFile } from 'node:fs/promises';
2
3
  /** Write a file whole or not at all: a crash mid-write leaves the old one, never a torn one. */
3
4
  export async function writeAtomic(file, text, mode) {
@@ -5,3 +6,26 @@ export async function writeAtomic(file, text, mode) {
5
6
  await writeFile(tmp, text, { mode });
6
7
  await rename(tmp, file);
7
8
  }
9
+ // What a rename over a file another process holds open meets on Windows (a scanner, an indexer).
10
+ const HELD = new Set(['EPERM', 'EACCES', 'EBUSY']);
11
+ /**
12
+ * The same, at once: for state written as it changes, where two writes must not interleave. A
13
+ * file held for a moment is tried again for up to half a second; then the error goes up and the
14
+ * temporary file goes.
15
+ */
16
+ export function writeAtomicSync(file, text) {
17
+ const tmp = `${file}.${process.pid}.tmp`;
18
+ writeFileSync(tmp, text);
19
+ for (let i = 0;; i++)
20
+ try {
21
+ renameSync(tmp, file);
22
+ return;
23
+ }
24
+ catch (e) {
25
+ if (!HELD.has(e.code ?? '') || i >= 10) {
26
+ rmSync(tmp, { force: true });
27
+ throw e;
28
+ }
29
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
30
+ }
31
+ }
@@ -30,10 +30,11 @@ function images(v) {
30
30
  }
31
31
  const SLUG = /^[a-z0-9][a-z0-9-]*$/;
32
32
  /**
33
- * What a message attaches (Round2-review §3): an item, a file of the project. They go into the
34
- * message's text, as a line the agent reads: it opens them itself.
33
+ * What a message attaches (Round2-review §3): an item, a file of the project, a design unit of
34
+ * `units` (Board-PRD §5.13). They go into the message's text, as a line the agent reads: it
35
+ * opens them itself.
35
36
  */
36
- function attachLine(v) {
37
+ function attachLine(v, units) {
37
38
  if (v === undefined)
38
39
  return '';
39
40
  if (!Array.isArray(v) || v.length > 10)
@@ -42,6 +43,11 @@ function attachLine(v) {
42
43
  const { kind, ref } = (a ?? {});
43
44
  if (kind === 'item' && typeof ref === 'string' && SLUG.test(ref))
44
45
  return `item ${ref} (gcf/work/${ref}.md)`;
46
+ // A unit the board read lists: its file is the core's, not the page's word.
47
+ if (kind === 'unit' && typeof ref === 'string' && units?.has(ref))
48
+ return `unit ${ref} (${units.get(ref)})`;
49
+ if (kind === 'unit')
50
+ throw bad(`no design unit ${String(ref)} on the board`);
45
51
  // A project path, as the operator names it: relative, inside the project, nothing a shell
46
52
  // would expand (`~`, `%VAR%`, `$VAR`) and no drive or scheme (`:`).
47
53
  const file = typeof ref === 'string' ? ref.trim() : '';
@@ -52,16 +58,22 @@ function attachLine(v) {
52
58
  !/[:%$]/.test(file) &&
53
59
  !file.split(/[\\/]/).some((part) => part.trim() === '..'))
54
60
  return `file ${file}`;
55
- throw bad('an attachment is {kind: item, ref: <id>} or {kind: file, ref: <project path>}');
61
+ throw bad('an attachment is {kind: item, ref: <id>}, {kind: unit, ref: <id>} or {kind: file, ref: <project path>}');
56
62
  });
57
63
  return refs.length ? `\n\n[attached: ${refs.join('; ')}]` : '';
58
64
  }
59
- /** The line a request writes into the chat input: a message, a stop of the step, an answer. */
60
- export function chatInput(body) {
65
+ /** Whether a body attaches a design unit: its route reads the board's units for it. */
66
+ export const attachesUnit = (body) => Array.isArray(body.attach) &&
67
+ body.attach.some((a) => a?.kind === 'unit');
68
+ /**
69
+ * The line a request writes into the chat input: a message, a stop of the step, an answer.
70
+ * `units`: the design units an attachment may name.
71
+ */
72
+ export function chatInput(body, units) {
61
73
  if (body.type === 'interrupt')
62
74
  return { type: 'interrupt' };
63
75
  if (body.type === 'say') {
64
- const text = typeof body.text === 'string' ? body.text + attachLine(body.attach) : body.text;
76
+ const text = typeof body.text === 'string' ? body.text + attachLine(body.attach, units) : body.text;
65
77
  if (typeof text !== 'string' || !text.trim() || text.length > TEXT_MAX)
66
78
  throw bad(`a message is text, up to ${TEXT_MAX} characters`);
67
79
  const list = images(body.images);
@@ -81,11 +93,11 @@ export function chatInput(body) {
81
93
  throw bad('type is say, interrupt or answer');
82
94
  }
83
95
  /** The line a request writes into a project chat thread: an item chat's, a card's, a handoff. */
84
- export function talkInput(body) {
96
+ export function talkInput(body, units) {
85
97
  if (body.type === 'handoff')
86
98
  return { type: 'handoff' };
87
99
  if (body.type !== 'allow' && body.type !== 'deny')
88
- return chatInput(body);
100
+ return chatInput(body, units);
89
101
  const id = body.request_id;
90
102
  if (typeof id !== 'string' || !/^[A-Za-z0-9_][\w-]*$/.test(id))
91
103
  throw bad(`${body.type} names its request_id`);
@@ -56,9 +56,14 @@ export function briefError(err) {
56
56
  * `input` goes to its stdin: a text longer than a command line may be.
57
57
  */
58
58
  export function runCli(entry, cwd, args, timeoutMs = 120_000, input) {
59
+ // A move from the board is the operator's: a board started inside a Claude Code session or a
60
+ // run would otherwise pass as the owner of that session's mark (Methodology §4), and its
61
+ // commits as the session's or the run's moves (`GCF-By`).
62
+ const { CLAUDE_CODE_SESSION_ID: _, GCF_RUN_OWNER: __, GCF_MOVE_BY: ___, GCF_RUN_ITEM: ____, ...env } = process.env;
59
63
  return new Promise((resolve) => {
60
64
  const child = spawn(process.execPath, [entry, ...args], {
61
65
  cwd,
66
+ env,
62
67
  shell: false,
63
68
  stdio: ['pipe', 'pipe', 'pipe'],
64
69
  });
@@ -1,8 +1,9 @@
1
1
  // The files a board shows: an item, its plan, its run log. Only those shapes (or a plan an item
2
2
  // links), only inside the project, symlinks resolved: the API is not a way to read the disk.
3
- import { realpath, readFile, stat, open } from 'node:fs/promises';
3
+ import { lstat, realpath, readFile, stat, open } from 'node:fs/promises';
4
4
  import path from 'node:path';
5
5
  import { StringDecoder } from 'node:string_decoder';
6
+ import { attachedShape } from '../shared/board.js';
6
7
  import { HttpError } from './http-error.js';
7
8
  import { openStream } from './events.js';
8
9
  const SHOWN = [
@@ -47,6 +48,23 @@ async function readBytes(file, from, to) {
47
48
  await fh.close();
48
49
  }
49
50
  }
51
+ // The most of a past run's log part one answer gives: its end, the start cut.
52
+ const PART_MAX = 2 * 1024 * 1024;
53
+ /**
54
+ * The part `[from, to)` of item `id`'s run log a past run wrote (Board-V2-Data-Plan §3): `to`
55
+ * past the file's end is cut to it; past 2 MB the last 2 MB come, `cut` the bytes left out at
56
+ * its start. No log is a 404. A letter split at an edge is dropped, not mangled.
57
+ */
58
+ export async function logPart(root, id, from, to) {
59
+ const file = path.join(root, '.gcf-session', 'runs', `${id}.log`);
60
+ if (!(await inside(root, file)))
61
+ throw new HttpError(404, `${id} has no run log`);
62
+ const { size } = await stat(file);
63
+ const end = Math.min(to, size);
64
+ const start = Math.min(Math.max(from, end - PART_MAX), end);
65
+ const text = new StringDecoder('utf8').write(await readBytes(file, start, end));
66
+ return { text: text.replace(/^\uFFFD+/, ''), cut: Math.max(0, start - from) };
67
+ }
50
68
  /** Whether a file that exists resolves inside the project: a log may be a symlink. */
51
69
  async function inside(root, file) {
52
70
  const real = await realpath(file).catch(() => null);
@@ -102,3 +120,31 @@ export function follow(root, file, res, whole) {
102
120
  const timer = setInterval(tick, 1000);
103
121
  res.on('close', () => clearInterval(timer));
104
122
  }
123
+ const PICTURE = /\.(png|jpe?g|gif|webp)$/i;
124
+ /**
125
+ * An attachment of the project to hand out: its absolute path, its type, and whether it goes as
126
+ * a download. Refused, as a 404: a path of another place, one with `..`, a backslash, a drive or
127
+ * a stream (`:`), a NUL, or a link (a junction too) anywhere on it from the project's root, and
128
+ * one that resolves outside the project. A picture shows (svg is none: it may hold a script);
129
+ * any other file goes as a download. A hard link is not seen: it is the file it names.
130
+ */
131
+ export async function attachmentOf(root, rel) {
132
+ const no = () => new HttpError(404, `no attachment ${rel}`);
133
+ if (!attachedShape(rel) || /[\\:\0]/.test(rel))
134
+ throw no();
135
+ const parts = rel.split('/');
136
+ if (parts.some((s) => s === '' || s === '.' || s === '..'))
137
+ throw no();
138
+ for (let i = 1; i <= parts.length; i++) {
139
+ const st = await lstat(path.join(root, ...parts.slice(0, i))).catch(() => null);
140
+ if (!st || st.isSymbolicLink() || (i === parts.length && !st.isFile()))
141
+ throw no();
142
+ }
143
+ const file = path.join(root, ...parts);
144
+ if (!(await inside(root, file)))
145
+ throw no();
146
+ const ext = PICTURE.exec(rel)?.[1].toLowerCase();
147
+ return ext
148
+ ? { file, type: `image/${ext === 'jpg' ? 'jpeg' : ext}`, download: false }
149
+ : { file, type: 'application/octet-stream', download: true };
150
+ }