gcf-board 0.16.9 → 0.18.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.
@@ -12,13 +12,13 @@ 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, defaultsOf, listThreads, presetsOf, readThread, setThreadAgent, threadAgent, threadDir, threadOf, threadOfEntry, } from 'gcf-session';
15
- import { runModeOf } from '../shared/board.js';
15
+ import { runModeOf, toolOf } from '../shared/board.js';
16
16
  import { writeAtomic } from './atomic.js';
17
- import { briefError } from './cli.js';
17
+ import { briefError, refusalOf } from './cli.js';
18
18
  import { alive } from './events.js';
19
19
  import { HttpError } from './http-error.js';
20
20
  import { IMAGE_EXT } from './chat.js';
21
- import { homeDir } from './registry.js';
21
+ import { homeDir, yoloFile } from './registry.js';
22
22
  // The source runs the .ts files, the package its build beside this file.
23
23
  const own = (name) => fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? `${name}.ts` : `${name}.js`, import.meta.url));
24
24
  const RELAY = own('relay');
@@ -160,6 +160,7 @@ export function talkSpec(p, board, mcp, start = null) {
160
160
  ...(board.context?.window ? { window: board.context.window } : {}),
161
161
  skill: own?.skill ?? chat.skill,
162
162
  mainLock: path.join(p.path, '.gcf-session', 'runs', '.main-run.lock'),
163
+ yolo: yoloFile(),
163
164
  // The project's model and effort: a thread that picked none runs on them.
164
165
  pick: Object.fromEntries(['model', 'effort'].flatMap((k) => board.agent?.[k] ? [[k, board.agent[k]]] : [])),
165
166
  };
@@ -271,14 +272,14 @@ export function talkLive(p, t) {
271
272
  }
272
273
  }
273
274
  /**
274
- * What a thread's engine runs with: a thread's agent is a session of the operator's, whoever
275
- * started the board. A board started from a run or a session passes neither that one's owner
276
- * nor its maker on (`GCF-By`): the thread's moves are `session`.
275
+ * What a thread's engine runs with, whoever started the board. A board started from a run or a
276
+ * session passes neither that one's owner nor its maker on (`GCF-By`): the thread's moves are
277
+ * `thread`, and the core refuses the operator's moves from it (they go as proposals).
277
278
  */
278
279
  export function talkEnv(env = process.env) {
279
280
  // GCF_RUN_ITEM too: a run's guards would take the thread's agent for that run's.
280
281
  const { CLAUDE_CODE_SESSION_ID: _, GCF_RUN_OWNER: __, GCF_MOVE_BY: ___, GCF_RUN_ITEM: ____, ...rest } = env;
281
- return { ...rest, GCF_MOVE_BY: 'session' };
282
+ return { ...rest, GCF_MOVE_BY: 'thread' };
282
283
  }
283
284
  // When the board last started each thread: a second start meanwhile only finds the lock held.
284
285
  const starts = new Map();
@@ -450,7 +451,40 @@ export function chatCard(file) {
450
451
  cards.set(file, { stamp, card });
451
452
  return card;
452
453
  }
454
+ const ends = new Map();
455
+ /** How the last run in a run's chat file ended (`run_end`), or null; read again only when it changed. */
456
+ export function lastRunEnd(file) {
457
+ let stamp = '';
458
+ try {
459
+ const st = statSync(file);
460
+ stamp = `${st.mtimeMs}:${st.size}`;
461
+ }
462
+ catch {
463
+ return null;
464
+ }
465
+ const kept = ends.get(file);
466
+ if (kept?.stamp === stamp)
467
+ return kept.end;
468
+ const events = chatEvents(file);
469
+ const at = events.findLastIndex((e) => e.type === 'run_end');
470
+ // A session started after it: that run has not ended yet.
471
+ const later = events.slice(at + 1).some((e) => e.type === 'session');
472
+ const end = at < 0 || later ? null : events[at];
473
+ ends.set(file, { stamp, end });
474
+ return end;
475
+ }
453
476
  /** The events of a chat file: a thread's, or a run's `<id>.chat.jsonl`; none without one. */
477
+ /**
478
+ * The deny group the last session of a run's chat was refused by, for "Allow <group> and run
479
+ * again" (docs/Autonomy-Plan.md, E): its last refusal's, none from an older run. Never a group
480
+ * that guards history or the operator's own moves, nor an old alias.
481
+ */
482
+ export function deniedGroupOf(events) {
483
+ const start = events.findLastIndex((e) => e.type === 'session' && e.kind === 'start');
484
+ const denied = events.slice(Math.max(0, start)).filter((e) => e.type === 'denied');
485
+ const group = denied.at(-1)?.group ?? null;
486
+ return group && !['git-history', 'git-destroy', 'human-moves'].includes(group) ? group : null;
487
+ }
454
488
  export function chatEvents(file) {
455
489
  let text = '';
456
490
  try {
@@ -468,6 +502,8 @@ export function chatEvents(file) {
468
502
  }
469
503
  });
470
504
  }
505
+ /** What a record keeps that the list does not show. */
506
+ const INNER = ['existed', 'mark', 'head', 'cmd'];
471
507
  const recordsFile = (td) => path.join(td, 'proposals.json');
472
508
  function readRecords(td) {
473
509
  try {
@@ -480,7 +516,28 @@ function readRecords(td) {
480
516
  // One write of a thread's records at a time: each reads, changes and writes the whole file.
481
517
  const writing = new Map();
482
518
  function setRecord(td, id, rec) {
483
- const next = (writing.get(td) ?? Promise.resolve()).then(() => writeAtomic(recordsFile(td), `${JSON.stringify({ ...readRecords(td), [id]: rec }, null, 2)}\n`));
519
+ const next = (writing.get(td) ?? Promise.resolve()).then(() => {
520
+ const all = readRecords(td);
521
+ // The question an answer was proposed for stays with every later state of it.
522
+ const question = rec.question ?? all[id]?.question;
523
+ const kept = question === undefined ? rec : { ...rec, question };
524
+ return writeAtomic(recordsFile(td), `${JSON.stringify({ ...all, [id]: kept }, null, 2)}\n`);
525
+ });
526
+ writing.set(td, next.catch(() => { }));
527
+ return next;
528
+ }
529
+ /**
530
+ * Write `rec` only while proposal `id` has no record yet, in the same queue as setRecord: a
531
+ * click that wrote `accepting` or `accepted` meanwhile wins. Returns the record that holds.
532
+ */
533
+ function addRecord(td, id, rec) {
534
+ const next = (writing.get(td) ?? Promise.resolve()).then(async () => {
535
+ const all = readRecords(td);
536
+ if (all[id])
537
+ return all[id];
538
+ await writeAtomic(recordsFile(td), `${JSON.stringify({ ...all, [id]: rec }, null, 2)}\n`);
539
+ return rec;
540
+ });
484
541
  writing.set(td, next.catch(() => { }));
485
542
  return next;
486
543
  }
@@ -488,18 +545,26 @@ function setRecord(td, id, rec) {
488
545
  const accepting = new Set();
489
546
  /**
490
547
  * Make proposal `id` of thread `t` by its move (AD-16, AD-33): `accepting` is written first,
491
- * with the item it makes and whether that id was taken already; then `accepted` or `refused`
492
- * with the framework's words. `run` is the move; `ids` the items on the board now. A proposal
493
- * made already is made once: a second click, an edited id too, is refused (409), also when a
494
- * board that stopped mid-move left its record `accepting`.
548
+ * with the item it makes, whether that id was taken already and HEAD before it; then `accepted`
549
+ * or `refused` with the framework's words and its machine refusal. `run` is the move; `ids` the
550
+ * items on the board now. A proposal made already is made once: a second click, an edited id
551
+ * too, is refused (409), also when a board that stopped mid-move left its record `accepting`.
552
+ * `question`: for an answer, the question's text now (null when gone): one that changed since
553
+ * the proposal was first seen is refused (409), its id may hold another question now.
495
554
  */
496
- export async function acceptProposal(p, t, id, move, item, ids, run, mark) {
555
+ export async function acceptProposal(p, t, id, move, item, ids, run, mark, question) {
497
556
  const td = writeDir(p, t);
498
557
  const offered = eventsOf(td).find((e) => e.type === 'proposal' && e.id === id);
499
558
  if (offered?.type !== 'proposal')
500
559
  throw new HttpError(404, `no proposal ${id} in thread ${t}`);
501
- if (offered.move !== move)
560
+ // The engine reads the tool's name back with `-` for `:` (verdict:keep comes back verdict-keep).
561
+ if (toolOf(offered.move) !== toolOf(move))
502
562
  throw new HttpError(400, `proposal ${id} is ${offered.move}, not ${move}`);
563
+ if (question !== undefined) {
564
+ const seen = readRecords(td)[id]?.question;
565
+ if (question === null || (seen !== undefined && seen !== question))
566
+ throw new HttpError(409, 'the question changed since it was proposed: ask the agent again');
567
+ }
503
568
  const key = `${td} ${id}`;
504
569
  if (accepting.has(key))
505
570
  throw new HttpError(409, `proposal ${id} is being made already`);
@@ -509,19 +574,23 @@ export async function acceptProposal(p, t, id, move, item, ids, run, mark) {
509
574
  const made = await settled(td, id, readRecords(td)[id], async () => ids, true);
510
575
  if (made?.state === 'accepted')
511
576
  throw new HttpError(409, `proposal ${id} is made already: ${made.item ?? ''}`);
577
+ const head = git(projectOf(td), 'rev-parse', 'HEAD');
512
578
  await setRecord(td, id, {
513
579
  state: 'accepting',
514
580
  item,
515
581
  existed: ids.has(item),
516
582
  ...(mark ? { mark } : {}),
583
+ ...(head ? { head, cmd: move } : {}),
584
+ ...(question ? { question } : {}),
517
585
  at: now(),
518
586
  });
519
587
  const r = await run();
588
+ const refusal = r.ok ? undefined : refusalOf(r.err);
520
589
  await setRecord(td, id, {
521
- // The card shows the core's refusal, not node's stack around it.
590
+ // The card shows the core's refusal, not node's stack around it, and what it can fix.
522
591
  ...(r.ok
523
592
  ? { state: 'accepted', item }
524
- : { state: 'refused', error: briefError(r.err || r.out) }),
593
+ : { state: 'refused', error: briefError(r.err || r.out), ...(refusal && { refusal }) }),
525
594
  at: now(),
526
595
  });
527
596
  return r;
@@ -531,6 +600,25 @@ export async function acceptProposal(p, t, id, move, item, ids, run, mark) {
531
600
  }
532
601
  }
533
602
  const now = () => new Date().toISOString();
603
+ /** The project of a thread's folder: `<project>/.gcf-session/chats/<thread>`. */
604
+ const projectOf = (td) => path.resolve(td, '..', '..', '..');
605
+ /**
606
+ * Whether a commit after `head` made move `cmd` on `item`: its `GCF-Move` trailer, and the item
607
+ * in its `GCF-Items` (an answer names its question in the subject, `gcf(answer): <q-id>`).
608
+ */
609
+ function movedSince(projectDir, head, cmd, item) {
610
+ const log = git(projectDir, 'log', '--format=%s%x1f%b%x1e', `${head}..HEAD`);
611
+ return log.split('\x1e').some((c) => {
612
+ const [subject = '', body = ''] = c.trim().split('\x1f');
613
+ if (!body.split('\n').some((l) => l.trim() === `GCF-Move: ${cmd}`))
614
+ return false;
615
+ // A move with no target (inbox add) names nothing of its own: another one's commit is not it.
616
+ if (!item)
617
+ return false;
618
+ const items = /^GCF-Items: (.*)$/m.exec(body)?.[1].split(', ') ?? [];
619
+ return items.includes(item) || subject === `gcf(answer): ${item}`;
620
+ });
621
+ }
534
622
  /**
535
623
  * A proposal's record, an `accepting` one a board that stopped meanwhile left (AD-33) settled by
536
624
  * the board read (`ids()`, the items on it): its item there and not before, it was made.
@@ -550,11 +638,15 @@ async function settled(td, id, rec, ids, mine = false) {
550
638
  const latest = readRecords(td)[id];
551
639
  if (latest?.state !== 'accepting' || (!mine && accepting.has(`${td} ${id}`)))
552
640
  return latest;
553
- // The project of a thread's folder: `<project>/.gcf-session/chats/<thread>`.
554
- const projectDir = path.resolve(td, '..', '..', '..');
641
+ const projectDir = projectOf(td);
555
642
  const ours = !rec.mark ||
556
643
  git(projectDir, 'log', '-1', '--format=%H', `--grep=^GCF-Proposal: ${rec.mark}$`) !== '';
557
- const made = !rec.existed && Boolean(rec.item) && board.has(rec.item ?? '') && ours;
644
+ // A new item: there now and not before, by its own commit. A move on what is already there
645
+ // (an item, a question): its commit since the HEAD the record kept, by the trailers.
646
+ const made = (!rec.existed && Boolean(rec.item) && board.has(rec.item ?? '') && ours) ||
647
+ (!rec.mark &&
648
+ Boolean(rec.head && rec.cmd) &&
649
+ movedSince(projectDir, rec.head ?? '', rec.cmd ?? '', rec.item ?? ''));
558
650
  const next = made
559
651
  ? { state: 'accepted', item: rec.item, at: now() }
560
652
  : { state: 'refused', error: 'the board stopped while it was made: try again', at: now() };
@@ -564,17 +656,28 @@ async function settled(td, id, rec, ids, mine = false) {
564
656
  /**
565
657
  * Thread `td`'s proposals in the order offered, each with its record. One left `accepting` by
566
658
  * a board that stopped meanwhile (AD-33) is settled by the board read (`ids()`, the items on
567
- * it): its item there and not before, it was made.
659
+ * it). An answer seen for the first time keeps its question's text (`questionOf`): the id may
660
+ * hold another question later.
568
661
  */
569
- async function proposalsOf(td, events, ids) {
662
+ async function proposalsOf(td, events, ids, questionOf, writable = () => td) {
570
663
  const records = readRecords(td);
571
664
  const out = [];
572
665
  for (const e of events) {
573
666
  if (e.type !== 'proposal')
574
667
  continue;
575
- const rec = await settled(td, e.id, records[e.id], ids);
668
+ let rec = await settled(td, e.id, records[e.id], ids);
669
+ const target = typeof e.fields?.id === 'string' ? e.fields.id : '';
670
+ if (!rec && questionOf && target) {
671
+ const question = await questionOf(e.move, target).catch(() => undefined);
672
+ // A folder through a link takes no write (writeDir): no snapshot then.
673
+ if (typeof question === 'string')
674
+ rec = await Promise.resolve()
675
+ .then(() => addRecord(writable(), e.id, { state: 'offered', question }))
676
+ .catch(() => undefined);
677
+ }
576
678
  const shown = { ...(rec ?? { state: 'offered' }) };
577
- delete shown.existed;
679
+ for (const k of INNER)
680
+ delete shown[k];
578
681
  out.push({ id: e.id, move: e.move, ...shown });
579
682
  }
580
683
  return out;
@@ -640,7 +743,7 @@ function sayOf(td) {
640
743
  /** Whether the operator sent thread `t` a message yet. */
641
744
  export const talkSaid = (p, t) => sayOf(dirOf(p, t)) !== null;
642
745
  /** What the list shows of thread `th` (Board-PRD §5.13). */
643
- async function talkOf(p, th, ids) {
746
+ async function talkOf(p, th, ids, questionOf) {
644
747
  const td = threadDir(p.path, th.id);
645
748
  const events = eventsOf(td);
646
749
  const first = sayOf(td);
@@ -666,19 +769,20 @@ async function talkOf(p, th, ids) {
666
769
  card,
667
770
  // A thread whose engine died during the wait waits for nothing.
668
771
  limit_until: live ? limitIn(events) : null,
669
- proposals: await proposalsOf(td, events, ids),
772
+ proposals: await proposalsOf(td, events, ids, questionOf, () => writeDir(p, th.id)),
670
773
  };
671
774
  }
672
775
  /**
673
776
  * The project's threads, newest first; with `item`, its bound one only. `ids()` reads the
674
- * board's items when a proposal needs settling.
777
+ * board's items when a proposal needs settling; `questionOf` the question an answer proposal
778
+ * answers, when it is first seen.
675
779
  */
676
- export async function listTalks(p, ids, item) {
780
+ export async function listTalks(p, ids, item, questionOf) {
677
781
  const threads = listThreads(p.path).filter((th) => !item || th.item === item);
678
782
  // One board read at most, and only when a proposal needs it.
679
783
  let read = null;
680
784
  const once = () => (read ??= ids());
681
- return Promise.all(threads.map((th) => talkOf(p, th, once)));
785
+ return Promise.all(threads.map((th) => talkOf(p, th, once, questionOf)));
682
786
  }
683
787
  /** Where a thread's input is read to, and how far it is written. */
684
788
  function unread(td) {
@@ -0,0 +1,101 @@
1
+ // The account's usage limits, asked of Claude's `/usage` (Board-PRD decision 39): what the top
2
+ // bar shows over the last limit a run reported. The command is free (no model call) and answers
3
+ // in a second or two; it still starts a claude process, so it is asked only while a page is open.
4
+ import { exec } from 'node:child_process';
5
+ import os from 'node:os';
6
+ import { broadcast, watched } from './events.js';
7
+ /** How often an open page's bar is read again, and how long one ask may take. */
8
+ export const USAGE_EVERY_MS = 5 * 60_000;
9
+ const ASK_TIMEOUT_MS = 30_000;
10
+ // No user or local settings, no MCP, no saved session: the user's hooks and plugins do not run
11
+ // for a reading, and the operator's session list gets no entry per ask. The cwd is the temp
12
+ // folder, whose project settings are no one's.
13
+ const FLAGS = '-p "/usage" --output-format stream-json --verbose --no-session-persistence ' +
14
+ '--setting-sources project --strict-mcp-config';
15
+ let command = null;
16
+ let last = null;
17
+ let asking = null;
18
+ let askedAt = 0;
19
+ // An ask still going when the board is configured again writes nothing into the new setup.
20
+ let generation = 0;
21
+ /** Ask with `agent` (claude, or a stand-in in the tests); null asks nothing, as in the tests. */
22
+ export function configureUsage(agent) {
23
+ generation += 1;
24
+ command = agent;
25
+ last = null;
26
+ asking = null;
27
+ askedAt = 0;
28
+ }
29
+ /** The last reading, with the last ask's failure when the ask after it failed; null before any. */
30
+ export const lastUsage = () => last;
31
+ const isLimit = (l) => typeof l === 'object' &&
32
+ l !== null &&
33
+ typeof l.kind === 'string' &&
34
+ typeof l.percent === 'number';
35
+ /**
36
+ * The limits of `/usage`'s stream-json answer: its assistant event's
37
+ * `usage_report.rate_limits.limits`; null when no line carries them (an API-key account has no
38
+ * plan limits, an older claude no report).
39
+ */
40
+ export function limitsOf(out) {
41
+ for (const line of out.split(/\r?\n/)) {
42
+ let e;
43
+ try {
44
+ e = JSON.parse(line);
45
+ }
46
+ catch {
47
+ continue;
48
+ }
49
+ const limits = e?.usage_report?.rate_limits?.limits;
50
+ if (Array.isArray(limits))
51
+ return limits.filter(isLimit);
52
+ }
53
+ return null;
54
+ }
55
+ /**
56
+ * Why an ask failed: the last two lines of its stderr (cmd's "not recognized" spans two), a
57
+ * timeout, or the error itself.
58
+ */
59
+ export function reasonOf(e, err) {
60
+ if (!e)
61
+ return 'claude answered /usage without the plan limits (an API key has none)';
62
+ const tail = err.trim();
63
+ if (tail)
64
+ return tail.split(/\r?\n/).slice(-2).join(' ').slice(0, 300);
65
+ return e.killed ? `no answer in ${ASK_TIMEOUT_MS / 1000} s` : e.message.slice(0, 300);
66
+ }
67
+ /**
68
+ * Ask `/usage` now, once at a time: a second ask while one goes waits for it. A reading tells
69
+ * every page (`quota`); a failed ask keeps the last reading and says why beside it.
70
+ */
71
+ export function askUsage() {
72
+ if (!command)
73
+ return Promise.resolve();
74
+ if (asking)
75
+ return asking;
76
+ askedAt = Date.now();
77
+ const mine = generation;
78
+ // shortcut: a timeout kills the shell, not a claude it started on Windows; one stuck claude
79
+ // then lingers until it ends itself. Kill the tree (gcf-session's killTree) if that is seen.
80
+ asking = new Promise((resolve) => {
81
+ exec(`${command} ${FLAGS}`, { cwd: os.tmpdir(), timeout: ASK_TIMEOUT_MS, windowsHide: true, maxBuffer: 4 << 20 }, (e, out, err) => {
82
+ if (mine !== generation)
83
+ return resolve();
84
+ const limits = limitsOf(out);
85
+ const at = new Date().toISOString();
86
+ if (limits)
87
+ last = { at, limits };
88
+ else
89
+ last = { ...(last ?? { at: null, limits: [] }), failed: { at, error: reasonOf(e, err) } };
90
+ asking = null;
91
+ broadcast({ type: 'quota' });
92
+ resolve();
93
+ });
94
+ });
95
+ return asking;
96
+ }
97
+ /** Ask when a page is open and the last ask is older than `everyMs`. */
98
+ export function askIfDue(everyMs = USAGE_EVERY_MS, now = Date.now()) {
99
+ if (command && watched() && now - askedAt >= everyMs)
100
+ void askUsage();
101
+ }
@@ -19,3 +19,20 @@ export function runModeOf(board, id, asked) {
19
19
  const own = board.items.find((i) => i.id === id)?.run_mode;
20
20
  return own === 'main' || own === 'worktree' ? own : board.run_mode;
21
21
  }
22
+ /**
23
+ * The tool of a proposed move: `propose_<key>`, `-` and `:` as `_` (AD-12). The session engine
24
+ * reads the name back with `_` as `-`, so `verdict:keep` comes back `verdict-keep`: moveOfTool
25
+ * finds the domain's key again.
26
+ */
27
+ export const toolOf = (key) => `propose_${key.replace(/[-:]/g, '_')}`;
28
+ /**
29
+ * The domain's move key a proposal's `move` names: the key itself, else the one whose tool it
30
+ * is (a proposable move first); null when none is.
31
+ */
32
+ export function moveOfTool(moves, raw) {
33
+ if (!raw)
34
+ return null;
35
+ const tool = toolOf(raw);
36
+ const keys = Object.keys(moves).filter((k) => toolOf(k) === tool);
37
+ return keys.find((k) => moves[k].propose) ?? (Object.hasOwn(moves, raw) ? raw : keys[0]) ?? null;
38
+ }