gcf-board 0.12.1 → 0.16.3

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.
@@ -11,7 +11,7 @@ import { appendFileSync, existsSync, lstatSync, mkdirSync, readFileSync, statSyn
11
11
  import os from 'node:os';
12
12
  import path from 'node:path';
13
13
  import { fileURLToPath } from 'node:url';
14
- import { THREAD_ID, createThread, listThreads, presetsOf, readThread, setThreadAgent, threadAgent, threadDir, threadOf, threadOfEntry, } from 'gcf-session';
14
+ import { THREAD_ID, createThread, defaultsOf, listThreads, presetsOf, readThread, setThreadAgent, threadAgent, threadDir, threadOf, threadOfEntry, } from 'gcf-session';
15
15
  import { runModeOf } from '../shared/board.js';
16
16
  import { writeAtomic } from './atomic.js';
17
17
  import { alive } from './events.js';
@@ -31,10 +31,14 @@ const ASK = [
31
31
  { kind: 'edit', pattern: '' },
32
32
  { kind: 'shell', pattern: 'git *' },
33
33
  ];
34
+ // The files that steer an agent: a design thread that writes its files freely still asks for them.
35
+ const OWN_FILES = ['.claude/**', 'CLAUDE.md', 'AGENTS.md', '.ai-factory/**'].map((pattern) => ({ kind: 'edit', pattern }));
34
36
  /** What the operator picks a model and effort from: the agent's presets (Board-PRD decision 24). */
35
37
  export const agentPresets = () => presetsOf(process.env.GCF_SESSION_AGENT ?? DEFAULT_AGENT);
38
+ /** What a thread or a run runs on when neither it nor the project picks (decision 36). */
39
+ export const agentDefaults = () => defaultsOf(process.env.GCF_SESSION_AGENT ?? DEFAULT_AGENT);
36
40
  /**
37
- * Pick thread `t`'s model and effort (`default` or none: the agent's own); its next session
41
+ * Pick thread `t`'s model and effort (`default` or none: the project's setting, else the agent's default); its next session
38
42
  * takes them. A word that is not plain is a 400.
39
43
  */
40
44
  export function pickTalk(p, t, body) {
@@ -111,26 +115,49 @@ function homeRules() {
111
115
  return [
112
116
  { kind: 'read', pattern: `${home}/**` },
113
117
  { kind: 'search', pattern: `${home}/**` },
118
+ { kind: 'edit', pattern: `${home}/**` },
114
119
  ...[...spellings].map((s) => ({ kind: 'shell', pattern: `*${s}*` })),
115
120
  ];
116
121
  }
117
- /** What a thread of the project runs by (AD-5, AD-29, AD-31, AD-43), `spec.json`. */
118
- export function talkSpec(p, board, mcp) {
122
+ /** The design start a thread was opened for (Board-PRD §5.24), from the domain; none: null. */
123
+ export function startOf(board, start) {
124
+ if (!start)
125
+ return null;
126
+ const s = board.domain.starts?.[start];
127
+ if (!s)
128
+ throw new HttpError(400, `the project's core has no design start ${start}: update gcf-aif-ext`);
129
+ return s;
130
+ }
131
+ /**
132
+ * What a thread of the project runs by (AD-5, AD-29, AD-31, AD-43), `spec.json`. A design
133
+ * start's thread follows its own skill, and writes the files its start names without a card:
134
+ * an import writes dozens of units; every other edit, git and a changing gcf command still ask.
135
+ */
136
+ export function talkSpec(p, board, mcp, start = null) {
119
137
  const { chat, rules } = chatOf(board);
138
+ const own = startOf(board, start);
120
139
  return {
121
140
  agent: process.env.GCF_SESSION_AGENT ?? DEFAULT_AGENT,
122
141
  rules: {
123
142
  deny: [...rules.deny, { kind: 'edit', pattern: '.gcf-session/**' }, ...homeRules()],
124
- ask: [...ASK, ...chat.confirm],
143
+ // Claude holds ask over allow: the blanket edit ask would shadow the start's edits. The
144
+ // agent's own instructions and settings still ask, whatever the project allows.
145
+ ask: [
146
+ ...(own ? [...ASK.filter((r) => r.kind !== 'edit'), ...OWN_FILES] : ASK),
147
+ ...chat.confirm,
148
+ ],
125
149
  // The center's own MCP server only proposes: the proposal card's Create is the
126
150
  // operator's say, so the call asks no permission card before it.
127
- allow: [{ kind: 'mcp', pattern: 'gcf' }],
151
+ allow: [
152
+ { kind: 'mcp', pattern: 'gcf' },
153
+ ...(own?.edits ?? []).map((pattern) => ({ kind: 'edit', pattern })),
154
+ ],
128
155
  },
129
156
  mcp: [mcp],
130
157
  answerMin: board.chat?.answer_timeout_min,
131
158
  handoffPct: board.context?.handoff_pct,
132
159
  ...(board.context?.window ? { window: board.context.window } : {}),
133
- skill: chat.skill,
160
+ skill: own?.skill ?? chat.skill,
134
161
  mainLock: path.join(p.path, '.gcf-session', 'runs', '.main-run.lock'),
135
162
  // The project's model and effort: a thread that picked none runs on them.
136
163
  pick: Object.fromEntries(['model', 'effort'].flatMap((k) => board.agent?.[k] ? [[k, board.agent[k]]] : [])),
@@ -217,11 +244,12 @@ export async function prepareTalk(p, board, t) {
217
244
  const proposable = Object.fromEntries(Object.entries(board.domain.moves).filter(([, m]) => m.propose));
218
245
  const moves = path.join(td, 'moves.json');
219
246
  const mcp = path.join(td, 'mcp.json');
220
- const spec = talkSpec(p, board, mcp);
247
+ const rec = readThread(p.path, t);
248
+ const spec = talkSpec(p, board, mcp, rec.start?.id ?? null);
221
249
  await writeAtomic(moves, `${JSON.stringify(proposable, null, 2)}\n`);
222
250
  const server = { type: 'stdio', command: process.execPath, args: [MCP, moves] };
223
251
  await writeAtomic(mcp, `${JSON.stringify({ mcpServers: { gcf: server } }, null, 2)}\n`);
224
- await writeAtomic(path.join(td, 'context.md'), contextOf(p, board, readThread(p.path, t).item));
252
+ await writeAtomic(path.join(td, 'context.md'), contextOf(p, board, rec.item));
225
253
  await writeAtomic(path.join(td, 'spec.json'), `${JSON.stringify(spec, null, 2)}\n`);
226
254
  }
227
255
  /**
@@ -282,6 +310,62 @@ export function entryTalk(p, entry) {
282
310
  const had = threadOfEntry(p.path, entry);
283
311
  return { id: had ?? createThread(p.path, { entry }), created: !had };
284
312
  }
313
+ /**
314
+ * A new thread for design start `start` (Board-PRD §5.24): an uploaded GDD goes into its `att/`
315
+ * under a name `gcf anchor` keeps in `gcf/source/`. Returns the thread and the first message,
316
+ * `say` with `{file}` (the project path of that copy), `{unit}`, `{system}` and `{text}` filled in.
317
+ */
318
+ export function designTalk(p, board, start, given) {
319
+ const s = startOf(board, start);
320
+ if (!s)
321
+ throw new HttpError(404, `no design start ${start}`);
322
+ const name = given.file ? gddName(given.file.name) : null;
323
+ if (s.takes === 'file' && !given.file)
324
+ throw new HttpError(400, `${start} takes a GDD file (.md)`);
325
+ if (s.takes === 'unit' && !(board.units ?? []).some((u) => u.id === given.unit))
326
+ throw new HttpError(400, `${start} takes a unit of the design: ${String(given.unit)}`);
327
+ // A subsystem of the design: one the design check reads (decision 35's draft of its purpose).
328
+ const systems = board.design && !('error' in board.design) ? board.design.systems : {};
329
+ if (s.takes === 'system' && !Object.hasOwn(systems, given.system ?? ''))
330
+ throw new HttpError(400, `${start} takes a subsystem of the design: ${String(given.system)}`);
331
+ const text = String(given.text ?? '').trim();
332
+ if (s.takes === 'text' && !text)
333
+ throw new HttpError(400, `${start} takes the change in words`);
334
+ const t = createThread(p.path, { start: { id: start } });
335
+ let file = '';
336
+ if (given.file && name) {
337
+ const att = path.join(writeDir(p, t), 'att');
338
+ mkdirSync(att, { recursive: true });
339
+ writeFileSync(path.join(att, name), given.file.text);
340
+ file = path.relative(p.path, path.join(att, name)).replaceAll('\\', '/');
341
+ }
342
+ const say = s.say
343
+ .replaceAll('{file}', file)
344
+ .replaceAll('{unit}', given.unit ?? '')
345
+ .replaceAll('{system}', given.system ?? '')
346
+ .replaceAll('{text}', text);
347
+ return { id: t, say };
348
+ }
349
+ // A GDD's name kept in gcf/source/: the board's file route shows `[\w./-]` names only.
350
+ const GDD_NAME = /^[\w][\w.-]*\.md$/;
351
+ /**
352
+ * An uploaded GDD's file name, made a plain one: `.md` in lower case (gcf/source/ lists `*.md`),
353
+ * `gdd.md` for a name with no plain letter left (`Дизайн.md`). A name that is no markdown file
354
+ * is a 400.
355
+ */
356
+ export function gddName(name) {
357
+ const base = path.basename(String(name)).trim();
358
+ if (!/\.md$/i.test(base))
359
+ throw new HttpError(400, `a GDD is a markdown file (.md): ${name}`);
360
+ const plain = base
361
+ .slice(0, -3)
362
+ .replace(/[^\w.-]+/g, '-')
363
+ .replace(/^[-.]+|[-.]+$/g, '');
364
+ const file = `${/[a-z0-9]/i.test(plain) ? plain : 'gdd'}.md`;
365
+ if (!GDD_NAME.test(file))
366
+ throw new HttpError(400, `a GDD is a markdown file (.md): ${name}`);
367
+ return file;
368
+ }
285
369
  /** The inbox entry thread `t` drafts an item from; null for any other thread. */
286
370
  export const talkEntry = (p, t) => readThread(p.path, talkId(t)).entry ?? null;
287
371
  const lineId = () => randomBytes(6).toString('hex');
@@ -386,7 +470,7 @@ const accepting = new Set();
386
470
  * made already is made once: a second click, an edited id too, is refused (409), also when a
387
471
  * board that stopped mid-move left its record `accepting`.
388
472
  */
389
- export async function acceptProposal(p, t, id, move, item, ids, run) {
473
+ export async function acceptProposal(p, t, id, move, item, ids, run, mark) {
390
474
  const td = writeDir(p, t);
391
475
  const offered = eventsOf(td).find((e) => e.type === 'proposal' && e.id === id);
392
476
  if (offered?.type !== 'proposal')
@@ -402,7 +486,13 @@ export async function acceptProposal(p, t, id, move, item, ids, run) {
402
486
  const made = await settled(td, id, readRecords(td)[id], async () => ids, true);
403
487
  if (made?.state === 'accepted')
404
488
  throw new HttpError(409, `proposal ${id} is made already: ${made.item ?? ''}`);
405
- await setRecord(td, id, { state: 'accepting', item, existed: ids.has(item), at: now() });
489
+ await setRecord(td, id, {
490
+ state: 'accepting',
491
+ item,
492
+ existed: ids.has(item),
493
+ ...(mark ? { mark } : {}),
494
+ at: now(),
495
+ });
406
496
  const r = await run();
407
497
  await setRecord(td, id, {
408
498
  ...(r.ok ? { state: 'accepted', item } : { state: 'refused', error: r.err || r.out }),
@@ -434,7 +524,11 @@ async function settled(td, id, rec, ids, mine = false) {
434
524
  const latest = readRecords(td)[id];
435
525
  if (latest?.state !== 'accepting' || (!mine && accepting.has(`${td} ${id}`)))
436
526
  return latest;
437
- const made = !rec.existed && Boolean(rec.item) && board.has(rec.item ?? '');
527
+ // The project of a thread's folder: `<project>/.gcf-session/chats/<thread>`.
528
+ const projectDir = path.resolve(td, '..', '..', '..');
529
+ const ours = !rec.mark ||
530
+ git(projectDir, 'log', '-1', '--format=%H', `--grep=^GCF-Proposal: ${rec.mark}$`) !== '';
531
+ const made = !rec.existed && Boolean(rec.item) && board.has(rec.item ?? '') && ours;
438
532
  const next = made
439
533
  ? { state: 'accepted', item: rec.item, at: now() }
440
534
  : { state: 'refused', error: 'the board stopped while it was made: try again', at: now() };
@@ -535,6 +629,7 @@ async function talkOf(p, th, ids) {
535
629
  title,
536
630
  item: th.item,
537
631
  entry: th.entry ?? null,
632
+ start: th.start?.id ?? null,
538
633
  created_at: th.created_at,
539
634
  last_at: events.at(-1)?.at ?? null,
540
635
  cost_usd: Math.round(cost * 100) / 100,
@@ -1,10 +1,14 @@
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
1
+ // The themes: the designer's that ship with the board (`themes/` of the package), and the
2
+ // operator's, one JSON file each in `<board home>/themes/<id>.json`; an own file of the same id
3
+ // wins. A theme sets design tokens (`--gcf-<name>` of web/tokens.css) over the
3
4
  // built-in dark; the page checks the names, it owns the tokens. Read anew on each request.
4
5
  import { readdir, readFile, stat } from 'node:fs/promises';
5
6
  import path from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
6
8
  import { homeDir } from './registry.js';
7
9
  export const themesDir = () => path.join(homeDir(), 'themes');
10
+ // server/ in the source, dist/server/ once built: the package's themes/ either way.
11
+ const BUILT_IN = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? '../themes/' : '../../themes/', import.meta.url));
8
12
  const ID_RE = /^[a-z0-9-]{1,40}$/;
9
13
  const FILE_MAX = 64 * 1024;
10
14
  const VALUE_MAX = 200;
@@ -73,3 +77,9 @@ export async function readThemes(dir = themesDir()) {
73
77
  }
74
78
  return themes;
75
79
  }
80
+ /** The board's own themes, then the operator's; an own file replaces a built-in one of its id. */
81
+ export async function allThemes(own = themesDir()) {
82
+ const mine = await readThemes(own);
83
+ const ids = new Set(mine.map((t) => t.id));
84
+ return [...(await readThemes(BUILT_IN)).filter((t) => !ids.has(t.id)), ...mine];
85
+ }
@@ -0,0 +1,38 @@
1
+ // A file the operator picks on their machine (the page's file dialog): the page reads it and
2
+ // sends its bytes, as a browser never gives a path. The server writes it beside the project's
3
+ // session data (`.gcf-session/uploads/`, not in git), each under its own name in a folder of
4
+ // its own, so a command that copies it (`gcf item attach`) keeps the name.
5
+ import { randomBytes } from 'node:crypto';
6
+ import { mkdir, writeFile } from 'node:fs/promises';
7
+ import path from 'node:path';
8
+ import { HttpError } from './http-error.js';
9
+ const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
10
+ // The core's limit of an attachment (10 MB), as base64.
11
+ export const UPLOAD_MAX = 13_990_000;
12
+ /** Whether a value is a picked file as the page sends it: `{name, data}`, data in base64. */
13
+ export const isUpload = (v) => typeof v === 'object' &&
14
+ v !== null &&
15
+ typeof v.name === 'string' &&
16
+ typeof v.data === 'string';
17
+ /** Its name as a file of its own: no folder, nothing a shell or Windows reads, 100 characters. */
18
+ export function uploadName(name) {
19
+ const base = name.split(/[\\/]/).pop() ?? '';
20
+ const safe = base
21
+ .replace(/[^\p{L}\p{N}_.\- ()]/gu, '_')
22
+ .replace(/^[.\s]+/, '')
23
+ .trim()
24
+ .slice(-100);
25
+ return safe || 'file';
26
+ }
27
+ /** Write a picked file into the project's uploads: its absolute path. */
28
+ export async function saveUpload(root, v, max = UPLOAD_MAX) {
29
+ if (!isUpload(v) || !BASE64.test(v.data))
30
+ throw new HttpError(400, 'a file is {name, data}');
31
+ if (v.data.length > max)
32
+ throw new HttpError(400, `${v.name}: over ${Math.floor((max * 3) / 4 / 1e6)} MB`);
33
+ const dir = path.join(root, '.gcf-session', 'uploads', randomBytes(4).toString('hex'));
34
+ await mkdir(dir, { recursive: true });
35
+ const file = path.join(dir, uploadName(v.name));
36
+ await writeFile(file, Buffer.from(v.data, 'base64'));
37
+ return file;
38
+ }
@@ -1,6 +1,6 @@
1
1
  // The read model of `ai-factory gcf board --json` (Methodology §11): the board refuses a schema
2
2
  // it does not know. Types only, plus the version this board reads.
3
- export const BOARD_SCHEMA = 3;
3
+ export const BOARD_SCHEMA = 4;
4
4
  // Where a project keeps files given to an item or an inbox entry (Board-PRD §5.3, §5.6): only
5
5
  // there may the board hand out a file that is not text. One list: a later kind is one line.
6
6
  const ATTACHED = [